cinterface.py 25.9 KB
Newer Older
1 2
# encoding:UTF-8

H
hzcheng 已提交
3
import ctypes
4
import platform
5
import inspect
6
from ctypes import *
7

8 9 10 11 12 13 14 15
try:
    from typing import Any
except:
    pass

from .error import *
from .bind import *
from .field import *
16
from .schemaless import *
17

18
_UNSUPPORTED = {}
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

# stream callback
stream_callback_type = CFUNCTYPE(None, c_void_p, c_void_p, c_void_p)
stream_callback2_type = CFUNCTYPE(None, c_void_p)

# C interface class
class TaosOption:
    Locale = (0,)
    Charset = (1,)
    Timezone = (2,)
    ConfigDir = (3,)
    ShellActivityTimer = (4,)
    MaxOptions = (5,)


def _load_taos_linux():
    return ctypes.CDLL("libtaos.so")


def _load_taos_darwin():
    return ctypes.CDLL("libtaos.dylib")


def _load_taos_windows():
    return ctypes.windll.LoadLibrary("taos")
H
hzcheng 已提交
44

45

46 47 48 49 50 51
def _load_taos():
    load_func = {
        "Linux": _load_taos_linux,
        "Darwin": _load_taos_darwin,
        "Windows": _load_taos_windows,
    }
52 53 54
    pf = platform.system()
    if load_func[pf] is None:
        raise InterfaceError("unsupported platform: %s" % pf)
55
    try:
56 57 58
        return load_func[pf]()
    except Exception as err:
        raise InterfaceError("unable to load taos C library: %s" % err)
59

H
hzcheng 已提交
60

61
_libtaos = _load_taos()
62

63 64 65 66 67 68 69 70 71 72
_libtaos.taos_fetch_fields.restype = ctypes.POINTER(TaosField)
_libtaos.taos_init.restype = None
_libtaos.taos_connect.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.POINTER(ctypes.c_int)
_libtaos.taos_free_result.restype = None
_libtaos.taos_query.restype = ctypes.POINTER(ctypes.c_void_p)
73

74 75 76 77 78 79
try:
    _libtaos.taos_stmt_errstr.restype = c_char_p
except AttributeError:
    None
finally:
    None
H
hzcheng 已提交
80

81

82
_libtaos.taos_options.restype = None
83

84 85 86 87 88 89 90 91

def taos_options(option, *args):
    # type: (TaosOption, Any) -> None
    _libtaos.taos_options(option, *args)


def taos_init():
    # type: () -> None
H
hzcheng 已提交
92
    """
93 94 95 96 97 98
    C: taos_init
    """
    _libtaos.taos_init()


_libtaos.taos_cleanup.restype = None
H
hzcheng 已提交
99

100

101 102 103 104
def taos_cleanup():
    # type: () -> None
    """Cleanup workspace."""
    _libtaos.taos_cleanup()
H
hzcheng 已提交
105

106 107 108 109 110 111

_libtaos.taos_get_client_info.restype = c_char_p


def taos_get_client_info():
    # type: () -> str
112
    """Get client version info."""
113
    return _libtaos.taos_get_client_info().decode("utf-8")
114 115 116 117 118 119 120 121


_libtaos.taos_get_server_info.restype = c_char_p
_libtaos.taos_get_server_info.argtypes = (c_void_p,)


def taos_get_server_info(connection):
    # type: (c_void_p) -> str
122
    """Get server version as string."""
123
    return _libtaos.taos_get_server_info(connection).decode("utf-8")
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142


_libtaos.taos_close.restype = None
_libtaos.taos_close.argtypes = (c_void_p,)


def taos_close(connection):
    # type: (c_void_p) -> None
    """Close the TAOS* connection"""
    _libtaos.taos_close(connection)


_libtaos.taos_connect.restype = c_void_p
_libtaos.taos_connect.argtypes = c_char_p, c_char_p, c_char_p, c_char_p, c_uint16


