YDB API Reference

Driver

DriverConfig

class ydb.DriverConfig(endpoint, database=None, ca_cert=None, auth_token=None, channel_options=None, credentials=None, use_all_nodes=False, root_certificates=None, certificate_chain=None, private_key=None, grpc_keep_alive_timeout=None, table_client_settings=None, topic_client_settings=None, query_client_settings=None, endpoints=None, primary_user_agent='python-library', tracer=None, grpc_lb_policy_name='round_robin', discovery_request_timeout=10, compression=None)[source]

A driver config to initialize a driver instance

Parameters:
  • endpoint – A endpoint specified in pattern host:port to be used for initial channel initialization and for YDB endpoint discovery mechanism

  • database – A name of the database

  • ca_cert – A CA certificate when SSL should be used

  • auth_token – A authentication token

  • credentials – An instance of AbstractCredentials

  • use_all_nodes – A balancing policy that forces to use all available nodes.

  • root_certificates – The PEM-encoded root certificates as a byte string.

  • private_key – The PEM-encoded private key as a byte string, or None if no private key should be used.

  • certificate_chain – The PEM-encoded certificate chain as a byte string to use or or None if no certificate chain should be used.

  • grpc_keep_alive_timeout – GRpc KeepAlive timeout, ms

  • tracer (ydb.Tracer) – ydb.Tracer instance to trace requests in driver. If tracing aio ScopeManager must be ContextVarsScopeManager

  • grpc_lb_policy_name – A load balancing policy to be used for discovery channel construction. Default value is round_round

  • discovery_request_timeout – A default timeout to complete the discovery. The default value is 10 seconds.

topic_client_settings
query_client_settings
tracer
grpc_lb_policy_name
discovery_request_timeout
compression
set_database(database)[source]
classmethod default_from_endpoint_and_database(endpoint, database, root_certificates=None, credentials=None, **kwargs)[source]
classmethod default_from_connection_string(connection_string, root_certificates=None, credentials=None, **kwargs)[source]
set_grpc_keep_alive_timeout(timeout)[source]

Driver

class ydb.Driver(driver_config=None, connection_string=None, endpoint=None, database=None, root_certificates=None, credentials=None, **kwargs)[source]

Constructs a driver instance to be used in table and scheme clients. It encapsulates endpoints discovery mechanism and provides ability to execute RPCs on discovered endpoints

Parameters:
  • driver_config – A driver config

  • connection_string – A string in the following format: <protocol>://<hostame>:<port>/?database=/path/to/the/database

  • endpoint – An endpoint specified in the following format: <protocol>://<hostame>:<port>

  • database – A database path

  • credentials – A credentials. If not specifed credentials constructed by default.

scheme_client
table_client
async_wait(fail_fast=False)

Returns a future to subscribe on endpoints availability.

Returns:

A concurrent.futures.Future instance.

discovery_debug_details()

Returns debug string about last errors :return:

future(request, stub, rpc_name, wrap_result=None, settings=None, wrap_args=(), preferred_endpoint=None)

Sends request constructed by client

Parameters:
  • request – A request constructed by client

  • stub – A stub instance to wrap channel

  • rpc_name – A name of RPC to be executed

  • wrap_result – A callable that intercepts call and wraps received response

  • settings – An instance of BaseRequestSettings that can be used for RPC metadata construction

  • wrap_args – And arguments to be passed into wrap_result callable

Returns:

A future of computation

wait(timeout=None, fail_fast=False)

Waits for endpoints to be are available to serve user requests

Parameters:

timeout – A timeout to wait in seconds

Returns:

None

stop(timeout=10)[source]

Stops underlying discovery process and cleanups

Parameters:

timeout – A timeout to wait for stop completion

Returns:

None

Driver (AsyncIO)

class ydb.aio.Driver(driver_config=None, connection_string=None, endpoint=None, database=None, root_certificates=None, credentials=None, **kwargs)[source]

An object that encapsulates discovery logic and provides ability to execute user requests on discovered endpoints. :param driver_config: An instance of DriverConfig

discovery_debug_details()

Returns debug string about last errors :return:

async stop(timeout=10)[source]

Stops underlying discovery process and cleanups :param timeout: A timeout to wait for stop completion :return: None

async wait(timeout=7, fail_fast=False)

Waits for endpoints to be are available to serve user requests :param timeout: A timeout to wait in seconds :param fail_fast: Should wait fail fast? :return: None


Common

BaseRequestSettings

class ydb.BaseRequestSettings[source]

Request settings to be used for RPC execution

with_compression(compression) BaseRequestSettings[source]

Enables compression for the specific RPC :param compression: An RPCCompression enum value. :return The self instance.

Return type:

BaseRequestSettings

with_need_rpc_auth(need_rpc_auth) BaseRequestSettings[source]
Return type:

BaseRequestSettings

with_header(key, value) BaseRequestSettings[source]

Adds a key-value pair to the request headers. :param key: A string with a header key. :param value: A string with a header value. :return The self instance.

