firebird.driver.core

This is the main code module of the Firebird driver.

Constants and variables

C integer limit constants

  • SHRT_MIN

  • SHRT_MAX

  • USHRT_MAX

  • INT_MIN

  • INT_MAX

  • UINT_MAX

  • LONG_MIN

  • LONG_MAX

Translation dictionaries

firebird.driver.core.CHARSET_MAP

Python dictionary that maps Firebird character set names (key) to Python character sets (value).

Other constants and variables

firebird.driver.core.MAX_BLOB_SEGMENT_SIZE = 65535

Max BLOB segment size

firebird.driver.core.FS_ENCODING

Current filesystem encoding

firebird.driver.core._master

Firebird iMaster interface

firebird.driver.core._util

Firebird iUtil interface

firebird.driver.core.TIMEOUT: Sentinel

Sentinel that denotes timeout expiration

Context managers

firebird.driver.core.transaction(transact_object: Transactional, *, tpb: bytes = None, bypass: bool = False) Transactional[source]

Context manager for Transactional objects.

Starts new transaction when context is entered. On exit calls rollback() when exception was raised, or commit() if there was no error. Exception raised in managed context is NOT suppressed.

Parameters:
  • transact_object (Transactional) – Managed transactional object.

  • tpb (bytes) – Transaction parameter buffer used to start the transaction.

  • bypass (bool) – When both bypass and transact_object.is_active() are True when context is entered, the context manager does nothing on exit.

Return type:

Transactional

firebird.driver.core.temp_database(*args, **kwargs) Connection[source]

Context manager for temporary databases. Creates new database when context is entered, and drops it on exit. Exception raised in managed context is NOT suppressed.

All positional and keyword arguments are passed to create_database.

Return type:

Connection

Functions

firebird.driver.core.connect(database: str, *, user: str = None, password: str = None, role: str = None, no_gc: bool = None, no_db_triggers: bool = None, dbkey_scope: DBKeyScope = None, crypt_callback: iCryptKeyCallbackImpl = None, charset: str = None, auth_plugin_list: str = None, session_time_zone: str = None) Connection[source]

Establishes a connection to the database.

Parameters:
  • database (str) – DSN or Database configuration name.

  • user (str) – User name.

  • password (str) – User password.

  • role (str) – User role.

  • no_gc (bool) – Do not perform garbage collection for this connection.

  • no_db_triggers (bool) – Do not execute database triggers for this connection.

  • dbkey_scope (DBKeyScope) – DBKEY scope override for connection.

  • crypt_callback (iCryptKeyCallbackImpl) – Callback that provides encryption key for the database.

  • charset (str) – Character set for connection.

  • auth_plugin_list (str) – List of authentication plugins override

  • session_time_zone (str) – Session time zone [Firebird 4]

Return type:

Connection

Hooks:

Event ConnectionHook.ATTACH_REQUEST: Executed after all parameters are preprocessed and before Connection is created. Hook must have signature:

hook_func(dsn: str, dpb: bytes) -> Optional[Connection]

Hook may return Connection instance or None. First instance returned by any hook will become the return value of this function and other hooks are not called.

Event ConnectionHook.ATTACHED: Executed before Connection instance is returned. Hook must have signature:

hook_func(connection: Connection) -> None

Any value returned by hook is ignored.

firebird.driver.core.create_database(database: str, *, user: str = None, password: str = None, role: str = None, no_gc: bool = None, no_db_triggers: bool = None, dbkey_scope: DBKeyScope = None, crypt_callback: iCryptKeyCallbackImpl = None, charset: str = None, overwrite: bool = False, auth_plugin_list=None, session_time_zone: str = None) Connection[source]

Creates new database.

Parameters:
  • database (str) – DSN or Database configuration name.

  • user (str) – User name.

  • password (str) – User password.

  • role (str) – User role.

  • no_gc (bool) – Do not perform garbage collection for this connection.

  • no_db_triggers (bool) – Do not execute database triggers for this connection.

  • dbkey_scope (DBKeyScope) – DBKEY scope override for connection.

  • crypt_callback (iCryptKeyCallbackImpl) – Callback that provides encryption key for the database.

  • charset (str) – Character set for connection.

  • overwrite (bool) – Overwite the existing database.

  • auth_plugin_list – List of authentication plugins override

  • session_time_zone (str) – Session time zone [Firebird 4]

Return type:

Connection

Hooks:

Event ConnectionHook.ATTACHED: Executed before Connection instance is returned. Hook must have signature:

hook_func(connection: Connection) -> None

Any value returned by hook is ignored.

firebird.driver.core.connect_server(server: str, *, user: str = None, password: str = None, crypt_callback: iCryptKeyCallbackImpl = None, expected_db: str = None, role: str = None, encoding: str = None, encoding_errors: str = None) Server[source]

Establishes a connection to server’s service manager.

Parameters:
  • server (str) – Server host machine or Server configuration name.

  • user (str) – User name.

  • password (str) – User password.

  • crypt_callback (iCryptKeyCallbackImpl) – Callback that provides encryption key.

  • expected_db (str) – Database that would be accessed (for using services with non-default security database)

  • role (str) – SQL role used for connection.

  • encoding (str) – Encoding for string values passed in parameter buffer. Default is ServerConfig.encoding.

  • encoding_errors (str) – Error handler used for encoding errors. Default is ServerConfig.encoding_errors.

Return type:

Server

Hooks:

Event ServerHook.ATTACHED: Executed before Service instance is returned. Hook must have signature:

hook_func(server: Server) -> None

Any value returned by hook is ignored.

firebird.driver.core.tpb(isolation: Isolation, lock_timeout: int = -1, access_mode: TraAccessMode = TraAccessMode.WRITE) bytes[source]

Helper function to costruct simple TPB.

Parameters:
  • isolation (Isolation) – Isolation level.

  • lock_timeout (int) – Lock timeout (-1 = Infinity)

  • access – Access mode.

  • access_mode (TraAccessMode)

Return type:

bytes

Managers for parameter buffers

class firebird.driver.core.TPB(*, access_mode: TraAccessMode = TraAccessMode.WRITE, isolation: Isolation = Isolation.SNAPSHOT, lock_timeout: int = -1, no_auto_undo: bool = False, auto_commit: bool = False, ignore_limbo: bool = False, at_snapshot_number: int = None, encoding: str = 'ascii')[source]

Bases: object

Transaction Parameter Buffer.

Parameters:
clear() None[source]

Clear all information.

Return type:

None

get_buffer() bytes[source]

Create TPB from stored information.

Return type:

bytes

parse_buffer(buffer: bytes) None[source]

Load information from TPB.

Parameters:

buffer (bytes)

Return type:

None

reserve_table(name: str, share_mode: TableShareMode, access_mode: TableAccessMode) None[source]

Set information about table reservation.

Parameters:
Return type:

None

class firebird.driver.core.DPB(*, user: str = None, password: str = None, role: str = None, trusted_auth: bool = False, sql_dialect: int = 3, timeout: int = None, charset: str = 'UTF8', cache_size: int = None, no_gc: bool = False, no_db_triggers: bool = False, no_linger: bool = False, utf8filename: bool = False, dbkey_scope: DBKeyScope = None, dummy_packet_interval: int = None, overwrite: bool = False, db_cache_size: int = None, forced_writes: bool = None, reserve_space: bool = None, page_size: int = None, read_only: bool = False, sweep_interval: int = None, db_sql_dialect: int = None, db_charset: str = None, config: str = None, auth_plugin_list: str = None, session_time_zone: str = None, set_db_replica: ReplicaMode = None, set_bind: str = None, decfloat_round: DecfloatRound = None, decfloat_traps: List[DecfloatTraps] = None, parallel_workers: int = None)[source]

Bases: object

Database Parameter Buffer.

Parameters:
clear() None[source]

Clear all information.

Return type:

None

get_buffer(*, for_create: bool = False) bytes[source]

Create DPB from stored information.

Parameters:

for_create (bool)

Return type:

bytes

parse_buffer(buffer: bytes) None[source]

Load information from DPB.

Parameters:

buffer (bytes)

Return type:

None

auth_plugin_list: str

List of authentication plugins override

cache_size: int

Page cache size override for database connection

charset: str

Character set for database connection

config: str | None

Configuration override

db_buffers

Number of pages in database cache [db create only]

db_cache_size: int | None

