cinterface.js 23.0 KB
Newer Older
1 2 3 4 5
/**
 * C Interface with TDengine Module
 * @module CTaosInterface
 */

6 7 8 9
const ref = require('ref');
const ffi = require('ffi');
const ArrayType = require('ref-array');
const Struct = require('ref-struct');
10
const FieldTypes = require('./constants');
S
StoneT2000 已提交
11 12
const errors = require ('./error');
const TaosObjects = require('./taosobjects');
13
const { NULL_POINTER } = require('ref');
14 15 16 17

module.exports = CTaosInterface;

function convertMillisecondsToDatetime(time) {
S
StoneT2000 已提交
18
  return new TaosObjects.TaosTimestamp(time);
19 20
}
function convertMicrosecondsToDatetime(time) {
21
  return new TaosObjects.TaosTimestamp(time * 0.001, true);
22 23 24 25 26 27 28
}

function convertTimestamp(data, num_of_rows, nbytes = 0, offset = 0, micro=false) {
  timestampConverter = convertMillisecondsToDatetime;
  if (micro == true) {
    timestampConverter = convertMicrosecondsToDatetime;
  }
29
  data = ref.reinterpret(data, nbytes * num_of_rows, offset);
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
  let res = [];
  let currOffset = 0;
  while (currOffset < data.length) {
    let queue = [];
    let time = 0;
    for (let i = currOffset; i < currOffset + nbytes; i++) {
      queue.push(data[i]);
    }
    for (let i = queue.length - 1; i >= 0; i--) {
      time += queue[i] * Math.pow(16, i * 2);
    }
    currOffset += nbytes;
    res.push(timestampConverter(time));
  }
  return res;
}
function convertBool(data, num_of_rows, nbytes = 0, offset = 0, micro=false) {
47
  data = ref.reinterpret(data, nbytes * num_of_rows, offset);
48 49 50 51 52
  let res = new Array(data.length);
  for (let i = 0; i < data.length; i++) {
    if (data[i] == 0) {
      res[i] = false;
    }
53
    else if (data[i] == 1){
54 55
      res[i] = true;
    }
56 57 58
    else if (data[i] == FieldTypes.C_BOOL_NULL) {
      res[i] = null;
    }
59 60 61 62
  }
  return res;
}
function convertTinyint(data, num_of_rows, nbytes = 0, offset = 0, micro=false) {
63
  data = ref.reinterpret(data, nbytes * num_of_rows, offset);
64 65 66
  let res = [];
  let currOffset = 0;
  while (currOffset < data.length) {
67 68
    let d = data.readIntLE(currOffset,1);
    res.push(d == FieldTypes.C_TINYINT_NULL ? null : d);
69 70 71 72 73
    currOffset += nbytes;
  }
  return res;
}
function convertSmallint(data, num_of_rows, nbytes = 0, offset = 0, micro=false) {
74
  data = ref.reinterpret(data, nbytes * num_of_rows, offset);
75 76 77
  let res = [];
  let currOffset = 0;
  while (currOffset < data.length) {
78 79
    let d = data.readIntLE(currOffset,2);
    res.push(d == FieldTypes.C_SMALLINT_NULL ? null : d);
80 81 82 83 84
    currOffset += nbytes;
  }
  return res;
}
function convertInt(data, num_of_rows, nbytes = 0, offset = 0, micro=false) {
85
  data = ref.reinterpret(data, nbytes * num_of_rows, offset);
86 87 88
  let res = [];
  let currOffset = 0;
  while (currOffset < data.length) {
89 90
    let d = data.readInt32LE(currOffset);
    res.push(d == FieldTypes.C_INT_NULL ? null : d);
91 92 93 94 95
    currOffset += nbytes;
  }
  return res;
}
function convertBigint(data, num_of_rows, nbytes = 0, offset = 0, micro=false) {
96
  data = ref.reinterpret(data, nbytes * num_of_rows, offset);
97 98 99
  let res = [];
  let currOffset = 0;
  while (currOffset < data.length) {
100
    let d = data.readInt64LE(currOffset);
101
    res.push(d == FieldTypes.C_BIGINT_NULL ? null : d);
102 103 104 105 106
    currOffset += nbytes;
  }
  return res;
}
function convertFloat(data, num_of_rows, nbytes = 0, offset = 0, micro=false) {
107
  data = ref.reinterpret(data, nbytes * num_of_rows, offset);
108 109 110
  let res = [];
  let currOffset = 0;
  while (currOffset < data.length) {
111 112
    let d = parseFloat(data.readFloatLE(currOffset).toFixed(5));
    res.push(isNaN(d) ? null : d);
113 114 115 116 117
    currOffset += nbytes;
  }
  return res;
}
function convertDouble(data, num_of_rows, nbytes = 0, offset = 0, micro=false) {
118
  data = ref.reinterpret(data, nbytes * num_of_rows, offset);
119 120 121
  let res = [];
  let currOffset = 0;
  while (currOffset < data.length) {
122 123
    let d = parseFloat(data.readDoubleLE(currOffset).toFixed(16));
    res.push(isNaN(d) ? null : d);
124 125 126 127 128
    currOffset += nbytes;
  }
  return res;
}
function convertBinary(data, num_of_rows, nbytes = 0, offset = 0, micro=false) {
129
  data = ref.reinterpret(data, nbytes * num_of_rows, offset);
130 131 132
  let res = [];
  let currOffset = 0;
  while (currOffset < data.length) {
133 134 135 136 137 138 139
    let dataEntry = data.slice(currOffset, currOffset + nbytes);
    if (dataEntry[0] == FieldTypes.C_BINARY_NULL) {
      res.push(null);
    }
    else {
      res.push(ref.readCString(dataEntry));
    }
140 141 142 143 144
    currOffset += nbytes;
  }
  return res;
}
function convertNchar(data, num_of_rows, nbytes = 0, offset = 0, micro=false) {
145
  data = ref.reinterpret(data, nbytes * num_of_rows, offset);
146 147
  let res = [];
  let currOffset = 0;
148
  // every 4 bytes, a character is encoded;
149 150
  while (currOffset < data.length) {
    let dataEntry = data.slice(currOffset, currOffset + nbytes); //one entry in a row under a column;
151 152 153 154 155 156
    if (dataEntry.readInt64LE(0) == FieldTypes.C_NCHAR_NULL) {
      res.push(null);
    }
    else {
      res.push(dataEntry.toString("utf16le").replace(/\u0000/g, ""));
    }
157 158 159 160 161
    currOffset += nbytes;
  }
  return res;
}