Return type:

BaseRequestSettings

with_trace_id(trace_id) BaseRequestSettings[source]

Includes trace id for RPC headers :param trace_id: A trace id string :return: The self instance

Return type:

BaseRequestSettings

with_request_type(request_type) BaseRequestSettings[source]

Includes request type for RPC headers :param request_type: A request type string :return: The self instance

Return type:

BaseRequestSettings

with_operation_timeout(timeout) BaseRequestSettings[source]

Indicates that client is no longer interested in the result of operation after the specified duration starting from the time operation arrives at the server. Server will try to stop the execution of operation and if no result is currently available the operation will receive TIMEOUT status code, which will be sent back to client if it was waiting for the operation result. Timeout of operation does not tell anything about its result, it might be completed successfully or cancelled on server. :param timeout: :return: The self instance

Return type:

BaseRequestSettings

with_cancel_after(timeout) BaseRequestSettings[source]

Server will try to cancel the operation after the specified duration starting from the time the operation arrives at server. In case of successful cancellation operation will receive CANCELLED status code, which will be sent back to client if it was waiting for the operation result. In case when cancellation isn’t possible, no action will be performed. :param timeout: :return: The self instance

Return type:

BaseRequestSettings

with_timeout(timeout) BaseRequestSettings[source]

Client-side timeout to complete request. Since YDB doesn’t support request cancellation at this moment, this feature should be used properly to avoid server overload. :param timeout: timeout value in seconds :return: The self instance

Return type:

BaseRequestSettings

RetrySettings

class ydb.RetrySettings(max_retries=10, max_session_acquire_timeout=None, on_ydb_error_callback=None, backoff_ceiling=6, backoff_slot_duration=1, get_session_client_timeout=5, fast_backoff_settings=None, slow_backoff_settings=None, idempotent=False)[source]
with_fast_backoff(backoff_settings)[source]
with_slow_backoff(backoff_settings)[source]

Result Sets

class ydb.convert._ResultSet(columns, rows, truncated, snapshot=None)[source]
columns
rows
truncated
snapshot
classmethod from_message(message, table_client_settings=None, snapshot=None)[source]
classmethod lazy_from_message(message, table_client_settings=None, snapshot=None)[source]

Query Service

QueryClientSettings

class ydb.QueryClientSettings[source]
with_native_timestamp_in_result_sets(enabled: bool) QueryClientSettings[source]
Parameters:

enabled (bool)

Return type:

QueryClientSettings

with_native_interval_in_result_sets(enabled: bool) QueryClientSettings[source]
Parameters:

enabled (bool)

Return type:

QueryClientSettings

with_native_json_in_result_sets(enabled: bool) QueryClientSettings[source]
Parameters:

enabled (bool)

Return type:

QueryClientSettings

with_native_date_in_result_sets(enabled: bool) QueryClientSettings[source]
Parameters:

enabled (bool)

Return type:

QueryClientSettings

with_native_datetime_in_result_sets(enabled: bool) QueryClientSettings[source]
Parameters:

enabled (bool)

Return type:

QueryClientSettings

QuerySessionPool

class ydb.QuerySessionPool(driver: Driver | Driver, size: int = 100, *, query_client_settings: QueryClientSettings | None = None)[source]

QuerySessionPool is an object to simplify operations with sessions of Query Service.

Parameters:
  • driver (Driver | Driver) – A driver instance.

  • size (int) – Max size of Session Pool.

  • query_client_settings (QueryClientSettings | None) – ydb.QueryClientSettings object to configure QueryService behavior

acquire(timeout: float | None = None) QuerySession[source]

Acquire a session from Session Pool.

Parameters:

timeout (float | None) – A timeout to wait in seconds.

Return type:

QuerySession

:return A QuerySession object.

release(session: QuerySession) None[source]

Release a session back to Session Pool.

Parameters:

session (QuerySession)

Return type:

None

checkout(timeout: float | None = None) SimpleQuerySessionCheckout[source]

Return a Session context manager, that acquires session on enter and releases session on exit.

Parameters:

timeout (float | None) – A timeout to wait in seconds.

Return type:

SimpleQuerySessionCheckout

retry_operation_sync(callee: Callable, retry_settings: RetrySettings | None = None, *args, **kwargs)[source]

Special interface to execute a bunch of commands with session in a safe, retriable way.

Parameters:
  • callee (Callable) – A function, that works with session.

  • retry_settings (RetrySettings | None) – RetrySettings object.

Returns:

Result sets or exception in case of execution errors.

execute_with_retries(query: str, parameters: dict | None = None, retry_settings: RetrySettings | None = None, *args, **kwargs) List[_ResultSet][source]

Special interface to execute a one-shot queries in a safe, retriable way. Note: this method loads all data from stream before return, do not use this method with huge read queries.

Parameters:
  • query (str) – A query, yql or sql text.

  • parameters (dict | None) – dict with parameters and YDB types;

  • retry_settings (RetrySettings | None) – RetrySettings object.

