cinterface.py 22.4 KB
Newer Older
H
hzcheng 已提交
1 2 3 4 5 6
import ctypes
from .constants import FieldType
from .error import *
import math
import datetime

7

H
hzcheng 已提交
8
def _convert_millisecond_to_datetime(milli):
9 10
    return datetime.datetime.fromtimestamp(milli / 1000.0)

H
hzcheng 已提交
11 12

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

H
hzcheng 已提交
15 16 17 18

def _crow_timestamp_to_python(data, num_of_rows, nbytes=None, micro=False):
    """Function to convert C bool row to python row
    """
weixin_48148422's avatar
weixin_48148422 已提交
19
    _timestamp_converter = _convert_millisecond_to_datetime
H
hzcheng 已提交
20
    if micro:
weixin_48148422's avatar
weixin_48148422 已提交
21
        _timestamp_converter = _convert_microsecond_to_datetime
H
hzcheng 已提交
22 23

    if num_of_rows > 0:
24 25
        return list(map(_timestamp_converter, ctypes.cast(
            data, ctypes.POINTER(ctypes.c_long))[:abs(num_of_rows)]))
H
hzcheng 已提交
26
    else:
27 28 29
        return list(map(_timestamp_converter, ctypes.cast(
            data, ctypes.POINTER(ctypes.c_long))[:abs(num_of_rows)]))

H
hzcheng 已提交
30 31 32 33 34

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:
35 36 37 38 39
        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)]]
H
hzcheng 已提交
40
    else:
41 42 43 44 45 46
        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)]]

H
hzcheng 已提交
47 48 49 50 51

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:
52 53
        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)]]
H
hzcheng 已提交
54
    else:
55 56 57
        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)]]

58

59 60 61 62 63
def _crow_tinyint_unsigned_to_python(
        data,
        num_of_rows,
        nbytes=None,
        micro=False):
64 65 66
    """Function to convert C tinyint row to python row
    """
    if num_of_rows > 0:
67 68 69 70 71
        return [
            None if ele == FieldType.C_TINYINT_UNSIGNED_NULL else ele for ele in ctypes.cast(
                data, ctypes.POINTER(
                    ctypes.c_byte))[
                :abs(num_of_rows)]]
72
    else:
73 74 75 76 77 78
        return [
            None if ele == FieldType.C_TINYINT_UNSIGNED_NULL else ele for ele in ctypes.cast(
                data, ctypes.POINTER(
                    ctypes.c_byte))[
                :abs(num_of_rows)]]

79

H
hzcheng 已提交
80 81 82 83
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:
84 85 86 87 88
        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)]]
H
hzcheng 已提交
89
    else:
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)]]
H
hzcheng 已提交
95

96 97 98

def _crow_smallint_unsigned_to_python(
        data, num_of_rows, nbytes=None, micro=False):
99 100 101
    """Function to convert C smallint row to python row
    """
    if num_of_rows > 0:
102 103 104 105 106
        return [
            None if ele == FieldType.C_SMALLINT_UNSIGNED_NULL else ele for ele in ctypes.cast(
                data, ctypes.POINTER(
                    ctypes.c_short))[
                :abs(num_of_rows)]]
107
    else:
108 109 110 111 112 113
        return [
            None if ele == FieldType.C_SMALLINT_UNSIGNED_NULL else ele for ele in ctypes.cast(
                data, ctypes.POINTER(
                    ctypes.c_short))[
                :abs(num_of_rows)]]

114

H
hzcheng 已提交
115 116 117 118
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:
119 120
        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)]]
H
hzcheng 已提交
121
    else:
122 123 124
        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)]]

H
hzcheng 已提交
125

126 127 128 129
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:
130 131 132 133 134
        return [
            None if ele == FieldType.C_INT_UNSIGNED_NULL else ele for ele in ctypes.cast(
                data, ctypes.POINTER(
                    ctypes.c_int))[
                :abs(num_of_rows)]]
135
    else:
136 137 138 139 140 141
        return [
            None if ele == FieldType.C_INT_UNSIGNED_NULL else ele for ele in ctypes.cast(
                data, ctypes.POINTER(
                    ctypes.c_int))[
                :abs(num_of_rows)]]

142

H
hzcheng 已提交
143 144 145 146
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:
147 148
        return [None if ele == FieldType.C_BIGINT_NULL else ele for ele in ctypes.cast(
            data, ctypes.POINTER(ctypes.c_long))[:abs(num_of_rows)]]
H
hzcheng 已提交
149
    else:
150 151 152
        return [None if ele == FieldType.C_BIGINT_NULL else ele for ele in ctypes.cast(
            data, ctypes.POINTER(ctypes.c_long))[:abs(num_of_rows)]]

