cinterface.py 22.6 KB
Newer Older
1 2 3 4 5 6
import ctypes
from .constants import FieldType
from .error import *
import math
import datetime

7

8
def _convert_millisecond_to_datetime(milli):
9 10
    return datetime.datetime.fromtimestamp(milli / 1000.0)

11 12

def _convert_microsecond_to_datetime(micro):
13 14
    return datetime.datetime.fromtimestamp(micro / 1000000.0)

15 16 17 18 19 20 21 22 23

def _crow_timestamp_to_python(data, num_of_rows, nbytes=None, micro=False):
    """Function to convert C bool row to python row
    """
    _timestamp_converter = _convert_millisecond_to_datetime
    if micro:
        _timestamp_converter = _convert_microsecond_to_datetime

    if num_of_rows > 0:
24 25 26 27 28
        return [
            None if ele == FieldType.C_BIGINT_NULL else _timestamp_converter(ele) for ele in ctypes.cast(
                data, ctypes.POINTER(
                    ctypes.c_int64))[
                :abs(num_of_rows)]]
29
    else:
30 31 32 33 34
        return [
            None if ele == FieldType.C_BIGINT_NULL else _timestamp_converter(ele) for ele in ctypes.cast(
                data, ctypes.POINTER(
                    ctypes.c_int64))[
                :abs(num_of_rows)]]
35

36 37 38 39 40

def _crow_bool_to_python(data, num_of_rows, nbytes=None, micro=False):
    """Function to convert C bool row to python row
    """
    if num_of_rows > 0:
41 42 43 44 45
        return [
            None if ele == FieldType.C_BOOL_NULL else bool(ele) for ele in ctypes.cast(
                data, ctypes.POINTER(
                    ctypes.c_byte))[
                :abs(num_of_rows)]]
46
    else:
47 48 49 50 51 52
        return [
            None if ele == FieldType.C_BOOL_NULL else bool(ele) for ele in ctypes.cast(
                data, ctypes.POINTER(
                    ctypes.c_bool))[
                :abs(num_of_rows)]]

53 54 55 56 57

def _crow_tinyint_to_python(data, num_of_rows, nbytes=None, micro=False):
    """Function to convert C tinyint row to python row
    """
    if num_of_rows > 0:
58 59
        return [None if ele == FieldType.C_TINYINT_NULL else ele for ele in ctypes.cast(
            data, ctypes.POINTER(ctypes.c_byte))[:abs(num_of_rows)]]
60
    else:
61 62 63
        return [None if ele == FieldType.C_TINYINT_NULL else ele for ele in ctypes.cast(
            data, ctypes.POINTER(ctypes.c_byte))[:abs(num_of_rows)]]

64

65 66 67 68 69
def _crow_tinyint_unsigned_to_python(
        data,
        num_of_rows,
        nbytes=None,
        micro=False):
70 71 72
    """Function to convert C tinyint row to python row
    """
    if num_of_rows > 0:
73 74 75
        return [
            None if ele == FieldType.C_TINYINT_UNSIGNED_NULL else ele for ele in ctypes.cast(
                data, ctypes.POINTER(
76
                    ctypes.c_ubyte))[
77
                :abs(num_of_rows)]]
78
    else:
79 80 81
        return [
            None if ele == FieldType.C_TINYINT_UNSIGNED_NULL else ele for ele in ctypes.cast(
                data, ctypes.POINTER(
82
                    ctypes.c_ubyte))[
83 84
                :abs(num_of_rows)]]

85

86 87 88 89
def _crow_smallint_to_python(data, num_of_rows, nbytes=None, micro=False):
    """Function to convert C smallint row to python row
    """
    if num_of_rows > 0:
90 91 92 93 94
        return [
            None if ele == FieldType.C_SMALLINT_NULL else ele for ele in ctypes.cast(
                data, ctypes.POINTER(
                    ctypes.c_short))[
                :abs(num_of_rows)]]
95
    else:
96 97 98 99 100
        return [
            None if ele == FieldType.C_SMALLINT_NULL else ele for ele in ctypes.cast(
                data, ctypes.POINTER(
                    ctypes.c_short))[
                :abs(num_of_rows)]]
101

102 103 104

def _crow_smallint_unsigned_to_python(
        data, num_of_rows, nbytes=None, micro=False):
105 106 107
    """Function to convert C smallint row to python row
    """
    if num_of_rows > 0:
