firebird.driver.core

This is the main code module of the Firebird driver.

Constants and variables

Translation dictionaries

firebird.driver.core.CHARSET_MAP

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

Context managers

transaction

firebird.driver.core.transaction(transact_object, *, tpb=None, bypass=False)

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 (Optional[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

Functions

connect

firebird.driver.core.connect(database, *, user=None, password=None, role=None, no_gc=None, no_db_triggers=None, dbkey_scope=None, crypt_callback=None, charset=None)

Establishes a connection to the database.

Parameters
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.

Return type

Connection

create_database

firebird.driver.core.create_database(database, *, user=None, password=None, role=None, no_gc=None, no_db_triggers=None, dbkey_scope=None, crypt_callback=None, charset=None, overwrite=False)

Creates new database.

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

  • user (Optional[str]) – User name.

  • password (Optional[str]) – User password.

  • role (Optional[str]) – User role.

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

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

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

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

  • charset (Optional[str]) – Character set for connection.

  • overwrite (bool) – Overwite the existing database.

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.

Return type

Connection

connect_server

firebird.driver.core.connect_server(server, *, user=None, password=None, crypt_callback=None)

Establishes a connection to server’s service manager.

Parameters
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.

Return type

Server

tpb

firebird.driver.core.tpb(isolation, lock_timeout=-1, access=<TraAccessMode.WRITE: 9>)

Helper function to costruct simple TPB.

Parameters
  • isolation (Isolation) – Isolation level.

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

  • access (TraAccessMode) – Access mode.

Return type

bytes

Managers for parameter buffers

TPB

class firebird.driver.core.TPB(*, access_mode=<TraAccessMode.WRITE: 9>, isolation=<Isolation.SNAPSHOT: 2>, lock_timeout=-1, no_auto_undo=False, auto_commit=False, ignore_limbo=False)

Bases: object

Transaction Parameter Buffer

clear()

Clear all information.

Return type

None

get_buffer()

Create TPB from stored information.

Return type

bytes

parse_buffer(buffer)

Load information from TPB.

Return type

None

reserve_table(name, share_mode, access_mode)

Set information about table reservation

Return type

None

DPB

class firebird.driver.core.DPB(*, user=None, password=None, role=None, trusted_auth=False, sql_dialect=3, timeout=None, charset='UTF8', cache_size=None, no_gc=False, no_db_triggers=False, no_linger=False, utf8filename=False, dbkey_scope=None, dummy_packet_interval=None, overwrite=False, db_cache_size=None, forced_writes=None, reserve_space=None, page_size=None, read_only=False, sweep_interval=None, db_sql_dialect=None, db_charset=None, config=None, auth_plugin_list=None)

Bases: object

Database Parameter Buffer

clear()

Clear all information.

Return type

None

get_buffer(*, for_create=False)

Create DPB from stored information.

Return type

bytes

parse_buffer(buffer)

Load information from DPB.

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: Optional[str]

Configuration override

db_buffers

Number of pages in database cache [db create only]

db_cache_size: Optional[int]

Database cache size [db create only]

db_charset: Optional[str]

Character set for the database [db create only]

db_sql_dialect: Optional[int]

SQL dialect for the database [db create only]

dbkey_scope: Optional[DBKeyScope]

Scope for RDB$DB_KEY values

dummy_packet_interval: Optional[int]

Dummy packet interval for this database connection

forced_writes: Optional[bool]

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: Optional[int]

Database page size [db create only]

password: str

User password

read_only: bool

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

reserve_space: Optional[bool]

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

role: str

User role

sql_dialect: int

SQL Dialect for database connection

sweep_interval: Optional[int]

Sweep interval for the database [db create only]

timeout: Optional[int]

Connection timeout

trusted_auth: bool

Use trusted authentication

user: str

User name

utf8filename: bool

Database filename passed in UTF8

SPB_ATTACH

class firebird.driver.core.SPB_ATTACH(*, user=None, password=None, trusted_auth=False, config=None, auth_plugin_list=None)

Bases: object

Service Parameter Buffer

clear()

Clear all information.

Return type

None

get_buffer()

Create SPB_ATTACH from stored information.

Return type

bytes

parse_buffer(buffer)

Load information from SPB_ATTACH.

Return type

None

Buffer

class firebird.driver.core.Buffer(init, size=None, *, factory=<class 'firebird.base.buffer.BytesBufferFactory'>, max_size=Sentinel('UNLIMITED'), byteorder=<ByteOrder.LITTLE: 'little'>)

Bases: firebird.base.buffer.MemoryBuffer

MemoryBuffer with extensions

get_tag()

Read 1 byte number (c_ubyte)

Return type

int

is_truncated()

Return True when positioned on isc_info_truncated tag

Return type

bool

rewind()

Set current position in buffer to beginning.

Return type

None

seek_last_data()

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

Return type

int

CBuffer

class firebird.driver.core.CBuffer(init, size=None, *, max_size=Sentinel('UNLIMITED'), byteorder=<ByteOrder.LITTLE: 'little'>)

Bases: firebird.driver.core.Buffer

ctypes MemoryBuffer with extensions

Classes

Connection

class firebird.driver.core.Connection(att, dsn, dpb=None, sql_dialect=3, charset=None)

Bases: firebird.base.logging.LoggingIdMixin

Connection to the database.

Note

Implements context manager protocol to call close() automatically.

Variables

default_tpb (bytes) – Default Transaction parameter buffer for started transactions. Default is set to SNAPSHOT isolation with WAIT lock resolution (infinite lock timeout).

exception DataError(*args, **kwargs)

Bases: firebird.driver.types.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: firebird.base.types.Error

Exception raised for all errors reported by Firebird.

gds_codes: Tuple[int] = ()
sqlcode: int = None
sqlstate: str = 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: firebird.driver.types.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: firebird.base.types.Error

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

exception InternalError(*args, **kwargs)

Bases: firebird.driver.types.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: firebird.driver.types.DatabaseError

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

Important

This exceptions is never directly thrown by Firebird driver.

exception OperationalError(*args, **kwargs)

Bases: firebird.driver.types.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: firebird.driver.types.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=None)

Starts new transaction managed by main_transaction.

Parameters

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

Return type

None

close()

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=False)