Database cache size [db create only]

db_charset: str | None

Character set for the database [db create only]

db_sql_dialect: int | None

SQL dialect for the database [db create only]

dbkey_scope: DBKeyScope | None

Scope for RDB$DB_KEY values

decfloat_round: DecfloatRound | None

Set DECFLOAT ROUND [Firebird 4]

decfloat_traps: List[DecfloatTraps] | None

Set DECFLOAT TRAPS [Firebird 4]

dummy_packet_interval: int | None

Dummy packet interval for this database connection

forced_writes: bool | None

Database write mode (True = sync/False = async) [db create only]

no_db_triggers: bool

Disable database triggers for database connection

no_gc: bool

Disable garbage collection for database connection

no_linger: bool

Do not use linger for database connection

overwrite: bool

Overwrite existing database [db create only]

page_size: int | None

Database page size [db create only]

parallel_workers: int

Number of parallel workers

password: str

User password

read_only: bool

Database access mode (True = read-only/False = read-write) [db create only]

reserve_space: bool | None

Database data page space usage (True = reserve space, False = Use all space) [db create only]

role: str

User role

session_time_zone: str | None

Session time zone [Firebird 4]

set_bind: str | None

Set BIND [Firebird 4]

set_db_replica: ReplicaMode | None

Set replica mode [Firebird 4]

sql_dialect: int

SQL Dialect for database connection

sweep_interval: int | None

Sweep interval for the database [db create only]

timeout: int | None

Connection timeout

trusted_auth: bool

Use trusted authentication

user: str

User name

utf8filename: bool

Database filename passed in UTF8

class firebird.driver.core.SPB_ATTACH(*, user: str = None, password: str = None, trusted_auth: bool = False, config: str = None, auth_plugin_list: str = None, expected_db: str = None, encoding: str = 'ascii', errors: str = 'strict', role: str = None)[source]

Bases: object

Service Parameter Buffer.

Parameters:
  • user (str)

  • password (str)

  • trusted_auth (bool)

  • config (str)

  • auth_plugin_list (str)

  • expected_db (str)

  • encoding (str)

  • errors (str)

  • role (str)

clear() None[source]

Clear all information.

Return type:

None

get_buffer() bytes[source]

Create SPB_ATTACH from stored information.

Return type:

bytes

parse_buffer(buffer: bytes) None[source]

Load information from SPB_ATTACH.

Parameters:

buffer (bytes)

Return type:

None

class firebird.driver.core.Buffer(init: int | bytes, size: int = None, *, factory: ~typing.Type[~firebird.base.buffer.BufferFactory] = <class 'firebird.base.buffer.BytesBufferFactory'>, max_size: int | ~firebird.base.types.Sentinel = Sentinel('UNLIMITED'), byteorder: ~firebird.base.types.ByteOrder = ByteOrder.LITTLE)[source]

Bases: MemoryBuffer

MemoryBuffer with extensions.

Parameters:
  • init (Union[int, bytes])

  • size (int)

  • factory (Type[BufferFactory])

  • max_size (Union[int, Sentinel])

  • byteorder (ByteOrder)

get_tag() int[source]

Read 1 byte number (c_ubyte).

Return type:

int

is_truncated() bool[source]

Return True when positioned on isc_info_truncated tag.

Return type:

bool

rewind() None[source]

Set current position in buffer to beginning.

Return type:

None

seek_last_data() int[source]

Set the position in buffer to first non-zero byte when searched from the end of buffer.

Return type:

int

class firebird.driver.core.CBuffer(init: int | bytes, size: int = None, *, max_size: int | Sentinel = Sentinel('UNLIMITED'), byteorder: ByteOrder = ByteOrder.LITTLE)[source]

Bases: Buffer

ctypes MemoryBuffer with extensions.

Parameters:
  • init (Union[int, bytes])

  • size (int)

  • max_size (Union[int, Sentinel])

  • byteorder (ByteOrder)

Classes

class firebird.driver.core.Connection(att: iAttachment, dsn: str, dpb: bytes = None, sql_dialect: int = 3, charset: str = None)[source]

Bases: LoggingIdMixin

Connection to the database.

Note

Implements context manager protocol to call close() automatically.

Parameters:
exception DataError(*args, **kwargs)

Bases: DatabaseError

Exception raised for errors that are due to problems with the processed data like division by zero, numeric value out of range, etc.

Important

This exceptions is never directly thrown by Firebird driver.

exception DatabaseError(*args, **kwargs)

Bases: Error

Exception raised for all errors reported by Firebird.

gds_codes: Tuple[int] = ()

Tuple with all returned GDS error codes

sqlcode: int = None

Returned SQLCODE or None

sqlstate: str = None

Returned SQLSTATE or None

exception Error(*args, **kwargs)

Bases: Exception

Exception that is intended to be used as a base class of all application-related errors. The important difference from Exception class is that Error accepts keyword arguments, that are stored into instance attributes with the same name.

Important

Attribute lookup on this class never fails, as all attributes that are not actually set, have None value.

Example:

try:
    if condition:
        raise Error("Error message", err_code=1)
    else:
        raise Error("Unknown error")
except Error as e:
    if e.err_code is None:
        ...
    elif e.err_code == 1:
        ...

Note

Warnings are not considered errors and thus should not use this class as base.

exception IntegrityError(*args, **kwargs)

Bases: DatabaseError

Exception raised when the relational integrity of the database is affected, e.g. a foreign key check fails.

Important

This exceptions is never directly thrown by Firebird driver.

exception InterfaceError(*args, **kwargs)

Bases: Error

Exception raised for errors that are reported by the driver rather than the Firebird itself.

exception InternalError(*args, **kwargs)

Bases: DatabaseError

Exception raised when the database encounters an internal error, e.g. the cursor is not valid anymore, the transaction is out of sync, etc.

Important

This exceptions is never directly thrown by Firebird driver.

exception NotSupportedError(*args, **kwargs)

Bases: DatabaseError

Exception raised in case a method or database API was used which is not supported by the database.

exception OperationalError(*args, **kwargs)

Bases: DatabaseError

Exception raised for errors that are related to the database’s operation and not necessarily under the control of the programmer, e.g. an unexpected disconnect occurs, the data source name is not found, a transaction could not be processed, a memory allocation error occurred during processing, etc.

Important

This exceptions is never directly thrown by Firebird driver.

exception ProgrammingError(*args, **kwargs)

Bases: DatabaseError

Exception raised for programming errors, e.g. table not found or already exists, syntax error in the SQL statement, wrong number of parameters specified, etc.

Important

This exceptions is never directly thrown by Firebird driver.

exception Warning

Bases: Exception

Base class for warning categories.

begin(tpb: bytes = None) None[source]

Starts new transaction managed by main_transaction.

Parameters:

tpb (bytes) – Transaction parameter buffer with transaction parameters. If not specified, the default_tpb is used.

Return type:

None

close() None[source]

Close the connection and release all associated resources.

Closes all event collectors, transaction managers (with rollback) and statements associated with this connection before attempt (see Hooks) to close the connection itself.

Hooks:

Event ConnectionHook.DETACH_REQUEST: Executed before connection is closed. Hook must have signature:

hook_func(connection: Connection) -> bool

Note

If any hook function returns True, connection is NOT closed.

Event ConnectionHook.CLOSED: Executed after connection is closed. Hook must have signature:

hook_func(connection: Connection) -> None

Any value returned by hook is ignored.

Important

Closed connection SHALL NOT be used anymore.

Return type:

None

commit(*, retaining: bool = False) None[source]

Commits the transaction managed by main_transaction.

Parameters:

retaining (bool) – When True, the transaction context is retained after commit.

Return type:

None

cursor() Cursor[source]

Returns new Cursor instance associated with main_transaction.

Return type:

Cursor

drop_database() None[source]

Drops the connected database.

Note

Closes all event collectors, transaction managers (with rollback) and statements associated with this connection before attempt to drop the database.

Hooks:

Event ConnectionHook.DROPPED: Executed after database is sucessfuly dropped. Hook must have signature:

hook_func(connection: Connection) -> None

Any value returned by hook is ignored.

Return type:

None

event_collector(event_names: Sequence[str]) EventCollector[source]

Create new EventCollector instance for this connection.

Parameters:

event_names (Sequence[str]) – Sequence of database event names to whom the collector should be subscribed.

