Skip to content

Implement Python DB-API 2.0 compliance - #19369

Open
hongzhi-gao wants to merge 9 commits into
apache:masterfrom
hongzhi-gao:feat/python-dbapi2-compliance
Open

hongzhi-gao wants to merge 9 commits into
apache:masterfrom
hongzhi-gao:feat/python-dbapi2-compliance

Conversation

@hongzhi-gao

@hongzhi-gao hongzhi-gao commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Background

The IoTDB Python client already exposed a DB-API interface, but several behaviors differed from PEP 249. SQL execution errors could be swallowed and presented as empty results, making failures indistinguishable from successful queries with no rows. Parameters were interpolated with Python string formatting without consistent validation. Results were materialized through a DataFrame, cursor behavior and cleanup were inconsistent, and rollback() silently returned even though IoTDB does not support transactions.

Changes

  • Map connection and statement failures to the DB-API exception hierarchy and propagate them to callers.
  • Implement %s and %(name)s parameter styles with placeholder and parameter validation. Convert strings, numbers, date/time values, binary values, and NULL to SQL literals on the client side. This is client-side interpolation, not server-side prepared-statement binding. Escape literal percent signs in SQL as %% when parameters are supplied.
  • Return query rows as tuples and align fetchone(), fetchmany(), fetchall(), description, and rowcount with DB-API expectations. Unknown affected-row counts are reported as -1.
  • Close cursors when their connection closes and raise interface errors when closed objects are reused. commit() is a no-op and rollback() raises NotSupportedError because IoTDB does not support transactions.
  • Add DB-API module attributes, standard exceptions, date/time and binary constructors, and type-category objects. Convert result values to Python scalars while preserving nanosecond timestamp precision.
  • Add an optional fetch_size argument to Session.execute_statement(). When omitted, the request leaves the server fetch size unchanged. DB-API explicitly passes the configured connect(fetch_size=...) value, so its fetch-size behavior is opt-in at the DB-API boundary. The existing timeout argument continues to populate the request timeout. Successful USE statements also update the Session database state for reconnects.
  • Preserve the experimental SQLAlchemy dialect adapter, including its time-column markers and metadata handling. The dialect explicitly selects the tree SQL dialect while regular DB-API connections default to table.

Example parameterized query:

cursor.execute(
    "SELECT * FROM readings WHERE device = %(device)s",
    {"device": "pump-1"},
)

Impact on existing Python APIs

  • Existing direct Session calls do not need a new argument. The new fetch_size option on Session.execute_statement() defaults to None. If omitted, the request does not set the Thrift fetchSize field, so the Session does not impose a new client-side fetch-size default. The DB-API cursor explicitly passes the value configured through connect(fetch_size=...). The existing timeout argument continues to be sent as before.
  • A successful USE statement now updates the Session's remembered database. If the connection is re-established later, the Session restores that database. This makes queries after reconnect continue in the database selected by USE.
  • The SQLAlchemy adapter continues to select the tree SQL dialect explicitly. Regular DB-API connections use the table SQL dialect by default, as described in the DB-API changes above.

PEP 249 interface checklist

Status: Supported means the interface is provided. Limited means it is provided with an IoTDB-specific constraint. Not implemented means the optional API is absent. PEP 249 optional extensions are not required for core compliance.

Module interface

PEP 249 requirement Meaning IoTDB support Example
apilevel Declares the supported DB-API version Supported, value is 2.0 dbapi.apilevel
threadsafety Declares thread-sharing safety Supported, value is 1. The module may be shared, connections and cursors may not dbapi.threadsafety
paramstyle Declares SQL parameter placeholder style Supported, pyformat, accepts %s and %(name)s cursor.execute("SELECT * FROM t WHERE device=%s", ("d1",))
connect() Creates a database connection Supported conn = dbapi.connect("localhost", 6667)

Exceptions

PEP 249 requirement Meaning IoTDB support Example
Warning Database-related warning Exception class provided except dbapi.Warning: ...
Error Base class for DB-API errors Supported except dbapi.Error: ...
InterfaceError Interface, connection, or cursor misuse Supported. Reusing closed objects raises it except dbapi.InterfaceError: ...
DatabaseError Base class for database-operation errors Supported except dbapi.DatabaseError: ...
DataError Invalid data value or range Supported except dbapi.DataError: ...
OperationalError Connection or runtime failure Supported except dbapi.OperationalError: ...
IntegrityError Integrity constraint failure Exception class provided. Mapping depends on the server status except dbapi.IntegrityError: ...
InternalError Internal database failure Supported except dbapi.InternalError: ...
ProgrammingError SQL, parameter, or cursor programming error Supported. Placeholder mismatches raise it except dbapi.ProgrammingError: ...
NotSupportedError Unsupported database or driver operation Supported. rollback() raises it except dbapi.NotSupportedError: ...

Connection methods

PEP 249 requirement Meaning IoTDB support Example
Connection.close() Closes the connection and releases resources Supported. Also closes its cursors conn.close()
Connection.commit() Commits the current transaction Supported as a no-op. IoTDB writes take effect immediately conn.commit()
Connection.rollback() Rolls back the current transaction Method provided, but raises NotSupportedError because IoTDB has no transaction rollback conn.rollback()
Connection.cursor() Creates a cursor for statements and results Supported cursor = conn.cursor()

Cursor attributes and methods

