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

temp_database

firebird.driver.core.temp_database(*args, **kwargs)

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

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

Establishes a connection to the 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.

  • auth_plugin_list (Optional[str]) – List of authentication plugins override

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

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

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.

  • auth_plugin_list – List of authentication plugins override

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

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, expected_db=None, role=None, encoding=None, encoding_errors=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_mode=TraAccessMode.WRITE)

Helper function to costruct simple TPB.

Parameters
  • isolation (Isolation) – Isolation level.

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

  • access – Access mode.

Return type

bytes

Managers for parameter buffers

TPB

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

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, session_time_zone=None, set_db_replica=None, set_bind=None, decfloat_round=None, decfloat_traps=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

decfloat_round: Optional[DecfloatRound]

Set DECFLOAT ROUND [Firebird 4]

decfloat_traps: Optional[List[DecfloatTraps]]

Set DECFLOAT TRAPS [Firebird 4]

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

session_time_zone: Optional[str]

Session time zone [Firebird 4]

set_bind: Optional[str]

Set BIND [Firebird 4]

set_db_replica: Optional[ReplicaMode]

Set replica mode [Firebird 4]

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, expected_db=None, encoding='ascii', errors='strict', role=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)

Bases: 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)

Bases: Buffer

ctypes MemoryBuffer with extensions.

Classes

Connection

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

Bases: LoggingIdMixin

Connection to the database.

Note

Implements context manager protocol to call close() automatically.

default_tpb

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

Type

bytes

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

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: str

Connection character set.

Return type

str

default_tpb: bytes

Default TPB for newly created transaction managers

property dsn: str

Connection string.

Return type

str

property info: Union[DatabaseInfoProvider3, DatabaseInfoProvider]

Access to various information about attached database.

Return type

Union[DatabaseInfoProvider3, DatabaseInfoProvider]

property main_transaction: TransactionManager

Main transaction manager for this connection.

Return type

TransactionManager

property monitor: firebird.lib.monitor.Monitor

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

Return type

firebird.lib.monitor.Monitor

property query_transaction: TransactionManager

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

Return type

TransactionManager

property schema: firebird.lib.schema.Schema

Access to database schema. Requires firebird.lib package.

Return type

firebird.lib.schema.Schema

property sql_dialect: int

Connection SQL dialect.

Return type

int

property transactions: List[TransactionManager]

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)

Bases: LoggingIdMixin

Transaction manager.

Note

Implements context manager protocol to call close() automatically.

default_tpb

Default Transaction parameter buffer.

Type

bytes

default_action

Default action for implicit transaction end.

Type

DefaultAction

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: List[Cursor]

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: Union[TransactionInfoProvider3, TransactionInfoProvider]

Access to various information about active transaction.

Return type

Union[TransactionInfoProvider3, TransactionInfoProvider]

property log_context: Connection
Return type

Connection

DistributedTransactionManager

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

Bases: TransactionManager

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

Note

Implements context manager protocol to call close() automatically.

default_tpb

Default Transaction parameter buffer

Type

bytes

default_action

Default action for implicit transaction end

Type

DefaultAction

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

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 log_context: Connection
Return type

Connection

Statement

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

Bases: 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: str

Execution plan in new format (explained).

Return type

str

property log_context: Connection
Return type

Connection

property plan: str

Execution plan in classic format.

Return type

str

property sql: str

SQL statement.

Return type

str

property timeout: int

Statement timeout.

Return type

int

property type: StatementType

Statement type.

Return type

StatementType

Cursor

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

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.

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

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

Connection associated with cursor.

Return type

Connection

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)

Return type

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

property log_context: Connection
Return type

Connection

property name: str

Name set for cursor.

Return type

str

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.

Return type

int

property statement: 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: TransactionManager

Transaction manager associated with cursor.

Return type

TransactionManager

Server

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

Bases: 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: Union[ServerDbServices3, ServerDbServices]

Access to various database-related actions and services.

Return type

Union[ServerDbServices3, ServerDbServices]

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.

Return type

ServerInfoProvider

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.

Return type

ServerTraceServices

property user: ServerUserServices

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.

ServerDbServices3

class firebird.driver.core.ServerDbServices3(server)

Bases: ServerServiceProvider

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

activate_shadow(*, database, role=None)

Activate database shadow.

Parameters
  • database (Union[str, Path]) – Database specification or alias.

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

Return type

None

backup(*, database, backup, backup_file_sizes=(), flags=SrvBackupFlag.NONE, role=None, callback=None, stats=None, verbose=False, verbint=None, skip_data=None, include_data=None, keyhoder=None, keyname=None, crypt=None)

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