def taos_connect(host=None, user="root", password="taosdata", db=None, port=0):
    # type: (None|str, str, str, None|str, int) -> c_void_p
    """Create TDengine database connection.
143

144 145 146
    - host: server hostname/FQDN
    - user: user name
    - password: user password
147 148
    - db: database name (optional)
    - port: server port
H
hzcheng 已提交
149

150
    @rtype: c_void_p, TDengine handle
H
hzcheng 已提交
151
    """
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
    # host
    try:
        _host = c_char_p(host.encode("utf-8")) if host is not None else None
    except AttributeError:
        raise AttributeError("host is expected as a str")

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

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

    # db
    try:
        _db = c_char_p(db.encode("utf-8")) if db is not None else None
    except AttributeError:
        raise AttributeError("db is expected as a str")
175

176 177 178 179 180
    # port
    try:
        _port = c_uint16(port)
    except TypeError:
        raise TypeError("port is expected as an uint16")
181

182 183 184 185 186 187
    connection = cast(_libtaos.taos_connect(_host, _user, _password, _db, _port), c_void_p)

    if connection.value is None:
        raise ConnectionError("connect to TDengine failed")
    return connection

188

S
Shengliang Guan 已提交
189 190
_libtaos.taos_connect_auth.restype = c_void_p
_libtaos.taos_connect_auth.argtypes = c_char_p, c_char_p, c_char_p, c_char_p, c_uint16
191 192 193 194 195 196 197

_libtaos.taos_connect_auth.restype = c_void_p
_libtaos.taos_connect_auth.argtypes = c_char_p, c_char_p, c_char_p, c_char_p, c_uint16


def taos_connect_auth(host=None, user="root", auth="", db=None, port=0):
    # type: (None|str, str, str, None|str, int) -> c_void_p
198
    """Connect server with auth token.
199

200 201
    - host: server hostname/FQDN
    - user: user name
202 203 204
    - auth: base64 encoded auth token
    - db: database name (optional)
    - port: server port
205

206
    @rtype: c_void_p, TDengine handle
H
hzcheng 已提交
207
    """
208 209 210 211 212
    # host
    try:
        _host = c_char_p(host.encode("utf-8")) if host is not None else None
    except AttributeError:
        raise AttributeError("host is expected as a str")
H
hzcheng 已提交
213

214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
    # user
    try:
        _user = c_char_p(user.encode("utf-8"))
    except AttributeError:
        raise AttributeError("user is expected as a str")

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

    # db
    try:
        _db = c_char_p(db.encode("utf-8")) if db is not None else None
    except AttributeError:
        raise AttributeError("db is expected as a str")

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

    connection = c_void_p(_libtaos.taos_connect_auth(_host, _user, _auth, _db, _port))

    if connection.value is None:
        raise ConnectionError("connect to TDengine failed")
    return connection

244

245 246 247 248 249 250 251 252 253 254 255
_libtaos.taos_query.restype = c_void_p
_libtaos.taos_query.argtypes = c_void_p, c_char_p


def taos_query(connection, sql):
    # type: (c_void_p, str) -> c_void_p
    """Run SQL

    - sql: str, sql string to run

    @return: TAOS_RES*, result pointer
256

257
    """
258 259 260 261 262 263 264 265 266 267 268
    try:
        ptr = c_char_p(sql.encode("utf-8"))
        res = c_void_p(_libtaos.taos_query(connection, ptr))
        errno = taos_errno(res)
        if errno != 0:
            errstr = taos_errstr(res)
            taos_free_result(res)
            raise ProgrammingError(errstr, errno)
        return res
    except AttributeError:
        raise AttributeError("sql is expected as a string")
269

270

271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
async_query_callback_type = CFUNCTYPE(None, c_void_p, c_void_p, c_int)
_libtaos.taos_query_a.restype = None
_libtaos.taos_query_a.argtypes = c_void_p, c_char_p, async_query_callback_type, c_void_p


def taos_query_a(connection, sql, callback, param):
    # type: (c_void_p, str, async_query_callback_type, c_void_p) -> c_void_p
    _libtaos.taos_query_a(connection, c_char_p(sql.encode("utf-8")), async_query_callback_type(callback), param)