Return type:

EventCollector

execute_immediate(sql: str) None[source]

Executes SQL statement.

Important

The statement MUST NOT return any result. The statement is executed in the context of main_transaction.

Parameters:

sql (str) – SQL statement to be executed.

Return type:

None

is_active() bool[source]

Returns True if main_transaction has active transaction.

Return type:

bool

is_closed() bool[source]

Returns True if connection to the database is closed.

Important

Closed connection SHALL NOT be used anymore.

Return type:

bool

ping() None[source]

Checks connection status. If test fails the only operation possible with connection is to close it.

Raises:

DatabaseError – When connection is dead.

Return type:

None

rollback(*, retaining: bool = False, savepoint: str = None) None[source]

Rolls back the transaction managed by main_transaction.

Parameters:
  • retaining (bool) – When True, the transaction context is retained after rollback.

  • savepoint (str) – When specified, the transaction is rolled back to savepoint with given name.

Return type:

None

savepoint(name: str) None[source]

Creates a new savepoint for transaction managed by main_transaction.

Parameters:

name (str) – Name for the savepoint

Return type:

None

transaction_manager(default_tpb: bytes = None, default_action: DefaultAction = DefaultAction.COMMIT) TransactionManager[source]

Create new TransactionManager instance for this connection.

Parameters:
  • default_tpb (bytes) – Default Transaction parameter buffer.

  • default_action (DefaultAction) – Default action to be performed on implicit transaction end.

Return type:

TransactionManager

property charset: str

Connection character set.

default_tpb: bytes

Default TPB for newly created transaction managers

property dsn: str

Connection string.

property info: DatabaseInfoProvider3 | DatabaseInfoProvider

Access to various information about attached database.

property main_transaction: TransactionManager

Main transaction manager for this connection.

property monitor: firebird.lib.monitor.Monitor

Access to database monitoring tables. Requires firebird.lib package.

property query_transaction: TransactionManager

Transaction manager for Read-committed Read-only query transactions.

property schema: firebird.lib.schema.Schema

Access to database schema. Requires firebird.lib package.

property sql_dialect: int

Connection SQL dialect.

property transactions: List[TransactionManager]

List of all transaction managers associated with connection.

Note

The first two are always main_transaction and query_transaction managers.

class firebird.driver.core.TransactionManager(connection: Connection, default_tpb: bytes, default_action: DefaultAction = DefaultAction.COMMIT)[source]

Bases: LoggingIdMixin

Transaction manager.

Note

Implements context manager protocol to call close() automatically.

Parameters:
begin(tpb: bytes = None) None[source]

Starts new transaction managed by this instance.

Parameters:

tpb (bytes) – Transaction parameter buffer with transaction’s parameters. If not specified, the default_tpb is used.

Return type:

None

close() None[source]

Close the transaction manager and release all associated resources.

Important

Closed instance SHALL NOT be used anymore.

Return type:

None

commit(*, retaining: bool = False) None[source]

Commits the transaction managed by this instance.

Parameters:

retaining (bool) – When True, the transaction context is retained after commit.

Return type:

None

cursor() Cursor[source]

Returns new Cursor instance associated with this instance.

Return type:

Cursor

execute_immediate(sql: str) None[source]

Executes SQL statement. The statement MUST NOT return any result.

Parameters:

sql (str) – SQL statement to be executed.

Return type:

None

is_active() bool[source]

Returns True if transaction is active.

Return type:

bool

is_closed() bool[source]

Returns True if this transaction manager is closed.

Return type:

bool

rollback(*, retaining: bool = False, savepoint: str = None) None[source]

Rolls back the transaction managed by this instance.

Parameters:
  • retaining (bool) – When True, the transaction context is retained after rollback.

  • savepoint (str) – When specified, the transaction is rolled back to savepoint with given name.

Raises:

InterfaceError – When both retaining and savepoint parameters are specified.

Return type:

None

savepoint(name: str) None[source]

Creates a new savepoint for transaction managed by this instance.

Parameters:

name (str) – Name for the savepoint

Return type:

None

property cursors: List[Cursor]

Cursors associated with this transaction.

default_action: DefaultAction

Default action (commit/rollback) to be performed when transaction is closed.

default_tpb: bytes

Default Transaction Parameter Block used to start transaction

property info: TransactionInfoProvider3 | TransactionInfoProvider

Access to various information about active transaction.

property log_context: Connection

Logging context [connection].

class firebird.driver.core.DistributedTransactionManager(connections: Sequence[Connection], default_tpb: bytes = None, default_action: DefaultAction = DefaultAction.COMMIT)[source]

Bases: TransactionManager

Manages distributed transaction over multiple connections that use two-phase commit protocol.

Note

Implements context manager protocol to call close() automatically.

Parameters:
begin(tpb: bytes = None) None[source]

Starts new distributed transaction managed by this instance.

Parameters:

tpb (bytes) – Transaction parameter buffer with transaction’s parameters. If not specified, the default_tpb is used.

Return type:

None

close() None[source]

Close the distributed transaction manager and release all associated resources.

Important

Closed instance SHALL NOT be used anymore.

Return type:

None

commit(*, retaining: bool = False) None[source]

Commits the distributed transaction managed by this instance.

Parameters:

retaining (bool) – When True, the transaction context is retained after commit.

Return type:

None

cursor(connection: Connection) Cursor[source]

Returns new Cursor instance associated with specified connection and this distributed transaction manager.

Raises:

InterfaceError – When specified connection is not associated with distributed connection manager.

Parameters:

connection (Connection)

Return type:

Cursor

execute_immediate(sql: str) None[source]

Executes SQL statement on all connections in distributed transaction. The statement MUST NOT return any result.

Parameters:

sql (str) – SQL statement to be executed.

Return type:

None

prepare() None[source]

Manually triggers the first phase of a two-phase commit (2PC).

Note

Direct use of this method is optional; if preparation is not triggered manually, it will be performed implicitly by commit() in a 2PC.

Return type:

None

rollback(*, retaining: bool = False, savepoint: str = None) None[source]

Rolls back the distributed transaction managed by this instance.

Parameters:
  • retaining (bool) – When True, the transaction context is retained after rollback.

  • savepoint (str) – When specified, the transaction is rolled back to savepoint with given name.

Raises:

InterfaceError – When both retaining and savepoint parameters are specified.

Return type:

None

savepoint(name: str) None[source]

Creates a new savepoint for distributed transaction managed by this instance.

Parameters:

name (str) – Name for the savepoint

Return type:

None

property log_context: Connection

Logging context [connection].

class firebird.driver.core.Statement(connection: Connection, stmt: iStatement, sql: str, dialect: int)[source]

Bases: LoggingIdMixin

Prepared SQL statement.

Note

Implements context manager protocol to call free() automatically.

Parameters:
can_repeat() bool[source]

Returns True if statement could be executed repeatedly.

Return type:

bool

free() None[source]

Release the statement and all associated resources.

Important

The statement SHALL NOT be used after call to this method.

Return type:

None

has_cursor() bool[source]

Returns True if statement has cursor (can return multiple rows).

Return type:

bool

property detailed_plan: str

Execution plan in new format (explained).

property log_context: Connection

Logging context [Connection]

property plan: str

Execution plan in classic format.

property sql: str

SQL statement.

property timeout: int

Statement timeout.

property type: StatementType

Statement type.

class firebird.driver.core.Cursor(connection: Connection, transaction: TransactionManager)[source]

Bases: LoggingIdMixin

Represents a database cursor, which is used to execute SQL statement and manage the context of a fetch operation.

Note

Implements context manager protocol to call close() automatically.

Parameters:
call_procedure(proc_name: str, parameters: Sequence = None) Tuple | None[source]

Executes a stored procedure with the given name.

Parameters:
  • proc_name (str) – Stored procedure name.

  • parameters (Sequence) – Sequence of parameters. Must contain one entry for each argument that the procedure expects.

Returns:

None or tuple with values returned by stored procedure.

Return type:

Tuple | None

callproc(proc_name: str, parameters: Sequence = None) None[source]

Executes a stored procedure with the given name.

Parameters:
  • proc_name (str) – Stored procedure name.

  • parameters (Sequence) – Sequence of parameters. Must contain one entry for each argument that the procedure expects.

Return type:

None

Note