162
// Object with all the relevant converters from pblock data to javascript readable data
163
let convertFunctions = {
164 165 166 167 168 169 170 171 172 173
    [FieldTypes.C_BOOL] : convertBool,
    [FieldTypes.C_TINYINT] : convertTinyint,
    [FieldTypes.C_SMALLINT] : convertSmallint,
    [FieldTypes.C_INT] : convertInt,
    [FieldTypes.C_BIGINT] : convertBigint,
    [FieldTypes.C_FLOAT] : convertFloat,
    [FieldTypes.C_DOUBLE] : convertDouble,
    [FieldTypes.C_BINARY] : convertBinary,
    [FieldTypes.C_TIMESTAMP] : convertTimestamp,
    [FieldTypes.C_NCHAR] : convertNchar
174 175 176 177 178 179 180
}

// Define TaosField structure
var char_arr = ArrayType(ref.types.char);
var TaosField = Struct({
                      'name': char_arr,
                      });
181
TaosField.fields.name.type.size = 65;
182
TaosField.defineProperty('type', ref.types.char);
183 184
TaosField.defineProperty('bytes', ref.types.short);

185

186
/**
S
StoneT2000 已提交
187
 *
188 189
 * @param {Object} config - Configuration options for the interface
 * @return {CTaosInterface}
S
StoneT2000 已提交
190 191 192
 * @class CTaosInterface
 * @classdesc The CTaosInterface is the interface through which Node.JS communicates data back and forth with TDengine. It is not advised to
 * access this class directly and use it unless you understand what these functions do.
193
 */
