Skip to main content

TiDB Cloud Lake Python Driver

Project description

tidbcloudlake-driver

TiDB Cloud Lake Python Client

image License image

Usage

PEP 249 Cursor Object

from tidbcloudlake_driver import BlockingLakeClient

client = BlockingLakeClient('lake://root:root@localhost:8000/?sslmode=disable')
cursor = client.cursor()

cursor.execute(
    """
    CREATE TABLE test (
        i64 Int64,
        u64 UInt64,
        f64 Float64,
        s   String,
        s2  String,
        d   Date,
        t   DateTime
    )
    """
)
cursor.execute("INSERT INTO test VALUES (?, ?, ?, ?, ?, ?, ?)", (1, 1, 1.0, 'hello', 'world', '2021-01-01', '2021-01-01 00:00:00'))
cursor.execute("SELECT * FROM test")
rows = cursor.fetchall()
for row in rows:
    print(row.values())
cursor.close()

Blocking Connection Object

from tidbcloudlake_driver import BlockingLakeClient

client = BlockingLakeClient('lake://root:root@localhost:8000/?sslmode=disable')
conn = client.get_conn()
conn.exec(
    """
    CREATE TABLE test (
        i64 Int64,
        u64 UInt64,
        f64 Float64,
        s   String,
        s2  String,
        d   Date,
        t   DateTime
    )
    """
)
rows = conn.query_iter("SELECT * FROM test")
for row in rows:
    print(row.values())
conn.close()

Asyncio Connection Object

import asyncio
from tidbcloudlake_driver import AsyncLakeClient

async def main():
    client = AsyncLakeClient('lake://root:root@localhost:8000/?sslmode=disable')
    conn = await client.get_conn()
    await conn.exec(
        """
        CREATE TABLE test (
            i64 Int64,
            u64 UInt64,
            f64 Float64,
            s   String,
            s2  String,
            d   Date,
            t   DateTime
        )
        """
    )
    rows = await conn.query_iter("SELECT * FROM test")
    async for row in rows:
        print(row.values())
    await conn.close()

asyncio.run(main())

Parameter bindings

# Test with positional parameters
row = await context.conn.query_row("SELECT ?, ?, ?, ?", (3, False, 4, "55"))
row = await context.conn.query_row(
    "SELECT :a, :b, :c, :d", {"a": 3, "b": False, "c": 4, "d": "55"}
)
row = await context.conn.query_row(
    "SELECT ?", 3
)
row = await context.conn.query_row("SELECT ?, ?, ?, ?", params = (3, False, 4, "55"))

Query ID tracking and query management

# Get the last executed query ID
query_id = conn.last_query_id()
print(f"Last query ID: {query_id}")

# Execute a query and get its ID
await conn.query_row("SELECT 1")
query_id = conn.last_query_id()
print(f"Query ID: {query_id}")

# Kill a running query (if needed)
try:
    await conn.kill_query("some-query-id")
    print("Query killed successfully")
except Exception as e:
    print(f"Failed to kill query: {e}")

Type Mapping

TiDB Cloud Lake Types

General Data Types

TiDB Cloud Lake Python
BOOLEAN bool
TINYINT int
SMALLINT int
INT int
BIGINT int
FLOAT float
DOUBLE float
DECIMAL decimal.Decimal
DATE datetime.date
TIMESTAMP datetime.datetime
INTERVAL datetime.timedelta
VARCHAR str
BINARY bytes

Semi-Structured Data Types

TiDB Cloud Lake Python
ARRAY list
TUPLE tuple
MAP dict
VARIANT str
BITMAP str
GEOMETRY str
GEOGRAPHY str

Note: VARIANT is a json encoded string. Example:

CREATE TABLE example (
    data VARIANT
);
INSERT INTO example VALUES ('{"a": 1, "b": "hello"}');
row = await conn.query_row("SELECT * FROM example limit 1;")
data = row.values()[0]
value = json.loads(data)
print(value)

GEOMETRY and GEOGRAPHY follow the current geometry_output_format setting. Text formats such as GeoJSON or WKT return str; binary formats such as WKB or EWKB return bytes.

For example:

row = await conn.query_row("settings(geometry_output_format='WKB') SELECT st_point(60, 37)")
assert isinstance(row.values()[0], bytes)

APIs

Exception Classes (PEP 249 Compliant)

The driver provides a complete set of exception classes that follow the PEP 249 standard for database interfaces:

# Base exceptions
class Warning(Exception): ...
class Error(Exception): ...

# Interface errors
class InterfaceError(Error): ...