Commits the transaction managed by main_transaction.

Parameters

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

Return type

None

cursor()

Returns new Cursor instance associated with main_transaction.

Return type

Cursor

drop_database()

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)

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)

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()

Returns True if main_transaction has active transaction.

Return type

bool

is_closed()

Returns True if connection to the database is closed.

Important

Closed connection SHALL NOT be used anymore.

Return type

bool

ping()

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=False, savepoint=None)

Rolls back the transaction managed by main_transaction.

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

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

Return type

None

savepoint(name)

Creates a new savepoint for transaction managed by main_transaction.

Parameters

name (str) – Name for the savepoint

Return type

None

transaction_manager(default_tpb=None, default_action=<DefaultAction.COMMIT: 1>)

Create new TransactionManager instance for this connection.

Parameters
  • default_tpb (Optional[bytes]) – Default Transaction parameter buffer.

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

Return type

TransactionManager

property charset

Connection character set.

Return type

str

default_tpb: bytes

Default TPB for newly created transaction managers

property dsn

Connection string

Return type

str

property info

Access to various information about attached database.

Return type

DatabaseInfoProvider

property main_transaction

Main transaction manager for this connection.

Return type

TransactionManager

property query_transaction

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

Return type

TransactionManager

property sql_dialect

Connection SQL dialect.

Return type

int

property transactions

List of all transaction managers associated with connection.

Note

The first two are always main_transaction and query_transaction managers.

Return type

List[TransactionManager]

TransactionManager

class firebird.driver.core.TransactionManager(connection, default_tpb, default_action=<DefaultAction.COMMIT: 1>)

Bases: firebird.base.logging.LoggingIdMixin

Transaction manager.

Note

Implements context manager protocol to call close() automatically.

Variables
begin(tpb=None)

Starts new transaction managed by this instance.

Parameters

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

Return type

None

close()

Close the transaction manager and release all associated resources.

Important