194 195 196
function CTaosInterface (config = null, pass = false) {
  ref.types.char_ptr = ref.refType(ref.types.char);
  ref.types.void_ptr = ref.refType(ref.types.void);
197
  ref.types.void_ptr2 = ref.refType(ref.types.void_ptr);
198
  /*Declare a bunch of functions first*/
199
  /* Note, pointers to TAOS_RES, TAOS, are ref.types.void_ptr. The connection._conn buffer is supplied for pointers to TAOS *  */
200 201 202 203 204 205 206
  this.libtaos = ffi.Library('libtaos', {
    'taos_options': [ ref.types.int, [ ref.types.int , ref.types.void_ptr ] ],
    'taos_init': [ ref.types.void, [ ] ],
    //TAOS *taos_connect(char *ip, char *user, char *pass, char *db, int port)
    'taos_connect': [ ref.types.void_ptr, [ ref.types.char_ptr, ref.types.char_ptr, ref.types.char_ptr, ref.types.char_ptr, ref.types.int ] ],
    //void taos_close(TAOS *taos)
    'taos_close': [ ref.types.void, [ ref.types.void_ptr ] ],
207 208
    //int *taos_fetch_lengths(TAOS_RES *taos);
    'taos_fetch_lengths': [ ref.types.void_ptr, [ ref.types.void_ptr ] ],
209
    //int taos_query(TAOS *taos, char *sqlstr)
210
    'taos_query': [ ref.types.void_ptr, [ ref.types.void_ptr, ref.types.char_ptr ] ],
211 212 213
    //int taos_affected_rows(TAOS *taos)
    'taos_affected_rows': [ ref.types.int, [ ref.types.void_ptr] ],
    //int taos_fetch_block(TAOS_RES *res, TAOS_ROW *rows)
214
    'taos_fetch_block': [ ref.types.int, [ ref.types.void_ptr, ref.types.void_ptr2] ],
215 216 217 218 219
    //int taos_num_fields(TAOS_RES *res);
    'taos_num_fields': [ ref.types.int, [ ref.types.void_ptr] ],
    //TAOS_ROW taos_fetch_row(TAOS_RES *res)
    //TAOS_ROW is void **, but we set the return type as a reference instead to get the row
    'taos_fetch_row': [ ref.refType(ref.types.void_ptr2), [ ref.types.void_ptr ] ],
220 221 222 223 224 225 226 227 228 229 230
    //int taos_result_precision(TAOS_RES *res)
    'taos_result_precision': [ ref.types.int, [ ref.types.void_ptr ] ],
    //void taos_free_result(TAOS_RES *res)
    'taos_free_result': [ ref.types.void, [ ref.types.void_ptr] ],
    //int taos_field_count(TAOS *taos)
    'taos_field_count': [ ref.types.int, [ ref.types.void_ptr ] ],
    //TAOS_FIELD *taos_fetch_fields(TAOS_RES *res)
    'taos_fetch_fields': [ ref.refType(TaosField),  [ ref.types.void_ptr ] ],
    //int taos_errno(TAOS *taos)
    'taos_errno': [ ref.types.int, [ ref.types.void_ptr] ],
    //char *taos_errstr(TAOS *taos)
231
    'taos_errstr': [ ref.types.char_ptr, [ ref.types.void_ptr] ],
232 233 234 235 236 237
    //void taos_stop_query(TAOS_RES *res);
    'taos_stop_query': [ ref.types.void, [ ref.types.void_ptr] ],
    //char *taos_get_server_info(TAOS *taos);
    'taos_get_server_info': [ ref.types.char_ptr, [ ref.types.void_ptr ] ],
    //char *taos_get_client_info();
    'taos_get_client_info': [ ref.types.char_ptr, [ ] ],
238 239 240 241 242

    // ASYNC
    // void taos_query_a(TAOS *taos, char *sqlstr, void (*fp)(void *, TAOS_RES *, int), void *param)
    'taos_query_a': [ ref.types.void, [ ref.types.void_ptr, ref.types.char_ptr, ref.types.void_ptr, ref.types.void_ptr ] ],
    // void taos_fetch_rows_a(TAOS_RES *res, void (*fp)(void *param, TAOS_RES *, int numOfRows), void *param);
243 244 245
    'taos_fetch_rows_a': [ ref.types.void, [ ref.types.void_ptr, ref.types.void_ptr, ref.types.void_ptr ]],

    // Subscription
S
StoneT2000 已提交
246 247 248 249
    //TAOS_SUB *taos_subscribe(TAOS* taos, int restart, const char* topic, const char *sql, TAOS_SUBSCRIBE_CALLBACK fp, void *param, int interval)
    'taos_subscribe': [ ref.types.void_ptr, [ ref.types.void_ptr, ref.types.int, ref.types.char_ptr, ref.types.char_ptr, ref.types.void_ptr, ref.types.void_ptr, ref.types.int] ],
    // TAOS_RES *taos_consume(TAOS_SUB *tsub)
    'taos_consume': [ ref.types.void_ptr, [ref.types.void_ptr] ],
250 251 252 253 254 255 256 257 258 259
    //void taos_unsubscribe(TAOS_SUB *tsub);
    'taos_unsubscribe': [ ref.types.void, [ ref.types.void_ptr ] ],

    // Continuous Query
    //TAOS_STREAM *taos_open_stream(TAOS *taos, char *sqlstr, void (*fp)(void *param, TAOS_RES *, TAOS_ROW row),
    //                              int64_t stime, void *param, void (*callback)(void *));
    'taos_open_stream': [ ref.types.void_ptr, [ ref.types.void_ptr, ref.types.char_ptr, ref.types.void_ptr, ref.types.int64, ref.types.void_ptr, ref.types.void_ptr ] ],
    //void taos_close_stream(TAOS_STREAM *tstr);
    'taos_close_stream': [ ref.types.void, [ ref.types.void_ptr ] ]

260 261 262 263 264 265 266
  });
  if (pass == false) {
    if (config == null) {
      this._config = ref.alloc(ref.types.char_ptr, ref.NULL);
    }
    else {
      try {
267
        this._config = ref.allocCString(config);
268 269 270 271 272 273 274 275 276 277
      }
      catch(err){
        throw "Attribute Error: config is expected as a str";
      }
    }
    if (config != null) {
      this.libtaos.taos_options(3, this._config);
    }
    this.libtaos.taos_init();
  }
278
  return this;
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
}
CTaosInterface.prototype.config = function config() {
    return this._config;
  }