# Database errors
class DatabaseError(Error): ...

# Specific database error types
class DataError(DatabaseError): ...
class OperationalError(DatabaseError): ...
class IntegrityError(DatabaseError): ...
class InternalError(DatabaseError): ...
class ProgrammingError(DatabaseError): ...
class NotSupportedError(DatabaseError): ...

These exceptions are automatically mapped from TiDB Cloud Lake error codes to appropriate PEP 249 exception types based on the nature of the error.

Note: stream_load and load_file support an optional method parameter, it accepts two string values:

  • stage: Data is first uploaded to a temporary stage and then loaded. This is the default behavior.
  • streaming: Data is directly streamed to the TiDB Cloud Lake server.

AsyncLakeClient

class AsyncLakeClient:
    def __init__(self, dsn: str): ...
    async def get_conn(self) -> AsyncLakeConnection: ...

AsyncLakeConnection

class AsyncLakeConnection:
    async def info(self) -> ConnectionInfo: ...
    async def version(self) -> str: ...
    async def close(self) -> None: ...
    def last_query_id(self) -> str | None: ...
    async def kill_query(self, query_id: str) -> None: ...
    async def exec(self, sql: str, params: list[string] | tuple[string] | any = None) -> int: ...
    async def query_row(self, sql: str, params: list[string] | tuple[string] | any = None) -> Row: ...
    async def query_iter(self, sql: str, params: list[string] | tuple[string] | any = None) -> RowIterator: ...
    async def stream_load(self, sql: str, data: list[list[str]], method: str = None) -> ServerStats: ...
    async def load_file(self, sql: str, file: str, method: str = None) -> ServerStats: ...

BlockingLakeClient

class BlockingLakeClient:
    def __init__(self, dsn: str): ...
    def get_conn(self) -> BlockingLakeConnection: ...
    def cursor(self) -> BlockingLakeCursor: ...

BlockingLakeConnection

class BlockingLakeConnection:
    def info(self) -> ConnectionInfo: ...
    def version(self) -> str: ...
    def close(self) -> None: ...
    def last_query_id(self) -> str | None: ...
    def kill_query(self, query_id: str) -> None: ...
    def exec(self, sql: str, params: list[string] | tuple[string] | any = None) -> int: ...
    def query_row(self, sql: str, params: list[string] | tuple[string] | any = None) -> Row: ...
    def query_iter(self, sql: str, params: list[string] | tuple[string] | any = None) -> RowIterator: ...
    def stream_load(self, sql: str, data: list[list[str]], method: str = None) -> ServerStats: ...
    def load_file(self, sql: str, file: str, method: str = None, format_option: dict = None, copy_options: dict = None) -> ServerStats: ...

BlockingLakeCursor

class BlockingLakeCursor:
    @property
    def description(self) -> list[tuple[str, str, int | None, int | None, int | None, int | None, bool | None]] | None: ...
    @property
    def rowcount(self) -> int: ...
    def close(self) -> None: ...
    def execute(self, operation: str, params: list[string] | tuple[string] = None) -> None | int: ...
    def executemany(self, operation: str, params: list[string] | tuple[string] = None, values: list[list[string] | tuple[string]]) -> None | int: ...
    def fetchone(self) -> Row | None: ...
    def fetchmany(self, size: int = 1) -> list[Row]: ...
    def fetchall(self) -> list[Row]: ...

    # Optional DB API Extensions
    def next(self) -> Row: ...
    def __next__(self) -> Row: ...
    def __iter__(self) -> BlockingLakeCursor: ...

Row

class Row:
    def values(self) -> tuple: ...
    def __len__(self) -> int: ...
    def __iter__(self) -> Row: ...
    def __next__(self) -> any: ...
    def __dict__(self) -> dict: ...
    def __getitem__(self, key: int | str) -> any: ...

RowIterator

class RowIterator:
    def schema(self) -> Schema: ...

    def __iter__(self) -> RowIterator: ...
    def __next__(self) -> Row: ...

    def __aiter__(self) -> RowIterator: ...
    async def __anext__(self) -> Row: ...

Field

class Field:
    @property
    def name(self) -> str: ...
    @property
    def data_type(self) -> str: ...

Schema

class Schema:
    def fields(self) -> list[Field]: ...

ServerStats

class ServerStats:
    @property
    def total_rows(self) -> int: ...
    @property
    def total_bytes(self) -> int: ...
    @property
    def read_rows(self) -> int: ...
    @property
    def read_bytes(self) -> int: ...
    @property
    def write_rows(self) -> int: ...
    @property
    def write_bytes(self) -> int: ...
    @property
    def running_time_ms(self) -> float: ...