async_fetch_rows_callback_type = CFUNCTYPE(None, c_void_p, c_void_p, c_int)
_libtaos.taos_fetch_rows_a.restype = None
_libtaos.taos_fetch_rows_a.argtypes = c_void_p, async_fetch_rows_callback_type, c_void_p


def taos_fetch_rows_a(result, callback, param):
    # type: (c_void_p, async_fetch_rows_callback_type, c_void_p) -> c_void_p
    _libtaos.taos_fetch_rows_a(result, async_fetch_rows_callback_type(callback), param)


def taos_affected_rows(result):
    # type: (c_void_p) -> c_int
    """The affected rows after runing query"""
    return _libtaos.taos_affected_rows(result)

296

297 298 299 300 301 302 303 304 305 306 307
subscribe_callback_type = CFUNCTYPE(None, c_void_p, c_void_p, c_void_p, c_int)
_libtaos.taos_subscribe.restype = c_void_p
# _libtaos.taos_subscribe.argtypes = c_void_p, c_int, c_char_p, c_char_p, subscribe_callback_type, c_void_p, c_int


def taos_subscribe(connection, restart, topic, sql, interval, callback=None, param=None):
    # type: (c_void_p, bool, str, str, c_int, subscribe_callback_type, c_void_p | None) -> c_void_p
    """Create a subscription
    @restart boolean,
    @sql string, sql statement for data query, must be a 'select' statement.
    @topic string, name of this subscription
H
hzcheng 已提交
308
    """
309 310 311 312 313 314 315 316
    if callback != None:
        callback = subscribe_callback_type(callback)
    return c_void_p(
        _libtaos.taos_subscribe(
            connection,
            1 if restart else 0,
            c_char_p(topic.encode("utf-8")),
            c_char_p(sql.encode("utf-8")),
317 318
            callback,
            c_void_p(param),
319 320 321 322 323 324
            interval,
        )
    )


_libtaos.taos_consume.restype = c_void_p
325
_libtaos.taos_consume.argstype = (c_void_p,)
326 327 328 329 330 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 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426


def taos_consume(sub):
    """Consume data of a subscription"""
    return c_void_p(_libtaos.taos_consume(sub))


_libtaos.taos_unsubscribe.restype = None
_libtaos.taos_unsubscribe.argstype = c_void_p, c_int


def taos_unsubscribe(sub, keep_progress):
    """Cancel a subscription"""
    _libtaos.taos_unsubscribe(sub, 1 if keep_progress else 0)


def taos_use_result(result):
    """Use result after calling self.query, it's just for 1.6."""
    fields = []
    pfields = taos_fetch_fields_raw(result)
    for i in range(taos_field_count(result)):
        fields.append(
            {
                "name": pfields[i].name,
                "bytes": pfields[i].bytes,
                "type": pfields[i].type,
            }
        )

    return fields


_libtaos.taos_fetch_block.restype = c_int
_libtaos.taos_fetch_block.argtypes = c_void_p, c_void_p


def taos_fetch_block_raw(result):
    pblock = ctypes.c_void_p(0)
    num_of_rows = _libtaos.taos_fetch_block(result, ctypes.byref(pblock))
    if num_of_rows == 0:
        return None, 0
    return pblock, abs(num_of_rows)


def taos_fetch_block(result, fields=None, field_count=None):
    pblock = ctypes.c_void_p(0)
    num_of_rows = _libtaos.taos_fetch_block(result, ctypes.byref(pblock))
    if num_of_rows == 0:
        return None, 0
    precision = taos_result_precision(result)
    if fields == None:
        fields = taos_fetch_fields(result)
    if field_count == None:
        field_count = taos_field_count(result)
    blocks = [None] * field_count
    fieldLen = taos_fetch_lengths(result, field_count)
    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:
            raise DatabaseError("Invalid data type returned from database")
        blocks[i] = CONVERT_FUNC_BLOCK[fields[i]["type"]](data, num_of_rows, fieldLen[i], precision)

    return blocks, abs(num_of_rows)


_libtaos.taos_fetch_row.restype = c_void_p
_libtaos.taos_fetch_row.argtypes = (c_void_p,)