Returns:

Result sets or exception in case of execution errors.

Return type:

List[_ResultSet]

stop(timeout=None)[source]

QuerySession

class ydb.QuerySession(driver: Driver | Driver, settings: QueryClientSettings | None = None)[source]

Session object for Query Service. It is not recommended to control session’s lifecycle manually - use a QuerySessionPool is always a better choise.

Parameters:
delete(settings: BaseRequestSettings | None = None) None[source]

Deletes a Session of Query Service on server side and releases resources.

Returns:

None

Parameters:

settings (BaseRequestSettings | None)

Return type:

None

create(settings: BaseRequestSettings | None = None) QuerySession[source]

Creates a Session of Query Service on server side and attaches it.

Returns:

QuerySession object.

Parameters:

settings (BaseRequestSettings | None)

Return type:

QuerySession

transaction(tx_mode: BaseQueryTxMode | None = None) QueryTxContext[source]

Creates a transaction context manager with specified transaction mode.

Parameters:

tx_mode (BaseQueryTxMode | None) – Transaction mode, which is a one from the following choises: 1) QuerySerializableReadWrite() which is default mode; 2) QueryOnlineReadOnly(allow_inconsistent_reads=False); 3) QuerySnapshotReadOnly(); 4) QueryStaleReadOnly().

Return type:

QueryTxContext

:return transaction context manager.

execute(query: str, parameters: dict | None = None, syntax: QuerySyntax | None = None, exec_mode: QueryExecMode | None = None, concurrent_result_sets: bool = False, settings: BaseRequestSettings | None = None) SyncResponseContextIterator[source]

Sends a query to Query Service

Parameters:
  • query (str) – (YQL or SQL text) to be executed.

  • syntax (QuerySyntax | None) – Syntax of the query, which is a one from the following choises: 1) QuerySyntax.YQL_V1, which is default; 2) QuerySyntax.PG.

  • parameters (dict | None) – dict with parameters and YDB types;

  • concurrent_result_sets (bool) – A flag to allow YDB mix parts of different result sets. Default is False;

  • exec_mode (QueryExecMode | None)

  • settings (BaseRequestSettings | None)

Returns:

Iterator with result sets

Return type:

SyncResponseContextIterator

QueryTxContext

class ydb.QueryTxContext(driver, session_state, session, tx_mode)[source]

An object that provides a simple transaction context manager that allows statements execution in a transaction. You don’t have to open transaction explicitly, because context manager encapsulates transaction control logic, and opens new transaction if:

  1. By explicit .begin() method;

  2. On execution of a first statement, which is strictly recommended method, because that avoids useless round trip

This context manager is not thread-safe, so you should not manipulate on it concurrently.

Parameters:
  • driver – A driver instance

  • session_state – A state of session

  • tx_mode – Transaction mode, which is a one from the following choises: 1) QuerySerializableReadWrite() which is default mode; 2) QueryOnlineReadOnly(allow_inconsistent_reads=False); 3) QuerySnapshotReadOnly(); 4) QueryStaleReadOnly().

begin(settings: BaseRequestSettings | None = None) QueryTxContext[source]

Explicitly begins a transaction

Parameters:

settings (BaseRequestSettings | None) – An additional request settings BaseRequestSettings;

Returns:

Transaction object or exception if begin is failed

Return type:

QueryTxContext

commit(settings: BaseRequestSettings | None = None) None[source]

Calls commit on a transaction if it is open otherwise is no-op. If transaction execution failed then this method raises PreconditionFailed.

Parameters:

settings (BaseRequestSettings | None) – An additional request settings BaseRequestSettings;

Returns:

A committed transaction or exception if commit is failed

Return type:

None

rollback(settings: BaseRequestSettings | None = None) None[source]

Calls rollback on a transaction if it is open otherwise is no-op. If transaction execution failed then this method raises PreconditionFailed.

Parameters:

settings (BaseRequestSettings | None) – An additional request settings BaseRequestSettings;

Returns:

A committed transaction or exception if commit is failed

Return type:

None

execute(query: str, parameters: dict | None = None, commit_tx: bool | None = False, syntax: QuerySyntax | None = None, exec_mode: QueryExecMode | None = None, concurrent_result_sets: bool | None = False, settings: BaseRequestSettings | None = None) SyncResponseContextIterator[source]

Sends a query to Query Service

Parameters:
  • query (str) – (YQL or SQL text) to be executed.

  • parameters (dict | None) – dict with parameters and YDB types;

  • commit_tx (bool | None) – A special flag that allows transaction commit.

  • syntax (QuerySyntax | None) – Syntax of the query, which is a one from the following choises: 1) QuerySyntax.YQL_V1, which is default; 2) QuerySyntax.PG.

  • exec_mode (QueryExecMode | None) – Exec mode of the query, which is a one from the following choises: 1) QueryExecMode.EXECUTE, which is default; 2) QueryExecMode.EXPLAIN; 3) QueryExecMode.VALIDATE; 4) QueryExecMode.PARSE.

  • concurrent_result_sets (bool | None) – A flag to allow YDB mix parts of different result sets. Default is False;

  • settings (BaseRequestSettings | None) – An additional request settings BaseRequestSettings;