CTaosInterface.prototype.connect = function connect(host=null, user="root", password="taosdata", db=null, port=0) {
  let _host,_user,_password,_db,_port;
  try  {
    _host = host != null ? ref.allocCString(host) : ref.alloc(ref.types.char_ptr, ref.NULL);
  }
  catch(err) {
    throw "Attribute Error: host is expected as a str";
  }
  try {
    _user = ref.allocCString(user)
  }
  catch(err) {
    throw "Attribute Error: user is expected as a str";
  }
  try {
    _password = ref.allocCString(password);
  }
  catch(err) {
    throw "Attribute Error: password is expected as a str";
  }
  try {
    _db = db != null ? ref.allocCString(db) : ref.alloc(ref.types.char_ptr, ref.NULL);
  }
  catch(err) {
    throw "Attribute Error: db is expected as a str";
  }
  try {
    _port = ref.alloc(ref.types.int, port);
  }
  catch(err) {
    throw TypeError("port is expected as an int")
  }
  let connection = this.libtaos.taos_connect(_host, _user, _password, _db, _port);
  if (ref.isNull(connection)) {
    throw new errors.TDError('Failed to connect to TDengine');
  }
  else {
    console.log('Successfully connected to TDengine');
  }
  return connection;
}
CTaosInterface.prototype.close = function close(connection) {
  this.libtaos.taos_close(connection);
  console.log("Connection is closed");
}
CTaosInterface.prototype.query = function query(connection, sql) {
S
StoneT2000 已提交
329
    return this.libtaos.taos_query(connection, ref.allocCString(sql));
330 331 332 333
}
CTaosInterface.prototype.affectedRows = function affectedRows(connection) {
  return this.libtaos.taos_affected_rows(connection);
}
334 335
CTaosInterface.prototype.useResult = function useResult(result) {

336 337 338
  let fields = [];
  let pfields = this.fetchFields(result);
  if (ref.isNull(pfields) == false) {
339
    pfields = ref.reinterpret(pfields, this.fieldsCount(result) * 68, 0);
340
    for (let i = 0; i < pfields.length; i += 68) {
341 342
      //0 - 63 = name //64 - 65 = bytes, 66 - 67 = type
      fields.push( {
343 344 345
        name: ref.readCString(ref.reinterpret(pfields,65,i)),
        type: pfields[i + 65],
        bytes: pfields[i + 66]
346 347 348
      })
    }
  }
349
  return {fields:fields}
350 351
}
CTaosInterface.prototype.fetchBlock = function fetchBlock(result, fields) {
352 353 354 355
  let pblock = ref.ref(ref.NULL); // equal to our raw data
  pblock = this.libtaos.taos_fetch_row(result);

  if (pblock == 0) {
356 357
    return {block:null, num_of_rows:0};
  }
358
  let isMicro = (this.libtaos.taos_result_precision(result) == FieldTypes.C_TIMESTAMP_MICRO)
359 360 361
  

  //num_of_rows = Math.abs(num_of_rows);
362
  let offset = 0;
363 364 365 366
  //pblock = pblock.deref();
  
  var fieldL = this.libtaos.taos_fetch_lengths(result);
  var numoffields = this.libtaos.taos_field_count(result);
367

368 369 370 371 372 373 374 375 376 377 378 379
  let blocks = new Array(numoffields);
  blocks.fill(null);
  var fieldlens = [];
  
  if (ref.isNull(fieldL) == false) {
    
    for (let i = 0; i < numoffields; i ++) {
      let plen = ref.reinterpret(fieldL, 4, i*4);
      //plen = ref.readPointer(plen,0,ref.types.int);
      let len = plen.readInt32LE(0);
       fieldlens.push(len);
       //console.log(len);
380 381
    }
  }
382 383 384 385 386 387 388 389 390 391 392 393
  for (let i = 0; i < numoffields; i++) {
    if (!convertFunctions[fields['fields'][i]['type']] ) {
      throw new errors.DatabaseError("Invalid data type returned from database");
    }
    prow = ref.reinterpret(pblock,8,i*8);
    console.log(fieldlens[i]);
    blocks[i] = convertFunctions[fields['fields'][i]['type']](prow, 1, fieldlens[i], 0, isMicro);
    console.log('******************************');
    console.log(blocks[i]);
    //offset += fields[i]['bytes'] * num_of_rows;
  }
  return {blocks: blocks, num_of_rows:1}
394
}
395 396 397 398
CTaosInterface.prototype.fetchRow = function fetchRow(result, fields) {
  let row = this.libtaos.taos_fetch_row(result);
  return row;
}
399 400 401 402
CTaosInterface.prototype.freeResult = function freeResult(result) {
  this.libtaos.taos_free_result(result);
  result = null;
}
403 404 405 406
/** Number of fields returned in this result handle, must use with async */
CTaosInterface.prototype.numFields = function numFields(result) {
  return this.libtaos.taos_num_fields(result);
}
407
// Fetch fields count by connection, the latest query
408 409
CTaosInterface.prototype.fieldsCount = function fieldsCount(result) {
  return this.libtaos.taos_field_count(result);
410 411 412 413
}
CTaosInterface.prototype.fetchFields = function fetchFields(result) {
  return this.libtaos.taos_fetch_fields(result);
}
414 415
CTaosInterface.prototype.errno = function errno(result) {
  return this.libtaos.taos_errno(result);
416
}
417 418
CTaosInterface.prototype.errStr = function errStr(result) {
  return ref.readCString(this.libtaos.taos_errstr(result));
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
}
// Async
CTaosInterface.prototype.query_a = function query_a(connection, sql, callback, param = ref.ref(ref.NULL)) {
  // void taos_query_a(TAOS *taos, char *sqlstr, void (*fp)(void *param, TAOS_RES *, int), void *param)
  callback = ffi.Callback(ref.types.void, [ ref.types.void_ptr, ref.types.void_ptr, ref.types.int ], callback);
  this.libtaos.taos_query_a(connection, ref.allocCString(sql), callback, param);
  return param;
}
/** Asynchrnously fetches the next block of rows. Wraps callback and transfers a 4th argument to the cursor, the row data as blocks in javascript form
 * Note: This isn't a recursive function, in order to fetch all data either use the TDengine cursor object, TaosQuery object, or implement a recrusive
 * function yourself using the libtaos.taos_fetch_rows_a function
 */