def taos_fetch_row_raw(result):
    # type: (c_void_p) -> c_void_p
    row = c_void_p(_libtaos.taos_fetch_row(result))
    if row:
        return row
    return None


def taos_fetch_row(result, fields):
    # type: (c_void_p, Array[TaosField]) -> tuple(c_void_p, int)
    pblock = ctypes.c_void_p(0)
    pblock = taos_fetch_row_raw(result)
    if pblock:
        num_of_rows = 1
        precision = taos_result_precision(result)
        field_count = taos_field_count(result)
        blocks = [None] * field_count
        field_lens = taos_fetch_lengths(result, field_count)
        for i in range(field_count):
            data = ctypes.cast(pblock, ctypes.POINTER(ctypes.c_void_p))[i]
            if fields[i].type not in CONVERT_FUNC:
                raise DatabaseError("Invalid data type returned from database")
            if data is None:
                blocks[i] = [None]
            else:
                blocks[i] = CONVERT_FUNC[fields[i].type](data, num_of_rows, field_lens[i], precision)
    else:
        return None, 0
    return blocks, abs(num_of_rows)


_libtaos.taos_free_result.argtypes = (c_void_p,)
427

H
hzcheng 已提交
428

429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 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 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
def taos_free_result(result):
    # type: (c_void_p) -> None
    if result != None:
        _libtaos.taos_free_result(result)


_libtaos.taos_field_count.restype = c_int
_libtaos.taos_field_count.argstype = (c_void_p,)


def taos_field_count(result):
    # type: (c_void_p) -> int
    return _libtaos.taos_field_count(result)


def taos_num_fields(result):
    # type: (c_void_p) -> int
    return _libtaos.taos_num_fields(result)


_libtaos.taos_fetch_fields.restype = c_void_p
_libtaos.taos_fetch_fields.argstype = (c_void_p,)


def taos_fetch_fields_raw(result):
    # type: (c_void_p) -> c_void_p
    return c_void_p(_libtaos.taos_fetch_fields(result))


def taos_fetch_fields(result):
    # type: (c_void_p) -> TaosFields
    fields = taos_fetch_fields_raw(result)
    count = taos_field_count(result)
    return TaosFields(fields, count)


def taos_fetch_lengths(result, field_count=None):
    # type: (c_void_p, int) -> Array[int]
    """Make sure to call taos_fetch_row or taos_fetch_block before fetch_lengths"""
    lens = _libtaos.taos_fetch_lengths(result)
    if field_count == None:
        field_count = taos_field_count(result)
    if not lens:
        raise OperationalError("field length empty, use taos_fetch_row/block before it")
    return lens[:field_count]


def taos_result_precision(result):
    # type: (c_void_p) -> c_int
    return _libtaos.taos_result_precision(result)


_libtaos.taos_errno.restype = c_int
_libtaos.taos_errno.argstype = (c_void_p,)


def taos_errno(result):
    # type: (ctypes.c_void_p) -> c_int
    """Return the error number."""
    return _libtaos.taos_errno(result)


_libtaos.taos_errstr.restype = c_char_p
_libtaos.taos_errstr.argstype = (c_void_p,)


def taos_errstr(result=c_void_p(None)):
    # type: (ctypes.c_void_p) -> str
    """Return the error styring"""
    return _libtaos.taos_errstr(result).decode("utf-8")


_libtaos.taos_stop_query.restype = None
_libtaos.taos_stop_query.argstype = (c_void_p,)


def taos_stop_query(result):
    # type: (ctypes.c_void_p) -> None
    """Stop current query"""
    return _libtaos.taos_stop_query(result)


511 512 513 514 515
try:
    _libtaos.taos_load_table_info.restype = c_int
    _libtaos.taos_load_table_info.argstype = (c_void_p, c_char_p)
except Exception as err:
    _UNSUPPORTED["taos_open_stream"] = err
516 517 518 519 520


def taos_load_table_info(connection, tables):
    # type: (ctypes.c_void_p, str) -> None
    """Stop current query"""
