Skip to content

Python driver API reference

View as Markdown

This file lists the public API of pycoradb 0.9.0. Everything here can be imported from the top-level package (import pycoradb). The exceptions are Connection, Cursor and the constants, which are in pycoradb.connection, pycoradb.cursor and pycoradb.constants.

The driver follows DB-API 2.0 (PEP 249). This file adds the CoraDB-specific behaviour and the extensions.

Name Value Meaning
__version__ "0.9.0" Driver version.
apilevel "2.0" DB-API level.
threadsafety 1 Threads may share the module, but not a connection. Use one connection per thread.
paramstyle "qmark" Placeholders are ?, e.g. WHERE id = ?.
pycoradb.connect(
host="localhost", port=33000, database="", user="dba", password="",
decode_collections=False, json_deserializer=None, ssl=None, charset="utf-8",
**kwargs,
) -> Connection

Opens a connection to a CoraDB broker and returns a connected Connection.

Parameter Type / default Description
host str, "localhost" Broker host name or IP address.
port int, 33000 Broker port.
database str, "" Database name.
user str, "dba" Database user.
password str, "" Password.
decode_collections bool, False False: SET/MULTISET/SEQUENCE values come back as raw bytes. True: they are decoded. SET becomes a frozenset (a tuple if its elements are unhashable); MULTISET and SEQUENCE become a list.
json_deserializer Callable or None None: JSON columns come back as str. Otherwise the callable is applied to the JSON text (for example json.loads).
ssl None / bool / ssl.SSLContext None or False: plain TCP. True: TLS with ssl.create_default_context(), TLS 1.2 minimum, certificate and host-name checks. SSLContext: TLS with your own context, used as-is.
charset str, "utf-8" Encoding used for SQL text, bound strings, credentials, character values, metadata names and error messages. Accepts any Python codec or a CoraDB name (utf8, euckr, iso88591). Set it to the database charset. JSON is always UTF-8.

Keyword options (**kwargs):