108 109 110
        return [
            None if ele == FieldType.C_SMALLINT_UNSIGNED_NULL else ele for ele in ctypes.cast(
                data, ctypes.POINTER(
111
                    ctypes.c_ushort))[
112
                :abs(num_of_rows)]]
113
    else:
114 115 116
        return [
            None if ele == FieldType.C_SMALLINT_UNSIGNED_NULL else ele for ele in ctypes.cast(
                data, ctypes.POINTER(
117
                    ctypes.c_ushort))[
118 119
                :abs(num_of_rows)]]

120

121 122 123 124
def _crow_int_to_python(data, num_of_rows, nbytes=None, micro=False):
    """Function to convert C int row to python row
    """
    if num_of_rows > 0:
125 126
        return [None if ele == FieldType.C_INT_NULL else ele for ele in ctypes.cast(
            data, ctypes.POINTER(ctypes.c_int))[:abs(num_of_rows)]]
127
    else:
128 129 130
        return [None if ele == FieldType.C_INT_NULL else ele for ele in ctypes.cast(
            data, ctypes.POINTER(ctypes.c_int))[:abs(num_of_rows)]]

131

132 133 134 135
def _crow_int_unsigned_to_python(data, num_of_rows, nbytes=None, micro=False):
    """Function to convert C int row to python row
    """
    if num_of_rows > 0:
136 137 138
        return [
            None if ele == FieldType.C_INT_UNSIGNED_NULL else ele for ele in ctypes.cast(
                data, ctypes.POINTER(
139
                    ctypes.c_uint))[
140
                :abs(num_of_rows)]]
141
    else:
142 143 144
        return [
            None if ele == FieldType.C_INT_UNSIGNED_NULL else ele for ele in ctypes.cast(
                data, ctypes.POINTER(
145
                    ctypes.c_uint))[
146 147
                :abs(num_of_rows)]]

148

149 150 151 152
def _crow_bigint_to_python(data, num_of_rows, nbytes=None, micro=False):
    """Function to convert C bigint row to python row
    """
    if num_of_rows > 0:
153
        return [None if ele == FieldType.C_BIGINT_NULL else ele for ele in ctypes.cast(
154
            data, ctypes.POINTER(ctypes.c_int64))[:abs(num_of_rows)]]
155
    else:
156
        return [None if ele == FieldType.C_BIGINT_NULL else ele for ele in ctypes.cast(
157
            data, ctypes.POINTER(ctypes.c_int64))[:abs(num_of_rows)]]
158

159

160 161 162 163 164
def _crow_bigint_unsigned_to_python(
        data,
        num_of_rows,
        nbytes=None,
        micro=False):
165 166 167
    """Function to convert C bigint row to python row
    """
    if num_of_rows > 0:
168 169 170
        return [
            None if ele == FieldType.C_BIGINT_UNSIGNED_NULL else ele for ele in ctypes.cast(
                data, ctypes.POINTER(
171
                    ctypes.c_uint64))[
172
                :abs(num_of_rows)]]
173
    else:
174 175 176
        return [
            None if ele == FieldType.C_BIGINT_UNSIGNED_NULL else ele for ele in ctypes.cast(
                data, ctypes.POINTER(
177
                    ctypes.c_uint64))[
178 179
                :abs(num_of_rows)]]

180

181 182 183 184
def _crow_float_to_python(data, num_of_rows, nbytes=None, micro=False):
    """Function to convert C float row to python row
    """
    if num_of_rows > 0:
185 186
        return [None if math.isnan(ele) else ele for ele in ctypes.cast(
            data, ctypes.POINTER(ctypes.c_float))[:abs(num_of_rows)]]
187
    else:
188 189 190
        return [None if math.isnan(ele) else ele for ele in ctypes.cast(
            data, ctypes.POINTER(ctypes.c_float))[:abs(num_of_rows)]]

191 192 193 194 195

def _crow_double_to_python(data, num_of_rows, nbytes=None, micro=False):
    """Function to convert C double row to python row
    """
    if num_of_rows > 0:
196 197
        return [None if math.isnan(ele) else ele for ele in ctypes.cast(
            data, ctypes.POINTER(ctypes.c_double))[:abs(num_of_rows)]]
198
    else:
199 200 201
        return [None if math.isnan(ele) else ele for ele in ctypes.cast(
            data, ctypes.POINTER(ctypes.c_double))[:abs(num_of_rows)]]

202 203 204 205 206 207

def _crow_binary_to_python(data, num_of_rows, nbytes=None, micro=False):
    """Function to convert C binary row to python row
    """
    assert(nbytes is not None)
    if num_of_rows > 0:
208 209
        return [None if ele.value[0:1] == FieldType.C_BINARY_NULL else ele.value.decode(
            'utf-8') for ele in (ctypes.cast(data, ctypes.POINTER(ctypes.c_char * nbytes)))[:abs(num_of_rows)]]
210
    else:
211 212 213
        return [None if ele.value[0:1] == FieldType.C_BINARY_NULL else ele.value.decode(
            'utf-8') for ele in (ctypes.cast(data, ctypes.POINTER(ctypes.c_char * nbytes)))[:abs(num_of_rows)]]

214 215 216 217 218

def _crow_nchar_to_python(data, num_of_rows, nbytes=None, micro=False):
    """Function to convert C nchar row to python row
    """
    assert(nbytes is not None)
219
    res = []
220 221 222 223
    for i in range(abs(num_of_rows)):
        try:
            if num_of_rows >= 0:
                tmpstr = ctypes.c_char_p(data)
224
                res.append(tmpstr.value.decode())
225
            else:
226 227
                res.append((ctypes.cast(data + nbytes * i,
                                        ctypes.POINTER(ctypes.c_wchar * (nbytes // 4))))[0].value)
228 229 230
        except ValueError:
            res.append(None)

231 232
    return res

233 234 235 236 237

def _crow_binary_to_python_block(data, num_of_rows, nbytes=None, micro=False):
    """Function to convert C binary row to python row
    """
    assert(nbytes is not None)
238
    res = []
239 240 241
    if num_of_rows > 0:
        for i in range(abs(num_of_rows)):
            try:
242 243 244 245 246 247 248
                rbyte = ctypes.cast(
                    data + nbytes * i,
                    ctypes.POINTER(
                        ctypes.c_short))[
                    :1].pop()
                tmpstr = ctypes.c_char_p(data + nbytes * i + 2)
                res.append(tmpstr.value.decode()[0:rbyte])
249 250 251 252 253
            except ValueError:
                res.append(None)
    else:
        for i in range(abs(num_of_rows)):
            try:
254 255 256 257 258 259 260
                rbyte = ctypes.cast(
                    data + nbytes * i,
                    ctypes.POINTER(
                        ctypes.c_short))[
                    :1].pop()
                tmpstr = ctypes.c_char_p(data + nbytes * i + 2)
                res.append(tmpstr.value.decode()[0:rbyte])
261 262 263 264
            except ValueError:
                res.append(None)
    return res

265

266 267 268 269
def _crow_nchar_to_python_block(data, num_of_rows, nbytes=None, micro=False):
    """Function to convert C nchar row to python row
    """
    assert(nbytes is not None)
270
    res = []
271 272 273
    if num_of_rows >= 0:
        for i in range(abs(num_of_rows)):
            try:
274 275
                tmpstr = ctypes.c_char_p(data + nbytes * i + 2)
                res.append(tmpstr.value.decode())
276 277 278 279 280
            except ValueError:
                res.append(None)
    else:
        for i in range(abs(num_of_rows)):
            try:
281 282
                res.append((ctypes.cast(data + nbytes * i + 2,
                                        ctypes.POINTER(ctypes.c_wchar * (nbytes // 4))))[0].value)
283 284 285 286
            except ValueError:
                res.append(None)
    return res

287

288 289
_CONVERT_FUNC = {
    FieldType.C_BOOL: _crow_bool_to_python,
290 291 292 293 294 295
    FieldType.C_TINYINT: _crow_tinyint_to_python,
    FieldType.C_SMALLINT: _crow_smallint_to_python,
    FieldType.C_INT: _crow_int_to_python,
    FieldType.C_BIGINT: _crow_bigint_to_python,
    FieldType.C_FLOAT: _crow_float_to_python,
    FieldType.C_DOUBLE: _crow_double_to_python,
296
    FieldType.C_BINARY: _crow_binary_to_python,
297 298 299 300 301 302
    FieldType.C_TIMESTAMP: _crow_timestamp_to_python,
    FieldType.C_NCHAR: _crow_nchar_to_python,
    FieldType.C_TINYINT_UNSIGNED: _crow_tinyint_unsigned_to_python,
    FieldType.C_SMALLINT_UNSIGNED: _crow_smallint_unsigned_to_python,
    FieldType.C_INT_UNSIGNED: _crow_int_unsigned_to_python,
    FieldType.C_BIGINT_UNSIGNED: _crow_bigint_unsigned_to_python
303 304 305 306
}

_CONVERT_FUNC_BLOCK = {
    FieldType.C_BOOL: _crow_bool_to_python,
307 308 309 310 311 312
    FieldType.C_TINYINT: _crow_tinyint_to_python,
    FieldType.C_SMALLINT: _crow_smallint_to_python,
    FieldType.C_INT: _crow_int_to_python,
    FieldType.C_BIGINT: _crow_bigint_to_python,
    FieldType.C_FLOAT: _crow_float_to_python,
    FieldType.C_DOUBLE: _crow_double_to_python,
313
    FieldType.C_BINARY: _crow_binary_to_python_block,
314 315 316 317 318 319
    FieldType.C_TIMESTAMP: _crow_timestamp_to_python,
    FieldType.C_NCHAR: _crow_nchar_to_python_block,
    FieldType.C_TINYINT_UNSIGNED: _crow_tinyint_unsigned_to_python,
    FieldType.C_SMALLINT_UNSIGNED: _crow_smallint_unsigned_to_python,
    FieldType.C_INT_UNSIGNED: _crow_int_unsigned_to_python,
    FieldType.C_BIGINT_UNSIGNED: _crow_bigint_unsigned_to_python
320 321 322
}

# Corresponding TAOS_FIELD structure in C
323 324


325 326 327 328 329 330
class TaosField(ctypes.Structure):
    _fields_ = [('name', ctypes.c_char * 65),
                ('type', ctypes.c_char),
                ('bytes', ctypes.c_short)]

# C interface class
331 332


333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
class CTaosInterface(object):

    libtaos = ctypes.CDLL('libtaos.dylib')

    libtaos.taos_fetch_fields.restype = ctypes.POINTER(TaosField)
    libtaos.taos_init.restype = None
    libtaos.taos_connect.restype = ctypes.c_void_p
    #libtaos.taos_use_result.restype = ctypes.c_void_p
    libtaos.taos_fetch_row.restype = ctypes.POINTER(ctypes.c_void_p)
    libtaos.taos_errstr.restype = ctypes.c_char_p
    libtaos.taos_subscribe.restype = ctypes.c_void_p
    libtaos.taos_consume.restype = ctypes.c_void_p
    libtaos.taos_fetch_lengths.restype = ctypes.c_void_p
    libtaos.taos_free_result.restype = None
    libtaos.taos_errno.restype = ctypes.c_int
    libtaos.taos_query.restype = ctypes.POINTER(ctypes.c_void_p)

    def __init__(self, config=None):
        '''
        Function to initialize the class
        @host     : str, hostname to connect
        @user     : str, username to connect to server
        @password : str, password to connect to server
        @db       : str, default db to use when log in
        @config   : str, config directory

        @rtype    : None
        '''
        if config is None:
            self._config = ctypes.c_char_p(None)
        else:
            try:
                self._config = ctypes.c_char_p(config.encode('utf-8'))
            except AttributeError:
                raise AttributeError("config is expected as a str")

369
        if config is not None:
370 371 372 373 374 375 376 377 378 379
            CTaosInterface.libtaos.taos_options(3, self._config)

        CTaosInterface.libtaos.taos_init()

    @property
    def config(self):
        """ Get current config
        """
        return self._config

380 381 382 383 384 385 386
    def connect(
            self,
            host=None,
            user="root",
            password="taosdata",
            db=None,
            port=0):
387 388 389 390 391 392 393 394
        '''
        Function to connect to server

        @rtype: c_void_p, TDengine handle
        '''
        # host
        try:
            _host = ctypes.c_char_p(host.encode(
395
                "utf-8")) if host is not None else ctypes.c_char_p(None)
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
        except AttributeError:
            raise AttributeError("host is expected as a str")

        # user
        try:
            _user = ctypes.c_char_p(user.encode("utf-8"))
        except AttributeError:
            raise AttributeError("user is expected as a str")

        # password
        try:
            _password = ctypes.c_char_p(password.encode("utf-8"))
        except AttributeError:
            raise AttributeError("password is expected as a str")

        # db
        try:
            _db = ctypes.c_char_p(
414
                db.encode("utf-8")) if db is not None else ctypes.c_char_p(None)
415 416 417 418 419 420 421 422 423 424 425 426
        except AttributeError:
            raise AttributeError("db is expected as a str")

        # port
        try:
            _port = ctypes.c_int(port)
        except TypeError:
            raise TypeError("port is expected as an int")

        connection = ctypes.c_void_p(CTaosInterface.libtaos.taos_connect(
            _host, _user, _password, _db, _port))

427
        if connection.value is None:
428 429 430
            print('connect to TDengine failed')
            raise ConnectionError("connect to TDengine failed")
            # sys.exit(1)
431
        # else:
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
        #    print('connect to TDengine success')

        return connection

    @staticmethod
    def close(connection):
        '''Close the TDengine handle
        '''
        CTaosInterface.libtaos.taos_close(connection)
        #print('connection is closed')

    @staticmethod
    def query(connection, sql):
        '''Run SQL

        @sql: str, sql string to run

        @rtype: 0 on success and -1 on failure
        '''
        try:
452 453
            return CTaosInterface.libtaos.taos_query(
                connection, ctypes.c_char_p(sql.encode('utf-8')))
454 455 456 457 458 459 460 461 462 463 464 465 466 467
        except AttributeError:
            raise AttributeError("sql is expected as a string")
        # finally:
        #     CTaosInterface.libtaos.close(connection)

    @staticmethod
    def affectedRows(result):
        """The affected rows after runing query
        """
        return CTaosInterface.libtaos.taos_affected_rows(result)

    @staticmethod
    def subscribe(connection, restart, topic, sql, interval):
        """Create a subscription
468
         @restart boolean,
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
         @sql string, sql statement for data query, must be a 'select' statement.
         @topic string, name of this subscription
        """
        return ctypes.c_void_p(CTaosInterface.libtaos.taos_subscribe(
            connection,
            1 if restart else 0,
            ctypes.c_char_p(topic.encode('utf-8')),
            ctypes.c_char_p(sql.encode('utf-8')),
            None,
            None,
            interval))

    @staticmethod
    def consume(sub):
        """Consume data of a subscription
        """
        result = ctypes.c_void_p(CTaosInterface.libtaos.taos_consume(sub))
        fields = []
        pfields = CTaosInterface.fetchFields(result)
        for i in range(CTaosInterface.libtaos.taos_num_fields(result)):
            fields.append({'name': pfields[i].name.decode('utf-8'),
                           'bytes': pfields[i].bytes,
                           'type': ord(pfields[i].type)})
        return result, fields

    @staticmethod
    def unsubscribe(sub, keepProgress):
        """Cancel a subscription
        """
        CTaosInterface.libtaos.taos_unsubscribe(sub, 1 if keepProgress else 0)

    @staticmethod
    def useResult(result):
        '''Use result after calling self.query
        '''
        fields = []
        pfields = CTaosInterface.fetchFields(result)
        for i in range(CTaosInterface.fieldsCount(result)):
            fields.append({'name': pfields[i].name.decode('utf-8'),
                           'bytes': pfields[i].bytes,
                           'type': ord(pfields[i].type)})

        return fields

    @staticmethod
    def fetchBlock(result, fields):
        pblock = ctypes.c_void_p(0)
        num_of_rows = CTaosInterface.libtaos.taos_fetch_block(
            result, ctypes.byref(pblock))
        if num_of_rows == 0:
            return None, 0
520 521
        isMicro = (CTaosInterface.libtaos.taos_result_precision(
            result) == FieldType.C_TIMESTAMP_MICRO)
522 523
        blocks = [None] * len(fields)
        fieldL = CTaosInterface.libtaos.taos_fetch_lengths(result)
524 525 526 527 528
        fieldLen = [
            ele for ele in ctypes.cast(
                fieldL, ctypes.POINTER(
                    ctypes.c_int))[
                :len(fields)]]
529 530 531 532
        for i in range(len(fields)):
            data = ctypes.cast(pblock, ctypes.POINTER(ctypes.c_void_p))[i]
            if fields[i]['type'] not in _CONVERT_FUNC_BLOCK:
                raise DatabaseError("Invalid data type returned from database")
533 534
            blocks[i] = _CONVERT_FUNC_BLOCK[fields[i]['type']](
                data, num_of_rows, fieldLen[i], isMicro)
535 536

        return blocks, abs(num_of_rows)
537

538 539 540
    @staticmethod
    def fetchRow(result, fields):
        pblock = ctypes.c_void_p(0)
541 542
        pblock = CTaosInterface.libtaos.taos_fetch_row(result)
        if pblock:
543
            num_of_rows = 1
544 545
            isMicro = (CTaosInterface.libtaos.taos_result_precision(
                result) == FieldType.C_TIMESTAMP_MICRO)
546 547
            blocks = [None] * len(fields)
            fieldL = CTaosInterface.libtaos.taos_fetch_lengths(result)
548 549 550 551 552
            fieldLen = [
                ele for ele in ctypes.cast(
                    fieldL, ctypes.POINTER(
                        ctypes.c_int))[
                    :len(fields)]]
553 554 555
            for i in range(len(fields)):
                data = ctypes.cast(pblock, ctypes.POINTER(ctypes.c_void_p))[i]
                if fields[i]['type'] not in _CONVERT_FUNC:
556 557
                    raise DatabaseError(
                        "Invalid data type returned from database")
558 559 560
                if data is None:
                    blocks[i] = [None]
                else:
561 562
                    blocks[i] = _CONVERT_FUNC[fields[i]['type']](
                        data, num_of_rows, fieldLen[i], isMicro)
563 564 565 566 567 568 569 570 571 572 573 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
        else:
            return None, 0
        return blocks, abs(num_of_rows)

    @staticmethod
    def freeResult(result):
        CTaosInterface.libtaos.taos_free_result(result)
        result.value = None

    @staticmethod
    def fieldsCount(result):
        return CTaosInterface.libtaos.taos_field_count(result)

    @staticmethod
    def fetchFields(result):
        return CTaosInterface.libtaos.taos_fetch_fields(result)

    # @staticmethod
    # def fetchRow(result, fields):
    #     l = []
    #     row = CTaosInterface.libtaos.taos_fetch_row(result)
    #     if not row:
    #         return None

    #     for i in range(len(fields)):
    #         l.append(CTaosInterface.getDataValue(
    #             row[i], fields[i]['type'], fields[i]['bytes']))

    #     return tuple(l)

    # @staticmethod
    # def getDataValue(data, dtype, byte):
    #     '''
    #     '''
    #     if not data:
    #         return None

    #     if (dtype == CTaosInterface.TSDB_DATA_TYPE_BOOL):
    #         return ctypes.cast(data,  ctypes.POINTER(ctypes.c_bool))[0]
    #     elif (dtype == CTaosInterface.TSDB_DATA_TYPE_TINYINT):
    #         return ctypes.cast(data,  ctypes.POINTER(ctypes.c_byte))[0]
    #     elif (dtype == CTaosInterface.TSDB_DATA_TYPE_SMALLINT):
    #         return ctypes.cast(data,  ctypes.POINTER(ctypes.c_short))[0]
    #     elif (dtype == CTaosInterface.TSDB_DATA_TYPE_INT):
    #         return ctypes.cast(data,  ctypes.POINTER(ctypes.c_int))[0]
    #     elif (dtype == CTaosInterface.TSDB_DATA_TYPE_BIGINT):
609
    #         return ctypes.cast(data,  ctypes.POINTER(ctypes.c_int64))[0]
610 611 612 613 614 615 616
    #     elif (dtype == CTaosInterface.TSDB_DATA_TYPE_FLOAT):
    #         return ctypes.cast(data,  ctypes.POINTER(ctypes.c_float))[0]
    #     elif (dtype == CTaosInterface.TSDB_DATA_TYPE_DOUBLE):
    #         return ctypes.cast(data,  ctypes.POINTER(ctypes.c_double))[0]
    #     elif (dtype == CTaosInterface.TSDB_DATA_TYPE_BINARY):
    #         return (ctypes.cast(data,  ctypes.POINTER(ctypes.c_char))[0:byte]).rstrip('\x00')
    #     elif (dtype == CTaosInterface.TSDB_DATA_TYPE_TIMESTAMP):
617
    #         return ctypes.cast(data,  ctypes.POINTER(ctypes.c_int64))[0]
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
    #     elif (dtype == CTaosInterface.TSDB_DATA_TYPE_NCHAR):
    #         return (ctypes.cast(data,  ctypes.c_char_p).value).rstrip('\x00')

    @staticmethod
    def errno(result):
        """Return the error number.
        """
        return CTaosInterface.libtaos.taos_errno(result)

    @staticmethod
    def errStr(result):
        """Return the error styring
        """
        return CTaosInterface.libtaos.taos_errstr(result).decode('utf-8')


if __name__ == '__main__':
    cinter = CTaosInterface()
    conn = cinter.connect()
    result = cinter.query(conn, 'show databases')

    print('Query Affected rows: {}'.format(cinter.affectedRows(result)))

    fields = CTaosInterface.useResult(result)

    data, num_of_rows = CTaosInterface.fetchBlock(result, fields)

    print(data)

    cinter.freeResult(result)
    cinter.close(conn)