521
    _check_if_supported()
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
    errno = _libtaos.taos_load_table_info(connection, c_char_p(tables.encode("utf-8")))
    if errno != 0:
        msg = taos_errstr()
        raise OperationalError(msg, errno)


_libtaos.taos_validate_sql.restype = c_int
_libtaos.taos_validate_sql.argstype = (c_void_p, c_char_p)


def taos_validate_sql(connection, sql):
    # type: (ctypes.c_void_p, str) -> None | str
    """Get taosd server info"""
    errno = _libtaos.taos_validate_sql(connection, ctypes.c_char_p(sql.encode("utf-8")))
    if errno != 0:
        msg = taos_errstr()
        return msg
    return None


_libtaos.taos_print_row.restype = c_int
_libtaos.taos_print_row.argstype = (c_char_p, c_void_p, c_void_p, c_int)


def taos_print_row(row, fields, num_fields, buffer_size=4096):
    # type: (ctypes.c_void_p, ctypes.c_void_p | TaosFields, int, int) -> str
    """Print an row to string"""
    p = ctypes.create_string_buffer(buffer_size)
    if isinstance(fields, TaosFields):
        _libtaos.taos_print_row(p, row, fields.as_ptr(), num_fields)
    else:
        _libtaos.taos_print_row(p, row, fields, num_fields)
    if p:
        return p.value.decode("utf-8")
    raise OperationalError("taos_print_row failed")


_libtaos.taos_select_db.restype = c_int
_libtaos.taos_select_db.argstype = (c_void_p, c_char_p)


def taos_select_db(connection, db):
    # type: (ctypes.c_void_p, str) -> None
    """Select database, eq to sql: use <db>"""
    res = _libtaos.taos_select_db(connection, ctypes.c_char_p(db.encode("utf-8")))
    if res != 0:
        raise DatabaseError("select database error", res)


try:
    _libtaos.taos_open_stream.restype = c_void_p
    _libtaos.taos_open_stream.argstype = c_void_p, c_char_p, stream_callback_type, c_int64, c_void_p, Any
574 575
except Exception as err:
    _UNSUPPORTED["taos_open_stream"] = err
576 577 578 579


def taos_open_stream(connection, sql, callback, stime=0, param=None, callback2=None):
    # type: (ctypes.c_void_p, str, stream_callback_type, c_int64, c_void_p, c_void_p) -> ctypes.pointer
580
    _check_if_supported()
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
    if callback2 != None:
        callback2 = stream_callback2_type(callback2)
    """Open an stream"""
    return c_void_p(
        _libtaos.taos_open_stream(
            connection, ctypes.c_char_p(sql.encode("utf-8")), stream_callback_type(callback), stime, param, callback2
        )
    )


_libtaos.taos_close_stream.restype = None
_libtaos.taos_close_stream.argstype = (c_void_p,)


def taos_close_stream(stream):
    # type: (c_void_p) -> None
    """Open an stream"""
    return _libtaos.taos_close_stream(stream)


_libtaos.taos_stmt_init.restype = c_void_p
_libtaos.taos_stmt_init.argstype = (c_void_p,)


def taos_stmt_init(connection):
    # type: (c_void_p) -> (c_void_p)
    """Create a statement query
    @param(connection): c_void_p TAOS*
    @rtype: c_void_p, *TAOS_STMT
    """
    return c_void_p(_libtaos.taos_stmt_init(connection))

613

614 615 616 617 618 619 620 621
_libtaos.taos_stmt_prepare.restype = c_int
_libtaos.taos_stmt_prepare.argstype = (c_void_p, c_char_p, c_int)


def taos_stmt_prepare(stmt, sql):
    # type: (ctypes.c_void_p, str) -> None
    """Prepare a statement query
    @stmt: c_void_p TAOS_STMT*
622
    """
623 624 625 626 627
    buffer = sql.encode("utf-8")
    res = _libtaos.taos_stmt_prepare(stmt, ctypes.c_char_p(buffer), len(buffer))
    if res != 0:
        raise StatementError(msg=taos_stmt_errstr(stmt), errno=res)

628

629 630
_libtaos.taos_stmt_close.restype = c_int
_libtaos.taos_stmt_close.argstype = (c_void_p,)
631