Closed instance SHALL NOT be used anymore.

Return type

None

commit(*, retaining=False)

Commits the transaction managed by this instance.

Parameters

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

Return type

None

cursor()

Returns new Cursor instance associated with this instance.

Return type

Cursor

execute_immediate(sql)

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

Parameters

sql (str) – SQL statement to be executed.

Return type

None

is_active()

Returns True if transaction is active.

Return type

bool

is_closed()

Returns True if this transaction manager is closed.

Return type

bool

rollback(*, retaining=False, savepoint=None)

Rolls back the transaction managed by this instance.

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

  • savepoint (Optional[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)

Creates a new savepoint for transaction managed by this instance.

Parameters

name (str) – Name for the savepoint

Return type

None

property cursors

Cursors associated with this transaction

Return type

List[Cursor]

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

Access to various information about active transaction.

Return type

TransactionInfoProvider

property log_context
Return type

Connection

DistributedTransactionManager

class firebird.driver.core.DistributedTransactionManager(connections, default_tpb=None, default_action=<DefaultAction.COMMIT: 1>)

Bases: firebird.driver.core.TransactionManager

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

Note

Implements context manager protocol to call close() automatically.

Variables
  • default_tpb (bytes) – Default Transaction parameter buffer

  • default_action (DefaultAction) – Default action for implicit transaction end

begin(tpb=None)

Starts new distributed transaction managed by this instance.

Parameters

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

Return type

None

close()

Close the distributed transaction manager and release all associated resources.

Important

Closed instance SHALL NOT be used anymore.

Return type

None

commit(*, retaining=False)

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)

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.

Return type

Cursor

execute_immediate(sql)

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()

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=False, savepoint=None)

Rolls back the distributed transaction managed by this instance.

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

  • savepoint (Optional[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)

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

Parameters

name (str) – Name for the savepoint

Return type

None

property log_context
Return type

Connection

Statement

class firebird.driver.core.Statement(connection, stmt, sql, dialect)

Bases: firebird.base.logging.LoggingIdMixin

Prepared SQL statement.

Note

Implements context manager protocol to call free() automatically.

can_repeat()

Returns True if statement could be executed repeatedly.

Return type

bool

free()

Release the statement and all associated resources.

Important

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

Return type

None

has_cursor()

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

Return type

bool

property detailed_plan

Execution plan in new format (explained).

Return type

str

property log_context
Return type

Connection

property plan

Execution plan in classic format.

Return type

str

property sql

SQL statement.

Return type

str

property type

Statement type.

Return type

StatementType

Cursor

class firebird.driver.core.Cursor(connection, transaction)

Bases: firebird.base.logging.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.

call_procedure(proc_name, parameters=None)

Executes a stored procedure with the given name.

Parameters
  • proc_name (str) – Stored procedure name.

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

Return type

Optional[Tuple]

Returns

None or tuple with values returned by stored procedure.

callproc(proc_name, parameters=None)

Executes a stored procedure with the given name.

Parameters
  • proc_name (str) – Stored procedure name.

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

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.

Return type

None

close()

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, parameters=None)

Executes SQL command or prepared Statement.

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

Parameters
Return type

Cursor