Returns:

Iterator with result sets

Return type:

SyncResponseContextIterator

property session_id: str

A transaction’s session id

Returns:

A transaction’s session id

property tx_id: str | None

Returns an id of open transaction or None otherwise

Returns:

An id of open transaction or None otherwise

QuerySessionPool (AsyncIO)

class ydb.aio.QuerySessionPool(driver: Driver | Driver, size: int = 100, *, query_client_settings: QueryClientSettings | None = None, loop: AbstractEventLoop | None = None)[source]

QuerySessionPool is an object to simplify operations with sessions of Query Service.

Parameters:
  • driver (Driver | Driver) – A driver instance

  • size (int) – Size of session pool

  • query_client_settings (QueryClientSettings | None) – ydb.QueryClientSettings object to configure QueryService behavior

  • loop (AbstractEventLoop | None)

async acquire() QuerySession[source]

Acquire a session from Session Pool.

:return A QuerySession object.

Return type:

QuerySession

async release(session: QuerySession) None[source]

Release a session back to Session Pool.

Parameters:

session (QuerySession)

Return type:

None

checkout() SimpleQuerySessionCheckoutAsync[source]

Return a Session context manager, that acquires session on enter and releases session on exit.

Return type:

SimpleQuerySessionCheckoutAsync

async retry_operation_async(callee: Callable, retry_settings: RetrySettings | None = None, *args, **kwargs)[source]

Special interface to execute a bunch of commands with session in a safe, retriable way.

Parameters:
  • callee (Callable) – A function, that works with session.

  • retry_settings (RetrySettings | None) – RetrySettings object.

Returns:

Result sets or exception in case of execution errors.

async execute_with_retries(query: str, parameters: dict | None = None, retry_settings: RetrySettings | None = None, *args, **kwargs) List[_ResultSet][source]

Special interface to execute a one-shot queries in a safe, retriable way. Note: this method loads all data from stream before return, do not use this method with huge read queries.

Parameters:
  • query (str) – A query, yql or sql text.

  • parameters (dict | None) – dict with parameters and YDB types;

  • retry_settings (RetrySettings | None) – RetrySettings object.

Returns:

Result sets or exception in case of execution errors.

Return type:

List[_ResultSet]

async stop()[source]

QuerySession (AsyncIO)

class ydb.aio.QuerySession(driver: Driver | Driver, settings: QueryClientSettings | None = None, loop: AbstractEventLoop | None = None)[source]

Session object for Query Service. It is not recommended to control session’s lifecycle manually - use a QuerySessionPool is always a better choise.

Parameters:
async delete(settings: BaseRequestSettings | None = None) None[source]

Deletes a Session of Query Service on server side and releases resources.

Returns:

None

Parameters:

settings (BaseRequestSettings | None)

Return type:

None

async create(settings: BaseRequestSettings | None = None) QuerySession[source]

Creates a Session of Query Service on server side and attaches it.

Returns:

QuerySession object.

Parameters:

settings (BaseRequestSettings | None)

Return type:

QuerySession

transaction(tx_mode=None) QueryTxContext[source]
Return type:

QueryTxContext

async execute(query: str, parameters: dict | None = None, syntax: QuerySyntax | None = None, exec_mode: QueryExecMode | None = None, concurrent_result_sets: bool = False, settings: BaseRequestSettings | None = None) AsyncResponseContextIterator[source]

Sends a query to Query Service

Parameters:
  • query (str) – (YQL or SQL text) to be executed.

  • syntax (QuerySyntax | None) – Syntax of the query, which is a one from the following choises: 1) QuerySyntax.YQL_V1, which is default; 2) QuerySyntax.PG.

  • parameters (dict | None) – dict with parameters and YDB types;

  • concurrent_result_sets (bool) – A flag to allow YDB mix parts of different result sets. Default is False;

  • exec_mode (QueryExecMode | None)

  • settings (BaseRequestSettings | None)

Returns:

Iterator with result sets

Return type:

AsyncResponseContextIterator

QueryTxContext (AsyncIO)

class ydb.aio.QueryTxContext(driver, session_state, session, tx_mode)[source]

An object that provides a simple transaction context manager that allows statements execution in a transaction. You don’t have to open transaction explicitly, because context manager encapsulates transaction control logic, and opens new transaction if:

  1. By explicit .begin() method;

  2. On execution of a first statement, which is strictly recommended method, because that avoids useless round trip

This context manager is not thread-safe, so you should not manipulate on it concurrently.

Parameters:
  • driver – A driver instance

  • session_state – A state of session

  • tx_mode – Transaction mode, which is a one from the following choises: 1) QuerySerializableReadWrite() which is default mode; 2) QueryOnlineReadOnly(allow_inconsistent_reads=False); 3) QuerySnapshotReadOnly(); 4) QueryStaleReadOnly().