632

633 634 635 636
def taos_stmt_close(stmt):
    # type: (ctypes.c_void_p) -> None
    """Close a statement query
    @stmt: c_void_p TAOS_STMT*
H
hzcheng 已提交
637
    """
638 639 640 641
    res = _libtaos.taos_stmt_close(stmt)
    if res != 0:
        raise StatementError(msg=taos_stmt_errstr(stmt), errno=res)

642

643 644 645
try:
    _libtaos.taos_stmt_errstr.restype = c_char_p
    _libtaos.taos_stmt_errstr.argstype = (c_void_p,)
646 647
except Exception as err:
    _UNSUPPORTED["taos_stmt_set_tbname"] = err
H
hzcheng 已提交
648

649 650 651 652 653

def taos_stmt_errstr(stmt):
    # type: (ctypes.c_void_p) -> str
    """Get error message from stetement query
    @stmt: c_void_p TAOS_STMT*
654
    """
655
    _check_if_supported()
656 657 658 659
    err = c_char_p(_libtaos.taos_stmt_errstr(stmt))
    if err:
        return err.value.decode("utf-8")

660

661 662 663
try:
    _libtaos.taos_stmt_set_tbname.restype = c_int
    _libtaos.taos_stmt_set_tbname.argstype = (c_void_p, c_char_p)
664 665
except Exception as err:
    _UNSUPPORTED["taos_stmt_set_tbname"] = err
666

667 668 669 670 671

def taos_stmt_set_tbname(stmt, name):
    # type: (ctypes.c_void_p, str) -> None
    """Set table name of a statement query if exists.
    @stmt: c_void_p TAOS_STMT*
H
hzcheng 已提交
672
    """
673
    _check_if_supported()
674 675 676 677
    res = _libtaos.taos_stmt_set_tbname(stmt, c_char_p(name.encode("utf-8")))
    if res != 0:
        raise StatementError(msg=taos_stmt_errstr(stmt), errno=res)

678

679 680 681
try:
    _libtaos.taos_stmt_set_tbname_tags.restype = c_int
    _libtaos.taos_stmt_set_tbname_tags.argstype = (c_void_p, c_char_p, c_void_p)
682 683
except Exception as err:
    _UNSUPPORTED["taos_stmt_set_tbname_tags"] = err
684 685 686 687 688 689 690


def taos_stmt_set_tbname_tags(stmt, name, tags):
    # type: (c_void_p, str, c_void_p) -> None
    """Set table name with tags bind params.
    @stmt: c_void_p TAOS_STMT*
    """
691
    _check_if_supported()
692 693 694 695
    res = _libtaos.taos_stmt_set_tbname_tags(stmt, ctypes.c_char_p(name.encode("utf-8")), tags)

    if res != 0:
        raise StatementError(msg=taos_stmt_errstr(stmt), errno=res)
696

697

698 699 700 701 702 703 704 705
_libtaos.taos_stmt_is_insert.restype = c_int
_libtaos.taos_stmt_is_insert.argstype = (c_void_p, POINTER(c_int))


def taos_stmt_is_insert(stmt):
    # type: (ctypes.c_void_p) -> bool
    """Set table name with tags bind params.
    @stmt: c_void_p TAOS_STMT*
H
hzcheng 已提交
706
    """
707 708 709 710 711 712 713 714 715
    is_insert = ctypes.c_int()
    res = _libtaos.taos_stmt_is_insert(stmt, ctypes.byref(is_insert))
    if res != 0:
        raise StatementError(msg=taos_stmt_errstr(stmt), errno=res)
    return is_insert == 0


_libtaos.taos_stmt_num_params.restype = c_int
_libtaos.taos_stmt_num_params.argstype = (c_void_p, POINTER(c_int))
716

717

718 719 720 721
def taos_stmt_num_params(stmt):
    # type: (ctypes.c_void_p) -> int
    """Params number of the current statement query.
    @stmt: TAOS_STMT*
H
hzcheng 已提交
722
    """