CTaosInterface.prototype.fetch_rows_a = function fetch_rows_a(result, callback, param = ref.ref(ref.NULL)) {
  // void taos_fetch_rows_a(TAOS_RES *res, void (*fp)(void *param, TAOS_RES *, int numOfRows), void *param);
  var cti = this;
  // wrap callback with a function so interface can access the numOfRows value, needed in order to properly process the binary data
  let asyncCallbackWrapper = function (param2, result2, numOfRows2) {
    // Data preparation to pass to cursor. Could be bottleneck in query execution callback times.
    let row = cti.libtaos.taos_fetch_row(result2);
438
    console.log(row);
439
    let fields = cti.fetchFields_a(result2);
440 441
    

442
    let isMicro = (cti.libtaos.taos_result_precision(result2) == FieldTypes.C_TIMESTAMP_MICRO);
443 444 445 446
    let blocks = new Array(fields.length);
    blocks.fill(null);
    numOfRows2 = Math.abs(numOfRows2);
    let offset = 0;
447 448 449 450 451 452 453 454 455 456 457 458 459 460
    var fieldL = cti.libtaos.taos_fetch_lengths(result);
    var fieldlens = [];
    if (ref.isNull(fieldL) == false) {
      
      for (let i = 0; i < fields.length; i ++) {
        let plen = ref.reinterpret(fieldL, 8, i*8);
        let len = ref.get(plen,0,ref.types.int32);
        fieldlens.push(len);
        console.log('11111111111111111111');
        console.log(fields.length);
        console.log(len);
      }
    }

461 462 463 464 465
    if (numOfRows2 > 0){
      for (let i = 0; i < fields.length; i++) {
        if (!convertFunctions[fields[i]['type']] ) {
          throw new errors.DatabaseError("Invalid data type returned from database");
        }
466 467 468 469 470
        let prow = ref.reinterpret(row,8,i*8);
        //blocks[i] = convertFunctions[fields[i]['type']](ref.get(prow,0,ref.types.void_ptr), numOfRows2, fieldlens[i], 0, isMicro);
        console.log(prow);
        blocks[i] = convertFunctions[fields[i]['type']](ref.readPointer(prow), numOfRows2, fieldlens[i], 0, isMicro);
        //offset += fields[i]['bytes'] * numOfRows2;
471 472 473 474
      }
    }
    callback(param2, result2, numOfRows2, blocks);
  }
475
  asyncCallbackWrapper = ffi.Callback(ref.types.void, [ ref.types.void_ptr, ref.types.void_ptr, ref.types.int ], asyncCallbackWrapper);
476 477 478 479 480 481 482 483 484 485 486
  this.libtaos.taos_fetch_rows_a(result, asyncCallbackWrapper, param);
  return param;
}
// Fetch field meta data by result handle
CTaosInterface.prototype.fetchFields_a = function fetchFields_a (result) {
  let pfields = this.fetchFields(result);
  let pfieldscount = this.numFields(result);
  let fields = [];
  if (ref.isNull(pfields) == false) {
    pfields = ref.reinterpret(pfields, 68 * pfieldscount , 0);
    for (let i = 0; i < pfields.length; i += 68) {
487
      //0 - 64 = name //65 = type, 66 - 67 = bytes
488
      fields.push( {
489 490 491
        name: ref.readCString(ref.reinterpret(pfields,65,i)),
        type: pfields[i + 65],
        bytes: pfields[i + 66]
492 493 494 495
      })
    }
  }
  return fields;
496
}
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
// Stop a query by result handle
CTaosInterface.prototype.stopQuery = function stopQuery(result) {
  if (result != null){
    this.libtaos.taos_stop_query(result);
  }
  else {
    throw new errors.ProgrammingError("No result handle passed to stop query");
  }
}
CTaosInterface.prototype.getServerInfo = function getServerInfo(connection) {
  return ref.readCString(this.libtaos.taos_get_server_info(connection));
}
CTaosInterface.prototype.getClientInfo = function getClientInfo() {
  return ref.readCString(this.libtaos.taos_get_client_info());
}