async begin(settings: BaseRequestSettings | None = None) QueryTxContext[source]

Explicitly begins a transaction

Parameters:

settings (BaseRequestSettings | None) – An additional request settings BaseRequestSettings;

Returns:

None or exception if begin is failed

Return type:

QueryTxContext

async commit(settings: BaseRequestSettings | None = None) None[source]

Calls commit on a transaction if it is open otherwise is no-op. If transaction execution failed then this method raises PreconditionFailed.

Parameters:

settings (BaseRequestSettings | None) – An additional request settings BaseRequestSettings;

Returns:

A committed transaction or exception if commit is failed

Return type:

None

async rollback(settings: BaseRequestSettings | None = None) None[source]

Calls rollback on a transaction if it is open otherwise is no-op. If transaction execution failed then this method raises PreconditionFailed.

Parameters:

settings (BaseRequestSettings | None) – An additional request settings BaseRequestSettings;

Returns:

A committed transaction or exception if commit is failed

Return type:

None

async execute(query: str, parameters: dict | None = None, commit_tx: bool | None = False, syntax: QuerySyntax | None = None, exec_mode: QueryExecMode | None = None, concurrent_result_sets: bool | None = False, settings: BaseRequestSettings | None = None) AsyncResponseContextIterator[source]

Sends a query to Query Service

Parameters:
  • query (str) – (YQL or SQL text) to be executed.

  • parameters (dict | None) – dict with parameters and YDB types;

  • commit_tx (bool | None) – A special flag that allows transaction commit.

  • syntax (QuerySyntax | None) – Syntax of the query, which is a one from the following choises: 1) QuerySyntax.YQL_V1, which is default; 2) QuerySyntax.PG.

  • exec_mode (QueryExecMode | None) – Exec mode of the query, which is a one from the following choises: 1) QueryExecMode.EXECUTE, which is default; 2) QueryExecMode.EXPLAIN; 3) QueryExecMode.VALIDATE; 4) QueryExecMode.PARSE.

  • concurrent_result_sets (bool | None) – A flag to allow YDB mix parts of different result sets. Default is False;

  • settings (BaseRequestSettings | None)

Returns:

Iterator with result sets

Return type:

AsyncResponseContextIterator

property session_id: str

A transaction’s session id

Returns:

A transaction’s session id

property tx_id: str | None

Returns an id of open transaction or None otherwise

Returns:

An id of open transaction or None otherwise

Query Tx Mode

class ydb.BaseQueryTxMode[source]

Abstract class for Query Transaction Modes.

class ydb.QueryOnlineReadOnly(allow_inconsistent_reads: bool = False)[source]

Each read operation in the transaction is reading the data that is most recent at execution time. The consistency of retrieved data depends on the allow_inconsistent_reads setting:

  • false (consistent reads): Each individual read operation returns consistent data, but no consistency is guaranteed between reads. Reading the same table range twice may return different results.

  • true (inconsistent reads): Even the data fetched by a particular read operation may contain inconsistent results.

Parameters:

allow_inconsistent_reads (bool)

with_allow_inconsistent_reads() QueryOnlineReadOnly[source]
Return type:

QueryOnlineReadOnly

class ydb.QuerySerializableReadWrite[source]

This mode guarantees that the result of successful parallel transactions is equivalent to their serial execution, and there are no read anomalies for successful transactions.

class ydb.QuerySnapshotReadOnly[source]

All the read operations within a transaction access the database snapshot. All the data reads are consistent. The snapshot is taken when the transaction begins, meaning the transaction sees all changes committed before it began.

class ydb.QueryStaleReadOnly[source]

Read operations within a transaction may return results that are slightly out-of-date (lagging by fractions of a second). Each individual read returns consistent data, but no consistency between different reads is guaranteed.


Table Service

TableClient

class ydb.TableClient(driver: Driver, table_client_settings: TableClientSettings | None = None)[source]
Parameters:
async_scan_query(query: ydb.ScanQuery, parameters: tuple = None, settings: ydb.BaseRequestSettings = None) ydb.AsyncResponseIterator[source]
Parameters:
Return type:

ydb.AsyncResponseIterator

async_bulk_upsert(table_path: str, rows: list, column_types: AbstractTypeBuilder | PrimitiveType, settings: BaseRequestSettings = None) None[source]
Parameters:
  • table_path (str)

  • rows (list)

  • column_types (AbstractTypeBuilder | PrimitiveType)

  • settings (BaseRequestSettings)

Return type:

None

create_table(path: str, table_description: TableDescription, settings: BaseRequestSettings | None = None) Operation[source]

Create a YDB table.

Parameters:
  • path (str) – A table path

  • table_description (TableDescription) – TableDescription instanse.

  • settings (BaseRequestSettings | None) – An instance of BaseRequestSettings that describes how rpc should be invoked.

Returns:

Operation or YDB error otherwise.