723 724 725 726 727
    num_params = ctypes.c_int()
    res = _libtaos.taos_stmt_num_params(stmt, ctypes.byref(num_params))
    if res != 0:
        raise StatementError(msg=taos_stmt_errstr(stmt), errno=res)
    return num_params.value
728

729

730 731 732 733 734 735 736 737 738
_libtaos.taos_stmt_bind_param.restype = c_int
_libtaos.taos_stmt_bind_param.argstype = (c_void_p, c_void_p)


def taos_stmt_bind_param(stmt, bind):
    # type: (ctypes.c_void_p, Array[TaosBind]) -> None
    """Bind params in the statement query.
    @stmt: TAOS_STMT*
    @bind: TAOS_BIND*
H
hzcheng 已提交
739
    """
740 741 742 743 744 745
    # ptr = ctypes.cast(bind, POINTER(TaosBind))
    # ptr = pointer(bind)
    res = _libtaos.taos_stmt_bind_param(stmt, bind)
    if res != 0:
        raise StatementError(msg=taos_stmt_errstr(stmt), errno=res)

746

747 748 749
try:
    _libtaos.taos_stmt_bind_param_batch.restype = c_int
    _libtaos.taos_stmt_bind_param_batch.argstype = (c_void_p, c_void_p)
750 751
except Exception as err:
    _UNSUPPORTED["taos_stmt_bind_param_batch"] = err
752

753

754 755 756 757 758
def taos_stmt_bind_param_batch(stmt, bind):
    # type: (ctypes.c_void_p, Array[TaosMultiBind]) -> None
    """Bind params in the statement query.
    @stmt: TAOS_STMT*
    @bind: TAOS_BIND*
759
    """
760 761
    # ptr = ctypes.cast(bind, POINTER(TaosMultiBind))
    # ptr = pointer(bind)
762
    _check_if_supported()
763 764 765 766
    res = _libtaos.taos_stmt_bind_param_batch(stmt, bind)
    if res != 0:
        raise StatementError(msg=taos_stmt_errstr(stmt), errno=res)

767

768 769 770
try:
    _libtaos.taos_stmt_bind_single_param_batch.restype = c_int
    _libtaos.taos_stmt_bind_single_param_batch.argstype = (c_void_p, c_void_p, c_int)
771 772
except Exception as err:
    _UNSUPPORTED["taos_stmt_bind_single_param_batch"] = err
773 774 775 776 777 778 779 780


def taos_stmt_bind_single_param_batch(stmt, bind, col):
    # type: (ctypes.c_void_p, Array[TaosMultiBind], c_int) -> None
    """Bind params in the statement query.
    @stmt: TAOS_STMT*
    @bind: TAOS_MULTI_BIND*
    @col: column index
781
    """
782
    _check_if_supported()
783 784 785
    res = _libtaos.taos_stmt_bind_single_param_batch(stmt, bind, col)
    if res != 0:
        raise StatementError(msg=taos_stmt_errstr(stmt), errno=res)
H
hzcheng 已提交
786

787

788 789
_libtaos.taos_stmt_add_batch.restype = c_int
_libtaos.taos_stmt_add_batch.argstype = (c_void_p,)
790

791

792 793 794 795 796 797 798 799
def taos_stmt_add_batch(stmt):
    # type: (ctypes.c_void_p) -> None
    """Add current params into batch
    @stmt: TAOS_STMT*
    """
    res = _libtaos.taos_stmt_add_batch(stmt)
    if res != 0:
        raise StatementError(msg=taos_stmt_errstr(stmt), errno=res)
800 801


802 803
_libtaos.taos_stmt_execute.restype = c_int
_libtaos.taos_stmt_execute.argstype = (c_void_p,)
804 805


806 807 808 809 810 811 812 813
def taos_stmt_execute(stmt):
    # type: (ctypes.c_void_p) -> None
    """Execute a statement query
    @stmt: TAOS_STMT*
    """
    res = _libtaos.taos_stmt_execute(stmt)
    if res != 0:
        raise StatementError(msg=taos_stmt_errstr(stmt), errno=res)
814 815


816 817
_libtaos.taos_stmt_use_result.restype = c_void_p
_libtaos.taos_stmt_use_result.argstype = (c_void_p,)
818