If stored procedure does have output parameters, you must retrieve their values saparatelly by Cursor.fetchone() call. This method is not very convenient, but conforms to Python DB API 2.0. If you don’t require conformance to Python DB API, it’s recommended to use more convenient method Cursor.call_procedure() instead.

close() None[source]

Close the cursor and release all associated resources.

The result set (if any) from last executed statement is released, and if executed Statement was not supplied externally, it’s released as well.

Note

The closed cursor could be used to execute further SQL commands.

Return type:

None

execute(operation: str | Statement, parameters: Sequence[Any] = None) Cursor[source]

Executes SQL command or prepared Statement.

Starts new transaction if transaction manager associated with cursor is not active.

Parameters:
  • operation (str | Statement) – SQL command or prepared Statement.

  • parameters (Sequence[Any]) – Sequence of parameters. Must contain one entry for each argument that the operation expects.

Returns:

self so call to execute could be used as iterator over returned rows.

Return type:

Cursor

Note

If operation is a string with SQL command that is exactly the same as the last executed command, the internally prepared Statement from last execution is reused.

If cursor is open, it’s closed before new statement is executed.

executemany(operation: str | Statement, seq_of_parameters: Sequence[Sequence[Any]]) None[source]

Executes SQL command or prepared statement against all parameter sequences found in the sequence seq_of_parameters.

Starts new transaction if transaction manager associated with cursor is not active.

Parameters:
  • operation (str | Statement) – SQL command or prepared Statement.

  • seq_of_parameters (Sequence[Sequence[Any]]) – Sequence of sequences of parameters. Must contain one sequence of parameters for each execution that has one entry for each argument that the operation expects.

Return type:

None

Note

This function simply calls execute in a loop, feeding it with parameters from seq_of_parameters. Because execute reuses the statement, calling executemany is equally efective as direct use of prepared Statement and calling execute in a loop directly in application.

fetch_absolute(position: int) Tuple | None[source]

Fetch the row of a scrollable query result set specified by absolute position.

Returns None if there is no row to be fetched.

Parameters:

position (int) – Absolute position number of row in result set.

Return type:

Tuple | None

fetch_first() Tuple | None[source]

Fetch the first row of a scrollable query result set.

Returns None if there is no row to be fetched.

Return type:

Tuple | None

fetch_last() Tuple | None[source]

Fetch the last row of a scrollable query result set.

Returns None if there is no row to be fetched.

Return type:

Tuple | None

fetch_next() Tuple | None[source]

Fetch the next row of a scrollable query result set.

Returns None if there is no row to be fetched.

Return type:

Tuple | None

fetch_prior() Tuple | None[source]

Fetch the previous row of a scrollable query result set.

Returns None if there is no row to be fetched.

Return type:

Tuple | None

fetch_relative(offset: int) Tuple | None[source]

Fetch the row of a scrollable query result set specified by relative position.

Returns None if there is no row to be fetched.

Parameters:

offset (int) – Relative position number of row in result set. Negative value refers to previous row, positive to next row.

Return type:

Tuple | None

fetchall() List[Tuple][source]

Fetch all remaining rows of a query result set.

Return type:

List[Tuple]

fetchmany(size: int = None) List[Tuple][source]

Fetch the next set of rows of a query result, returning a sequence of sequences (e.g. a list of tuples).

An empty sequence is returned when no more rows are available. The number of rows to fetch per call is specified by the parameter. If it is not given, the cursor’s arraysize determines the number of rows to be fetched. The method does try to fetch as many rows as indicated by the size parameter. If this is not possible due to the specified number of rows not being available, fewer rows may be returned.

Parameters:

size (int) – The number of rows to fetch.

Return type:

List[Tuple]

fetchone() Tuple[source]

Fetch the next row of a query result set.

Return type:

Tuple

is_bof() bool[source]

Returns True is scrollable cursor is positioned at the beginning.

Return type:

bool

is_closed() bool[source]

Returns True if cursor is closed.

Return type:

bool

is_eof() bool[source]

Returns True is scrollable cursor is positioned at the end.

Return type:

bool

open(operation: str | Statement, parameters: Sequence[Any] = None) Cursor[source]

Executes SQL command or prepared Statement as scrollable.

Starts new transaction if transaction manager associated with cursor is not active.

Parameters:
  • operation (str | Statement) – SQL command or prepared Statement.

  • parameters (Sequence[Any]) – Sequence of parameters. Must contain one entry for each argument that the operation expects.

Return type:

Cursor

Note

If operation is a string with SQL command that is exactly the same as the last executed command, the internally prepared Statement from last execution is reused.

If cursor is open, it’s closed before new statement is executed.

prepare(operation: str) Statement[source]

Creates prepared statement for repeated execution.

Parameters:

operation (str) – SQL command.

Return type:

Statement

set_cursor_name(name: str) None[source]

Sets name for the SQL cursor.

Parameters:

name (str) – Cursor name.

Return type:

None

setinputsizes(sizes: Sequence[Type]) None[source]

Required by Python DB API 2.0, but pointless for Firebird, so it does nothing.

Parameters:

sizes (Sequence[Type])

Return type:

None

setoutputsize(size: int, column: int = None) None[source]

Required by Python DB API 2.0, but pointless for Firebird, so it does nothing.

Parameters:
Return type:

None

to_dict(row: Tuple, into: Dict = None) Dict[source]

Returns row tuple as dictionary with field names as keys. Returns new dictionary if into argument is not provided, otherwise returns into dictionary updated with row data.

Parameters:
  • row (Tuple) – Row data returned by fetch_* method.

  • into (Dict) – Dictionary that shouold be updated with row data.

Return type:

Dict

property affected_rows: int

Specifies the number of rows that the last execute or open produced (for DQL statements like select) or affected (for DML statements like update or insert ).

The attribute is -1 in case no statement was executed on the cursor or the rowcount of the last operation is not determinable by the interface.

Note

The database engine’s own support for the determination of “rows affected”/”rows selected” is quirky. The database engine only supports the determination of rowcount for INSERT, UPDATE, DELETE, and SELECT statements. When stored procedures become involved, row count figures are usually not available to the client.

arraysize: int = 1

This read/write attribute specifies the number of rows to fetch at a time with .fetchmany(). It defaults to 1 meaning to fetch a single row at a time.

Required by Python DB API 2.0

property connection: Connection

Connection associated with cursor.

property description: Tuple[Tuple[str, type, int, int, int, int, bool]]

Tuple of DESCRIPTION tuples (with 7-items).

Each of these tuples contains information describing one result column: (name, type_code, display_size, internal_size, precision, scale, null_ok)

property log_context: Connection