Returns

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

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, seq_of_parameters)

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 (Union[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.

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.

Return type

None

fetch_absolute(position)

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

Optional[Tuple]

fetch_first()

Fetch the first row of a scrollable query result set.

Returns None if there is no row to be fetched.

Return type

Optional[Tuple]

fetch_last()

Fetch the last row of a scrollable query result set.

Returns None if there is no row to be fetched.

Return type

Optional[Tuple]

fetch_next()

Fetch the next row of a scrollable query result set.

Returns None if there is no row to be fetched.

Return type

Optional[Tuple]

fetch_prior()

Fetch the previous row of a scrollable query result set.

Returns None if there is no row to be fetched.

Return type

Optional[Tuple]

fetch_relative(offset)

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

Optional[Tuple]

fetchall()

Fetch all remaining rows of a query result set.

Return type

List[Tuple]

fetchmany(size=None)

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 (Optional[int]) – The number of rows to fetch.

Return type

List[Tuple]

fetchone()

Fetch the next row of a query result set.

Return type

Tuple

is_bof()

Returns True is scrollable cursor is positioned at the beginning.

Return type

bool

is_closed()

Returns True if cursor is closed.

Return type

bool

is_eof()

Returns True is scrollable cursor is positioned at the end.

Return type

bool

open(operation, parameters=None)

Executes SQL command or prepared Statement as scrollable.

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

Parameters

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.

Return type

Cursor

prepare(operation)

Creates prepared statement for repeated execution.

Parameters

operation (str) – SQL command.

Return type

Statement

set_cursor_name(name)

Sets name for the SQL cursor.

Parameters

name (str) – Cursor name.

Return type

None

setinputsizes(sizes)

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

Return type

None

setoutputsize(size, column=None)

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

Return type

None

property affected_rows

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.

Return type

int

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 associated with cursor.

Return type

Connection

property description

List of 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)

Return type

Tuple[str, type, int, int, int, int, bool]

property log_context
Return type

Connection

property name

Name set for cursor.

Return type

str

property rowcount

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.

Return type

int

property statement

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

Return type

Statement

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

Transaction manager associated with cursor.

Return type

TransactionManager

Server

class firebird.driver.core.Server(svc, spb, host)

Bases: firebird.base.logging.LoggingIdMixin

Represents connection to Firebird Service Manager.

Note

Implements context manager protocol to call close() automatically.

close()

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()

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()

Get next line of textual output from last service query.

Return type

Optional[str]

readlines()

Get list of remaining output lines from last service query.

Return type

List[str]

wait()

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

Return type

None

property database

Access to various database-related actions and services.

Return type

ServerDbServices

host: str

Server host

property info

Access to various information about attached server.

Return type

ServerInfoProvider

response: CBuffer

Response buffer used to comunicate with service

spb: bytes

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

property trace

Access to various database-related actions and services.

Return type

ServerTraceServices

property user

Access to various user-related actions and services.

Return type

ServerUserServices

ServerServiceProvider

class firebird.driver.core.ServerServiceProvider(server)

Bases: object

Base class for server service providers.

ServerDbServices

class firebird.driver.core.ServerDbServices(server)

Bases: firebird.driver.core.ServerServiceProvider

Database-related actions and services.

activate_shadow(*, database)

Activate database shadow.

Parameters

database (str) – Database specification or alias.

Return type

None

backup(*, database, backup, backup_file_sizes=(), flags=<SrvBackupFlag.NONE: 0>, callback=None, stats=None, verbose=False, skip_data=None)

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

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

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

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

  • flags (SrvBackupFlag) – Backup options.

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

  • stats (Optional[str]) – Backup statistic options (TDWR).

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

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

Return type

None

bring_online(*, database, mode=<OnlineMode.NORMAL: 0>)

Bring previously shut down database back online.

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

  • mode (OnlineMode) – Online mode.

Return type

None

commit_limbo_transaction(*, database, transaction_id)

Resolve limbo transaction with commit.

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

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

Return type

None

get_limbo_transaction_ids(*, database)

Returns list of transactions in limbo.

Parameters

database (str) – Database specification or alias.

Return type

List[int]

get_statistics(*, database, flags=<SrvStatFlag.DEFAULT: 9>, tables=None, callback=None)

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

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

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

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

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

Return type

None

local_backup(*, database, backup_stream, flags=<SrvBackupFlag.NONE: 0>, skip_data=None)

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

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

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

  • flags (SrvBackupFlag) – Backup options.

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

Return type

None

local_restore(*, backup_stream, database, db_file_pages=(), flags=<SrvRestoreFlag.CREATE: 8192>, skip_data=None, page_size=None, buffers=None, access_mode=<DbAccessMode.READ_WRITE: 40>)

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

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

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

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

  • flags (SrvRestoreFlag) – Restore options.

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

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

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

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

Return type

None

nbackup(*, database, backup, level=0, direct=None, flags=<SrvNBackupFlag.NONE: 0>)

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

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

  • backup (str) – Backup file specification.

  • level (int) – Backup level.

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

  • flags (SrvNBackupFlag) – Backup options.

Return type

None

no_linger(*, database)

Set one-off override for database linger.

Parameters

database (str) – Database specification or alias.

Return type

None

nrestore(*, backups, database, direct=False, flags=<SrvNBackupFlag.NONE: 0>)

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

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

  • database (str) – Database specification or alias.

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

  • flags (SrvNBackupFlag) – Restore options.

Return type

None

repair(*, database, flags=<SrvRepairFlag.REPAIR: 164>)

Perform database repair operation. (SYNC service)

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

  • flags (SrvRepairFlag) – Repair flags.

Return type

bytes

restore(*, backup, database, db_file_pages=(), flags=<SrvRestoreFlag.CREATE: 8192>, callback=None, stats=None, verbose=True, skip_data=None, page_size=None, buffers=None, access_mode=<DbAccessMode.READ_WRITE: 40>)

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

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

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

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

  • flags (SrvRestoreFlag) – Restore options.

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

  • stats (Optional[str]) – Restore statistic options (TDWR).

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

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

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

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

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

Return type

None

rollback_limbo_transaction(*, database, transaction_id)

Resolve limbo transaction with rollback.

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

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

Return type

None

set_access_mode(*, database, mode)

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

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

  • mode (DbAccessMode) – New value.

Return type

None

set_default_cache_size(*, database, size)

Set individual page cache size for database.

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

  • size (int) – New value.

Return type

None

set_space_reservation(*, database, mode)

Set space reservation for database.

Parameters
Return type

None

set_sql_dialect(*, database, dialect)

Set database SQL dialect.

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

  • dialect (int) – New value.

Return type

None

set_sweep_interval(*, database, interval)

Set database sweep interval.

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

  • interval (int) – New value.

Return type

None

set_write_mode(*, database, mode)

Set database write mode (SYNC/ASYNC).

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

  • mode (DbWriteMode) – New value.

Return type

None

shutdown(*, database, mode, method, timeout)

Database shutdown.

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

  • mode (ShutdownMode) – Shutdown mode.

  • method (ShutdownMethod) – Shutdown method.

  • timeout (int) – Timeout for shutdown.

Return type

None

sweep(*, database)

Perform database sweep operation.

Parameters

database (str) – Database specification or alias.

Return type

None

validate(*, database, include_table=None, exclude_table=None, include_index=None, exclude_index=None, lock_timeout=None, callback=None)

Perform database validation. (ASYNC service)

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

  • flags – Repair flags.

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

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

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

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

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

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

Return type

None

ServerUserServices

class firebird.driver.core.ServerUserServices(server)

Bases: firebird.driver.core.ServerServiceProvider

User-related actions and services.

add(*, user_name, password, user_id=None, group_id=None, first_name=None, middle_name=None, last_name=None, admin=None, database=None, sql_role=None)

Add new user.

Parameters
  • user_name (str) – User name.

  • password (str) – User password.

  • user_id (Optional[int]) – User ID.

  • group_id (Optional[int]) – Group ID.

  • firest_name – User’s first name.

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

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

  • admin (Optional[bool]) – Admin flag.

  • database (Optional[str]) – Database specification or alias.

  • sql_role (Optional[str]) – SQL role name.

Return type

None

delete(user_name, *, database=None, sql_role=None)

Delete user.

Parameters
  • user_name (str) – User name.

  • database (Optional[str]) – Database specification or alias.

  • sql_role (Optional[str]) – SQL role name.

Return type

None

exists(user_name, *, database=None, sql_role=None)

Returns True if user exists.

Parameters
  • user_name (str) – User name.

  • database (Optional[str]) – Database specification or alias.

  • sql_role (Optional[str]) – SQL role name.

Return type

bool

get(user_name, *, database=None, sql_role=None)

Get information about user.

Parameters
  • user_name (str) – User name.

  • database (Optional[str]) – Database specification or alias.

  • sql_role (Optional[str]) – SQL role name.

Return type

Optional[UserInfo]

get_all(*, database=None, sql_role=None)

Get information about users.

Parameters
Return type

List[UserInfo]

update(user_name, *, password=None, user_id=None, group_id=None, first_name=None, middle_name=None, last_name=None, admin=None)

Update user information.

Parameters
Return type

None

ServerTraceServices

class firebird.driver.core.ServerTraceServices(server)

Bases: firebird.driver.core.ServerServiceProvider

Trace session actions and services.

resume(*, session_id)

Resume trace session.

Parameters

session_id (int) – Trace session ID.

Return type

None

start(*, config, name=None)

Start new trace session. (ASYNC service)

Parameters
  • config (str) – Trace session configuration.

  • name (Optional[str]) – Trace session name.

Return type

int

Returns

Trace session ID.

stop(*, session_id)

Stop trace session.

Parameters

session_id (int) – Trace session ID.

Return type

None

suspend(*, session_id)

Suspend trace session.

Parameters

session_id (int) – Trace session ID.

Return type

None

property sessions

Dictionary with active trace sessions.

Return type

Dict[int, TraceSession]

InfoProvider

class firebird.driver.core.InfoProvider(charset, buffer_size=256)

Bases: abc.ABC

Abstract base class for embedded information providers.

Variables
  • response (CBuffer) – Internal buffer for response packet acquired via Firebird API.

  • request (Buffer) – Internal buffer for information request packet needed by Firebird API.

abstract _acquire(request)

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()

Close the information source.

Return type

None

_get_data(request, max_size=32767)

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

DatabaseInfoProvider

class firebird.driver.core.DatabaseInfoProvider(connection)

Bases: firebird.driver.core.InfoProvider

Provides access to information about attached database.

Important

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

_acquire(request)

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()

Drops the association with attached database.

Return type

None

get_active_transaction_count()

Returns number of active transactions.

Return type

int

get_active_transaction_ids()

Returns list of IDs of active transactions.

Return type

List[int]

get_info(info_code, page_number=None)

Returns requested information from associated attachment.

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

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

Return type

Any

Returns

The data type of returned value depends on information required.

get_page_content(page_number)

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()

Returns actual table access statistics.

Return type

List[TableAccessStats]

is_compressed()

Returns True if connection to the server uses data compression

Return type

bool

is_encrypted()

Returns True if connection to the server uses data encryption

Return type

bool

property access_mode

Database access mode (READ_ONLY or READ_WRITE).

Return type

DbAccessMode

property attachment_id

Attachment ID.

Return type

int

property cache_hit_ratio

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

Return type

int

property charset

Database character set.

Return type

str

property creation_date

Date when database was created.

Return type

date

property current_memory

Total amount of memory curretly used by database engine.

Return type

int

property db_class

Database Class.

Return type

DbClass

property engine_version

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

Return type

float

property fetches

Current I/O statistics - Fetches from page cache

Return type

int

property firebird_version

Firebird server version.

Return type

str

property implementation

Implementation (old format).

Return type

Implementation

property marks

Current I/O statistics - Writes to page in cache

Return type

int

property max_memory

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

Return type

int

property name

Database name (filename or alias).

Return type

str

property next_transaction

ID for next transaction.

Return type

int

property oat

ID of Oldest Active Transaction.

Return type

int

property ods

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

Return type

float

property ods_minor_version

Database On-Disk Structure MINOR version.

Return type

int

property ods_version

Database On-Disk Structure MAJOR version.

Return type

int

property oit

ID of Oldest Interesting Transaction.

Return type

int

property ost

ID of Oldest Snapshot Transaction.

Return type

int

property page_cache_size

Size of page cache used by connection.

Return type

int

property page_size

Page size (in bytes).

Return type

int

property pages_allocated

Number of pages allocated for database.

Return type

int

property pages_free

Number of free allocated pages in database.

Return type

int

property pages_used

Number of database pages in active use.

Return type

int

property provider

Database Provider.

Return type

DbProvider

property reads

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

Return type

int

property server_version

Firebird server version (compatible with InterBase version).

Return type

str

property site

Database site name.

Return type

str

property space_reservation

Data page space usage (USE_FULL or RESERVE).

Return type

DbSpaceReservation

property sql_dialect

SQL dialect used by connected database.

Return type

int

property sweep_interval

Sweep interval.

Return type

int

property version

Firebird version as SEMVER string.

Return type

str

property write_mode

Database write mode (SYNC or ASYNC).

Return type

DbWriteMode

property writes

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

Return type

int

TransactionInfoProvider

class firebird.driver.core.TransactionInfoProvider(charset, tra)

Bases: firebird.driver.core.InfoProvider

Provides access to information about attached database.

Important

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

get_info(info_code)
Return type

Any

is_read_only()

Returns True if transaction is Read Only.

Return type

bool

property database

Database filename

Return type

str

property id

Transaction ID

Return type

int

property isolation

Isolation level

Return type

Isolation

property lock_timeout

Lock timeout

Return type

int

property oat

ID of Oldest Active Transaction at the time this transaction started

Return type

int

property oit

ID of Oldest Interesting Transaction at the time this transaction started

Return type

int

property ost

ID of Oldest Snapshot Transaction at the time this transaction started

Return type

int

ServerInfoProvider

class firebird.driver.core.ServerInfoProvider(charset, server)

Bases: firebird.driver.core.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.

_acquire(request)

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()

Drops the association with attached server.

Return type

None

get_info(info_code)

Returns requested information from connected server.

Parameters

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

Return type

Any

Returns

The data type of returned value depends on information required.

get_log(callback=None)

Request content of Firebird Server log. (ASYNC service)

Parameters

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

Return type

None

property architecture

Server implementation description.

Return type

str

property attached_databases

List of attached databases.

Return type

List[str]

property capabilities

Server capabilities.

Return type

ServerCapability

property connection_count

Number of database attachments.

Return type

int

property engine_version

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

Return type

float

property home_directory

Server home directory.

Return type

str

property lock_directory

Directory with lock file(s).

Return type

str

property manager_version

Service manager version.

Return type

int

property message_directory

Directory with message file(s).

Return type

str

property security_database

Path to security database.

Return type

str

property version

Firebird version as SEMVER string.

Return type

str

EventCollector

class firebird.driver.core.EventCollector(db_handle, event_names)

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.

begin()

Starts listening for events.

Must be called directly or through context manager interface.

Return type

None

close()

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()

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

Return type

None

is_closed()

Returns True if collector is closed.

Return type

bool

wait(timeout=None)

Wait for events.

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

Parameters

timeout (Union[int, float, None]) – 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.

Return type

Dict[str, int]

Returns

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

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.

EventBlock

class firebird.driver.core.EventBlock(queue, db_handle, event_names)

Bases: object

Used internally by EventCollector.

close()

Close this block canceling managed events.

Return type

None

count_and_reregister()

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

Return type

Dict[str, int]

is_closed()

Returns True if event block is closed.

Return type

bool

BlobReader

class firebird.driver.core.BlobReader(blob, blob_id, sub_type, length, segment_size, charset, owner=None)

Bases: io.IOBase, firebird.base.logging.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.

Variables
  • sub_type (int) – BLOB sub-type

  • newline (str) – Sequence used as line terminator, default '\n'

Note

Implements context manager protocol to call close() automatically.

Variables

sub_type (int) – BLOB sub-type

close()

Flush and close the IO object.

This method has no effect if the file is already closed.

Return type

None

flush()

Does nothing.

Return type

None

is_text()

True if BLOB is a text BLOB

Return type

bool

read(size=- 1)

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.

Return type

Union[str, bytes]

readline(size=- 1)

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.

Return type

str

readlines(hint=- 1)

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.

Return type

List[str]

seek(offset, whence=0)

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

Warning

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

Return type

None

tell()

Return current position in BLOB.

See:

io.IOBase.tell() for details.

Return type

int

property blob_id

BLOB ID

Return type

ISC_QUAD

property blob_type

BLOB type

Return type

BlobType

property closed

True if the BLOB is closed.

Return type

bool

property length

BLOB length

Return type

int

property log_context
Return type

Any

property mode

File mode (‘r’ or ‘rb’)

Return type

str