Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

v2.0 compatibility #14

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 22 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,21 @@ influxdb.setReadTimeout(10);
influxdb.setWriteTimeout(10);
```

Usage with InfluxDB v2.0 is similar, but the instantiation is a bit different.

```matlab
% Build an InfluxDB client
URL = 'http://localhost:8086';
TOKEN = 'token'
ORG = 'organization'
DATABASE = 'server_stats';
influxdb = InfluxDB(URL, TOKEN, ORG, DATABASE);
```

The v2.0 client uses the v1.x compatible API. The [compatibility API](https://docs.influxdata.com/influxdb/v2.0/reference/api/influxdb-1x/) supports InfluxQL, with the following caveats:

- The `INTO` clause (e.g. `SELECT ... INTO ...`) is not supported.
- With the exception of `DELETE` and `DROP MEASUREMENT` queries, which are still allowed, InfluxQL database management commands are not supported.

Writing data
------------
Expand Down Expand Up @@ -206,19 +221,19 @@ License
-------

MIT License

Copyright (c) 2018 Enric Sala

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
Expand All @@ -228,6 +243,6 @@ License
SOFTWARE.


[matlab]: https://en.wikipedia.org/wiki/MATLAB
[influxdb]: https://en.wikipedia.org/wiki/InfluxDB
[influxdb-docs]: https://docs.influxdata.com/influxdb
[matlab]: https://en.wikipedia.org/wiki/MATLAB
[influxdb]: https://en.wikipedia.org/wiki/InfluxDB
[influxdb-docs]: https://docs.influxdata.com/influxdb
31 changes: 31 additions & 0 deletions example_v2.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
clear; clc;
addpath('influxdb-client');

% Configure database
URL = 'http://localhost:8086';
TOKEN = 'x7sBilbi0evsHydoT6kQWRQmJdEbuhgB';
DATABASE = 'vehicle';
ORG = 'f1tenth';
influxdb = InfluxDBv2(URL, TOKEN, ORG, DATABASE);

% Check the status of the InfluxDB instance
[ok, ping] = influxdb.ping();

% Change the current database
influxdb.use('vehicle');

% Show databases
influxdb.databases()

% Write data
series1 = Series('position') ...
.tags('city', 'antwerp', 'country', 'belgium') ...
.fields('x', 825, 'y', 433.65) ...
.time(datetime('now', 'TimeZone', 'local'));

influxdb.writer().append(series1).execute()

% Read data
result = influxdb.query('position').execute();
result.series('position').timetable('Europe/Paris')

179 changes: 179 additions & 0 deletions influxdb-client/InfluxDBv2.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
classdef InfluxDBv2 < handle

properties(Access = private)
Url = ''
Token = ''
Database = ''
Organization = ''
ReadTimeout = 10
WriteTimeout = 10
end

methods
% Constructor
function obj = InfluxDBv2(url, token, org, database)
obj.Url = url;
obj.Token = token;
obj.Organization = org;
obj.use(database);
end

% Set the read timeout
function obj = setReadTimeout(obj, timeout)
obj.ReadTimeout = timeout;
end

% Set the write timeout
function obj = setWriteTimeout(obj, timeout)
obj.WriteTimeout = timeout;
end

% Check the status of the InfluxDB instance
function [ok, millis] = ping(obj)
try
timer = tic;
webread([obj.Url '/ping']);
millis = toc(timer) * 1000;
ok = true;
catch
millis = Inf;
ok = false;
end
end

% Show databases
function databases = databases(obj)
result = obj.runCommand('SHOW DATABASES');
databases = result.series().field('name');
end

% Change the current database
function obj = use(obj, database)
obj.Database = database;

% Delete existing retention policies associated to the new
% database.
params = {['org=' obj.Organization]};
url = [obj.Url '/api/v2/dbrps?' strjoin(params, '&')];
opts = weboptions('KeyName', 'Authorization', 'KeyValue',['Token ' obj.Token]);
response = webread(url, opts);
dbrps = response.content;

for i=1:length(dbrps)
dbrp = dbrps(i);
if strcmp(dbrp.database, obj.Database)
params = {['org=' obj.Organization]};
url = [obj.Url '/api/v2/dbrps/' dbrp.id '?' strjoin(params, '&')];
opts = weboptions('RequestMethod', 'delete', 'KeyName', 'Authorization', 'KeyValue',['Token ' obj.Token]);
webread(url, opts);
end
end

% Get bucket ID
params = {['org=' obj.Organization], ['name=' obj.Database]};
url = [obj.Url '/api/v2/buckets?' strjoin(params, '&')];
opts = weboptions('KeyName', 'Authorization', 'KeyValue',['Token ' obj.Token]);
response = webread(url, opts);
bucketID = response.buckets.id;

% Create DBRP mapping
data = struct;
data.bucketID = bucketID;
data.database = obj.Database;
data.org = obj.Organization;
data.retention_policy = [obj.Database '-rp'];
url = [obj.Url '/api/v2/dbrps'];
opts = weboptions('MediaType','application/json','KeyName','Authorization','KeyValue',['Token ' obj.Token]);
webwrite(url, data, opts);
end

% Execute a query string
function result = runQuery(obj, query, database, epoch)
if nargin < 3 || isempty(database)
database = obj.Database;
end
if nargin < 4 || isempty(epoch)
epoch = 'ms';
else
TimeUtils.validateEpoch(epoch);
end
if iscell(query)
query = strjoin(query, ';');
end
params = {['db=' database], ['epoch=' epoch], ['q=' query]};
url = [obj.Url '/query?' strjoin(params, '&')];
opts = weboptions('Timeout', obj.ReadTimeout, ...
'KeyName', 'Authorization', 'KeyValue',['Token ' obj.Token]);
response = webread(url, opts);
result = QueryResult.from(response, epoch);
end

% Obtain a query builder
function builder = query(obj, varargin)
if nargin > 2
builder = QueryBuilder().series(varargin).influxdb(obj);
elseif nargin > 1
builder = QueryBuilder().series(varargin{1}).influxdb(obj);
else
builder = QueryBuilder().influxdb(obj);
end
end

% Execute a write of a line protocol string
function [] = runWrite(obj, lines, database, precision, retention, consistency)
lines
params = {};
if nargin > 2 && ~isempty(database)
params{end + 1} = ['db=' urlencode(database)];
else
params{end + 1} = ['db=' urlencode(obj.Database)];
end
if nargin > 3 && ~isempty(precision)
TimeUtils.validatePrecision(precision);
params{end + 1} = ['precision=' precision];
end
if nargin > 4 && ~isempty(retention)
params{end + 1} = ['rp=' urlencode(retention)];
end
if nargin > 5 && ~isempty(consistency)
assert(any(strcmp(consistency, {'any', 'one', 'quorum', 'all'})), ...
'consistency:unknown', '"%s" is not a valid consistency', consistency);
params{end + 1} = ['consistency=' consistency];
end
url = [obj.Url '/write?' strjoin(params, '&')];
opts = weboptions('Timeout', obj.WriteTimeout, ...
'KeyName', 'Authorization', 'KeyValue',['Token ' obj.Token]);
webwrite(url, lines, opts);
end

% Obtain a write builder
function builder = writer(obj)
builder = WriteBuilder().influxdb(obj);
end

% Execute other queries or commands
function result = runCommand(obj, command, varargin)
idx = find(cellfun(@ischar, varargin), 1, 'first');
database = iif(isempty(idx), '', varargin{idx});
idx = find(cellfun(@islogical, varargin), 1, 'first');
requiresPost = iif(isempty(idx), false, varargin{idx});

if isempty(database)
params = {'q', command};
else
params = {'db', database, 'q', command};
end
url = [obj.Url '/query'];
opts = weboptions('KeyName', 'Authorization', 'KeyValue',['Token ' obj.Token]);
if requiresPost
opts.Timeout = obj.WriteTimeout;
response = webwrite(url, params{:}, opts);
else
opts.Timeout = obj.ReadTimeout;
response = webread(url, params{:}, opts);
end
result = QueryResult.from(response);
end
end

end