AsyncPG#

High-performance async PostgreSQL adapter using asyncpg. Supports native pipelines, Arrow export, and Cloud SQL / AlloyDB connectors.

Configuration#

class sqlspec.adapters.asyncpg.AsyncpgConfig[source]#

Bases: AsyncDatabaseConfig[PoolConnectionProxy, Pool[Record], AsyncpgDriver]

Configuration for AsyncPG database connections using TypedDict.

driver_type#

alias of AsyncpgDriver

connection_type#

alias of PoolConnectionProxy

__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 AsyncPG configuration.

Parameters:
  • connection_config -- Connection and pool configuration parameters (TypedDict or dict)

  • connection_instance -- Existing pool instance to use

  • migration_config -- Migration configuration

  • statement_config -- Statement configuration override

  • driver_features -- Driver features configuration (TypedDict or dict)

  • bind_key -- Optional unique identifier for this configuration

  • extension_config -- Extension-specific configuration

  • observability_config -- Adapter-level observability overrides for lifecycle hooks and observers

  • **kwargs -- Additional keyword arguments

get_cloud_sql_connector()[source]#

Return the configured Cloud SQL connector instance.

Return type:

Any | None

get_alloydb_connector()[source]#

Return the configured AlloyDB connector instance.

Return type:

Any | None

async create_connection()[source]#

Create a single async connection from the pool.

Return type:

PoolConnectionProxy

Returns:

An AsyncPG connection instance.

provide_session(*_args, statement_config=None, **_kwargs)[source]#

Provide an async driver session context manager.

Parameters:
  • *_args (Any) -- Additional arguments.

  • statement_config (StatementConfig | None) -- Optional statement configuration override.

  • **_kwargs (Any) -- Additional keyword arguments.

Return type:

AsyncpgSessionContext

Returns:

An AsyncPG driver session context manager.

async provide_pool(*args, **kwargs)[source]#

Provide async pool instance.

Returns:

The async connection pool.

get_signature_namespace()[source]#

Get the signature namespace for AsyncPG types.

This provides all AsyncPG-specific types that Litestar needs to recognize to avoid serialization attempts.

Return type:

dict[str, typing.Any]

Returns:

Dictionary mapping type names to types.

get_event_runtime_hints()[source]#

Return polling defaults for PostgreSQL queue fallback.

Return type:

EventRuntimeHints

JSON and JSONB Codecs#

AsyncPG connections register binary json and jsonb codecs by default. This lets regular statement execution and load_from_arrow() pass Python dict and list values into PostgreSQL JSON / JSONB columns while preserving asyncpg's binary COPY protocol expectations for jsonb payloads. Set driver_features={"enable_json_codecs": False} when an application needs to manage asyncpg JSON codecs manually.

class sqlspec.adapters.asyncpg.config.AsyncpgPoolConfig[source]#

Bases: AsyncpgConnectionConfig

TypedDict for AsyncPG pool parameters, inheriting connection parameters.

class sqlspec.adapters.asyncpg.config.AsyncpgConnectionConfig[source]#

Bases: TypedDict

TypedDict for AsyncPG connection parameters.

Driver#

class sqlspec.adapters.asyncpg.AsyncpgDriver[source]#

Bases: AsyncDriverAdapterBase

AsyncPG PostgreSQL driver for async database operations.

Supports COPY operations, numeric parameter style handling, PostgreSQL exception handling, transaction management, SQL statement compilation and caching, and parameter processing with type coercion.

__init__(connection, statement_config=None, driver_features=None)[source]#

Initialize driver adapter with connection and configuration.

Parameters:
  • connection (PoolConnectionProxy) -- Database connection instance

  • statement_config (StatementConfig | None) -- Statement configuration for the driver

  • driver_features (dict[str, typing.Any] | None) -- Driver-specific features like extensions, secrets, and connection callbacks

  • observability -- Optional runtime handling lifecycle hooks, observers, and spans

async dispatch_execute(cursor, statement)[source]#

Execute single SQL statement.

Handles both SELECT queries and non-SELECT operations.

Parameters:
  • cursor (PoolConnectionProxy) -- AsyncPG connection object

  • statement (SQL) -- SQL statement to execute

Return type:

ExecutionResult

Returns:

ExecutionResult with statement execution details

async dispatch_execute_many(cursor, statement)[source]#

Execute SQL with multiple parameter sets using AsyncPG's executemany.

Parameters:
  • cursor (PoolConnectionProxy) -- AsyncPG connection object

  • statement (SQL) -- SQL statement with multiple parameter sets

Return type:

ExecutionResult

Returns:

ExecutionResult with batch execution details

async dispatch_execute_script(cursor, statement)[source]#

Execute SQL script with statement splitting and parameter handling.

Parameters:
  • cursor (PoolConnectionProxy) -- AsyncPG connection object

  • statement (SQL) -- SQL statement containing multiple statements

Return type:

ExecutionResult

Returns:

ExecutionResult with script execution details

async dispatch_special_handling(cursor, statement)[source]#

Handle PostgreSQL COPY operations and other special cases.

Parameters:
  • cursor (PoolConnectionProxy) -- AsyncPG connection object

  • statement (SQL) -- SQL statement to analyze

Return type:

SQLResult | None

Returns:

SQLResult if special operation was handled, None for standard execution

async begin()[source]#

Begin a database transaction.

Return type:

None

async commit()[source]#

Commit the current transaction.

Return type:

None

async rollback()[source]#

Rollback the current transaction.

Return type:

None

async set_migration_session_schema(schema)[source]#

Set the PostgreSQL search path for migration SQL.

Return type:

None

async set_migration_non_transactional_schema(schema)[source]#

Set the PostgreSQL search path for non-transactional migration SQL.

Return type:

None

async reset_migration_session_schema()[source]#

Reset the PostgreSQL search path after non-transactional migration SQL.

Return type:

None

async has_schema(schema)[source]#

Return whether a PostgreSQL schema exists.

Return type:

bool

with_cursor(connection)[source]#

Create context manager for AsyncPG cursor.

Return type:

AsyncpgCursor

dispatch_select_stream(statement, chunk_size)[source]#

Return a native asyncpg row stream backed by a cursor in a stream-owned transaction.

Return type:

Optional[AsyncRowStream[dict[str, typing.Any]]]

handle_database_exceptions()[source]#

Handle database exceptions with PostgreSQL error codes.

Return type:

AsyncpgExceptionHandler

async execute_stack(stack, *, continue_on_error=False)[source]#

Execute a StatementStack using asyncpg's rapid batching.

Return type:

tuple[StackResult, ...]

async select_to_storage(statement, destination, /, *parameters, statement_config=None, partitioner=None, format_hint=None, telemetry=None, **kwargs)[source]#

Execute a query and persist results to storage once native COPY is available.

Return type:

StorageBridgeJob

async load_from_arrow(table, source, *, partitioner=None, overwrite=False, telemetry=None)[source]#

Load Arrow data into a PostgreSQL table via COPY.

Return type:

StorageBridgeJob

async load_from_storage(table, source, *, file_format, partitioner=None, overwrite=False)[source]#

Read an artifact from storage and ingest it via COPY.

Return type:

StorageBridgeJob

property data_dictionary: AsyncpgDataDictionary#

Get the data dictionary for this driver.

Returns:

Data dictionary instance for metadata queries

collect_rows(cursor, fetched)[source]#

Collect asyncpg rows for the direct execution path.

Return type:

tuple[list[typing.Any], list[str], int]

resolve_rowcount(cursor)[source]#

Resolve rowcount from asyncpg status for the direct execution path.

Return type:

int

Extension Dialects#

AsyncPG supports the pgvector and ParadeDB dialects for vector similarity search and full-text search operators. See the Dialects reference for operator details.

Data Dictionary#

class sqlspec.adapters.asyncpg.data_dictionary.AsyncpgDataDictionary[source]#

Bases: AsyncDataDictionaryBase

PostgreSQL-specific async data dictionary.

dialect: ClassVar[str] = 'postgres'#

Dialect identifier. Must be defined by subclasses as a class attribute.

async get_metadata_capabilities(driver, domains=None)[source]#

Get PostgreSQL replacement data-dictionary capability profile.

Return type:

MetadataCapabilityProfile

async get_system_metadata_capabilities(driver, domains=None)[source]#

Get PostgreSQL opt-in system metadata capability disclosures.

Return type:

tuple[SystemMetadataCapability, ...]

async get_schemas(driver)[source]#

Get schema metadata.

Return type:

MetadataResult

async get_objects(driver, schema=None)[source]#

Get database object metadata.

Return type:

MetadataResult

async get_table_details(driver, table, schema=None)[source]#

Get rich table metadata.

Return type:

MetadataResult

async get_constraints(driver, table=None, schema=None)[source]#

Get constraint metadata.

Return type:

MetadataResult

async get_views(driver, schema=None)[source]#

Get view metadata.

Return type:

MetadataResult

async get_routines(driver, schema=None)[source]#

Get routine metadata.

Return type:

MetadataResult

async get_privileges(driver, object_name=None, schema=None)[source]#

Get privilege metadata.

Return type:

MetadataResult

async get_dependencies(driver, object_name=None, schema=None)[source]#

Get dependency metadata.

Return type:

MetadataResult

async get_ddl(driver, object_name, schema=None, *, object_type='table', include_dependencies=True, prefer_native=True, redact=True)[source]#

Get object DDL where PostgreSQL exposes native definition helpers.

Return type:

DDLResult

async get_system_metadata(driver, request=None, **kwargs)[source]#

Get opt-in PostgreSQL system metadata.

Return type:

SystemMetadataResult

async get_version(driver)[source]#

Get PostgreSQL database version information.

Parameters:

driver (AsyncpgDriver) -- Async database driver instance.

Return type:

VersionInfo | None

Returns:

PostgreSQL version information or None if detection fails.

async get_feature_flag(driver, feature)[source]#

Check if PostgreSQL database supports a specific feature.

Parameters:
  • driver (AsyncpgDriver) -- Async database driver instance.

  • feature (str) -- Feature name to check.

Return type:

bool

Returns:

True if feature is supported, False otherwise.

async get_optimal_type(driver, type_category)[source]#

Get optimal PostgreSQL type for a category.

Parameters:
  • driver (AsyncpgDriver) -- Async database driver instance.

  • type_category (str) -- Type category.

Return type:

str

Returns:

PostgreSQL-specific type name.

async get_tables(driver, schema=None)[source]#

Get tables sorted by topological dependency order using Recursive CTE.

Return type:

list[TableMetadata]

async get_columns(driver, table=None, schema=None)[source]#

Get column information for a table or schema.

Return type:

list[ColumnMetadata]

async get_indexes(driver, table=None, schema=None)[source]#

Get index metadata for a table or schema.

Return type:

list[IndexMetadata]

async get_foreign_keys(driver, table=None, schema=None)[source]#

Get foreign key metadata.

Return type:

list[ForeignKeyMetadata]