PEP 249 requirement Meaning IoTDB support Example
Cursor.description Describes result columns Supported. Seven fields per column, or None without a result set cursor.description
Cursor.rowcount Number of rows returned or affected Supported. -1 when IoTDB cannot report a reliable count cursor.rowcount
Cursor.arraysize Default number of rows fetched by fetchmany() Supported, defaults to 1 cursor.arraysize = 100
Cursor.callproc() Calls a stored procedure Not implemented. The client currently has no stored procedure API —
Cursor.close() Closes a cursor and releases result resources Supported cursor.close()
Cursor.execute(operation, parameters) Executes one SQL operation with optional parameters Limited. Accepts SQL strings and sequences or mappings, not precompiled statement objects cursor.execute("SELECT * FROM t WHERE device=%(d)s", {"d": "d1"})
Cursor.executemany(operation, seq_of_parameters) Repeats an operation for multiple parameter sets Supported as individual executions. Result-producing operations raise NotSupportedError. Execution is not atomic cursor.executemany("INSERT INTO t VALUES (%s)", [(1,), (2,)])
Cursor.fetchone() Fetches the next result row Supported. Returns a tuple or None at exhaustion row = cursor.fetchone()
Cursor.fetchmany(size) Fetches a specified number of result rows Supported. Defaults to arraysize; size 0 returns an empty list rows = cursor.fetchmany(10)
Cursor.fetchall() Fetches all remaining result rows Supported, returns a list rows = cursor.fetchall()
Cursor.nextset() Advances to another result set Not implemented. Multiple result sets are not exposed —
Cursor.setinputsizes(sizes) Hints input parameter types or sizes Supported as a no-op cursor.setinputsizes([dbapi.STRING])
Cursor.setoutputsize(size, column) Hints output buffer size Supported as a no-op cursor.setoutputsize(1024)

Type objects and constructors

PEP 249 requirement Meaning IoTDB support Example
Date(year, month, day) Constructs a date Supported, returns Python date dbapi.Date(2026, 11, 23)
Time(hour, minute, second) Constructs a time Supported, returns Python time. IoTDB has no standalone TIME column dbapi.Time(12, 30, 0)
Timestamp(year, month, day, hour, minute, second) Constructs a timestamp Supported, returns Python datetime dbapi.Timestamp(2026, 11, 23, 12, 30, 0)
DateFromTicks(ticks) Constructs a date from epoch seconds Supported dbapi.DateFromTicks(1700000000)
TimeFromTicks(ticks) Constructs a time from epoch seconds Supported dbapi.TimeFromTicks(1700000000)
TimestampFromTicks(ticks) Constructs a timestamp from epoch seconds Supported dbapi.TimestampFromTicks(1700000000)
Binary(value) Constructs a binary parameter Supported dbapi.Binary(b"\x00\xff")
STRING Identifies string types Supported and comparable with column type codes dbapi.STRING == cursor.description[0][1]
BINARY Identifies binary types Supported and comparable with column type codes dbapi.BINARY == cursor.description[0][1]
NUMBER Identifies numeric types Supported and comparable with column type codes dbapi.NUMBER == cursor.description[0][1]
DATETIME Identifies date and timestamp types Supported and comparable with column type codes dbapi.DATETIME == cursor.description[0][1]
ROWID Identifies row ID types Type object provided. IoTDB has no corresponding DB-API column type dbapi.ROWID

Optional interfaces and extensions

PEP 249 requirement Meaning IoTDB support Example
Cursor.next() and iteration Fetches rows through the iterator protocol Supported as an extension. Iteration emits a warning for row in cursor: print(row)
Cursor.scroll() Moves forward or backward in a result set Not implemented —
Cursor.rownumber Reports the current result position Not implemented —
Cursor.connection Returns the cursor's connection Not implemented —
Cursor.lastrowid Reports the last inserted row ID Not implemented. IoTDB does not expose this DB-API row ID —
messages and errorhandler Exposes messages or custom error handling Not implemented —
Connection.autocommit Reads or changes automatic commit mode Not implemented. IoTDB writes take effect immediately —
Connection context manager Manages connection resource cleanup with with Supported. Exiting closes the connection, without transaction semantics with dbapi.connect("localhost", 6667) as conn: ...
Cursor context manager Manages cursor resource cleanup with with Supported. Exiting closes the cursor with conn.cursor() as cursor: ...

Tests

Added a dedicated PEP 249 contract test module at tests/unit/dbapi/test_pep249.py. It groups checks by the checklist above and covers module attributes, exception inheritance, connection and transaction methods, cursor metadata and fetching, type constructors, and supported optional extensions. Existing DB-API tests continue to cover parameter edge cases, status-code mapping, timestamp precision, reconnect behavior, and SQLAlchemy time-column compatibility.

Validation: python -m pytest tests/unit/dbapi -q — 82 passed. Thrift Python sources were generated with the repository Maven Wrapper.

Scope

This PR focuses on DB-API 2.0 behavior and compatibility with the existing experimental SQLAlchemy dialect. SQLAlchemy table-model support and integrations with pandas, Superset, and other upper-layer applications are outside this PR.

Default DB-API connections to the table dialect and support typed pyformat
parameters, streaming tuple results, standard metadata and exceptions.
Preserve nanosecond timestamps, synchronize database changes and correct
fetch-size/timeout arguments. Report unsupported rollback explicitly.

Remove SQLAlchemy-specific result rewriting from the generic DB-API and
reject the legacy adapter mode pending separate SQLAlchemy adaptation.
Document the supported interface and add contract and round-trip tests.

Validation: 105 unit tests and 6 DB-API integration tests against a local
Edge server passed; Black, diff checks and wheel build passed.

@Caideyipi Caideyipi left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed head 2e1d9c85d0b65a56965482a47f1c73793ee00781 against base aa116e0b9656da943cfd7eea108f8da4affa6d3b. I found two correctness issues: empty positional parameter sequences fail on statements with no placeholders, and tree-dialect rows expose the implicit timestamp as an integer rather than a Python datetime as documented. git diff --check passes. I did not run the Python suite locally; several CI checks remain pending.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants