Db2#
Sync and async IBM Db2 adapter built on ibm_db.
It binds positional parameters (?), pools connections, reflects the Db2
catalog, and compiles SQL through SQLSpec's built-in db2 SQLGlot dialect.
Supported Databases#
Db2 for Linux, UNIX and Windows (LUW) 11.5 and later. Catalog queries read the
SYSCATviews, and feature detection assumes the 11.5 SQL level.Db2 for z/OS and Db2 for IBM i are not supported. They expose different catalogs and SQL, and SQLSpec does not test against them.
SQLSpec's integration suite runs the Db2 adapter against Db2 Community Edition 11.5.9 alongside the other databases; the test container is started automatically and needs a Docker daemon that allows privileged containers.
Installation#
pip install "sqlspec[db2]"
The extra installs ibm_db 3.3.0 or later, which bundles the IBM CLI driver
(clidriver). Wheels are published for CPython 3.9 through 3.14. Linux wheels
are manylinux_2_34 x86_64 because the bundled CLI driver needs glibc 2.34 or
newer. On other platforms pip builds ibm_db from source: set
CLIDRIVER_VERSION=v11.5.9 to download a compatible CLI driver, or point
IBM_DB_HOME at an existing Db2 client installation.
Quick Start#
from sqlspec import SQLSpec
from sqlspec.adapters.db2 import Db2SyncConfig
spec = SQLSpec()
db = spec.add_config(
Db2SyncConfig(
connection_config={
"database": "SAMPLE",
"hostname": "db2.example.com",
"port": 50000,
"user": "db2inst1",
"password": "secret",
}
)
)
with spec.provide_session(db) as session:
rows = session.select("SELECT id, name FROM users WHERE active = ?", 1)
Use Db2AsyncConfig with async with sessions for asyncio applications. It
runs on ibm_db_dbi.AsyncConnection and accepts the same connection parameters
plus the async pool settings below.
from sqlspec.adapters.db2 import Db2AsyncConfig
config = Db2AsyncConfig(
connection_config={
"database": "SAMPLE",
"hostname": "db2.example.com",
"user": "db2inst1",
"password": "secret",
"max_size": 10,
"acquire_timeout": 30.0,
}
)
async def active_users() -> list[dict]:
async with config.provide_session() as session:
return await session.select("SELECT id, name FROM users WHERE active = ?", 1)
Connection Parameters#
Each parameter renders as one IBM CLI connection keyword. Unknown keys raise
ImproperConfigurationError when the config is created.
Parameter |
CLI keyword |
Notes |
|---|---|---|
|
|
Required, directly or through |
|
|
Omit it to connect to a cataloged database alias. |
|
|
Defaults to |
|
|
Defaults to |
|
|
|
|
|
Default schema for unqualified names. |
|
|
|
|
|
Path to the server certificate (ARM or PEM file). |
|
|
For example |
|
|
Seconds. |
|
(none) |
Autocommit mode new connections open in. Defaults to |
|
(parsed) |
|
|
(verbatim) |
Additional CLI keywords, for example |
Values that contain ; or {, or that start or end with whitespace, are
wrapped in braces when the connection string is rendered, so passwords such as
"pa;ss" work as written. CLI connection strings cannot represent };
a value containing it raises ImproperConfigurationError.
TLS example:
from sqlspec.adapters.db2 import Db2SyncConfig
config = Db2SyncConfig(
connection_config={
"database": "SAMPLE",
"hostname": "db2.example.com",
"port": 50001,
"user": "db2inst1",
"password": "secret",
"security": "SSL",
"ssl_server_certificate": "/etc/db2/server.arm",
"current_schema": "APP",
}
)
config.get_connection_string() returns the rendered CLI connection string.
Connection Pooling#
Db2SyncConfig keeps one connection per thread that uses the config,
including worker threads that run async_() wrappers. The pool has no maximum
size: the number of open connections equals the number of threads that have used
it. Connections are replaced after pool_recycle_seconds (default 86400) and
pinged with SELECT 1 FROM SYSIBM.SYSDUMMY1 before reuse once idle for
health_check_interval seconds (default 30).
Db2AsyncConfig holds at most max_size connections (default 10). A
session that cannot get a connection within acquire_timeout seconds (default
30) raises ConnectionTimeoutError. Recycling and health checks use the same
two settings as the sync pool.
Transactions#
Connections open in autocommit mode by default, so each statement outside a transaction commits immediately.
session.begin()turns autocommit off for the unit of work;commit()androllback()end it and turn autocommit back on.session.transaction()wraps a block inbegin()/commit()and rolls back when the block raises. Nested blocks use savepoints.provide_session(transaction=True)starts the session inside a transaction.A session that exits with an unfinished transaction rolls it back and restores the connection's autocommit mode before the connection returns to the pool.
with config.provide_session() as session:
with session.transaction():
session.execute("INSERT INTO users (id, name) VALUES (?, ?)", 101, "Ada")
session.execute("UPDATE accounts SET owner_id = ? WHERE id = ?", 101, 7)
Set "autocommit": False in connection_config to make every session a
single unit of work that you commit explicitly.
Result Column Names#
Db2 folds unquoted identifiers to uppercase, so SELECT id FROM users reports a
column named ID. With enable_lowercase_column_names (default True),
names that consist only of uppercase letters, digits, and underscores are
lowercased in result rows, so row["id"] works. Quoted mixed-case names such as
"MixedCase" are kept as written. Set
driver_features={"enable_lowercase_column_names": False} to keep the names
Db2 reports.
The Db2 Dialect#
SQLSpec registers a db2 SQLGlot dialect. Use it to transpile SQL written for
other databases or with the query builder (sql.select(..., dialect="db2")):
import sqlglot
import sqlspec.dialects.db2 # noqa: F401
print(sqlglot.transpile("SELECT id FROM users ORDER BY id LIMIT 10 OFFSET 20", read="postgres", write="db2")[0])
# SELECT id FROM users ORDER BY id OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY
print(sqlglot.transpile("SELECT CURRENT_TIMESTAMP + INTERVAL '1 day'", read="postgres", write="db2")[0])
# SELECT CURRENT TIMESTAMP + 1 DAY FROM SYSIBM.SYSDUMMY1
The dialect covers:
FETCH FIRST n ROWS ONLYandOFFSET m ROWS FETCH NEXT n ROWS ONLYpaging.SYSIBM.SYSDUMMY1forSELECTstatements without aFROMclause, andVALUESstatements.Special registers (
CURRENT TIMESTAMP,CURRENT DATE,CURRENT SCHEMA,CURRENT SERVER,CURRENT TIMEZONE) and labeled durations (CURRENT DATE + 1 DAYS - 2 MONTHS).Isolation and lock clauses (
WITH UR,WITH CS,WITH RS,WITH RR,USE AND KEEP ... LOCKS), which round-trip unchanged.Db2 types such as
DECFLOAT,GRAPHIC,VARGRAPHIC,DBCLOB,CLOBandBLOB.MERGEstatements for builder upserts (sql.upsert(..., dialect="db2")).
Row locks from the query builder translate to Db2 isolation clauses:
for_update()rendersWITH RS USE AND KEEP UPDATE LOCKS.for_share()rendersWITH RS USE AND KEEP SHARE LOCKS.skip_locked=TrueappendsSKIP LOCKED DATA.nowait=Trueandof=...raiseSQLBuilderError. Db2 has noNOWAIT; setCURRENT LOCK TIMEOUTon the session instead.
from sqlspec import sql
query = (
sql.select("id", "payload", dialect="db2")
.from_("jobs")
.where("status = 'new'")
.order_by("id")
.limit(5)
.for_update(skip_locked=True)
)
print(query.build().sql)
# ... FETCH FIRST 5 ROWS ONLY WITH RS USE AND KEEP UPDATE LOCKS SKIP LOCKED DATA
Warning
IBM's db2-sqlglot-dialect package registers the same db2 entry point in
sqlglot.dialects and pins sqlglot<30.10, which conflicts with SQLSpec's
sqlglot>=30.13 requirement. Do not install both packages in one
environment.
Data Dictionary#
session.data_dictionary reads the SYSCAT catalog views. Unqualified
lookups use CURRENT SCHEMA.
with config.provide_session() as session:
tables = session.data_dictionary.get_tables(session)
columns = session.data_dictionary.get_columns(session, table="USERS")
foreign_keys = session.data_dictionary.get_foreign_keys(session, table="ORDERS")
Arrow#
session.select_to_arrow() converts result rows into a pyarrow.Table. The
conversion runs in Python; for columnar reads straight from the database, use the
arrow-odbc adapter with the Db2 ODBC driver (see its
IBM Db2 section).
Extensions#
Both configs provide stores for the Litestar session backend, the events queue, and the Google ADK session and memory services. Stores create their tables on first use, and every timestamp they write is stored in UTC.
Extension |
Sync config |
Async config |
|---|---|---|
Litestar sessions |
|
|
Events queue |
|
|
ADK sessions |
|
|
ADK memory |
|
|
SQLSpec migrations run on both configs.
API Reference#
Configuration#
- class sqlspec.adapters.db2.Db2SyncConfig[source]#
Bases:
SyncDatabaseConfig[Connection,Db2SyncConnectionPool,Db2SyncDriver]Configuration for IBM Db2 synchronous connections.
- driver_type#
alias of
Db2SyncDriver
- connection_type#
alias of
Connection
- migration_tracker_type#
alias of
Db2SyncMigrationTracker
- __init__(*, connection_config=None, connection_instance=None, migration_config=None, statement_config=None, driver_features=None, bind_key=None, extension_config=None, observability_config=None, **kwargs)[source]#
Initialize Db2 configuration.
- create_connection()[source]#
Open a standalone connection owned by the caller.
- Returns:
A newly opened physical connection.
- Return type:
Connection
- class sqlspec.adapters.db2.Db2AsyncConfig[source]#
Bases:
AsyncDatabaseConfig[AsyncConnection,Db2AsyncConnectionPool,Db2AsyncDriver]Configuration for IBM Db2 asynchronous connections over
ibm_db_dbi.AsyncConnection.- driver_type#
alias of
Db2AsyncDriver
- connection_type#
alias of
AsyncConnection
- migration_tracker_type#
alias of
Db2AsyncMigrationTracker
- __init__(*, connection_config=None, connection_instance=None, migration_config=None, statement_config=None, driver_features=None, bind_key=None, extension_config=None, observability_config=None, **kwargs)[source]#
Initialize Db2 async configuration.
max_sizeandacquire_timeoutare kept for the pool; every other key is validated and normalized like the sync configuration's connection parameters.
- async create_connection()[source]#
Open a standalone connection owned by the caller.
- Returns:
A newly opened
ibm_db_dbi.AsyncConnection.- Return type:
AsyncConnection
- class sqlspec.adapters.db2.Db2ConnectionParams[source]#
Bases:
TypedDictIBM Db2 connection parameters.
Each modeled parameter renders under one CLI keyword:
database:
DATABASE. Required, either directly or throughdsn. hostname:HOSTNAME. Omit it to connect to a cataloged database alias. port:PORT. Defaults to 50000 whenhostnameis set. protocol:PROTOCOL. Defaults toTCPIPwhenhostnameis set. user:UID. password:PWD. current_schema:CURRENTSCHEMA. security:SECURITY, for example"SSL". ssl_server_certificate:SSLSERVERCERTIFICATE. authentication:AUTHENTICATION. connect_timeout:CONNECTTIMEOUTin seconds. autocommit: Autocommit mode new connections start in. Never rendered into the DSN. dsn:KEY=VALUE;...connection string ordb2://user:password@host:port/database?Key=ValueURL. Explicit parameters override values parsed from it.
extra: Additional CLI keywords rendered verbatim after the modeled parameters.
- class sqlspec.adapters.db2.Db2PoolParams[source]#
Bases:
Db2ConnectionParamsIBM Db2 pool parameters.
pool_recycle_seconds: Seconds after which a pooled connection is replaced. Defaults to 86400. health_check_interval: Idle seconds after which a pooled connection is pinged before reuse.
Defaults to 30.0.
- class sqlspec.adapters.db2.Db2AsyncPoolParams[source]#
Bases:
Db2PoolParamsIBM Db2 async pool parameters.
max_size: Maximum number of connections checked out or being opened at once. Defaults to 10. acquire_timeout: Seconds to wait for a free connection before raising
ConnectionTimeoutError. Defaults to 30.0.
- class sqlspec.adapters.db2.Db2DriverFeatures[source]#
Bases:
TypedDictIBM Db2 driver feature flags.
- json_serializer: Custom JSON serializer function.
Defaults to sqlspec.utils.serializers.to_json.
- json_deserializer: Custom JSON deserializer function.
Defaults to sqlspec.utils.serializers.from_json.
- on_connection_create: Callback executed when a connection is created.
Receives the raw Db2 connection (
ibm_db_dbi.ConnectionforDb2SyncConfig,ibm_db_dbi.AsyncConnectionforDb2AsyncConfig) for low-level driver configuration. Runs after connection creation;Db2AsyncConfigawaits an awaitable result.
enable_events: Enable database event channel support. events_backend: Event channel backend selection. enable_lowercase_column_names: Normalize implicit uppercase column names to lowercase.
Defaults to True.
Drivers#
- class sqlspec.adapters.db2.Db2SyncDriver[source]#
Bases:
SyncDriverAdapterBaseIBM Db2 database driver.
- __init__(connection, statement_config=None, driver_features=None)[source]#
Initialize driver adapter with connection and configuration.
- Parameters:
- dispatch_execute(cursor, statement)[source]#
Execute a single SQL statement.
Must be implemented by each driver for database-specific execution logic.
- Parameters:
- Return type:
- Returns:
ExecutionResult with execution data
- dispatch_execute_many(cursor, statement)[source]#
Execute SQL with multiple parameter sets (executemany).
Must be implemented by each driver for database-specific executemany logic.
- Parameters:
- Return type:
- Returns:
ExecutionResult with execution data for the many operation
- dispatch_execute_script(cursor, statement)[source]#
Execute a SQL script containing multiple statements.
Default implementation splits the script and executes statements individually. Drivers can override for database-specific script execution methods.
- Parameters:
- Return type:
- Returns:
ExecutionResult with script execution data including statement counts
- begin()[source]#
Begin a transaction by turning autocommit off for its duration.
Does nothing while a transaction started by this driver is active. When the connection was in autocommit mode,
commit()androllback()switch it back on.- Raises:
SQLSpecError -- When the driver reports an error.
- Return type:
- commit()[source]#
Commit the current unit of work and restore the autocommit baseline.
- Raises:
SQLSpecError -- When the driver reports an error.
- Return type:
- rollback()[source]#
Roll back the current unit of work and restore the autocommit baseline.
- Raises:
SQLSpecError -- When the driver reports an error.
- Return type:
- release_open_work(*, autocommit_baseline)[source]#
Roll back work left open before the connection is returned to its pool.
A transaction started by this driver is always rolled back; on a connection whose autocommit baseline is off, any pending unit of work is rolled back as well. A rollback failure is logged and not raised, so it never masks an error from the session body.
- with_cursor(connection)[source]#
Create and return a context manager for cursor acquisition and cleanup.
Returns a context manager that yields a cursor for database operations. Concrete implementations handle database-specific cursor creation and cleanup.
- Return type:
Db2SyncCursor
- handle_database_exceptions()[source]#
Handle database-specific exceptions and wrap them appropriately.
- Return type:
Db2SyncExceptionHandler- Returns:
Exception handler with deferred exception pattern for mypyc compatibility. The handler stores mapped exceptions in pending_exception rather than raising from __exit__ to avoid ABI boundary violations.
- dispatch_select_stream(statement, chunk_size)[source]#
Return a native Db2 row stream backed by cursor.fetchmany().
- Return type:
Optional[SyncRowStream[dict[str, typing.Any]]]
- set_migration_session_schema(schema)[source]#
Switch the session's current schema, remembering the schema in effect on the first switch.
- reset_migration_session_schema()[source]#
Restore the current schema captured by
set_migration_session_schema.- Return type:
- property data_dictionary: Db2SyncDataDictionary#
Return the Db2 data dictionary bound to this driver.
- Returns:
The lazily created data dictionary instance.
- collect_rows(cursor, fetched)[source]#
Collect rows from cursor after fetchall for the direct execution path.
Adapters should override this method to provide optimized row collection that bypasses full dispatch_execute overhead.
- Parameters:
- Return type:
- Returns:
Tuple of (data, column_names, row_count).
- Raises:
NotImplementedError -- If the adapter does not implement this method.
- resolve_rowcount(cursor)[source]#
Resolve the number of affected rows from cursor for the direct execution path.
Adapters should override this method to provide optimized rowcount resolution that bypasses full dispatch_execute overhead.
- Parameters:
- Return type:
- Returns:
Number of affected rows, or 0 when unknown.
- Raises:
NotImplementedError -- If the adapter does not implement this method.
- class sqlspec.adapters.db2.Db2AsyncDriver[source]#
Bases:
AsyncDriverAdapterBaseIBM Db2 async database driver over
ibm_db_dbi.AsyncConnection.- __init__(connection, statement_config=None, driver_features=None)[source]#
Initialize driver adapter with connection and configuration.
- Parameters:
- async dispatch_execute(cursor, statement)[source]#
Execute a single SQL statement.
Must be implemented by each driver for database-specific execution logic.
- Parameters:
- Return type:
- Returns:
ExecutionResult with execution data
- async dispatch_execute_many(cursor, statement)[source]#
Execute SQL with multiple parameter sets (executemany).
Must be implemented by each driver for database-specific executemany logic.
- Parameters:
- Return type:
- Returns:
ExecutionResult with execution data for the many operation
- async dispatch_execute_script(cursor, statement)[source]#
Execute a SQL script containing multiple statements.
Default implementation splits the script and executes statements individually. Drivers can override for database-specific script execution methods.
- Parameters:
- Return type:
- Returns:
ExecutionResult with script execution data including statement counts
- async begin()[source]#
Begin a transaction by turning autocommit off for its duration.
Does nothing while a transaction started by this driver is active. When the connection was in autocommit mode,
commit()androllback()switch it back on.- Raises:
SQLSpecError -- When the driver reports an error.
- Return type:
- async commit()[source]#
Commit the current unit of work and restore the autocommit baseline.
- Raises:
SQLSpecError -- When the driver reports an error.
- Return type:
- async rollback()[source]#
Roll back the current unit of work and restore the autocommit baseline.
- Raises:
SQLSpecError -- When the driver reports an error.
- Return type:
- async release_open_work(*, autocommit_baseline)[source]#
Roll back work left open before the connection is returned to its pool.
A transaction started by this driver is always rolled back; on a connection whose autocommit baseline is off, any pending unit of work is rolled back as well. A rollback failure is logged and not raised, so it never masks an error from the session body.
- with_cursor(connection)[source]#
Create and return an async context manager for cursor acquisition and cleanup.
Returns an async context manager that yields a cursor for database operations. Concrete implementations handle database-specific cursor creation and cleanup.
- Return type:
Db2AsyncCursor
- handle_database_exceptions()[source]#
Handle database-specific exceptions and wrap them appropriately.
- Return type:
Db2AsyncExceptionHandler- Returns:
Exception handler with deferred exception pattern for mypyc compatibility. The handler stores mapped exceptions in pending_exception rather than raising from __aexit__ to avoid ABI boundary violations.
- dispatch_select_stream(statement, chunk_size)[source]#
Return a native Db2 row stream backed by
AsyncCursor.fetchmany().- Return type:
Optional[AsyncRowStream[dict[str, typing.Any]]]
- async create_savepoint(name)[source]#
Create a transaction savepoint retaining open cursors.
- Return type:
- async set_migration_session_schema(schema)[source]#
Switch the session's current schema, remembering the schema in effect on the first switch.
- async reset_migration_session_schema()[source]#
Restore the current schema captured by
set_migration_session_schema.- Return type:
- property data_dictionary: Db2AsyncDataDictionary#
Return the Db2 async data dictionary bound to this driver.
- Returns:
The lazily created data dictionary instance.
- collect_rows(cursor, fetched)[source]#
Collect rows from cursor after fetchall for the direct execution path.
Adapters should override this method to provide optimized row collection that bypasses full dispatch_execute overhead.
- Parameters:
- Return type:
- Returns:
Tuple of (data, column_names, row_count).
- Raises:
NotImplementedError -- If the adapter does not implement this method.
- resolve_rowcount(cursor)[source]#
Resolve the number of affected rows from cursor for the direct execution path.
Adapters should override this method to provide optimized rowcount resolution that bypasses full dispatch_execute overhead.
- Parameters:
- Return type:
- Returns:
Number of affected rows, or 0 when unknown.
- Raises:
NotImplementedError -- If the adapter does not implement this method.
Connection Pools#
- class sqlspec.adapters.db2.pool.Db2SyncConnectionPool[source]#
Bases:
objectThread-local connection manager for IBM Db2.
- __init__(connection_parameters, recycle_seconds=86400, health_check_interval=30.0, on_connection_create=None)[source]#
Initialize the thread-local connection manager.
- Parameters:
connection_parameters¶ (
dict[str, typing.Any]) -- Normalized Db2 connection parameters. The CLI connection string is rendered from them once, here;autocommit(default True) sets the autocommit mode every new connection opens in.recycle_seconds¶ (
int) -- Connection recycle time in seconds (default 24h).health_check_interval¶ (
float) -- Seconds of idle time before running health check.on_connection_create¶ (typing.Callable[[MyTypeAliasForwardRef('typing.Any')],
None] |None) -- Callback executed when connection is created.
- new_connection()[source]#
Open a standalone connection configured like a pooled one.
The connection opens in the pool's autocommit mode.
The result is owned by the caller: it is not thread-local and is not tracked for pool shutdown.
- Returns:
A newly opened, fully configured Db2 connection.
- Return type:
- Raises:
MissingDependencyError -- When ibm_db is not installed.
- get_connection()[source]#
Context manager to yield a thread-local connection.
- Yields:
A thread-local Db2 database connection.
- class sqlspec.adapters.db2.pool.Db2AsyncConnectionPool[source]#
Bases:
objectBounded asyncio pool of
ibm_db_dbi.AsyncConnectionobjects.At most
max_sizeconnections are checked out or being opened at once; callers waiting longer thanacquire_timeoutgetConnectionTimeoutError. Idle connections are reused most-recently-released first, replaced once older thanrecycle_seconds, and pinged when idle for longer thanhealth_check_interval. Closing the pool closes idle connections immediately and checked-out connections when they are released.- __init__(connection_parameters, *, max_size=10, acquire_timeout=30.0, recycle_seconds=86400, health_check_interval=30.0, on_connection_create=None)[source]#
Initialize the pool.
- Parameters:
connection_parameters¶ (
dict[str, typing.Any]) -- Normalized Db2 connection parameters. The CLI connection string is rendered from them once, here;autocommit(default True) sets the autocommit mode every new connection opens in.max_size¶ (
int) -- Maximum number of connections checked out or being opened at once.acquire_timeout¶ (
float) -- Seconds to wait for a free slot before raising.recycle_seconds¶ (
int) -- Connection age in seconds after which it is replaced (0 disables).health_check_interval¶ (
float) -- Seconds of idle time before a connection is pinged on reuse.on_connection_create¶ (typing.Callable[[MyTypeAliasForwardRef('typing.Any')],
Awaitable[None] |None] |None) -- Callback run on every new connection; awaited when it returns an awaitable.
- async new_connection()[source]#
Open a standalone connection configured like a pooled one.
The connection opens in the pool's autocommit mode and the creation hook runs on it. The result is owned by the caller and is not tracked by the pool.
- Returns:
A newly opened
ibm_db_dbi.AsyncConnection.- Return type:
- Raises:
MissingDependencyError -- When ibm_db is not installed.
- async acquire()[source]#
Check a connection out of the pool.
- Returns:
A pooled
ibm_db_dbi.AsyncConnection.- Return type:
- Raises:
DatabaseConnectionError -- When the pool is closed.
ConnectionTimeoutError -- When no slot frees up within
acquire_timeoutseconds.
- async release(connection)[source]#
Return a checked-out connection to the pool.
Connections the pool did not hand out are ignored. After
close()the connection is closed instead of being kept.
- get_connection()[source]#
Return an async context manager that acquires and releases a pooled connection.
- Returns:
The connection context manager.
- Return type:
Db2AsyncPoolConnectionContext
Data Dictionaries#
- class sqlspec.adapters.db2.Db2SyncDataDictionary[source]#
Bases:
SyncDataDictionaryBaseIBM Db2 sync data dictionary for metadata reflection.
- dialect: ClassVar[str] = 'db2'#
Dialect identifier. Must be defined by subclasses as a class attribute.
- get_metadata_capabilities(driver, domains=None)[source]#
Get Db2 data-dictionary capability profile.
- Return type:
- get_version(driver)[source]#
Get Db2 database version information.
The instance service level is parsed once per driver and cached. Query errors propagate as mapped driver errors.
- Parameters:
driver¶ (
Db2SyncDriver) -- Db2 driver.- Return type:
Db2VersionInfo|None- Returns:
The parsed version, or
Nonewhen the service level cannot be parsed.
- get_tables(driver, schema=None)[source]#
Get tables sorted by dependency order with catalog fallback.
- Return type:
- get_columns(driver, table=None, schema=None)[source]#
Get columns for a table or schema from SYSCAT.COLUMNS.
- Return type:
- get_indexes(driver, table=None, schema=None)[source]#
Get indexes for a table or schema from SYSCAT.INDEXES and SYSCAT.INDEXCOLUSE.
- Return type:
- get_foreign_keys(driver, table=None, schema=None)[source]#
Get foreign keys from SYSCAT.REFERENCES and SYSCAT.KEYCOLUSE.
- Return type:
- get_objects(driver, schema=None)[source]#
Get tables, views, aliases, sequences and routines from the Db2 catalog.
- Parameters:
driver¶ (
Db2SyncDriver) -- Db2 driver.schema¶ (
str|None) -- Schema to list; defaults to the session'sCURRENT SCHEMA.
- Return type:
- Returns:
Objects-domain metadata result.
- class sqlspec.adapters.db2.Db2AsyncDataDictionary[source]#
Bases:
AsyncDataDictionaryBaseIBM Db2 async data dictionary for metadata reflection.
- dialect: ClassVar[str] = 'db2'#
Dialect identifier. Must be defined by subclasses as a class attribute.
- async get_metadata_capabilities(driver, domains=None)[source]#
Get Db2 data-dictionary capability profile.
- Return type:
- async get_version(driver)[source]#
Get Db2 database version information.
The instance service level is parsed once per driver and cached. Query errors propagate as mapped driver errors.
- Parameters:
driver¶ (
Db2AsyncDriver) -- Async Db2 driver.- Return type:
Db2VersionInfo|None- Returns:
The parsed version, or
Nonewhen the service level cannot be parsed.
- async get_optimal_type(driver, type_category)[source]#
Get optimal Db2 type for a category.
- Return type:
- async get_tables(driver, schema=None)[source]#
Get tables sorted by dependency order with catalog fallback.
- Return type:
- async get_columns(driver, table=None, schema=None)[source]#
Get columns for a table or schema from SYSCAT.COLUMNS.
- Return type:
- async get_indexes(driver, table=None, schema=None)[source]#
Get indexes for a table or schema from SYSCAT.INDEXES and SYSCAT.INDEXCOLUSE.
- Return type:
- async get_foreign_keys(driver, table=None, schema=None)[source]#
Get foreign keys from SYSCAT.REFERENCES and SYSCAT.KEYCOLUSE.
- Return type:
- async get_constraints(driver, table=None, schema=None)[source]#
Get Db2 constraint metadata.
- Return type:
- async get_objects(driver, schema=None)[source]#
Get tables, views, aliases, sequences and routines from the Db2 catalog.
- Parameters:
driver¶ (
Db2AsyncDriver) -- Async Db2 driver.schema¶ (
str|None) -- Schema to list; defaults to the session'sCURRENT SCHEMA.
- Return type:
- Returns:
Objects-domain metadata result.