H
hzcheng 已提交
153

154 155 156 157 158
def _crow_bigint_unsigned_to_python(
        data,
        num_of_rows,
        nbytes=None,
        micro=False):
159 160 161
    """Function to convert C bigint row to python row
    """
    if num_of_rows > 0:
162 163 164 165 166
        return [
            None if ele == FieldType.C_BIGINT_UNSIGNED_NULL else ele for ele in ctypes.cast(
                data, ctypes.POINTER(
                    ctypes.c_long))[
                :abs(num_of_rows)]]
167
    else:
168 169 170 171 172 173
        return [
            None if ele == FieldType.C_BIGINT_UNSIGNED_NULL else ele for ele in ctypes.cast(
                data, ctypes.POINTER(
                    ctypes.c_long))[
                :abs(num_of_rows)]]

174

H
hzcheng 已提交
175 176 177 178
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:
179 180
        return [None if math.isnan(ele) else ele for ele in ctypes.cast(
            data, ctypes.POINTER(ctypes.c_float))[:abs(num_of_rows)]]
H
hzcheng 已提交
181
    else:
182 183 184
        return [None if math.isnan(ele) else ele for ele in ctypes.cast(
            data, ctypes.POINTER(ctypes.c_float))[:abs(num_of_rows)]]

H
hzcheng 已提交
185 186 187 188 189

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:
190 191
        return [None if math.isnan(ele) else ele for ele in ctypes.cast(
            data, ctypes.POINTER(ctypes.c_double))[:abs(num_of_rows)]]
H
hzcheng 已提交
192
    else:
193 194 195
        return [None if math.isnan(ele) else ele for ele in ctypes.cast(
            data, ctypes.POINTER(ctypes.c_double))[:abs(num_of_rows)]]

H
hzcheng 已提交
196 197 198 199

def _crow_binary_to_python(data, num_of_rows, nbytes=None, micro=False):
    """Function to convert C binary row to python row
    """
200
    assert(nbytes is not None)
H
hzcheng 已提交
201
    if num_of_rows > 0:
202 203
        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)]]
H
hzcheng 已提交
204
    else:
205 206 207
        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)]]

H
hzcheng 已提交
208 209 210 211 212

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)
213
    res = []
H
hzcheng 已提交
214 215 216
    for i in range(abs(num_of_rows)):
        try:
            if num_of_rows >= 0:
217
                tmpstr = ctypes.c_char_p(data)
218
                res.append(tmpstr.value.decode())
H
hzcheng 已提交
219
            else:
220 221
                res.append((ctypes.cast(data + nbytes * i,
                                        ctypes.POINTER(ctypes.c_wchar * (nbytes // 4))))[0].value)
H
hzcheng 已提交
222 223 224
        except ValueError:
            res.append(None)

225 226
    return res

227 228 229 230

def _crow_binary_to_python_block(data, num_of_rows, nbytes=None, micro=False):
    """Function to convert C binary row to python row
    """
231
    assert(nbytes is not None)
232
    res = []
233 234 235
    if num_of_rows > 0:
        for i in range(abs(num_of_rows)):
            try:
236 237 238 239 240 241 242
                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])
243 244 245 246 247
            except ValueError:
                res.append(None)
    else:
        for i in range(abs(num_of_rows)):
            try:
248 249 250 251 252 253 254
                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])
255 256 257 258
            except ValueError:
                res.append(None)
    return res

259

260 261 262 263
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)
264
    res = []
265 266 267
    if num_of_rows >= 0:
        for i in range(abs(num_of_rows)):
            try:
268 269
                tmpstr = ctypes.c_char_p(data + nbytes * i + 2)
                res.append(tmpstr.value.decode())
270 271 272 273 274
            except ValueError:
                res.append(None)
    else:
        for i in range(abs(num_of_rows)):
            try:
275 276
                res.append((ctypes.cast(data + nbytes * i + 2,
                                        ctypes.POINTER(ctypes.c_wchar * (nbytes // 4))))[0].value)
277 278
            except ValueError:
                res.append(None)
H
hzcheng 已提交
279 280
    return res

281

H
hzcheng 已提交
282 283
_CONVERT_FUNC = {
    FieldType.C_BOOL: _crow_bool_to_python,
284 285 286 287 288 289
    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,
H
hzcheng 已提交
290
    FieldType.C_BINARY: _crow_binary_to_python,
291 292 293 294 295 296
    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
H
hzcheng 已提交
297 298
}

299 300
_CONVERT_FUNC_BLOCK = {
    FieldType.C_BOOL: _crow_bool_to_python,
301 302 303 304 305 306
    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,
307
    FieldType.C_BINARY: _crow_binary_to_python_block,
308 309 310 311 312 313
    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
314 315
}

H
hzcheng 已提交
316
# Corresponding TAOS_FIELD structure in C
317 318


H
hzcheng 已提交
319
class TaosField(ctypes.Structure):
B
Bomin Zhang 已提交
320 321 322
    _fields_ = [('name', ctypes.c_char * 65),
                ('type', ctypes.c_char),
                ('bytes', ctypes.c_short)]
H
hzcheng 已提交
323 324

# C interface class
325 326


H
hzcheng 已提交
327 328 329 330 331 332 333
class CTaosInterface(object):

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

    libtaos.taos_fetch_fields.restype = ctypes.POINTER(TaosField)
    libtaos.taos_init.restype = None
    libtaos.taos_connect.restype = ctypes.c_void_p
334
    #libtaos.taos_use_result.restype = ctypes.c_void_p
H
hzcheng 已提交
335 336
    libtaos.taos_fetch_row.restype = ctypes.POINTER(ctypes.c_void_p)
    libtaos.taos_errstr.restype = ctypes.c_char_p
weixin_48148422's avatar
weixin_48148422 已提交
337 338
    libtaos.taos_subscribe.restype = ctypes.c_void_p
    libtaos.taos_consume.restype = ctypes.c_void_p
339
    libtaos.taos_fetch_lengths.restype = ctypes.c_void_p
340
    libtaos.taos_free_result.restype = None
T
Tao Liu 已提交
341
    libtaos.taos_errno.restype = ctypes.c_int
T
Tao Liu 已提交
342
    libtaos.taos_query.restype = ctypes.POINTER(ctypes.c_void_p)
H
hzcheng 已提交
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362

    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")

363
        if config is not None:
H
hzcheng 已提交
364 365 366 367 368 369 370 371 372 373
            CTaosInterface.libtaos.taos_options(3, self._config)

        CTaosInterface.libtaos.taos_init()

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

374 375 376 377 378 379 380
    def connect(
            self,
            host=None,
            user="root",
            password="taosdata",
            db=None,
            port=0):
H
hzcheng 已提交
381 382 383 384 385 386 387 388
        '''
        Function to connect to server

        @rtype: c_void_p, TDengine handle
        '''
        # host
        try:
            _host = ctypes.c_char_p(host.encode(
389
                "utf-8")) if host is not None else ctypes.c_char_p(None)
H
hzcheng 已提交
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
        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(
408
                db.encode("utf-8")) if db is not None else ctypes.c_char_p(None)
H
hzcheng 已提交
409 410 411 412 413 414 415 416 417 418 419 420
        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))

421
        if connection.value is None:
H
hzcheng 已提交
422
            print('connect to TDengine failed')
423
            raise ConnectionError("connect to TDengine failed")
H
hzcheng 已提交
424
            # sys.exit(1)
425
        # else:
426
        #    print('connect to TDengine success')
H
hzcheng 已提交
427 428 429 430 431 432 433 434

        return connection

    @staticmethod
    def close(connection):
        '''Close the TDengine handle
        '''
        CTaosInterface.libtaos.taos_close(connection)
435
        #print('connection is closed')
H
hzcheng 已提交
436 437 438 439 440 441 442 443 444 445

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

        @sql: str, sql string to run

        @rtype: 0 on success and -1 on failure
        '''
        try:
446 447
            return CTaosInterface.libtaos.taos_query(
                connection, ctypes.c_char_p(sql.encode('utf-8')))
H
hzcheng 已提交
448 449
        except AttributeError:
            raise AttributeError("sql is expected as a string")
H
Hongze Cheng 已提交
450 451
        # finally:
        #     CTaosInterface.libtaos.close(connection)
452

H
hzcheng 已提交
453
    @staticmethod
454
    def affectedRows(result):
H
hzcheng 已提交
455 456
        """The affected rows after runing query
        """
457
        return CTaosInterface.libtaos.taos_affected_rows(result)
H
hzcheng 已提交
458

weixin_48148422's avatar
weixin_48148422 已提交
459 460 461
    @staticmethod
    def subscribe(connection, restart, topic, sql, interval):
        """Create a subscription
462
         @restart boolean,
weixin_48148422's avatar
weixin_48148422 已提交
463 464 465 466 467 468 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
         @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)

H
hzcheng 已提交
494
    @staticmethod
495
    def useResult(result):
H
hzcheng 已提交
496 497 498 499
        '''Use result after calling self.query
        '''
        fields = []
        pfields = CTaosInterface.fetchFields(result)
500
        for i in range(CTaosInterface.fieldsCount(result)):
H
hzcheng 已提交
501 502 503 504
            fields.append({'name': pfields[i].name.decode('utf-8'),
                           'bytes': pfields[i].bytes,
                           'type': ord(pfields[i].type)})

505
        return fields
H
hzcheng 已提交
506 507 508

    @staticmethod
    def fetchBlock(result, fields):
509 510 511 512 513
        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
514 515
        isMicro = (CTaosInterface.libtaos.taos_result_precision(
            result) == FieldType.C_TIMESTAMP_MICRO)
516 517
        blocks = [None] * len(fields)
        fieldL = CTaosInterface.libtaos.taos_fetch_lengths(result)
518 519 520 521 522
        fieldLen = [
            ele for ele in ctypes.cast(
                fieldL, ctypes.POINTER(
                    ctypes.c_int))[
                :len(fields)]]
523 524 525 526
        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")
527 528
            blocks[i] = _CONVERT_FUNC_BLOCK[fields[i]['type']](
                data, num_of_rows, fieldLen[i], isMicro)
529 530

        return blocks, abs(num_of_rows)
531

532 533
    @staticmethod
    def fetchRow(result, fields):
H
hzcheng 已提交
534
        pblock = ctypes.c_void_p(0)
535 536
        pblock = CTaosInterface.libtaos.taos_fetch_row(result)
        if pblock:
L
liuyq-617 已提交
537
            num_of_rows = 1
538 539
            isMicro = (CTaosInterface.libtaos.taos_result_precision(
                result) == FieldType.C_TIMESTAMP_MICRO)
L
liuyq-617 已提交
540 541
            blocks = [None] * len(fields)
            fieldL = CTaosInterface.libtaos.taos_fetch_lengths(result)
542 543 544 545 546
            fieldLen = [
                ele for ele in ctypes.cast(
                    fieldL, ctypes.POINTER(
                        ctypes.c_int))[
                    :len(fields)]]
L
liuyq-617 已提交
547 548 549
            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:
550 551
                    raise DatabaseError(
                        "Invalid data type returned from database")
L
liuyq-617 已提交
552 553 554
                if data is None:
                    blocks[i] = [None]
                else:
555 556
                    blocks[i] = _CONVERT_FUNC[fields[i]['type']](
                        data, num_of_rows, fieldLen[i], isMicro)
L
liuyq-617 已提交
557
        else:
H
hzcheng 已提交
558 559
            return None, 0
        return blocks, abs(num_of_rows)
560

H
hzcheng 已提交
561 562 563 564 565 566
    @staticmethod
    def freeResult(result):
        CTaosInterface.libtaos.taos_free_result(result)
        result.value = None

    @staticmethod
567 568
    def fieldsCount(result):
        return CTaosInterface.libtaos.taos_field_count(result)
H
hzcheng 已提交
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 609 610 611 612 613 614 615

    @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):
    #         return ctypes.cast(data,  ctypes.POINTER(ctypes.c_long))[0]
    #     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):
    #         return ctypes.cast(data,  ctypes.POINTER(ctypes.c_long))[0]
    #     elif (dtype == CTaosInterface.TSDB_DATA_TYPE_NCHAR):
    #         return (ctypes.cast(data,  ctypes.c_char_p).value).rstrip('\x00')

    @staticmethod
616
    def errno(result):
H
hzcheng 已提交
617 618
        """Return the error number.
        """
619
        return CTaosInterface.libtaos.taos_errno(result)
H
hzcheng 已提交
620 621

    @staticmethod
622
    def errStr(result):
H
hzcheng 已提交
623 624
        """Return the error styring
        """
625
        return CTaosInterface.libtaos.taos_errstr(result).decode('utf-8')
weixin_48148422's avatar
weixin_48148422 已提交
626 627 628 629 630


if __name__ == '__main__':
    cinter = CTaosInterface()
    conn = cinter.connect()
631
    result = cinter.query(conn, 'show databases')
weixin_48148422's avatar
weixin_48148422 已提交
632

633
    print('Query Affected rows: {}'.format(cinter.affectedRows(result)))
weixin_48148422's avatar
weixin_48148422 已提交
634

635
    fields = CTaosInterface.useResult(result)
weixin_48148422's avatar
weixin_48148422 已提交
636

637
    data, num_of_rows = CTaosInterface.fetchBlock(result, fields)
weixin_48148422's avatar
weixin_48148422 已提交
638 639 640

    print(data)

T
Tao Liu 已提交
641
    cinter.freeResult(result)
642
    cinter.close(conn)