H
hzcheng 已提交
819

820 821 822 823 824 825 826 827 828 829
def taos_stmt_use_result(stmt):
    # type: (ctypes.c_void_p) -> None
    """Get result of the statement.
    @stmt: TAOS_STMT*
    """
    result = c_void_p(_libtaos.taos_stmt_use_result(stmt))
    if result == None:
        raise StatementError(taos_stmt_errstr(stmt))
    return result

830

831
try:
832 833
    _libtaos.taos_schemaless_insert.restype = c_void_p
    _libtaos.taos_schemaless_insert.argstype = c_void_p, c_void_p, c_int, c_int, c_int
834 835 836
except Exception as err:
    _UNSUPPORTED["taos_schemaless_insert"] = err

H
hzcheng 已提交
837

838
def taos_schemaless_insert(connection, lines, protocol, precision):
839
    # type: (c_void_p, list[str] | tuple(str), SmlProtocol, SmlPrecision) -> int
840
    _check_if_supported()
841 842 843 844
    num_of_lines = len(lines)
    lines = (c_char_p(line.encode("utf-8")) for line in lines)
    lines_type = ctypes.c_char_p * num_of_lines
    p_lines = lines_type(*lines)
845 846
    res = c_void_p(_libtaos.taos_schemaless_insert(connection, p_lines, num_of_lines, protocol, precision))
    errno = taos_errno(res)
847
    affected_rows = taos_affected_rows(res)
848
    if errno != 0:
849 850
        errstr = taos_errstr(res)
        taos_free_result(res)
851
        raise SchemalessError(errstr, errno, affected_rows)
852 853

    taos_free_result(res)
854
    return affected_rows
855

856 857 858 859 860 861 862 863 864 865 866 867

def _check_if_supported():
    func = inspect.stack()[1][3]
    if func in _UNSUPPORTED:
        raise InterfaceError("C function %s is not supported in v%s: %s" % (func, taos_get_client_info(), _UNSUPPORTED[func]))


def unsupported_methods():
    for m, e in range(_UNSUPPORTED):
        print("unsupported %s: %s", m, e)


868
class CTaosInterface(object):
H
hzcheng 已提交
869
    def __init__(self, config=None):
870
        """
H
hzcheng 已提交
871 872 873 874 875 876 877 878
        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
879
        """
H
hzcheng 已提交
880 881 882 883
        if config is None:
            self._config = ctypes.c_char_p(None)
        else:
            try:
884
                self._config = ctypes.c_char_p(config.encode("utf-8"))
H
hzcheng 已提交
885 886 887
            except AttributeError:
                raise AttributeError("config is expected as a str")

888
        if config is not None:
889
            taos_options(3, self._config)
H
hzcheng 已提交
890

891
        taos_init()
H
hzcheng 已提交
892 893 894

    @property
    def config(self):
895
        """Get current config"""
H
hzcheng 已提交
896 897
        return self._config

898 899
    def connect(self, host=None, user="root", password="taosdata", db=None, port=0):
        """
H
hzcheng 已提交
900 901 902 903
        Function to connect to server

        @rtype: c_void_p, TDengine handle
        """
904
        return taos_connect(host, user, password, db, port)
weixin_48148422's avatar
weixin_48148422 已提交
905 906


907
if __name__ == "__main__":
weixin_48148422's avatar
weixin_48148422 已提交
908 909
    cinter = CTaosInterface()
    conn = cinter.connect()
910
    result = cinter.query(conn, "show databases")
weixin_48148422's avatar
weixin_48148422 已提交
911

912
    print("Query Affected rows: {}".format(cinter.affected_rows(result)))
weixin_48148422's avatar
weixin_48148422 已提交
913

914
    fields = taos_fetch_fields_raw(result)
weixin_48148422's avatar
weixin_48148422 已提交
915

916
    data, num_of_rows = taos_fetch_block(result, fields)
weixin_48148422's avatar
weixin_48148422 已提交
917 918 919

    print(data)

920
    cinter.free_result(result)
921
    cinter.close(conn)