ConnectionInfo

class ConnectionInfo:
    @property
    def handler(self) -> str: ...
    @property
    def host(self) -> str: ...
    @property
    def port(self) -> int: ...
    @property
    def user(self) -> str: ...
    @property
    def database(self) -> str | None: ...
    @property
    def warehouse(self) -> str | None: ...

Development

cd tests
make up
cd bindings/python
uv sync
source .venv/bin/activate
maturin develop --uv

behave tests/asyncio
behave tests/blocking
behave tests/cursor

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tidbcloudlake_driver-0.1.5a4.tar.gz (151.7 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

tidbcloudlake_driver-0.1.5a4-cp39-abi3-manylinux_2_28_aarch64.whl (8.6 MB view details)

Uploaded CPython 3.9+manylinux: glibc 2.28+ ARM64

tidbcloudlake_driver-0.1.5a4-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (9.2 MB view details)

Uploaded CPython 3.9+manylinux: glibc 2.17+ x86-64

tidbcloudlake_driver-0.1.5a4-cp39-abi3-macosx_11_0_arm64.whl (8.1 MB view details)

Uploaded CPython 3.9+macOS 11.0+ ARM64

tidbcloudlake_driver-0.1.5a4-cp39-abi3-macosx_10_12_x86_64.whl (8.7 MB view details)

Uploaded CPython 3.9+macOS 10.12+ x86-64

tidbcloudlake_driver-0.1.5a4-cp38-cp38-manylinux_2_28_aarch64.whl (8.8 MB view details)

Uploaded CPython 3.8manylinux: glibc 2.28+ ARM64

tidbcloudlake_driver-0.1.5a4-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (9.4 MB view details)

Uploaded CPython 3.8manylinux: glibc 2.17+ x86-64

tidbcloudlake_driver-0.1.5a4-cp38-cp38-macosx_11_0_arm64.whl (8.2 MB view details)

Uploaded CPython 3.8macOS 11.0+ ARM64

tidbcloudlake_driver-0.1.5a4-cp38-cp38-macosx_10_12_x86_64.whl (8.9 MB view details)

Uploaded CPython 3.8macOS 10.12+ x86-64

File details

Details for the file tidbcloudlake_driver-0.1.5a4.tar.gz.

File metadata

  • Download URL: tidbcloudlake_driver-0.1.5a4.tar.gz
  • Upload date:
  • Size: 151.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for tidbcloudlake_driver-0.1.5a4.tar.gz
Algorithm Hash digest
SHA256 61c768f4fc5db8848b1201c6204ba8e28fffd6fb94c63bd205982f4716d7513a
MD5 7e4033b0a5825e0bc8110435e5ff32e1
BLAKE2b-256 d2f9114dee2d14eba2e9608da1fe36d4dd0a47b500759d4553ed4c856b5aab62

See more details on using hashes here.

Provenance

The following attestation bundles were made for tidbcloudlake_driver-0.1.5a4.tar.gz:

Publisher: release.yml on tidbcloud/lakesql

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file tidbcloudlake_driver-0.1.5a4-cp39-abi3-manylinux_2_28_aarch64.whl.

File metadata

File hashes

Hashes for tidbcloudlake_driver-0.1.5a4-cp39-abi3-manylinux_2_28_aarch64.whl
Algorithm Hash digest
SHA256 c56e1eae7bab10f6aee8dfd8dd005450378ae6a92c98655742caded0e6cdbcb2
MD5 a2928472fca8c842e9bbd8e7a0611c97
BLAKE2b-256 03feddb58d428ff0cf28e2ff3fb5383b594102b5e971027d21835b12351e877f

See more details on using hashes here.

Provenance

The following attestation bundles were made for tidbcloudlake_driver-0.1.5a4-cp39-abi3-manylinux_2_28_aarch64.whl:

Publisher: release.yml on tidbcloud/lakesql

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file tidbcloudlake_driver-0.1.5a4-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for tidbcloudlake_driver-0.1.5a4-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 7908308e2255e12e5e07834eb37e470953aa2bf3c5607a91c37f306b914d1093
MD5 b36cd1a552b989bf353119e724b63606
BLAKE2b-256 9c82a088e22b09af62d312f1bcd07773b415a794c482fa8e4612f1ab42029d1c

See more details on using hashes here.

Provenance

The following attestation bundles were made for tidbcloudlake_driver-0.1.5a4-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl:

Publisher: release.yml on tidbcloud/lakesql

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file tidbcloudlake_driver-0.1.5a4-cp39-abi3-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for tidbcloudlake_driver-0.1.5a4-cp39-abi3-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 69580c42a05a7ee700bc5c7322b5aee4b96d36149f023447e5c4351f295cf1e9
MD5 2014b7c6f187deceeaba7dc4b14b8923
BLAKE2b-256 2975d7be2946e957d6e677374bd76bb0b81f3542baa6899fa4cb52ad3369f60b

See more details on using hashes here.

Provenance

The following attestation bundles were made for tidbcloudlake_driver-0.1.5a4-cp39-abi3-macosx_11_0_arm64.whl:

Publisher: release.yml on tidbcloud/lakesql

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file tidbcloudlake_driver-0.1.5a4-cp39-abi3-macosx_10_12_x86_64.whl.

File metadata

File hashes

Hashes for tidbcloudlake_driver-0.1.5a4-cp39-abi3-macosx_10_12_x86_64.whl
Algorithm Hash digest
SHA256 2a01a469020cedc2e7861315cda4155d27eb92c6682d6e7dbfead728de79e969
MD5 1fdff9d1650aa6faa790d5678864078d
BLAKE2b-256 97c1fb56c3b987a846a5d54b745daf0c76c860ceb6af3a859679c547be3d382e

See more details on using hashes here.

Provenance

The following attestation bundles were made for tidbcloudlake_driver-0.1.5a4-cp39-abi3-macosx_10_12_x86_64.whl:

Publisher: release.yml on tidbcloud/lakesql

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file tidbcloudlake_driver-0.1.5a4-cp38-cp38-manylinux_2_28_aarch64.whl.

File metadata

File hashes

Hashes for tidbcloudlake_driver-0.1.5a4-cp38-cp38-manylinux_2_28_aarch64.whl
Algorithm Hash digest
SHA256 b09987287cb9d56b451226bada0eb1ecd198ac607834d47098b7c62572a0ec53
MD5 03461caa8ed4e0575c1a58cfd39a0c1a
BLAKE2b-256 ec76872e2183e4eb94e3a9df3560784c3b4660cc851bee33044df0bb0703e88a

See more details on using hashes here.

Provenance

The following attestation bundles were made for tidbcloudlake_driver-0.1.5a4-cp38-cp38-manylinux_2_28_aarch64.whl:

Publisher: release.yml on tidbcloud/lakesql

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file tidbcloudlake_driver-0.1.5a4-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for tidbcloudlake_driver-0.1.5a4-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 a4ffac55b64c7aba8cff3b8d064ff8a8db699c9715c9e1fcca2a2c78a05a57c4
MD5 1508735fba0c7f68b012037ca8d23b3c
BLAKE2b-256 ada3c803eb7f38d069532df00c54f0584fbef078bf803c3ea80513f77cdbde58

See more details on using hashes here.

Provenance

The following attestation bundles were made for tidbcloudlake_driver-0.1.5a4-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl:

Publisher: release.yml on tidbcloud/lakesql

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file tidbcloudlake_driver-0.1.5a4-cp38-cp38-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for tidbcloudlake_driver-0.1.5a4-cp38-cp38-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 7c9b62909119ba52977fc2e542785251dce15371990c4e5767230df94bcf978a
MD5 941c85b9f2e561e68fa92cee9c57d896
BLAKE2b-256 ccc3967506f08ed405b2d350c9601f3117e6eb848c3ae7ff57a087629f0811da

See more details on using hashes here.

Provenance

The following attestation bundles were made for tidbcloudlake_driver-0.1.5a4-cp38-cp38-macosx_11_0_arm64.whl:

Publisher: release.yml on tidbcloud/lakesql

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file tidbcloudlake_driver-0.1.5a4-cp38-cp38-macosx_10_12_x86_64.whl.

File metadata

File hashes

Hashes for tidbcloudlake_driver-0.1.5a4-cp38-cp38-macosx_10_12_x86_64.whl
Algorithm Hash digest
SHA256 4def83af247459c5852046416e01ab63afdb305971961b308444b768b831249a
MD5 dde995d0c5bbc392701a2eb9d4fb3472
BLAKE2b-256 cc1b2156371a82659425e6b2705d92aa7af59f310fb32a3b920c5a146ffc8769

See more details on using hashes here.

Provenance

The following attestation bundles were made for tidbcloudlake_driver-0.1.5a4-cp38-cp38-macosx_10_12_x86_64.whl:

Publisher: release.yml on tidbcloud/lakesql

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page