Option Default Description
autocommit False Turn auto-commit on right after connecting. Must be a bool (1 or "true" raise TypeError).
fetch_size 100 Rows requested from the server per network round trip. Must be ≥ 1. Each cursor can override it.
connect_timeout None Seconds allowed for the whole session setup: TCP connect, broker handshake, TLS handshake, login and the escape-mode probe. It applies again to every reconnect. None waits indefinitely (the TLS handshake is then still bounded by read_timeout, or 10 s).
read_timeout None Socket timeout in seconds for every request once the session is set up. None blocks until the server answers.
no_backslash_escapes None How a backslash in a string parameter is escaped. None: detect the server setting, with SELECT CHAR_LENGTH('\\'). True: backslash is a literal character (the server default). False: the server treats backslash as an escape character. Must be None or a bool: a string such as "false" raises TypeError (it would otherwise silently switch escaping off). See Escape mode.
enable_timing None True collects timing statistics (see TimingStats). None uses the PYCORADB_ENABLE_TIMING environment variable (1, true or yes).
zero_date_behavior "exception" (None means the same) How a zero date such as 0000-00-00 is returned (Python's datetime has no year 0). "exception" raises DataError; "convert_to_null" returns None; "round" returns date(1, 1, 1) or datetime(1, 1, 1, 0, 0) (a TZ value keeps its zone). It works like the JDBC zeroDateTimeBehavior option. See Zero dates.

If an option name is not recognised, it is ignored and an UnknownConnectionOptionWarning is issued. A typo such as read_timout=30 therefore produces a warning instead of being silently dropped.

Raises:

  • OperationalError: the broker is unreachable or refuses the connection, the TLS handshake fails, or a timeout expires.
  • DatabaseError (or a subclass): the login is rejected.
  • DataError: a credential cannot be encoded in charset.
  • ValueError / TypeError: an invalid argument, for example fetch_size=0, zero_date_behavior="null", a non-bool value for autocommit, decode_collections, no_backslash_escapes or enable_timing, or a timeout that is not a positive, finite number. These are raised before any network activity.

Login failures (error -21001) are OperationalError with SQLSTATE 28000.

conn = pycoradb.connect(host="db.local", database="e-commerce", user="dba",
password="secret", autocommit=True, read_timeout=30)

Returned by pycoradb.connect(). It can also be created directly as pycoradb.connection.Connection(host, port, database, user, password, **options); it then connects immediately.

Method Returns Description
cursor() Cursor Creates a cursor on this connection.
commit() None Commits the current transaction.
rollback() None Rolls back the current transaction.
close() None Closes all cursors of this connection and the session, with a single request (the server frees every open result). Calling it again does nothing. Uncommitted work is rolled back by the server.
ping(reconnect=True) bool Checks that the session is alive with a lightweight CHECK_CAS request; no SQL is run. If the session is dead and reconnect=True, it reconnects once and restores the session settings. Returns True when the connection is usable and False otherwise, including when the reconnect itself fails (for example with rejected credentials). A failed check always closes the broken session. After an explicit close() it returns False and does not reopen the connection; call connect() for that.
connect() None Re-opens the session after close(). The constructor and pycoradb.connect() call it for you. An autocommit value you set explicitly is re-applied.
get_server_version() str The CoraDB engine version string.
get_last_insert_id() str or None The auto-increment value the broker reported for the last INSERT made through a cursor of this connection, cached at that time; it is not re-queried. It is cleared by a new INSERT or batch, and when the session is replaced. CALL and stored-procedure INSERTs do not update it.
create_lob(lob_type) Lob Creates an empty server-side LOB. lob_type is CoraDBDataType.BLOB (23) or CoraDBDataType.CLOB (24). Same as Lob.create(conn, lob_type).
get_schema_info(schema_type, table_name="", pattern_match_flag=1, *, arg2=None) Schema result Starts a schema-information query and returns a result handle. Pass it to fetch_schema_info() or close_schema_info(). See below for the arguments.
fetch_schema_info(packet) list[tuple] Reads every row of a get_schema_info() result, then releases it.
close_schema_info(packet) None Releases a schema result without reading it. Releasing an already released result does nothing.

get_schema_info() arguments:

  • schema_type: a pycoradb.constants.CCISchemaType value, such as CLASS, ATTRIBUTE, PRIMARY_KEY, IMPORTED_KEYS, EXPORTED_KEYS, CONSTRAINT or TRIGGER (full list in Constants).
  • table_name: a table name, or a pattern when pattern_match_flag includes CCISchemaPatternMatchFlag.CLASS_NAME (1, the default). In a pattern % matches any text.
  • arg2: a second name, used for example as the attribute name for ATTRIBUTE, or the foreign table for CROSS_REFERENCE.
  • The returned handle also exposes tuple_count (number of rows) and columns (column metadata).
from pycoradb.constants import CCISchemaType
info = conn.get_schema_info(CCISchemaType.ATTRIBUTE, "users")
for row in conn.fetch_schema_info(info):
print(row)
Property Type Description
autocommit bool (read/write) The current auto-commit mode. Setting it (only a bool is accepted) sends the change to the server, then commits the open transaction. Like commit(), it closes the open results of every cursor first, so an unfinished cursor raises InterfaceError afterwards. If that commit fails, OperationalError is raised and the old value is kept.
timing_stats TimingStats or None Timing data if timing is enabled, otherwise None.
with pycoradb.connect(database="e-commerce") as conn:
...

On leaving the block, the connection commits if no exception was raised, rolls back if one was, and then closes.

  • If you closed the connection yourself inside the block, it is just closed.
  • If the connection was lost inside the block (and you caught that error), a normal exit raises OperationalError (SQLSTATE 08S01) saying the transaction was not committed, so the loss of the block's work is never silent.
  • On the exception path, a failing rollback is logged and your original exception propagates.

As PEP 249 allows, every exception class is also an attribute of the connection (conn.Error, conn.DatabaseError, conn.IntegrityError, ...), so you can write except conn.IntegrityError:.

Created with conn.cursor(). A cursor runs statements and holds the current result set.

Method Returns Description
execute(operation, parameters=None) Cursor (itself) Runs one SQL statement. parameters is a sequence of values, one per ? placeholder (see Parameters). Any previous result set is released first.
executemany(operation, seq_of_parameters) Cursor Runs operation once for each parameter sequence (any iterable of sequences, e.g. a generator). INSERT, UPDATE, DELETE and similar statements go to the server as one batch request, and rowcount is the total number of affected rows. Other statements run one at a time. An empty sequence or generator does nothing and sets rowcount to 0. If a row cannot be bound, nothing is sent and the previous result set is gone.
executemany_batch(sql_list, auto_commit=None) list[(stmt_type, count)] Sends a list of complete SQL strings (no parameters) as one batch. Returns one (statement type, affected rows) pair per statement. auto_commit=None uses the connection's setting. If any statement fails, the matching DatabaseError subclass is raised.
callproc(procname, parameters=()) The parameters sequence Runs CALL procname(?, ?, ...). A procedure's result, if any, can be fetched. procname must be a str identifier (letters, digits, _, .), otherwise ProgrammingError.
fetchone() tuple or None The next row, or None when there are no more rows.
fetchmany(size=None) list[tuple] Up to size rows; arraysize rows by default.
fetchall() list[tuple] All remaining rows.
close() None Releases the server-side result and closes the cursor. Using the cursor after that raises InterfaceError.
nextset() – CoraDB has no multiple result sets; always raises NotSupportedError.
setinputsizes(sizes) None DB-API method; does nothing here.
setoutputsize(size, column=None) None DB-API method; does nothing here.

Calling a fetch* method when there is no result set (for example after an INSERT) raises InterfaceError. The first rows arrive with the execute() reply (the server sizes that page); the rest are fetched in batches of fetch_size as you go.

Property Type Description
description tuple or None One 7-item tuple per result column: (name, type_code, display_size, internal_size, precision, scale, null_ok). type_code is a CoraDBDataType value, which you can compare with pycoradb.STRING, NUMBER and the other type objects. display_size and internal_size are always None. It is None for statements that return no rows.
rowcount int Rows affected by the last INSERT, UPDATE or DELETE (the total for executemany). -1 after a SELECT or when unknown.
lastrowid int or None The auto-increment value generated by the last INSERT on this cursor, if any. None if the server could not report it; the INSERT itself still succeeds.
arraysize int (read/write) Default fetchmany() size; starts at 1 and must be a positive integer.
fetch_size int (read/write) Rows per server round trip for this cursor; defaults to the connection's fetch_size and must be ≥ 1.
with conn.cursor() as cur: # closes the cursor at the end
cur.execute("SELECT id, name FROM users")
for user_id, name in cur: # same as calling fetchone() until None
...

pycoradb.Lob handles a server-side large object. Two simple cases need no Lob:

  • Writing: pass bytes (BLOB) or str (CLOB) as an ordinary parameter.
  • Reading: a BLOB/CLOB column comes back as a dict with the keys lob_type, lob_length, file_locator and packed_lob_handle.

To read a fetched column's content, wrap that dict in a Lob:

from pycoradb import Lob
from pycoradb.constants import CoraDBDataType
cur.execute("SELECT payload FROM docs WHERE id = ?", (1,))
handle = cur.fetchone()[0]
lob = Lob(conn, handle["lob_type"], handle["packed_lob_handle"])
data = lob.read(handle["lob_length"])
Member Description
Lob(connection, lob_type, lob_handle=b"") Wraps an existing LOB handle. lob_type must be CoraDBDataType.BLOB or CLOB; anything else raises ValueError.
Lob.create(connection, lob_type) (class method) Creates a new, empty LOB on the server. Same as conn.create_lob(lob_type).
write(data, offset=0) -> int Writes bytes at offset and returns the number of bytes written. Large data is sent in chunks of pycoradb.lob.LOB_WRITE_CHUNK_SIZE (128 KiB). Raises OperationalError if the server writes fewer bytes, for example when the disk is full; nothing after the short chunk is sent. Writing empty bytes returns 0 without contacting the server.
read(length, offset=0) -> bytes Reads up to length bytes from offset. Large reads are fetched in pieces automatically, because the broker sends at most ~80 KB per reply. Returns fewer bytes when the end of the LOB is reached. A CLOB is returned as encoded bytes; decode it yourself.
close() Marks this object closed on the client side only; there is no network call. Later read/write calls raise InterfaceError. The server frees the LOB when the session closes.
lob_type, lob_handle The type code and the raw handle bytes (read-only).

Lob objects can be used as context managers (with conn.create_lob(...) as lob:). They cannot be passed as statement parameters.

A LOB handle belongs to the session it was created or read on. After that session is replaced (ping() recovery, an implicit reconnect, or close() then connect()), read()/write() raise OperationalError instead of sending the old handle. A Lob built from a fetched row's handle dict is tied to the session that is current when the Lob is built, so build it right after fetching.

The driver substitutes parameters on the client side: each value is turned into a safe, correctly escaped SQL literal before the statement is sent. Do not put quotes around ? placeholders. The number of values must equal the number of ?, otherwise ProgrammingError is raised.

Python value Sent as
None NULL
bool 1 / 0
int Integer literal; at most 38 digits, otherwise DataError
float DOUBLE literal, always with an exponent: 1.5 → 1.5e0, 1e-07 → 1e-07 (NaN and infinity are rejected)
decimal.Decimal Fixed-point number, at most 38 digits; a zero such as Decimal('0E-50') is sent as 0
str Quoted string; escaping follows no_backslash_escapes
bytes, bytearray X'..' hex literal (BIT/VARBIT/BLOB)
datetime.date DATE'YYYY-MM-DD'
datetime.time TIME'HH:MM:SS' (microseconds and any tzinfo are dropped)
datetime.datetime DATETIME'...' with millisecond precision; DATETIMETZ'...' when timezone-aware. In a DST overlap (the same wall time twice, chosen with fold) the zone abbreviation is added, e.g. America/New_York EDT, or the numeric offset is sent when the abbreviation does not tell the two apart
list, tuple A comma-separated list of the elements' literals; see Lists and tuples
pycoradb.Set(...), Multiset(...), Sequence(...) SET{...}, MULTISET{...}, SEQUENCE{...} collection literals

Negative numbers are sent in parentheses, e.g. (-5), (-1.5e0), (-0.25), also as list and collection elements. That way a placeholder written after a minus sign (bal-?) can never form a -- SQL comment.

Other types raise ProgrammingError. That includes set, frozenset and dict, because their element order is undefined.

How backslashes in strings must be escaped depends on the server's no_backslash_escapes parameter. Unless you pin it with the no_backslash_escapes connection option, the driver detects it when the session opens. If a statement run through the driver changes it (SET SYSTEM PARAMETERS 'no_backslash_escapes=...', also when the setting is a bound parameter), the driver detects the mode again before the next statement with parameters, without touching your transaction. A mode you pinned is kept, and a warning is logged.

A list or tuple bound to one ? expands into a comma-separated list of literals. This is the usual way to fill an IN clause:

cur.execute("SELECT * FROM users WHERE id IN (?) AND active = ?", ([3, 7, 9], 1))
# sent as: SELECT * FROM users WHERE id IN (3, 7, 9) AND active = 1
cur.executemany("DELETE FROM users WHERE id IN (?)", [([1, 2],), ([5],)])
  • Each element is escaped exactly like a single parameter, so expansion is as safe against SQL injection as ordinary binding.
  • One list fills one ?, so the number of parameters still equals the number of ? placeholders.
  • The parentheses are yours to write: IN (?), not IN ?.
  • The expansion happens wherever the ? is, not only in IN. For example, INSERT INTO t VALUES (?) with ([1, "a"],) sends VALUES (1, 'a').
  • An empty list or tuple raises ProgrammingError, because IN () is not valid SQL. Check for an empty list in your code before running the query.
  • Nested containers are rejected with ProgrammingError. That covers a list inside a list, and a Set, Multiset or Sequence used as an element.
  • To bind a CoraDB collection value (one SET/MULTISET/SEQUENCE column value), use Set, Multiset or Sequence instead.
CoraDB type Python value
CHAR, VARCHAR/STRING, NCHAR, VARNCHAR, ENUM str
SHORT, INT, BIGINT int
FLOAT, DOUBLE, MONETARY float
NUMERIC decimal.Decimal
DATE / TIME datetime.date / datetime.time
DATETIME, TIMESTAMP datetime.datetime (no timezone)
DATETIMETZ, DATETIMELTZ, TIMESTAMPTZ, TIMESTAMPLTZ Timezone-aware datetime.datetime. A zone that cannot be resolved raises DataError; install tzdata
BIT, VARBIT bytes
JSON str, or the result of json_deserializer. With json_deserializer=json.loads, text nested too deeply or with an over-long number raises DataError
SET / MULTISET / SEQUENCE bytes, or decoded values when decode_collections=True (elements of every type, including the time-zone types)
BLOB, CLOB dict LOB handle (see Lob)
OBJECT (OID) str, such as `"OID:@page
GRAPH_OBJECT bytes (not decoded yet)
NULL None

CoraDB can store zero dates such as DATE'0000-00-00' and DATETIME'0000-00-00 00:00:00'. Python's datetime cannot represent year 0, so the zero_date_behavior connection option chooses what you get back:

zero_date_behavior Zero DATE Zero DATETIME / TIMESTAMP (and TZ/LTZ variants)
"exception" (default) DataError DataError
"convert_to_null" None None
"round" date(1, 1, 1) datetime(1, 1, 1, 0, 0); TZ/LTZ values keep their zone
conn = pycoradb.connect(database="e-commerce", zero_date_behavior="convert_to_null")
  • What counts as a zero date: year, month and day are all 0, and the time part (if any) is valid. Any other value Python cannot represent, such as 2024-02-30, still raises DataError.
  • Where it applies: to rows from execute() and fetch*(), to elements of decoded collections, and to schema-information rows.
  • After an error: with "exception", a DataError leaves the connection usable. You can also convert the value in SQL instead, for example with TO_CHAR(col, 'YYYY-MM-DD') or NULLIF(col, DATE'0000-00-00').

PEP 249 type objects compare equal to a description type_code, e.g. cur.description[0][1] == pycoradb.NUMBER.

Type object Matches
STRING CHAR, STRING, NCHAR, VARNCHAR, ENUM, CLOB, JSON
BINARY BIT, VARBIT, BLOB, GRAPH_OBJECT
NUMBER NUMERIC, INT, SHORT, BIGINT, FLOAT, DOUBLE, MONETARY
DATETIME DATE, TIME, TIMESTAMP, DATETIME and their TZ/LTZ variants
ROWID OBJECT (OID)
Constructor Returns
Date(year, month, day) datetime.date
Time(hour, minute, second) datetime.time
Timestamp(year, month, day, hour, minute, second) datetime.datetime
DateFromTicks(ticks) / TimeFromTicks(ticks) / TimestampFromTicks(ticks) date / time / datetime from a Unix timestamp
Binary(value) bytes (a str is encoded as UTF-8)
Set(iterable), Multiset(iterable), Sequence(iterable) Immutable collection parameters (see Binding). They support len(), iteration, == and .elements, and cannot be subclassed.

All exceptions are importable from pycoradb:

Warning
Error
├── InterfaceError driver misuse: closed cursor/connection, no result set, protocol problem
└── DatabaseError errors reported by the server
├── DataError bad value: out of range, unencodable text, invalid data
├── OperationalError connection lost, timeout, broker refused, TLS failure, server state
├── IntegrityError unique / primary key / foreign key / NOT NULL violations
├── InternalError server internal errors
├── ProgrammingError SQL syntax errors, unknown tables or columns, bad parameter count or type
└── NotSupportedError operation not supported (e.g. nextset())
UnknownConnectionOptionWarning (a UserWarning for unrecognised connect() options)
Attribute On Description
msg All errors The error message. Server messages may end with a hint, e.g. for a reserved word used as an identifier.
code All errors The error code as the server sent it (0 if there is none).
errno DatabaseError and subclasses The error number, e.g. -670 for a unique-key violation, or None. For an error raised by the broker/CAS itself it is the documented CAS code (e.g. -10003 for a communication error), while code keeps the value as sent (e.g. -1003).
sqlstate DatabaseError and subclasses The SQLSTATE code when known, or None. Driver-side connection failures (connect failed, connection lost, timeout) use 08S01.

Errors raised by the broker/CAS are classified by their code: communication, disconnect, timeout and resource errors are OperationalError; argument and binding errors are ProgrammingError or DataError; unsupported features are NotSupportedError. Errors from the database engine keep their usual mapping (for example unique-key violations are IntegrityError).

pycoradb.get_error_description(code) -> str | None returns a short description of a known CAS or server error code. pycoradb.error_codes.get_cas_error_description(code) describes a CAS error code given in either form (-1003 or -10003).

Turn timing on with connect(..., enable_timing=True) or the environment variable PYCORADB_ENABLE_TIMING=1, then read conn.timing_stats (a pycoradb.TimingStats).

Member Description
connect_count, connect_total_ns Number of connects and their total time in nanoseconds.
execute_count, execute_total_ns The same for statement execution.
fetch_count, fetch_total_ns The same for server fetches.
close_count, close_total_ns The same for closes.
reset() Sets all counters to zero.
repr(stats) / print(stats) A readable summary with totals and averages.

pycoradb.constants contains the protocol enumerations. All are IntEnum/IntFlag, so they can be used as plain integers.

Enum Use
CoraDBDataType Column type codes in description (CHAR=1, STRING=2, INT=8, NUMERIC=7, DATE=13, DATETIME=22, BLOB=23, CLOB=24, JSON=34, GRAPH_OBJECT=35, ...).
CCISchemaType get_schema_info() types: CLASS, VCLASS, QUERY_SPEC, ATTRIBUTE, CLASS_ATTRIBUTE, METHOD, CLASS_METHOD, METHOD_FILE, SUPERCLASS, SUBCLASS, CONSTRAINT, TRIGGER, CLASS_PRIVILEGE, ATTR_PRIVILEGE, DIRECT_SUPER_CLASS, PRIMARY_KEY, IMPORTED_KEYS, EXPORTED_KEYS, CROSS_REFERENCE.
CCISchemaPatternMatchFlag CLASS_NAME (1) and ATTR_NAME (2) pattern-matching flags.
CoraDBStatementType Statement type codes, such as the first item of each executemany_batch() result pair (SELECT=21, INSERT=20, UPDATE=22, DELETE=23, ...).
CoraDBIsolationLevel Isolation levels: REP_CLASS_COMMIT_INSTANCE (READ COMMITTED, the default), REP_CLASS_REP_INSTANCE (REPEATABLE READ), SERIALIZABLE.
ErrorCode Common CAS error codes, such as ER_COMMUNICATION.
CASProtocol Wire constants: VERSION (9), MAGIC_STRING ("CUBRK"), MAGIC_STRING_SSL ("CUBRS").