Return type:

Operation

drop_table(path: str, settings: BaseRequestSettings | None = None) Operation[source]

Drop a YDB table.

Parameters:
  • path (str) – A table path

  • settings (BaseRequestSettings | None) – An instance of BaseRequestSettings that describes how rpc should be invoked.

Returns:

Operation or YDB error otherwise.

Return type:

Operation

alter_table(path: str, add_columns: List[Column] | None = None, drop_columns: List[str] | None = None, settings: BaseRequestSettings | None = None, alter_attributes: Dict[str, str] | None = None, add_indexes: List[TableIndex] | None = None, drop_indexes: List[str] | None = None, set_ttl_settings: TtlSettings | None = None, drop_ttl_settings: Any | None = None, add_column_families: List[ColumnFamily] | None = None, alter_column_families: List[ColumnFamily] | None = None, alter_storage_settings: StorageSettings | None = None, set_compaction_policy: str | None = None, alter_partitioning_settings: PartitioningSettings | None = None, set_key_bloom_filter: FeatureFlag | None = None, set_read_replicas_settings: ReadReplicasSettings | None = None) Operation[source]

Alter a YDB table.

Parameters:
  • path (str) – A table path

  • add_columns (List[Column] | None) – List of ydb.Column to add

  • drop_columns (List[str] | None) – List of column names to drop

  • settings (BaseRequestSettings | None) – An instance of BaseRequestSettings that describes how rpc should be invoked.

  • alter_attributes (Dict[str, str] | None) – Dict of attributes to alter

  • add_indexes (List[TableIndex] | None) – List of ydb.TableIndex to add

  • drop_indexes (List[str] | None) – List of index names to drop

  • set_ttl_settings (TtlSettings | None) – ydb.TtlSettings to set

  • drop_ttl_settings (Any | None) – Any to drop

  • add_column_families (List[ColumnFamily] | None) – List of ydb.ColumnFamily to add

  • alter_column_families (List[ColumnFamily] | None) – List of ydb.ColumnFamily to alter

  • alter_storage_settings (StorageSettings | None) – ydb.StorageSettings to alter

  • set_compaction_policy (str | None) – Compaction policy

  • alter_partitioning_settings (PartitioningSettings | None) – ydb.PartitioningSettings to alter

  • set_key_bloom_filter (FeatureFlag | None) – ydb.FeatureFlag to set key bloom filter

  • set_read_replicas_settings (ReadReplicasSettings | None)

Returns:

Operation or YDB error otherwise.

Return type:

Operation

describe_table(path: str, settings: BaseRequestSettings | None = None) TableSchemeEntry[source]

Describe a YDB table.

Parameters:
  • path (str) – A table path

  • settings (BaseRequestSettings | None) – An instance of BaseRequestSettings that describes how rpc should be invoked.

Returns:

TableSchemeEntry or YDB error otherwise.

Return type:

TableSchemeEntry

copy_table(source_path: str, destination_path: str, settings: BaseRequestSettings | None = None) Operation[source]

Copy a YDB table.

Parameters:
  • source_path (str) – A table path

  • destination_path (str) – Destination table path

  • settings (BaseRequestSettings | None) – An instance of BaseRequestSettings that describes how rpc should be invoked.

Returns:

Operation or YDB error otherwise.

Return type:

Operation

copy_tables(source_destination_pairs: List[Tuple[str, str]], settings: BaseRequestSettings | None = None) Operation[source]

Copy a YDB tables.

Parameters:
  • source_destination_pairs (List[Tuple[str, str]]) – List of tuples (source_path, destination_path)

  • settings (BaseRequestSettings | None) – An instance of BaseRequestSettings that describes how rpc should be invoked.

Returns:

Operation or YDB error otherwise.

Return type:

Operation

rename_tables(rename_items: List[Tuple[str, str]], settings: BaseRequestSettings | None = None) Operation[source]

Rename a YDB tables.

Parameters:
  • rename_items (List[Tuple[str, str]]) – List of tuples (current_name, desired_name)

  • settings (BaseRequestSettings | None) – An instance of BaseRequestSettings that describes how rpc should be invoked.

Returns:

Operation or YDB error otherwise.

Return type:

Operation

bulk_upsert(table_path: str, rows: list, column_types: AbstractTypeBuilder | PrimitiveType, settings: BaseRequestSettings | None = None) None

Bulk upsert data

Parameters:
  • table_path (str) – A table path.

  • rows (list) – A list of structures.

  • column_types (AbstractTypeBuilder | PrimitiveType) – Bulk upsert column types.

  • settings (BaseRequestSettings | None)

Return type:

None

scan_query(query: ydb.ScanQuery, parameters: tuple = None, settings: ydb.BaseRequestSettings = None) ydb.SyncResponseIterator
Parameters:
Return type:

ydb.SyncResponseIterator

session() Session
Return type:

Session

TableClientSettings

class ydb.TableClientSettings[source]
with_native_timestamp_in_result_sets(enabled: bool) TableClientSettings[source]
Parameters:

enabled (bool)

Return type:

TableClientSettings

with_native_interval_in_result_sets(enabled: bool) TableClientSettings[source]
Parameters:

enabled (bool)

Return type:

TableClientSettings

with_native_json_in_result_sets(enabled: bool) TableClientSettings[source]
Parameters:

enabled (bool)

Return type:

TableClientSettings

with_native_date_in_result_sets(enabled: bool) TableClientSettings[source]
Parameters:

enabled (bool)

Return type:

TableClientSettings

with_native_datetime_in_result_sets(enabled: bool) TableClientSettings[source]
Parameters:

enabled (bool)

Return type:

TableClientSettings

with_client_query_cache(enabled: bool) TableClientSettings[source]
Parameters:

enabled (bool)

Return type:

TableClientSettings

with_lazy_result_sets(enabled: bool) TableClientSettings[source]
Parameters:

enabled (bool)

Return type:

TableClientSettings

with_allow_truncated_result(enabled: bool) TableClientSettings[source]
Parameters:

enabled (bool)

Return type:

TableClientSettings

Session Pool

class ydb.SessionPool(driver, size=100, workers_threads_count=4, initializer=None, min_pool_size=0)[source]

An object that encapsulates session creation, deletion and etc. and maintains a pool of active sessions of specified size

Parameters:
  • driver – A Driver instance

  • size – A maximum number of sessions to maintain in the pool

retry_operation_sync(callee, retry_settings=None, *args, **kwargs)[source]
property active_size
property free_size
property busy_size
property max_size
property waiters_count
subscribe()[source]
unsubscribe(waiter)[source]
acquire(blocking=True, timeout=None)[source]
release(session)[source]
async_checkout()[source]

Returns a context manager that asynchronously checkouts a session from the pool.

checkout(blocking=True, timeout=None)[source]
stop(timeout=None)[source]

Session

class ydb.Session(driver, table_client_settings)[source]
async_read_table(path, key_range=None, columns=(), ordered=False, row_limit=None, settings=None, use_snapshot=None)[source]

Perform an read table request.

Parameters:
  • path – A path to the table

  • key_range – (optional) A KeyRange instance that describes a range to read. The KeyRange instance should include from_bound and/or to_bound. Each of the bounds (if provided) should specify a value of the key bound, and type of the key prefix. See an example above.

  • columns – (optional) An iterable with table columns to read.

  • ordered – (optional) A flag that indicates that result should be ordered.

  • row_limit – (optional) A number of rows to read.

Returns:

AsyncResponseIterator instance

async_keep_alive(settings=None)[source]
async_create(settings=None)[source]
async_delete(settings=None)[source]
async_execute_scheme(yql_text, settings=None)[source]
async_prepare(query, settings=None)[source]
async_create_table(path, table_description, settings=None)[source]
async_drop_table(path, settings=None)[source]
async_alter_table(path, add_columns=None, drop_columns=None, settings=None, alter_attributes=None, add_indexes=None, drop_indexes=None, set_ttl_settings=None, drop_ttl_settings=None, add_column_families=None, alter_column_families=None, alter_storage_settings=None, set_compaction_policy=None, alter_partitioning_settings=None, set_key_bloom_filter=None, set_read_replicas_settings=None)[source]
async_copy_table(source_path, destination_path, settings=None)[source]
async_copy_tables(source_destination_pairs, settings=None)[source]
async_rename_tables(rename_tables, settings=None)[source]
async_describe_table(path, settings=None)[source]
alter_table(path, add_columns=None, drop_columns=None, settings=None, alter_attributes=None, add_indexes=None, drop_indexes=None, set_ttl_settings=None, drop_ttl_settings=None, add_column_families=None, alter_column_families=None, alter_storage_settings=None, set_compaction_policy=None, alter_partitioning_settings=None, set_key_bloom_filter=None, set_read_replicas_settings=None)
closing()

Returns True if session is closing.

copy_table(source_path, destination_path, settings=None)
copy_tables(source_destination_pairs, settings=None)
create(settings=None)
create_table(path, table_description, settings=None)

Create a YDB table.

Parameters:
  • path – A table path

  • table_description – A description of table to create. An instance TableDescription

  • settings – An instance of BaseRequestSettings that describes how rpc should invoked.

Returns:

A description of created scheme entry or error otherwise.

delete(settings=None)
describe_table(path, settings=None)

Returns a description of the table by provided path

Parameters:
  • path – A table path

  • settings – A request settings

Returns:

Description of a table

drop_table(path, settings=None)
execute_scheme(yql_text, settings=None)
explain(yql_text, settings=None)

Expiremental API.

Parameters:
  • yql_text

  • settings

Returns:

has_prepared(query)
initialized()

Return True if session is successfully initialized with a session_id and False otherwise.

keep_alive(settings=None)
pending_query()
prepare(query, settings=None)
read_table(path, key_range=None, columns=(), ordered=False, row_limit=None, settings=None, use_snapshot=None)