// Subscription
S
StoneT2000 已提交
514 515 516
CTaosInterface.prototype.subscribe = function subscribe(connection, restart, topic, sql, interval) {
  let topicOrig = topic;
  let sqlOrig = sql;
517
  try {
S
StoneT2000 已提交
518
    sql = sql != null ? ref.allocCString(sql) : ref.alloc(ref.types.char_ptr, ref.NULL);
519 520
  }
  catch(err) {
S
StoneT2000 已提交
521
    throw "Attribute Error: sql is expected as a str";
522 523
  }
  try {
S
StoneT2000 已提交
524
    topic = topic != null ? ref.allocCString(topic) : ref.alloc(ref.types.char_ptr, ref.NULL);
525 526
  }
  catch(err) {
S
StoneT2000 已提交
527 528
    throw TypeError("topic is expected as a str");
  }
S
StoneT2000 已提交
529

S
StoneT2000 已提交
530
  restart = ref.alloc(ref.types.int, restart);
S
StoneT2000 已提交
531

S
StoneT2000 已提交
532
  let subscription = this.libtaos.taos_subscribe(connection, restart, topic, sql, null, null, interval);
533 534 535 536
  if (ref.isNull(subscription)) {
    throw new errors.TDError('Failed to subscribe to TDengine | Database: ' + dbOrig + ', Table: ' + tableOrig);
  }
  else {
S
StoneT2000 已提交
537
    console.log('Successfully subscribed to TDengine - Topic: ' + topicOrig);
538 539 540
  }
  return subscription;
}
S
StoneT2000 已提交
541 542 543