Logging context [Connection

property name: str

Name set for cursor.

property rowcount: int

Specifies the number of rows that the last execute or open produced (for DQL statements like select) or affected (for DML statements like update or insert ).

The attribute is -1 in case no statement was executed on the cursor or the rowcount of the last operation is not determinable by the interface.

Note

The database engine’s own support for the determination of “rows affected”/”rows selected” is quirky. The database engine only supports the determination of rowcount for INSERT, UPDATE, DELETE, and SELECT statements. When stored procedures become involved, row count figures are usually not available to the client.

property statement: Statement

Executed Statement or None if cursor does not executed a statement yet.

stream_blob_threshold

BLOBs greater than threshold are returned as BlobReader instead in materialized form.

stream_blobs: List[str]

Names of columns that should be returned as BlobReader.

property transaction: TransactionManager

Transaction manager associated with cursor.

class firebird.driver.core.Server(svc: iService, spb: bytes, host: str, encoding: str, encoding_errors: str)[source]

Bases: LoggingIdMixin

Represents connection to Firebird Service Manager.

Note

Implements context manager protocol to call close() automatically.

Parameters:
close() None[source]

Close the server connection now (rather than whenever __del__ is called). The instance will be unusable from this point forward; an Error (or subclass) exception will be raised if any operation is attempted with the instance.

Return type:

None

is_running() bool[source]

Returns True if service is running.

Note

Some services like backup() or sweep() may take time to comlete, so they’re called asynchronously. Until they’re finished, no other async service could be started.

Return type:

bool

readline() str | None[source]

Get next line of textual output from last service query.

Returns:

Line of service output or None for EOF.

Return type:

str | None

Important

This method blocks until any output is available from server. Bacuse this method is used by iteration over Server and readlines method, they will block as well.

readline_timed(timeout: int) str | Sentinel | None[source]

Get next line of textual output from last service query.

Parameters:

timeout (int) – Time in seconds to wait for output.

Returns:

Line of service output, None for EOF or TIMEOUT sentinel for expired timeout.

Return type:

str | Sentinel | None

readlines() List[str][source]

Get list of remaining output lines from last service query.

Return type:

List[str]

wait() None[source]

Wait until running service completes, i.e. stops sending data.

Return type:

None

property database: ServerDbServices3 | ServerDbServices

Access to various database-related actions and services.

encoding: str

Encoding used for text data exchange with server

encoding_errors: str

codecs#error-handlers

Type:

Handler used for encoding errors. See

host: str

Server host

property info: ServerInfoProvider

Access to various information about attached server.

mode: SrvInfoCode

Service output mode (line or eof)

response: CBuffer

Response buffer used to comunicate with service

spb: bytes

Service Parameter Buffer (SPB) used to connect the service manager

property trace: ServerTraceServices

Access to various database-related actions and services.

property user: ServerUserServices

Access to various user-related actions and services.

class firebird.driver.core.ServerServiceProvider(server: Server)[source]

Bases: object

Base class for server service providers.

Parameters:

server (Server)

class firebird.driver.core.ServerDbServices3(server: Server)[source]

Bases: ServerServiceProvider

Database-related actions and services [Firebird 3+].

Parameters:

server (Server)

activate_shadow(*, database: str | Path, role: str = None) None[source]

Activate database shadow.

Parameters:
  • database (str | Path) – Database specification or alias.

  • role (str) – SQL ROLE name passed to gfix.

Return type:

None

backup(*, database: str | ~pathlib.Path, backup: str | ~pathlib.Path | ~typing.Sequence[str | ~pathlib.Path], backup_file_sizes: ~typing.Sequence[int] = (), flags: ~firebird.driver.types.SrvBackupFlag = <SrvBackupFlag.NONE: 0>, role: str = None, callback: ~typing.Callable[[str], None] = None, stats: str = None, verbose: bool = False, verbint: int = None, skip_data: str = None, include_data: str = None, keyhoder: str = None, keyname: str = None, crypt: str = None, parallel_workers: int = None) None[source]

Request logical (GBAK) database backup. (ASYNC service)

Parameters:
  • database (str | Path) – Database file specification or alias.

  • backup (str | Path | Sequence[str | Path]) – Backup filespec, or list of backup file specifications.

  • backup_file_sizes (Sequence[int]) – List of file sizes for backup files.

  • flags (SrvBackupFlag) – Backup options.

  • role (str) – SQL ROLE name passed to gbak.

  • callback (Callable[[str], None]) – Function to call back with each output line.

  • stats (str) – Backup statistic options (TDWR).

  • verbose (bool) – Whether output should be verbose or not.

  • verbint (int) – Verbose information with explicit interval (number of records)

  • skip_data (str) – String with table names whose data should be excluded from backup.

  • include_data (str) – String with table names whose data should be included into backup [Firebird 4].

  • keyholder – Keyholder name [Firebird 4]

  • keyname (str) – Key name [Firebird 4]

  • crypt (str) – Encryption specification [Firebird 4]

  • parallel_workers (int) – Number of parallel workers [Firebird 5]

  • keyhoder (str)

Return type:

None

bring_online(*, database: str | Path, mode: OnlineMode = OnlineMode.NORMAL, role: str = None) None[source]

Bring previously shut down database back online.

Parameters:
  • database (str | Path) – Database specification or alias.

  • mode (OnlineMode) – Online mode.

  • role (str) – SQL ROLE name passed to gfix.

Return type:

None

commit_limbo_transaction(*, database: str | Path, transaction_id: int) None[source]

Resolve limbo transaction with commit.

Parameters:
  • database (str | Path) – Database specification or alias.

  • transaction_id (int) – ID of Transaction to resolve.

Return type:

None

get_limbo_transaction_ids(*, database: str | Path) List[int][source]

Returns list of transactions in limbo.

Parameters:

database (str | Path) – Database specification or alias.

Return type:

List[int]

get_statistics(*, database: str | ~pathlib.Path, flags: ~firebird.driver.types.SrvStatFlag = <SrvStatFlag.DEFAULT: 9>, role: str = None, tables: ~typing.Sequence[str] = None, callback: ~typing.Callable[[str], None] = None) None[source]

Return database statistics produced by gstat utility. (ASYNC service)

Parameters:
  • database (str | Path) – Database specification or alias.

  • flags (SrvStatFlag) – Flags indicating which statistics shall be collected.

  • role (str) – SQL ROLE name passed to gstat.

  • tables (Sequence[str]) – List of database tables whose statistics are to be collected.

  • callback (Callable[[str], None]) – Function to call back with each output line.

Return type:

None

local_backup(*, database: str | ~pathlib.Path, backup_stream: ~typing.BinaryIO, flags: ~firebird.driver.types.SrvBackupFlag = <SrvBackupFlag.NONE: 0>, role: str = None, skip_data: str = None, include_data: str = None, keyhoder: str = None, keyname: str = None, crypt: str = None) None[source]

Request logical (GBAK) database backup into local byte stream. (SYNC service)

Parameters:
  • database (str | Path) – Database specification or alias.

  • backup_stream (BinaryIO) – Binary stream to which the backup is to be written.

  • flags (SrvBackupFlag) – Backup options.

  • role (str) – SQL ROLE name passed to gbak.

  • skip_data (str) – String with table names whose data should be excluded from backup.

  • include_data (str) – String with table names whose data should be included into backup [Firebird 4].

  • keyholder – Keyholder name [Firebird 4]

  • keyname (str) – Key name [Firebird 4]

  • crypt (str) – Encryption specification [Firebird 4]

  • keyhoder (str)

Return type:

None

local_restore(*, backup_stream: ~typing.BinaryIO, database: str | ~pathlib.Path | ~typing.Sequence[str | ~pathlib.Path], db_file_pages: ~typing.Sequence[int] = (), flags: ~firebird.driver.types.SrvRestoreFlag = <SrvRestoreFlag.CREATE: 8192>, role: str = None, skip_data: str = None, page_size: int = None, buffers: int = None, access_mode: ~firebird.driver.types.DbAccessMode = DbAccessMode.READ_WRITE, include_data: str = None, keyhoder: str = None, keyname: str = None, crypt: str = None, replica_mode: ~firebird.driver.types.ReplicaMode = None) None[source]

Request database restore from logical (GBAK) backup stored in local byte stream. (SYNC service)

Parameters:
  • backup_stream (BinaryIO) – Binary stream with the backup.

  • database (str | Path | Sequence[str | Path]) – Database specification or alias, or list of those.

  • db_file_pages (Sequence[int]) – List of database file sizes (in pages).

  • flags (SrvRestoreFlag) – Restore options.

  • role (str) – SQL ROLE name passed to gbak.

  • skip_data (str) – String with table names whose data should be excluded from restore.

  • page_size (int) – Page size for restored database.

  • buffers (int) – Cache size for restored database.

  • access_mode (DbAccessMode) – Restored database access mode (R/W or R/O).

  • include_data (str) – String with table names whose data should be included into backup [Firebird 4].

  • keyholder – Keyholder name [Firebird 4]

  • keyname (str) – Key name [Firebird 4]

  • crypt (str) – Encryption specification [Firebird 4]

  • replica_mode (ReplicaMode) – Replica mode for restored database [Firebird 4]

  • keyhoder (str)

Return type:

None

nbackup(*, database: str | ~pathlib.Path, backup: str | ~pathlib.Path, level: int = 0, direct: bool = None, flags: ~firebird.driver.types.SrvNBackupFlag = <SrvNBackupFlag.NONE: 0>, role: str = None, guid: str = None) None[source]

Perform physical (NBACKUP) database backup. (SYNC service)

Parameters:
  • database (str | Path) – Database specification or alias.

  • backup (str | Path) – Backup file specification.

  • level (int) – Backup level.

  • direct (bool) – Direct I/O override.

  • flags (SrvNBackupFlag) – Backup options.

  • role (str) – SQL ROLE name passed to nbackup.

  • guid (str) – Database backup GUID.

Return type:

None

Important

Parameters level and guid are mutually exclusive. If guid is specified, then level value is ignored.

no_linger(*, database: str | Path, role: str = None) None[source]

Set one-off override for database linger.

Parameters:
  • database (str | Path) – Database specification or alias.

  • role (str) – SQL ROLE name passed to gfix.

Return type:

None

nrestore(*, backups: ~typing.Sequence[str | ~pathlib.Path], database: str | ~pathlib.Path, direct: bool = False, flags: ~firebird.driver.types.SrvNBackupFlag = <SrvNBackupFlag.NONE: 0>, role: str = None) None[source]

Perform restore from physical (NBACKUP) database backup. (SYNC service)

Parameters:
  • backups (Sequence[str | Path]) – Backup file(s) specification.

  • database (str | Path) – Database specification or alias.

  • direct (bool) – Direct I/O override.

  • flags (SrvNBackupFlag) – Restore options.

  • role (str) – SQL ROLE name passed to nbackup.

Return type:

None

repair(*, database: str | ~pathlib.Path, flags: ~firebird.driver.types.SrvRepairFlag = <SrvRepairFlag.REPAIR: 164>, role: str = None) None[source]

Perform database repair operation. (SYNC service)

Parameters:
  • database (str | Path) – Database specification or alias.

  • flags (SrvRepairFlag) – Repair flags.

  • role (str) – SQL ROLE name passed to gfix.

Return type:

None

restore(*, backup: str | ~pathlib.Path | ~typing.Sequence[str | ~pathlib.Path], database: str | ~pathlib.Path | ~typing.Sequence[str | ~pathlib.Path], db_file_pages: ~typing.Sequence[int] = (), flags: ~firebird.driver.types.SrvRestoreFlag = <SrvRestoreFlag.CREATE: 8192>, role: str = None, callback: ~typing.Callable[[str], None] = None, stats: str = None, verbose: bool = False, verbint: int = None, skip_data: str = None, page_size: int = None, buffers: int = None, access_mode: ~firebird.driver.types.DbAccessMode = DbAccessMode.READ_WRITE, include_data: str = None, keyhoder: str = None, keyname: str = None, crypt: str = None, replica_mode: ~firebird.driver.types.ReplicaMode = None, parallel_workers: int = None) None[source]

Request database restore from logical (GBAK) backup. (ASYNC service)

Parameters:
  • backup (str | Path | Sequence[str | Path]) – Backup filespec, or list of backup file specifications.

  • database (str | Path | Sequence[str | Path]) – Database specification or alias, or list of those.

  • db_file_pages (Sequence[int]) – List of database file sizes (in pages).

  • flags (SrvRestoreFlag) – Restore options.

  • role (str) – SQL ROLE name passed to gbak.

  • callback (Callable[[str], None]) – Function to call back with each output line.

  • stats (str) – Restore statistic options (TDWR).

  • verbose (bool) – Whether output should be verbose or not.

  • verbint (int) – Verbose information with explicit interval (number of records)

  • skip_data (str) – String with table names whose data should be excluded from restore.

  • page_size (int) – Page size for restored database.

  • buffers (int) – Cache size for restored database.

  • access_mode (DbAccessMode) – Restored database access mode (R/W or R/O).

  • include_data (str) – String with table names whose data should be included into backup [Firebird 4].

  • keyholder – Keyholder name [Firebird 4]

  • keyname (str) – Key name [Firebird 4]

  • crypt (str) – Encryption specification [Firebird 4]

  • replica_mode (ReplicaMode) – Replica mode for restored database [Firebird 4]

  • parallel_workers (int) – Number of parallel workers [Firebird 5]

  • keyhoder (str)

Return type:

None

rollback_limbo_transaction(*, database: str | Path, transaction_id: int) None[source]

Resolve limbo transaction with rollback.

Parameters:
  • database (str | Path) – Database specification or alias.

  • transaction_id (int) – ID of Transaction to resolve.

Return type:

None

set_access_mode(*, database: str | Path, mode: DbAccessMode, role: str = None) None[source]

Set database access mode (R/W or R/O).

Parameters:
  • database (str | Path) – Database specification or alias.

  • mode (DbAccessMode) – New value.

  • role (str) – SQL ROLE name passed to gfix.

Return type:

None

set_default_cache_size(*, database: str | Path, size: int, role: str = None) None[source]

Set individual page cache size for database.

Parameters:
  • database (str | Path) – Database specification or alias.

  • size (int) – New value.

  • role (str) – SQL ROLE name passed to gfix.

Return type:

None

set_space_reservation(*, database: str | Path, mode: DbSpaceReservation, role: str = None) None[source]

Set space reservation for database.

Parameters:
  • database (str | Path) – Database specification or alias.

  • mode (DbSpaceReservation) – New value.

  • role (str) – SQL ROLE name passed to gfix.

Return type:

None

set_sql_dialect(*, database: str | Path, dialect: int, role: str = None) None[source]

Set database SQL dialect.

Parameters:
  • database (str | Path) – Database specification or alias.

  • dialect (int) – New value.

  • role (str) – SQL ROLE name passed to gfix.

Return type:

None

set_sweep_interval(*, database: str | Path, interval: int, role: str = None) None[source]

Set database sweep interval.

Parameters:
  • database (str | Path) – Database specification or alias.

  • interval (int) – New value.

  • role (str) – SQL ROLE name passed to gfix.

Return type:

None

set_write_mode(*, database: str | Path, mode: DbWriteMode, role: str = None) None[source]

Set database write mode (SYNC/ASYNC).

Parameters:
  • database (str | Path) – Database specification or alias.

  • mode (DbWriteMode) – New value.

  • role (str) – SQL ROLE name passed to gfix.

Return type:

None

shutdown(*, database: str | Path, mode: ShutdownMode, method: ShutdownMethod, timeout: int, role: str = None) None[source]

Database shutdown.

Parameters:
  • database (str | Path) – Database specification or alias.

  • mode (ShutdownMode) – Shutdown mode.

  • method (ShutdownMethod) – Shutdown method.

  • timeout (int) – Timeout for shutdown.

  • role (str) – SQL ROLE name passed to gfix.

Return type:

None

sweep(*, database: str | Path, role: str = None, parallel_workers: int = None) None[source]

Perform database sweep operation.

Parameters:
  • database (str | Path) – Database specification or alias.

  • role (str) – SQL ROLE name passed to gfix.

  • parallel_workers (int) – Number of parallel workers [Firebird 5]

Return type:

None

validate(*, database: str | Path, include_table: str = None, exclude_table: str = None, include_index: str = None, exclude_index: str = None, lock_timeout: int = None, role: str = None, callback: Callable[[str], None] = None) None[source]

Perform database validation. (ASYNC service)

Parameters:
  • database (str | Path) – Database specification or alias.

  • flags – Repair flags.

  • include_table (str) – Regex pattern for table names to include in validation run.

  • exclude_table (str) – Regex pattern for table names to exclude in validation run.

  • include_index (str) – Regex pattern for index names to include in validation run.

  • exclude_index (str) – Regex pattern for index names to exclude in validation run.

  • lock_timeout (int) – Lock timeout (seconds), used to acquire locks for table to validate, default is 10 secs. 0 is no-wait, -1 is infinite wait.

  • role (str) – SQL ROLE name passed to gfix.

  • callback (Callable[[str], None]) – Function to call back with each output line.

Return type:

None

class firebird.driver.core.ServerDbServices(server: Server)[source]

Bases: ServerDbServices4

Database-related actions and services [Firebird 5+].

Parameters:

server (Server)

upgrade(*, database: str | Path) bytes[source]

Perform database repair operation. (SYNC service)

Parameters:
  • database (str | Path) – Database specification or alias.

  • flags – Repair flags.

  • role – SQL ROLE name passed to gfix.

Return type:

bytes

class firebird.driver.core.ServerUserServices(server: Server)[source]

Bases: ServerServiceProvider

User-related actions and services.

Parameters:

server (Server)

add(*, user_name: str, password: str, user_id: int = None, group_id: int = None, first_name: str = None, middle_name: str = None, last_name: str = None, admin: bool = None, database: str | Path = None, sql_role: str = None) None[source]

Add new user.

Parameters:
  • user_name (str) – User name.

  • password (str) – User password.

  • user_id (int) – User ID.

  • group_id (int) – Group ID.

  • firest_name – User’s first name.

  • middle_name (str) – User’s middle name.

  • last_name (str) – User’s last name.

  • admin (bool) – Admin flag.

  • database (str | Path) – Database specification or alias.

  • sql_role (str) – SQL role name.

  • first_name (str)

Return type:

None

delete(user_name: str, *, database: str | Path = None, sql_role: str = None) None[source]

Delete user.

Parameters:
  • user_name (str) – User name.

  • database (str | Path) – Database specification or alias.

  • sql_role (str) – SQL role name.

Return type:

None

exists(user_name: str, *, database: str | Path = None, sql_role: str = None) bool[source]

Returns True if user exists.

Parameters:
  • user_name (str) – User name.

  • database (str | Path) – Database specification or alias.

  • sql_role (str) – SQL role name.

Return type:

bool

get(user_name: str, *, database: str | Path = None, sql_role: str = None) UserInfo | None[source]

Get information about user.

Parameters:
  • user_name (str) – User name.

  • database (str | Path) – Database specification or alias.

  • sql_role (str) – SQL role name.

Return type:

UserInfo | None

get_all(*, database: str | Path = None, sql_role: str = None) List[UserInfo][source]

Get information about users.

Parameters:
  • database (str | Path) – Database specification or alias.

  • sql_role (str) – SQL role name.

Return type:

List[UserInfo]

update(user_name: str, *, password: str = None, user_id: int = None, group_id: int = None, first_name: str = None, middle_name: str = None, last_name: str = None, admin: bool = None, database: str | Path = None) None[source]

Update user information.

Parameters:
  • user_name (str) – User name.

  • password (str) – User password.

  • user_id (int) – User ID.

  • group_id (int) – Group ID.

  • firest_name – User’s first name.

  • middle_name (str) – User’s middle name.

  • last_name (str) – User’s last name.

  • admin (bool) – Admin flag.

  • first_name (str)

  • database (str | Path)

Return type:

None

class firebird.driver.core.ServerTraceServices(server: Server)[source]

Bases: ServerServiceProvider

Trace session actions and services.

Parameters:

server (Server)

resume(*, session_id: int) str[source]

Resume trace session.

Parameters:

session_id (int) – Trace session ID.

Returns:

Text message ‘Trace session ID <x> resumed’.

Return type:

str

start(*, config: str, name: str = None) int[source]

Start new trace session. (ASYNC service)

Parameters:
  • config (str) – Trace session configuration.

  • name (str) – Trace session name.

Returns:

Trace session ID.

Return type:

int

stop(*, session_id: int) str[source]

Stop trace session.

Parameters:

session_id (int) – Trace session ID.

Returns:

Text message ‘Trace session ID <x> stopped’.

Return type:

str

suspend(*, session_id: int) str[source]

Suspend trace session.

Parameters:

session_id (int) – Trace session ID.

Returns:

Text message ‘Trace session ID <x> paused’.

Return type:

str

property sessions: Dict[int, TraceSession]

Dictionary with active trace sessions.

class firebird.driver.core.InfoProvider(charset: str, buffer_size: int = 256)[source]

Bases: ABC

Abstract base class for embedded information providers.

Parameters:
  • charset (str)

  • buffer_size (int)

response

Internal buffer for response packet acquired via Firebird API.

Type:

CBuffer

request

Internal buffer for information request packet needed by Firebird API.

Type:

Buffer

abstract _acquire(request: bytes) None[source]

Acquire information specified by parameter. Information must be stored in response buffer.

Parameters:

request (bytes) – Data specifying the required information.

Return type:

None

abstract _close() None[source]

Close the information source.

Return type:

None

_get_data(request: bytes, max_size: int = 32767) None[source]

Helper function that aquires information specified by parameter into internal response buffer. If information source couldn’t store all required data because the buffer is too small, this function tries to acquire() the information again with buffer of doubled size.

Parameters:
  • request (bytes) – Data specifying the required information.

  • max_size (int) – Maximum response size.

Raises:

InterfaceError – If information cannot be successfuly stored into buffer of max_size, or response is ivalid.

Return type:

None

class firebird.driver.core.DatabaseInfoProvider3(connection: Connection)[source]

Bases: InfoProvider

Provides access to information about attached database [Firebird 3+].

Important

Do NOT create instances of this class directly! Use Connection.info property to access the instance already bound to attached database.

Parameters:

connection (Connection)

_acquire(request: bytes) None[source]

Acquires information from associated attachment. Information is stored in native format in response buffer.

Parameters:

request (bytes) – Data specifying the required information.

Return type:

None

_close() None[source]

Drops the association with attached database.

Return type:

None

get_active_transaction_count() int[source]

Returns number of active transactions.

Return type:

int

get_active_transaction_ids() List[int][source]

Returns list of IDs of active transactions.

Return type:

List[int]

get_info(info_code: DbInfoCode, page_number: int = None) Any[source]

Returns requested information from associated attachment.

Parameters:
  • info_code (DbInfoCode) – A code specifying the required information.

  • page_number (int) – A page number for DbInfoCode.PAGE_CONTENTS request. Ignored for other requests.

Returns:

The data type of returned value depends on information required.

Return type:

Any

get_page_content(page_number: int) bytes[source]

Returns content of single database page.

Parameters:

page_number (int) – Sequence number of database page to be fetched from server.

Return type:

bytes

get_table_access_stats() List[TableAccessStats][source]

Returns actual table access statistics.

Return type:

List[TableAccessStats]

is_compressed() bool[source]

Returns True if connection to the server uses data compression.

Return type:

bool

is_encrypted() bool[source]

Returns True if connection to the server uses data encryption.

Return type:

bool

property access_mode: DbAccessMode

Database access mode (READ_ONLY or READ_WRITE).

property cache_hit_ratio: float

Cache hit ratio = 1 - (reads / fetches).

property charset: str

Database character set.

property creation_date: date

Date when database was created.

property current_memory: int

Total amount of memory curretly used by database engine.

property db_class: DbClass

Database Class.

property engine_version: float

Firebird version as <major>.<minor> float number.

property fetches: int

Current I/O statistics - Fetches from page cache.

property firebird_version: str

Firebird server version.

property id: int

Attachment ID.

property implementation: Implementation

Implementation (old format).

property marks: int

Current I/O statistics - Writes to page in cache.

property max_memory: int

Max. total amount of memory so far used by database engine.

property name: str

Database name (filename or alias).

property next_transaction: int

ID for next transaction.

property oat: int

ID of Oldest Active Transaction.

property ods: float

Database On-Disk Structure version (<major>.<minor>).

property ods_minor_version: int

Database On-Disk Structure MINOR version.

property ods_version: int

Database On-Disk Structure MAJOR version.

property oit: int

ID of Oldest Interesting Transaction.

property ost: int

ID of Oldest Snapshot Transaction.

property page_cache_size: int

Size of page cache used by connection.

property page_size: int

Page size (in bytes).

property pages_allocated: int

Number of pages allocated for database.

property pages_free: int

Number of free allocated pages in database.

property pages_used: int

Number of database pages in active use.

property provider: DbProvider

Database Provider.

property reads: int

Current I/O statistics - Reads from disk to page cache.

property server_version: str

Firebird server version (compatible with InterBase version).

property site: str

Database site name.

property size_in_pages: int

Database size in pages.

property space_reservation: DbSpaceReservation

Data page space usage (USE_FULL or RESERVE).

property sql_dialect: int

SQL dialect used by connected database.

property sweep_interval: int

Sweep interval.

property version: str

Firebird version as SEMVER string.

property write_mode: DbWriteMode

Database write mode (SYNC or ASYNC).

property writes: int

Current I/O statistics - Writes from page cache to disk.

class firebird.driver.core.DatabaseInfoProvider(connection: Connection)[source]

Bases: DatabaseInfoProvider3

Provides access to information about attached database [Firebird 4+].

Important

Do NOT create instances of this class directly! Use Connection.info property to access the instance already bound to attached database.

Parameters:

connection (Connection)

property idle_timeout: int

Attachment idle timeout.

property set_idle_timeout: int

Attachment idle timeout.

property set_statement_timeout: int

Statement timeout.

property statement_timeout: int

Statement timeout.

class firebird.driver.core.TransactionInfoProvider3(charset: str, tra: TransactionManager)[source]

Bases: InfoProvider

Provides access to information about transaction [Firebird 3+].

Important

Do NOT create instances of this class directly! Use TransactionManager.info property to access the instance already bound to transaction context.

Parameters:
get_info(info_code: TraInfoCode) Any[source]

Returns response for transaction INFO request. The type anc content of returned value(s) depend on INFO code passed as parameter.

Parameters:

info_code (TraInfoCode)

Return type:

Any

is_read_only() bool[source]

Returns True if transaction is Read Only.

Return type:

bool

property database: str

Database filename.

property id: int

Transaction ID.

property isolation: Isolation

Isolation level.

property lock_timeout: int

Lock timeout.

property oat: int

ID of Oldest Active Transaction at the time this transaction started.

property oit: int

ID of Oldest Interesting Transaction at the time this transaction started.

property ost: int

ID of Oldest Snapshot Transaction at the time this transaction started.

property snapshot_number: int

Snapshot number for this transaction.

Raises:

NotSupportedError – Requires Firebird 4+

class firebird.driver.core.TransactionInfoProvider(charset: str, tra: TransactionManager)[source]

Bases: TransactionInfoProvider3

Provides access to information about transaction [Firebird 4+].

Important

Do NOT create instances of this class directly! Use TransactionManager.info property to access the instance already bound to transaction context.

Parameters:
property snapshot_number: int

Snapshot number for this transaction.

class firebird.driver.core.ServerInfoProvider(charset: str, server: Server)[source]

Bases: InfoProvider

Provides access to information about attached server.

Important

Do NOT create instances of this class directly! Use Server.info property to access the instance already bound to connectected server.

Parameters:
_acquire(request: bytes) None[source]

Acquires information from associated attachment. Information is stored in native format in response buffer.

Parameters:

request (bytes) – Data specifying the required information.

Return type:

None

_close() None[source]

Drops the association with attached server.

Return type:

None

get_info(info_code: SrvInfoCode) Any[source]

Returns requested information from connected server.

Parameters:

info_code (SrvInfoCode) – A code specifying the required information.

Returns:

The data type of returned value depends on information required.

Return type:

Any

get_log(callback: Callable[[str], None] = None) None[source]

Request content of Firebird Server log. (ASYNC service)

Parameters:

callback (Callable[[str], None]) – Function to call back with each output line.

Return type:

None

property architecture: str

Server implementation description.

property attached_databases: List[str]

List of attached databases.

property capabilities: ServerCapability

Server capabilities.

property connection_count: int

Number of database attachments.

property engine_version: float

Firebird version as <major>.<minor> float number.

property home_directory: str

Server home directory.

property lock_directory: str

Directory with lock file(s).

property manager_version: int

Service manager version.

property message_directory: str

Directory with message file(s).

property security_database: str

Path to security database.

property version: str

Firebird version as SEMVER string.

class firebird.driver.core.EventCollector(db_handle: c_uint, event_names: Sequence[str])[source]

Bases: object

Collects database event notifications.

Notifications of events are not accumulated until begin() method is called.

From the moment the begin() is called, notifications of any events that occur will accumulate asynchronously within the conduit’s internal queue until the collector is closed either explicitly (via the close() method) or implicitly (via garbage collection).

Note

EventCollector implements context manager protocol to call method begin() and close() automatically.

Example:

with connection.event_collector(['event_a', 'event_b']) as collector:
    events = collector.wait()
    process_events(events)

Important

DO NOT create instances of this class directly! Use only Connection.event_collector to get EventCollector instances.

Parameters:
  • db_handle (a.FB_API_HANDLE)

  • event_names (Sequence[str])

begin() None[source]

Starts listening for events.

Must be called directly or through context manager interface.

Return type:

None

close() None[source]

Cancels the standing request for this collector to be notified of events.

After this method has been called, this EventCollector instance is useless, and should be discarded.

Return type:

None

flush() None[source]

Clear any event notifications that have accumulated in the collector’s internal queue.

Return type:

None

is_closed() bool[source]

Returns True if collector is closed.

Return type:

bool

wait(timeout: int | float = None) Dict[str, int][source]

Wait for events.

Blocks the calling thread until at least one of the events occurs, or the specified timeout (if any) expires.

Parameters:

timeout (int | float) – Number of seconds (use a float to indicate fractions of seconds). If not even one of the relevant events has occurred after timeout seconds, this method will unblock and return None. The default timeout is infinite.

Returns:

None if the wait timed out, otherwise a dictionary that maps event_name -> event_occurrence_count.

Return type:

Dict[str, int]

Example:

>>> collector = connection.event_collector(['event_a', 'event_b'])
>>> collector.begin()
>>> collector.wait()
{
 'event_a': 1,
 'event_b': 0
}

In the example above event_a occurred once and event_b did not occur at all.

Raises:

InterfaceError – When collector does not listen for events.

Parameters:

timeout (int | float)

Return type:

Dict[str, int]

class firebird.driver.core.EventBlock(queue, db_handle: c_uint, event_names: List[str])[source]

Bases: object

Used internally by EventCollector.

Parameters:
  • db_handle (a.FB_API_HANDLE)

  • event_names (List[str])

close() None[source]

Close this block canceling managed events.

Return type:

None

count_and_reregister() Dict[str, int][source]

Count event occurences and re-register interest in further notifications.

Return type:

Dict[str, int]

is_closed() bool[source]

Returns True if event block is closed.

Return type:

bool

class firebird.driver.core.BlobReader(blob: iBlob, blob_id: ISC_QUAD, sub_type: int, length: int, segment_size: int, charset: str, owner: Any = None)[source]

Bases: IOBase, LoggingIdMixin

Handler for large BLOB values returned by server.

The BlobReader is a “file-like” class, so it acts much like an open file instance.

Parameters:
  • blob (iBlob)

  • blob_id (a.ISC_QUAD)

  • sub_type (int)

  • length (int)

  • segment_size (int)

  • charset (str)

  • owner (Any)

sub_type

BLOB sub-type

Type:

int

newline

Sequence used as line terminator, default '\n'

Type:

str

Note

Implements context manager protocol to call close() automatically.

close() None[source]

Close the BlobReader.

Return type:

None

flush() None[source]

Does nothing.

Return type:

None

is_text() bool[source]

True if BLOB is a text BLOB.

Return type:

bool

read(size: int = -1) str | bytes[source]

Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. Like file.read().

Note

Performs automatic conversion to str for TEXT BLOBs.

Parameters:

size (int)

Return type:

str | bytes

readline(size: int = -1) str[source]

Read and return one line from the BLOB. If size is specified, at most size bytes will be read.

Uses newline as the line terminator.

Raises:

InterfaceError – For non-textual BLOBs.

Parameters:

size (int)

Return type:

str

readlines(hint: int = -1) List[str][source]

Read and return a list of lines from the stream. hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint.

Note

It’s already possible to iterate on BLOB using for line in blob: … without calling readlines().

Raises:

InterfaceError – For non-textual BLOBs.

Parameters:

hint (int)

Return type:

List[str]

seek(offset: int, whence: int = 0) None[source]

Set the file’s current position, like stdio‘s fseek().

See:

io.IOBase.seek() for details.

Parameters:
  • offset (int) – Offset from specified position.

  • whence (int) – Context for offset. Accepted values: os.SEEK_SET, os.SEEK_CUR or os.SEEK_END

Return type:

None

Warning

If BLOB was NOT CREATED as stream BLOB, this method raises DatabaseError exception. This constraint is set by Firebird.

tell() int[source]

Return current position in BLOB.

See:

io.IOBase.tell() for details.

Return type:

int

property blob_id: ISC_QUAD

BLOB ID.

property blob_type: BlobType

BLOB type.

property closed: bool

True if the BLOB is closed.

property length: int

BLOB length.

property log_context: Any

Logging context [owner]

property mode: str

File mode (‘r’ or ‘rb’).

class firebird.driver.core.EngineVersionProvider(charset: str)[source]

Bases: InfoProvider

Engine version provider for internal use by driver.

Parameters:

charset (str)

_acquire(request: bytes) None[source]

Acquires information from associated attachment. Information is stored in native format in response buffer.

Parameters:

request (bytes) – Data specifying the required information.

Return type:

None

get_engine_version(con: Connection | Server) float[source]

Returns Firebird version as <major>.<minor> float number.

Parameters:

con (Connection | Server)

Return type:

float

get_server_version(con: Connection | Server) str[source]

Returns server version sctring.

Parameters:

con (Connection | Server)

Return type:

str