Parameters
  • database (Union[str, Path]) – Database file specification or alias.

  • backup (Union[str, Path, Sequence[Union[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 (Optional[str]) – SQL ROLE name passed to gbak.

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

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

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

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

  • keyholder – Keyholder name [Firebird 4]

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

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

Return type

None

bring_online(*, database, mode=OnlineMode.NORMAL, role=None)

Bring previously shut down database back online.

Parameters
Return type

None

commit_limbo_transaction(*, database, transaction_id)

Resolve limbo transaction with commit.

Parameters
  • database (Union[str, Path]) – 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 (Union[str, Path]) – Database specification or alias.

Return type

List[int]

get_statistics(*, database, flags=SrvStatFlag.DEFAULT, role=None, tables=None, callback=None)

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

Parameters
  • database (Union[str, Path]) – Database specification or alias.

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

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

  • 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, role=None, skip_data=None, include_data=None, keyhoder=None, keyname=None, crypt=None)

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

Parameters
  • database (Union[str, Path]) – Database specification or alias.

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

  • flags (SrvBackupFlag) – Backup options.

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

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

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

  • keyholder – Keyholder name [Firebird 4]

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

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

Return type

None

local_restore(*, backup_stream, database, db_file_pages=(), flags=SrvRestoreFlag.CREATE, role=None, skip_data=None, page_size=None, buffers=None, access_mode=DbAccessMode.READ_WRITE, include_data=None, keyhoder=None, keyname=None, crypt=None, replica_mode=None)

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, Path, Sequence[Union[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 (Optional[str]) – SQL ROLE name passed to gbak.

  • 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).

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

  • keyholder – Keyholder name [Firebird 4]

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

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

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

Return type

None

nbackup(*, database, backup, level=0, direct=None, flags=SrvNBackupFlag.NONE, role=None, guid=None)

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

Parameters

Important

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

Return type

None

no_linger(*, database, role=None)

Set one-off override for database linger.

Parameters
  • database (Union[str, Path]) – Database specification or alias.

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

Return type

None

nrestore(*, backups, database, direct=False, flags=SrvNBackupFlag.NONE, role=None)

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

Parameters
Return type

None

repair(*, database, flags=SrvRepairFlag.REPAIR, role=None)

Perform database repair operation. (SYNC service)

Parameters
Return type

bytes

restore(*, backup, database, db_file_pages=(), flags=SrvRestoreFlag.CREATE, role=None, callback=None, stats=None, verbose=False, verbint=None, skip_data=None, page_size=None, buffers=None, access_mode=DbAccessMode.READ_WRITE, include_data=None, keyhoder=None, keyname=None, crypt=None, replica_mode=None)

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

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

  • database (Union[str, Path, Sequence[Union[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 (Optional[str]) – SQL ROLE name passed to gbak.

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

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

  • 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).

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

  • keyholder – Keyholder name [Firebird 4]

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

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

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

Return type

None

rollback_limbo_transaction(*, database, transaction_id)

Resolve limbo transaction with rollback.

Parameters
  • database (Union[str, Path]) – Database specification or alias.

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

Return type

None

set_access_mode(*, database, mode, role=None)

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

Parameters
Return type

None

set_default_cache_size(*, database, size, role=None)

Set individual page cache size for database.

Parameters
  • database (Union[str, Path]) – Database specification or alias.

  • size (int) – New value.

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

Return type

None

set_space_reservation(*, database, mode, role=None)

Set space reservation for database.

Parameters
Return type

None

set_sql_dialect(*, database, dialect, role=None)

Set database SQL dialect.

Parameters
  • database (Union[str, Path]) – Database specification or alias.

  • dialect (int) – New value.

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

Return type

None

set_sweep_interval(*, database, interval, role=None)

Set database sweep interval.

Parameters
  • database (Union[str, Path]) – Database specification or alias.

  • interval (int) – New value.

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

Return type

None

set_write_mode(*, database, mode, role=None)

Set database write mode (SYNC/ASYNC).

Parameters
Return type

None

shutdown(*, database, mode, method, timeout, role=None)

Database shutdown.

Parameters
Return type

None

sweep(*, database, role=None)

Perform database sweep operation.

Parameters
  • database (Union[str, Path]) – Database specification or alias.

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

Return type

None

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

Perform database validation. (ASYNC service)

Parameters
  • database (Union[str, Path]) – 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.

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

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

Return type

None

ServerDbServices

class firebird.driver.core.ServerDbServices(server)

Bases: ServerDbServices3

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

nfix_database(*, database, role=None, flags=SrvNBackupFlag.NONE)

Fixup database after filesystem copy.

Parameters
Return type

None

set_replica_mode(*, database, mode, role=None)

Manage replica database.

Parameters
Return type

None

ServerUserServices

class firebird.driver.core.ServerUserServices(server)

Bases: 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
Return type

None

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

Delete user.

Parameters
Return type

None

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

Returns True if user exists.

Parameters
Return type

bool

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

Get information about user.

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

Update user information.

Parameters
Return type

None

ServerTraceServices

class firebird.driver.core.ServerTraceServices(server)

Bases: ServerServiceProvider

Trace session actions and services.

resume(*, session_id)

Resume trace session.

Parameters

session_id (int) – Trace session ID.

Return type

str

Returns

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

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

str

Returns

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

suspend(*, session_id)

Suspend trace session.

Parameters

session_id (int) – Trace session ID.

Return type

str

Returns

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

property sessions: Dict[int, TraceSession]

Dictionary with active trace sessions.

Return type

Dict[int, TraceSession]

InfoProvider

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

Bases: ABC

Abstract base class for embedded information providers.

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)

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

property idle_timeout: int

Attachment idle timeout.

Return type

int

property statement_timeout: int

Statement timeout.

Return type

int

TransactionInfoProvider

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

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.

property snapshot_number: int

Snapshot number for this transaction.

Return type

int

ServerInfoProvider

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

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.

_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: str

Server implementation description.

Return type

str

property attached_databases: List[str]

List of attached databases.

Return type

List[str]

property capabilities: ServerCapability

Server capabilities.

Return type

ServerCapability

property connection_count: int

Number of database attachments.

Return type

int

property engine_version: float

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

Return type

float

property home_directory: str

Server home directory.

Return type

str

property lock_directory: str

Directory with lock file(s).

Return type

str

property manager_version: int

Service manager version.

Return type

int

property message_directory: str

Directory with message file(s).

Return type

str

property security_database: str

Path to security database.

Return type

str

property version: str

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

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.

sub_type

BLOB sub-type

Type

int

close()

Close the BlobReader.

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: ISC_QUAD

BLOB ID.

Return type

ISC_QUAD

property blob_type: BlobType

BLOB type.

Return type

BlobType

property closed: bool

True if the BLOB is closed.

Return type

bool

property length: int

BLOB length.

Return type

int

property log_context: Any
Return type

Any

property mode: str

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

Return type

str