CTaosInterface.prototype.consume = function consume(subscription) {
  let result = this.libtaos.taos_consume(subscription);
544
  let fields = [];
S
StoneT2000 已提交
545
  let pfields = this.fetchFields(result);
546
  if (ref.isNull(pfields) == false) {
S
StoneT2000 已提交
547
    pfields = ref.reinterpret(pfields, this.numFields(result) * 68, 0);
548 549 550 551 552 553 554 555 556
    for (let i = 0; i < pfields.length; i += 68) {
      //0 - 63 = name //64 - 65 = bytes, 66 - 67 = type
      fields.push( {
        name: ref.readCString(ref.reinterpret(pfields,64,i)),
        bytes: pfields[i + 64],
        type: pfields[i + 66]
      })
    }
  }
S
StoneT2000 已提交
557 558 559 560 561 562 563 564 565 566 567 568

  let data = [];
  while(true) {
    let { blocks, num_of_rows } = this.fetchBlock(result, fields);
    if (num_of_rows == 0) {
      break;
    }
    for (let i = 0; i < num_of_rows; i++) {
      data.push([]);
      let rowBlock = new Array(fields.length);
      for (let j = 0; j < fields.length; j++) {
        rowBlock[j] = blocks[j][i];
569
      }
S
StoneT2000 已提交
570
      data[data.length-1] = (rowBlock);
571 572
    }
  }
S
StoneT2000 已提交
573
  return { data: data, fields: fields, result: result };
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
}
CTaosInterface.prototype.unsubscribe = function unsubscribe(subscription) {
  //void taos_unsubscribe(TAOS_SUB *tsub);
  this.libtaos.taos_unsubscribe(subscription);
}

// Continuous Query
CTaosInterface.prototype.openStream = function openStream(connection, sql, callback, stime,stoppingCallback, param = ref.ref(ref.NULL)) {
  try {
    sql = ref.allocCString(sql);
  }
  catch(err) {
    throw "Attribute Error: sql string is expected as a str";
  }
  var cti = this;
  let asyncCallbackWrapper = function (param2, result2, row) {
    let fields = cti.fetchFields_a(result2);
    let isMicro = (cti.libtaos.taos_result_precision(result2) == FieldTypes.C_TIMESTAMP_MICRO);
    let blocks = new Array(fields.length);
    blocks.fill(null);
    let numOfRows2 = 1;
    let offset = 0;
    if (numOfRows2 > 0) {
      for (let i = 0; i < fields.length; i++) {
        if (!convertFunctions[fields[i]['type']] ) {
          throw new errors.DatabaseError("Invalid data type returned from database");
        }
        blocks[i] = convertFunctions[fields[i]['type']](row, numOfRows2, fields[i]['bytes'], offset, isMicro);
        offset += fields[i]['bytes'] * numOfRows2;
      }
    }
    callback(param2, result2, blocks, fields);
  }
  asyncCallbackWrapper = ffi.Callback(ref.types.void, [ ref.types.void_ptr, ref.types.void_ptr, ref.refType(ref.types.void_ptr2) ], asyncCallbackWrapper);
  asyncStoppingCallbackWrapper = ffi.Callback( ref.types.void, [ ref.types.void_ptr ], stoppingCallback);
  let streamHandle = this.libtaos.taos_open_stream(connection, sql, asyncCallbackWrapper, stime, param, asyncStoppingCallbackWrapper);
  if (ref.isNull(streamHandle)) {
    throw new errors.TDError('Failed to open a stream with TDengine');
    return false;
  }
  else {
    console.log("Succesfully opened stream");
    return streamHandle;
  }
}
CTaosInterface.prototype.closeStream = function closeStream(stream) {
  this.libtaos.taos_close_stream(stream);
  console.log("Closed stream");
}