Perform an read table request.

Parameters:
  • path – A path to the table

  • key_range – (optional) A KeyRange instance that describes a range to read. The KeyRange instance should include from_bound and/or to_bound. Each of the bounds (if provided) should specify a value of the key bound, and type of the key prefix. See an example above.

  • columns – (optional) An iterable with table columns to read.

  • ordered – (optional) A flag that indicates that result should be ordered.

  • row_limit – (optional) A number of rows to read.

Returns:

SyncResponseIterator instance

rename_tables(rename_items, settings=None)
reset()

Perform session state reset (that includes cleanup of the session_id, query cache, and etc.)

property session_id

Return session_id.

transaction(tx_mode=None, allow_split_transactions=None)

Transaction Context

class ydb.TxContext(driver, session_state, session, tx_mode=None, *, allow_split_transactions=None)[source]

An object that provides a simple transaction context manager that allows statements execution in a transaction. You don’t have to open transaction explicitly, because context manager encapsulates transaction control logic, and opens new transaction if:

  1. By explicit .begin() and .async_begin() methods;

  2. On execution of a first statement, which is strictly recommended method, because that avoids useless round trip

This context manager is not thread-safe, so you should not manipulate on it concurrently.

Parameters:
  • driver – A driver instance

  • session_state – A state of session

  • tx_mode – A transaction mode, which is a one from the following choices: 1) SerializableReadWrite() which is default mode; 2) OnlineReadOnly(); 3) StaleReadOnly().

async_execute(query, parameters=None, commit_tx=False, settings=None)[source]

Sends a query (yql text or an instance of DataQuery) to be executed with parameters. Execution with parameters supported only for DataQuery instances and not supported for YQL text.

Parameters:
  • query – A query: YQL text or DataQuery instance. E

  • parameters – A dictionary with parameters values.

  • commit_tx – A special flag that allows transaction commit

  • settings – A request settings (an instance of ExecDataQuerySettings)

Returns:

A future of query execution

async_commit(settings=None)[source]

Calls commit on a transaction if it is open otherwise is no-op. If transaction execution failed then this method raises PreconditionFailed.

Parameters:

settings – A request settings (an instance of BaseRequestSettings)

Returns:

A future of commit call

async_rollback(settings=None)[source]

Calls rollback on a transaction if it is open otherwise is no-op. If transaction execution failed then this method raises PreconditionFailed.

Parameters:

settings – A request settings

Returns:

A future of rollback call

async_begin(settings=None)[source]

Explicitly begins a transaction

Parameters:

settings – A request settings

Returns:

A future of begin call

session
begin(settings=None)

Explicitly begins a transaction

Parameters:

settings – A request settings

Returns:

An open transaction

commit(settings=None)

Calls commit on a transaction if it is open otherwise is no-op. If transaction execution failed then this method raises PreconditionFailed.

Parameters:

settings – A request settings

Returns:

A committed transaction or exception if commit is failed

execute(query, parameters=None, commit_tx=False, settings=None)

Sends a query (yql text or an instance of DataQuery) to be executed with parameters. Execution with parameters supported only for DataQuery instances and is not supported yql text queries.

Parameters:
  • query – A query, yql text or DataQuery instance.

  • parameters – A dictionary with parameters values.

  • commit_tx – A special flag that allows transaction commit

  • settings – An additional request settings

Returns:

A result sets or exception in case of execution errors

rollback(settings=None)

Calls rollback on a transaction if it is open otherwise is no-op. If transaction execution failed then this method raises PreconditionFailed.

Parameters:

settings – A request settings

Returns:

A rolled back transaction or exception if rollback is failed

property session_id

A transaction’s session id

Returns:

A transaction’s session id

property tx_id

Returns a id of open transaction or None otherwise

Returns:

A id of open transaction or None otherwise

DataQuery

class ydb.DataQuery(query_id: str, parameters_types: dict[str, Type], name: str | None = None)[source]
Parameters:
  • query_id (str)

  • parameters_types (dict[str, ydb_value_pb2.Type])

  • name (Optional[str])

yql_text
parameters_types
name

Scheme

SchemeClient

class ydb.SchemeClient(driver)[source]
async_make_directory(path, settings=None)[source]
async_remove_directory(path, settings=None)[source]
async_list_directory(path, settings=None)[source]
async_describe_path(path, settings=None)[source]
async_modify_permissions(path, settings)[source]

Modifies permissions for provided scheme entry

Parameters:
  • path – A path of scheme entry

  • settings – An instance of ModifyPermissionsSettings

Returns:

An future of computation

describe_path(path, settings=None)
list_directory(path, settings=None)
make_directory(path, settings=None)
modify_permissions(path, settings)

Modifies permissions for provided scheme entry

Parameters:
  • path – A path of scheme entry

  • settings – An instance of ModifyPermissionsSettings

Returns:

An operation if success or exception on case of failure

remove_directory(path, settings=None)