Skip to content

firebird.driver.core

This is the main code module of the Firebird driver.

Constants and variables

C integer limit constants

  • SHRT_MIN
  • SHRT_MAX
  • USHRT_MAX
  • INT_MIN
  • INT_MAX
  • UINT_MAX
  • LONG_MIN
  • LONG_MAX

Translation dictionaries

firebird.driver.core.CHARSET_MAP module-attribute

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

Other constants and variables

firebird.driver.core.MAX_BLOB_SEGMENT_SIZE module-attribute

Max BLOB segment size

firebird.driver.core.FS_ENCODING module-attribute

Current filesystem encoding

firebird.driver.core._master: iMaster module-attribute

Firebird .iMaster interface

firebird.driver.core._util: iUtil module-attribute

Firebird .iUtil interface

Context managers

firebird.driver.core.transaction(transact_object: Transactional, *, tpb: bytes | None = None, bypass: bool = False) -> Transactional

Context manager for ~firebird.driver.types.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:

Name Type Description Default
transact_object Transactional

Managed transactional object.

required
tpb bytes | None

Transaction parameter buffer used to start the transaction.

None
bypass bool

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

False
Source code in firebird/driver/core.py
@contextlib.contextmanager
def transaction(transact_object: Transactional, *, tpb: bytes | None=None, bypass: bool=False) -> Transactional:
    """Context manager for `~firebird.driver.types.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.

    Arguments:
        transact_object: Managed transactional object.
        tpb: Transaction parameter buffer used to start the transaction.
        bypass: When both `bypass` and `transact_object.is_active()` are `True` when
                context is entered, the context manager does nothing on exit.
    """
    if bypass and transact_object.is_active():
        yield transact_object
    else:
        try:
            transact_object.begin(tpb)
            yield transact_object
        except:
            transact_object.rollback()
            raise
        else:
            transact_object.commit()

firebird.driver.core.temp_database(*args, **kwargs) -> Connection

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.

Source code in firebird/driver/core.py
@contextlib.contextmanager
def temp_database(*args, **kwargs) -> Connection:
    """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`.
    """
    con = create_database(*args, **kwargs)
    try:
        yield con
    except:
        con.drop_database()
        raise
    else:
        con.drop_database()

Functions

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

Establishes a connection to the database.

Parameters:

Name Type Description Default
database str | Path

DSN or Database configuration name. Could be also a Path object.

required
user str | None

User name.

None
password str | None

User password.

None
role str | None

User role.

None
no_gc bool | None

Do not perform garbage collection for this connection.

None
no_db_triggers bool | None

Do not execute database triggers for this connection.

None
dbkey_scope DBKeyScope | None

DBKEY scope override for connection.

None
crypt_callback iCryptKeyCallbackImpl | None

Callback that provides encryption key for the database.

None
charset str | None

Character set for connection.

None
auth_plugin_list str | None

List of authentication plugins override

None
session_time_zone str | None

Session time zone [Firebird 4]

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

Source code in firebird/driver/core.py
def connect(database: str | Path, *, user: str | None=None, password: str | None=None,
            role: str | None=None, no_gc: bool | None=None, no_db_triggers: bool | None=None,
            dbkey_scope: DBKeyScope | None=None, crypt_callback: iCryptKeyCallbackImpl | None=None,
            charset: str | None=None, auth_plugin_list: str | None=None,
            session_time_zone: str | None=None) -> Connection:
    """Establishes a connection to the database.

    Arguments:
        database: DSN or Database configuration name. Could be also a Path object.
        user: User name.
        password: User password.
        role: User role.
        no_gc: Do not perform garbage collection for this connection.
        no_db_triggers: Do not execute database triggers for this connection.
        dbkey_scope: DBKEY scope override for connection.
        crypt_callback: Callback that provides encryption key for the database.
        charset: Character set for connection.
        auth_plugin_list: List of authentication plugins override
        session_time_zone: 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.
    """
    if isinstance(database, Path):
        database = str(database)
    db_config: DatabaseConfig = driver_config.get_database(database)
    dsn: str | None = None
    if db_config is None:
        db_config = driver_config.db_defaults
        srv_config = driver_config.server_defaults
        if _is_dsn(database):
            dsn = database
            database = None
            srv_config.host.clear()
    else:
        database = db_config.database.value
        dsn = db_config.dsn.value
        if db_config.server.value is None:
            srv_config = driver_config.server_defaults
        else:
            srv_config = driver_config.get_server(db_config.server.value)
            if srv_config is None:
                raise ValueError(f"Configuration for server '{db_config.server.value}' not found")
    if user is None:
        user = db_config.user.value
        if user is None:
            user = srv_config.user.value
    if password is None:
        password = db_config.password.value
        if password is None:
            password = srv_config.password.value
    if role is None:
        role = db_config.role.value
    if charset is None:
        charset = db_config.charset.value
    if charset:
        charset = charset.upper()
    if auth_plugin_list is None:
        auth_plugin_list = db_config.auth_plugin_list.value
    if session_time_zone is None:
        session_time_zone = db_config.session_time_zone.value
    dsn = _connect_helper(dsn, srv_config.host.value, srv_config.port.value,
                          database, db_config.protocol.value)
    dpb = DPB(user=user, password=password, role=role, trusted_auth=db_config.trusted_auth.value,
              sql_dialect=db_config.sql_dialect.value, timeout=db_config.timeout.value,
              charset=charset, cache_size=db_config.cache_size.value,
              no_linger=db_config.no_linger.value, utf8filename=db_config.utf8filename.value,
              no_gc=no_gc, no_db_triggers=no_db_triggers, dbkey_scope=dbkey_scope,
              dummy_packet_interval=db_config.dummy_packet_interval.value,
              config=db_config.config.value, auth_plugin_list=auth_plugin_list,
              session_time_zone=session_time_zone, set_bind=db_config.set_bind.value,
              decfloat_round=db_config.decfloat_round.value,
              decfloat_traps=db_config.decfloat_traps.value,
              parallel_workers=db_config.parallel_workers.value)
    return __make_connection(dsn, db_config.utf8filename.value, dpb.get_buffer(),
                             db_config.sql_dialect.value, charset, crypt_callback, create=False)

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

Creates new database.

Parameters:

Name Type Description Default
database str | Path

DSN or Database configuration name.

required
user str | None

User name.

None
password str | None

User password.

None
role str | None

User role.

None
no_gc bool | None

Do not perform garbage collection for this connection.

None
no_db_triggers bool | None

Do not execute database triggers for this connection.

None
dbkey_scope DBKeyScope | None

DBKEY scope override for connection.

None
crypt_callback iCryptKeyCallbackImpl | None

Callback that provides encryption key for the database.

None
charset str | None

Character set for connection.

None
overwrite bool

Overwite the existing database.

False
auth_plugin_list str | None

List of authentication plugins override

None
session_time_zone str | None

Session time zone [Firebird 4]

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

Source code in firebird/driver/core.py
def create_database(database: str | Path, *, user: str | None=None, password: str | None=None,
                    role: str | None=None, no_gc: bool | None=None, no_db_triggers: bool | None=None,
                    dbkey_scope: DBKeyScope | None=None, crypt_callback: iCryptKeyCallbackImpl | None=None,
                    charset: str | None=None, overwrite: bool=False, auth_plugin_list: str | None=None,
                    session_time_zone: str | None=None) -> Connection:
    """Creates new database.

    Arguments:
        database: DSN or Database configuration name.
        user: User name.
        password: User password.
        role: User role.
        no_gc: Do not perform garbage collection for this connection.
        no_db_triggers: Do not execute database triggers for this connection.
        dbkey_scope: DBKEY scope override for connection.
        crypt_callback: Callback that provides encryption key for the database.
        charset: Character set for connection.
        overwrite: Overwite the existing database.
        auth_plugin_list: List of authentication plugins override
        session_time_zone: 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.
    """
    if isinstance(database, Path):
        database = str(database)
    db_config: DatabaseConfig = driver_config.get_database(database)
    dsn: str | None = None
    if db_config is None:
        db_config = driver_config.db_defaults
        srv_config = driver_config.server_defaults
        if _is_dsn(database):
            dsn = database
            database = None
            srv_config.host.clear()
    else:
        database = db_config.database.value
        dsn = db_config.dsn.value
        if db_config.server.value is None:
            srv_config = driver_config.server_defaults
        else:
            srv_config = driver_config.get_server(db_config.server.value)
            if srv_config is None:
                raise ValueError(f"Configuration for server '{db_config.server.value}' not found")
    if user is None:
        user = db_config.user.value
        if user is None:
            user = srv_config.user.value
    if password is None:
        password = db_config.password.value
        if password is None:
            password = srv_config.password.value
    if role is None:
        role = db_config.role.value
    if charset is None:
        charset = db_config.charset.value
    if charset:
        charset = charset.upper()
    if auth_plugin_list is None:
        auth_plugin_list = db_config.auth_plugin_list.value
    if session_time_zone is None:
        session_time_zone = db_config.session_time_zone.value
    dsn = _connect_helper(dsn, srv_config.host.value, srv_config.port.value,
                          database, db_config.protocol.value)
    dpb = DPB(user=user, password=password, role=role, trusted_auth=db_config.trusted_auth.value,
              sql_dialect=db_config.db_sql_dialect.value, timeout=db_config.timeout.value,
              charset=charset, cache_size=db_config.cache_size.value,
              no_linger=db_config.no_linger.value, utf8filename=db_config.utf8filename.value,
              no_gc=no_gc, no_db_triggers=no_db_triggers, dbkey_scope=dbkey_scope,
              dummy_packet_interval=db_config.dummy_packet_interval.value,
              config=db_config.config.value, auth_plugin_list=auth_plugin_list,
              session_time_zone=session_time_zone, set_bind=db_config.set_bind.value,
              decfloat_round=db_config.decfloat_round.value,
              decfloat_traps=db_config.decfloat_traps.value,
              overwrite=overwrite, db_cache_size=db_config.db_cache_size.value,
              forced_writes=db_config.forced_writes.value, page_size=db_config.page_size.value,
              reserve_space=db_config.reserve_space.value, sweep_interval=db_config.sweep_interval.value,
              db_sql_dialect=db_config.db_sql_dialect.value, db_charset=db_config.db_charset.value)
    return __make_connection(dsn, db_config.utf8filename.value,
                             dpb.get_buffer(for_create=True), db_config.sql_dialect.value,
                             charset, crypt_callback, create=True)

firebird.driver.core.connect_server(server: str, *, user: str | None = None, password: str | None = None, crypt_callback: iCryptKeyCallbackImpl | None = None, expected_db: str | None = None, role: str | None = None, encoding: str | None = None, encoding_errors: str | None = None) -> Server

Establishes a connection to server's service manager.

Parameters:

Name Type Description Default
server str

Server host machine or Server configuration name.

required
user str | None

User name.

None
password str | None

User password.

None
crypt_callback iCryptKeyCallbackImpl | None

Callback that provides encryption key.

None
expected_db str | None

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

None
role str | None

SQL role used for connection.

None
encoding str | None

Encoding for string values passed in parameter buffer. Default is .ServerConfig.encoding.

None
encoding_errors str | None

Error handler used for encoding errors. Default is .ServerConfig.encoding_errors.

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

Source code in firebird/driver/core.py
def connect_server(server: str, *, user: str | None=None, password: str | None=None,
                   crypt_callback: iCryptKeyCallbackImpl | None=None,
                   expected_db: str | None=None, role: str | None=None, encoding: str | None=None,
                   encoding_errors: str | None=None) -> Server:
    """Establishes a connection to server's service manager.

    Arguments:
        server: Server host machine or Server configuration name.
        user: User name.
        password: User password.
        crypt_callback: Callback that provides encryption key.
        expected_db: Database that would be accessed (for using services with non-default
                     security database)
        role: SQL role used for connection.
        encoding: Encoding for string values passed in parameter buffer. Default is
            `.ServerConfig.encoding`.
        encoding_errors: Error handler used for encoding errors. Default is
            `.ServerConfig.encoding_errors`.

    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.
    """
    srv_config = driver_config.get_server(server)
    if srv_config is None:
        srv_config = driver_config.server_defaults
        #host = server or None
        #port = None
    #else:
    host = srv_config.host.value
    port = srv_config.port.value
    if host is None:
        host = 'service_mgr'
    if not host.endswith('service_mgr'):
        if host and not host.endswith(':'):
            if port:
                host += f"/{port}"
            host += ':'
        host += 'service_mgr'
    if user is None:
        user = srv_config.user.value
    if password is None:
        password = srv_config.password.value
    spb = SPB_ATTACH(user=user, password=password, config=srv_config.config.value,
                     trusted_auth=srv_config.trusted_auth.value,
                     auth_plugin_list=srv_config.auth_plugin_list.value,
                     expected_db=expected_db, encoding=srv_config.encoding.value,
                     errors=srv_config.encoding_errors.value, role=role)
    spb_buf = spb.get_buffer()
    with a.get_api().master.get_dispatcher() as provider:
        if crypt_callback is not None:
            provider.set_dbcrypt_callback(crypt_callback)
        svc = provider.attach_service_manager(host, spb_buf)
    con = Server(svc, spb_buf, host, srv_config.encoding.value if encoding is None else encoding,
                 srv_config.encoding_errors.value if encoding_errors is None else encoding_errors)
    for hook in get_callbacks(ServerHook.ATTACHED, con):
        hook(con)
    return con

firebird.driver.core.tpb(isolation: Isolation, lock_timeout: int = INFINITE_TIMEOUT, access_mode: TraAccessMode = TraAccessMode.WRITE) -> bytes

Helper function to costruct simple TPB.

Parameters:

Name Type Description Default
isolation Isolation

Isolation level.

required
lock_timeout int

Lock timeout (-1 = Infinity)

INFINITE_TIMEOUT
access_mode TraAccessMode

Access mode.

WRITE
Source code in firebird/driver/core.py
def tpb(isolation: Isolation, lock_timeout: int=INFINITE_TIMEOUT,
        access_mode: TraAccessMode=TraAccessMode.WRITE) -> bytes:
    """Helper function to costruct simple TPB.

    Arguments:
        isolation: Isolation level.
        lock_timeout: Lock timeout (-1 = Infinity)
        access_mode: Access mode.
    """
    return TPB(isolation=isolation, lock_timeout=lock_timeout, access_mode=access_mode).get_buffer()

Managers for parameter buffers

firebird.driver.core.TPB

Helper class to build and parse Transaction Parameter Buffers (TPB) used when starting transactions.

Source code in firebird/driver/core.py
class TPB:
    """Helper class to build and parse Transaction Parameter Buffers (TPB) used when starting transactions.
    """
    def __init__(self, *, access_mode: TraAccessMode=TraAccessMode.WRITE,
                 isolation: Isolation=Isolation.SNAPSHOT,
                 lock_timeout: int=INFINITE_TIMEOUT,
                 no_auto_undo: bool=False,
                 auto_commit: bool=False,
                 ignore_limbo: bool=False,
                 at_snapshot_number: int | None=None,
                 encoding: str='ascii'):
        self.encoding: str = encoding
        self.access_mode: TraAccessMode = access_mode
        self.isolation: Isolation = isolation
        self.lock_timeout: int = lock_timeout
        self.no_auto_undo: bool = no_auto_undo
        self.auto_commit: bool = auto_commit
        self.ignore_limbo: bool = ignore_limbo
        self._table_reservation: list[tuple[str, TableShareMode, TableAccessMode]] = []
        # Firebird 4
        self.at_snapshot_number: int | None = at_snapshot_number
    def clear(self) -> None:
        """Clear all information.
        """
        self.access_mode = TraAccessMode.WRITE
        self.isolation = Isolation.SNAPSHOT
        self.lock_timeout = -1
        self.no_auto_undo = False
        self.auto_commit = False
        self.ignore_limbo = False
        self._table_reservation = []
        # Firebird 4
        self.at_snapshot_number = None
    def parse_buffer(self, buffer: bytes) -> None:
        """Load information from TPB.
        """
        self.clear()
        with a.get_api().util.get_xpb_builder(XpbKind.TPB, buffer) as tpb:
            while not tpb.is_eof():
                tag = tpb.get_tag()
                if tag in TraAccessMode._value2member_map_:
                    self.access_mode = TraAccessMode(tag)
                elif tag in TraIsolation._value2member_map_:
                    isolation = TraIsolation(tag)
                    if isolation != TraIsolation.READ_COMMITTED:
                        self.isolation = Isolation(isolation)
                elif tag in TraReadCommitted._value2member_map_:
                    isolation = TraReadCommitted(tag)
                    if isolation == TraReadCommitted.RECORD_VERSION:
                        self.isolation = Isolation.READ_COMMITTED_RECORD_VERSION
                    elif isolation == TraReadCommitted.NO_RECORD_VERSION:
                        self.isolation = Isolation.READ_COMMITTED_NO_RECORD_VERSION
                    else:
                        self.isolation = Isolation.READ_COMMITTED_READ_CONSISTENCY
                elif tag in TraLockResolution._value2member_map_:
                    self.lock_timeout = -1 if TraLockResolution(tag) is TraLockResolution.WAIT else 0
                elif tag == TPBItem.AUTOCOMMIT:
                    self.auto_commit = True
                elif tag == TPBItem.NO_AUTO_UNDO:
                    self.no_auto_undo = True
                elif tag == TPBItem.IGNORE_LIMBO:
                    self.ignore_limbo = True
                elif tag == TPBItem.LOCK_TIMEOUT:
                    self.lock_timeout = tpb.get_int()
                elif tag == TPBItem.AT_SNAPSHOT_NUMBER:
                    self.at_snapshot_number = tpb.get_bigint()
                elif tag in TableAccessMode._value2member_map_:
                    tbl_access = TableAccessMode(tag)
                    tbl_name = tpb.get_string(encoding=self.encoding)
                    tpb.move_next()
                    if tpb.is_eof():
                        raise ValueError(f"Missing share mode value in table {tbl_name} reservation")
                    if (val := tpb.get_tag()) not in TableShareMode._value2member_map_:
                        raise ValueError(f"Missing share mode value in table {tbl_name} reservation")
                    tbl_share = TableShareMode(val)
                    self.reserve_table(tbl_name, tbl_share, tbl_access)
                tpb.move_next()
    def get_buffer(self) -> bytes:
        """Create TPB from stored information.
        """
        with a.get_api().util.get_xpb_builder(XpbKind.TPB) as tpb:
            tpb.insert_tag(self.access_mode)
            isolation = (Isolation.READ_COMMITTED_RECORD_VERSION
                         if self.isolation == Isolation.READ_COMMITTED
                         else self.isolation)
            if isolation in (Isolation.SNAPSHOT, Isolation.SERIALIZABLE):
                tpb.insert_tag(isolation)
            elif isolation == Isolation.READ_COMMITTED_READ_CONSISTENCY:
                tpb.insert_tag(TPBItem.READ_CONSISTENCY)
            else:
                tpb.insert_tag(TraIsolation.READ_COMMITTED)
                tpb.insert_tag(TraReadCommitted.RECORD_VERSION
                               if isolation == Isolation.READ_COMMITTED_RECORD_VERSION
                               else TraReadCommitted.NO_RECORD_VERSION)
            tpb.insert_tag(TraLockResolution.NO_WAIT if self.lock_timeout == 0 else TraLockResolution.WAIT)
            if self.lock_timeout > 0:
                tpb.insert_int(TPBItem.LOCK_TIMEOUT, self.lock_timeout)
            if self.auto_commit:
                tpb.insert_tag(TPBItem.AUTOCOMMIT)
            if self.no_auto_undo:
                tpb.insert_tag(TPBItem.NO_AUTO_UNDO)
            if self.ignore_limbo:
                tpb.insert_tag(TPBItem.IGNORE_LIMBO)
            if self.at_snapshot_number is not None:
                tpb.insert_bigint(TPBItem.AT_SNAPSHOT_NUMBER, self.at_snapshot_number)
            for table in self._table_reservation:
                # Access mode + table name
                tpb.insert_string(table[2], table[0], encoding=self.encoding)
                tpb.insert_tag(table[1])  # Share mode
            result = tpb.get_buffer()
        return result
    def reserve_table(self, name: str, share_mode: TableShareMode, access_mode: TableAccessMode) -> None:
        """Set information about table reservation.
        """
        self._table_reservation.append((name, share_mode, access_mode))

clear() -> None

Clear all information.

Source code in firebird/driver/core.py
def clear(self) -> None:
    """Clear all information.
    """
    self.access_mode = TraAccessMode.WRITE
    self.isolation = Isolation.SNAPSHOT
    self.lock_timeout = -1
    self.no_auto_undo = False
    self.auto_commit = False
    self.ignore_limbo = False
    self._table_reservation = []
    # Firebird 4
    self.at_snapshot_number = None

get_buffer() -> bytes

Create TPB from stored information.

Source code in firebird/driver/core.py
def get_buffer(self) -> bytes:
    """Create TPB from stored information.
    """
    with a.get_api().util.get_xpb_builder(XpbKind.TPB) as tpb:
        tpb.insert_tag(self.access_mode)
        isolation = (Isolation.READ_COMMITTED_RECORD_VERSION
                     if self.isolation == Isolation.READ_COMMITTED
                     else self.isolation)
        if isolation in (Isolation.SNAPSHOT, Isolation.SERIALIZABLE):
            tpb.insert_tag(isolation)
        elif isolation == Isolation.READ_COMMITTED_READ_CONSISTENCY:
            tpb.insert_tag(TPBItem.READ_CONSISTENCY)
        else:
            tpb.insert_tag(TraIsolation.READ_COMMITTED)
            tpb.insert_tag(TraReadCommitted.RECORD_VERSION
                           if isolation == Isolation.READ_COMMITTED_RECORD_VERSION
                           else TraReadCommitted.NO_RECORD_VERSION)
        tpb.insert_tag(TraLockResolution.NO_WAIT if self.lock_timeout == 0 else TraLockResolution.WAIT)
        if self.lock_timeout > 0:
            tpb.insert_int(TPBItem.LOCK_TIMEOUT, self.lock_timeout)
        if self.auto_commit:
            tpb.insert_tag(TPBItem.AUTOCOMMIT)
        if self.no_auto_undo:
            tpb.insert_tag(TPBItem.NO_AUTO_UNDO)
        if self.ignore_limbo:
            tpb.insert_tag(TPBItem.IGNORE_LIMBO)
        if self.at_snapshot_number is not None:
            tpb.insert_bigint(TPBItem.AT_SNAPSHOT_NUMBER, self.at_snapshot_number)
        for table in self._table_reservation:
            # Access mode + table name
            tpb.insert_string(table[2], table[0], encoding=self.encoding)
            tpb.insert_tag(table[1])  # Share mode
        result = tpb.get_buffer()
    return result

parse_buffer(buffer: bytes) -> None

Load information from TPB.

Source code in firebird/driver/core.py
def parse_buffer(self, buffer: bytes) -> None:
    """Load information from TPB.
    """
    self.clear()
    with a.get_api().util.get_xpb_builder(XpbKind.TPB, buffer) as tpb:
        while not tpb.is_eof():
            tag = tpb.get_tag()
            if tag in TraAccessMode._value2member_map_:
                self.access_mode = TraAccessMode(tag)
            elif tag in TraIsolation._value2member_map_:
                isolation = TraIsolation(tag)
                if isolation != TraIsolation.READ_COMMITTED:
                    self.isolation = Isolation(isolation)
            elif tag in TraReadCommitted._value2member_map_:
                isolation = TraReadCommitted(tag)
                if isolation == TraReadCommitted.RECORD_VERSION:
                    self.isolation = Isolation.READ_COMMITTED_RECORD_VERSION
                elif isolation == TraReadCommitted.NO_RECORD_VERSION:
                    self.isolation = Isolation.READ_COMMITTED_NO_RECORD_VERSION
                else:
                    self.isolation = Isolation.READ_COMMITTED_READ_CONSISTENCY
            elif tag in TraLockResolution._value2member_map_:
                self.lock_timeout = -1 if TraLockResolution(tag) is TraLockResolution.WAIT else 0
            elif tag == TPBItem.AUTOCOMMIT:
                self.auto_commit = True
            elif tag == TPBItem.NO_AUTO_UNDO:
                self.no_auto_undo = True
            elif tag == TPBItem.IGNORE_LIMBO:
                self.ignore_limbo = True
            elif tag == TPBItem.LOCK_TIMEOUT:
                self.lock_timeout = tpb.get_int()
            elif tag == TPBItem.AT_SNAPSHOT_NUMBER:
                self.at_snapshot_number = tpb.get_bigint()
            elif tag in TableAccessMode._value2member_map_:
                tbl_access = TableAccessMode(tag)
                tbl_name = tpb.get_string(encoding=self.encoding)
                tpb.move_next()
                if tpb.is_eof():
                    raise ValueError(f"Missing share mode value in table {tbl_name} reservation")
                if (val := tpb.get_tag()) not in TableShareMode._value2member_map_:
                    raise ValueError(f"Missing share mode value in table {tbl_name} reservation")
                tbl_share = TableShareMode(val)
                self.reserve_table(tbl_name, tbl_share, tbl_access)
            tpb.move_next()

reserve_table(name: str, share_mode: TableShareMode, access_mode: TableAccessMode) -> None

Set information about table reservation.

Source code in firebird/driver/core.py
def reserve_table(self, name: str, share_mode: TableShareMode, access_mode: TableAccessMode) -> None:
    """Set information about table reservation.
    """
    self._table_reservation.append((name, share_mode, access_mode))

firebird.driver.core.DPB

Helper class to build and parse Database Parameter Buffers (DPB) used when connecting databases.

Source code in firebird/driver/core.py
class DPB:
    """Helper class to build and parse Database Parameter Buffers (DPB) used when connecting databases.
    """
    def __init__(self, *, user: str | None=None, password: str | None=None, role: str | None=None,
                 trusted_auth: bool=False, sql_dialect: int=3, timeout: int | None=None,
                 charset: str='UTF8', cache_size: int | None=None, no_gc: bool=False,
                 no_db_triggers: bool=False, no_linger: bool=False,
                 utf8filename: bool=False, dbkey_scope: DBKeyScope | None=None,
                 dummy_packet_interval: int | None=None, overwrite: bool=False,
                 db_cache_size: int | None=None, forced_writes: bool | None=None,
                 reserve_space: bool | None=None, page_size: int | None=None, read_only: bool=False,
                 sweep_interval: int | None=None, db_sql_dialect: int | None=None,
                 db_charset: str | None=None, config: str | None=None,
                 auth_plugin_list: str | None=None, session_time_zone: str | None=None,
                 set_db_replica: ReplicaMode | None=None, set_bind: str | None=None,
                 decfloat_round: DecfloatRound | None=None,
                 decfloat_traps: list[DecfloatTraps] | None=None,
                 parallel_workers: int | None=None
                 ):
        # Available options:
        # AuthClient, WireCryptPlugin, Providers, ConnectionTimeout, WireCrypt,
        # WireCompression, DummyPacketInterval, RemoteServiceName, RemoteServicePort,
        # RemoteAuxPort, TcpNoNagle, IpcName, RemotePipeName, ClientBatchBuffer [FB4+]
        self.config: str | None = config
        "Configuration override"
        self.auth_plugin_list: str | None = auth_plugin_list
        "List of authentication plugins override"
        # Connect
        self.trusted_auth: bool = trusted_auth
        "Use trusted authentication"
        self.user: str | None = user
        "User name"
        self.password: str | None = password
        "User password"
        self.role: str | None = role
        "User role"
        self.sql_dialect: int = sql_dialect
        "SQL Dialect for database connection"
        self.charset: str = charset
        "Character set for database connection"
        self.timeout: int | None = timeout
        "Connection timeout"
        self.dummy_packet_interval: int | None = dummy_packet_interval
        "Dummy packet interval for this database connection"
        self.cache_size: int | None = cache_size
        "Page cache size override for database connection"
        self.no_gc: bool = no_gc
        "Disable garbage collection for database connection"
        self.no_db_triggers: bool = no_db_triggers
        "Disable database triggers for database connection"
        self.no_linger: bool = no_linger
        "Do not use linger for database connection"
        self.utf8filename: bool = utf8filename
        "Database filename passed in UTF8"
        self.dbkey_scope: DBKeyScope | None = dbkey_scope
        "Scope for RDB$DB_KEY values"
        self.session_time_zone: str | None = session_time_zone
        "Session time zone [Firebird 4]"
        self.set_db_replica: ReplicaMode | None = set_db_replica
        "Set replica mode [Firebird 4]"
        self.set_bind: str | None = set_bind
        "Set BIND [Firebird 4]"
        self.decfloat_round: DecfloatRound | None = decfloat_round
        "Set DECFLOAT ROUND [Firebird 4]"
        self.decfloat_traps: list[DecfloatTraps] | None = \
            None if decfloat_traps is None else list(decfloat_traps)
        "Set DECFLOAT TRAPS [Firebird 4]"
        # For db create
        self.page_size: int | None = page_size
        "Database page size [db create only]"
        self.overwrite: bool = overwrite
        "Overwrite existing database [db create only]"
        self.db_buffers: int | None= None
        "Number of pages in database cache [db create only]"
        self.db_cache_size: int | None = db_cache_size
        "Database cache size [db create only]"
        self.forced_writes: bool | None = forced_writes
        "Database write mode (True = sync/False = async) [db create only]"
        self.reserve_space: bool | None = reserve_space
        "Database data page space usage (True = reserve space, False = Use all space) [db create only]"
        self.read_only: bool = read_only
        "Database access mode (True = read-only/False = read-write) [db create only]"
        self.sweep_interval: int | None = sweep_interval
        "Sweep interval for the database [db create only]"
        self.db_sql_dialect: int | None = db_sql_dialect
        "SQL dialect for the database [db create only]"
        self.db_charset: str | None = db_charset
        "Character set for the database [db create only]"
        self.parallel_workers: int | None = parallel_workers
        "Number of parallel workers"
    def clear(self) -> None:
        """Clear all information.
        """
        self.config = None
        # Connect
        self.trusted_auth = False
        self.user = None
        self.password = None
        self.role = None
        self.sql_dialect = 3
        self.charset = 'UTF8'
        self.timeout = None
        self.dummy_packet_interval = None
        self.cache_size = None
        self.no_gc = False
        self.no_db_triggers = False
        self.no_linger = False
        self.utf8filename = False
        self.dbkey_scope = None
        self.session_time_zone = None
        self.set_db_replica = None
        self.set_bind = None
        self.decfloat_round = None
        self.decfloat_traps = None
        # For db create
        self.page_size = None
        self.overwrite = False
        self.db_buffers = None
        self.forced_writes = None
        self.reserve_space = None
        self.page_size = None
        self.read_only = False
        self.sweep_interval = None
        self.db_sql_dialect = None
        self.db_charset = None
    def parse_buffer(self, buffer: bytes) -> None:
        """Load information from DPB.
        """
        _py_charset: str = CHARSET_MAP.get(self.charset, 'ascii')
        self.clear()
        with a.get_api().util.get_xpb_builder(XpbKind.DPB, buffer) as dpb:
            while not dpb.is_eof():
                tag = dpb.get_tag()
                if tag == DPBItem.CONFIG:
                    self.config = dpb.get_string(encoding=_py_charset)
                elif tag == DPBItem.AUTH_PLUGIN_LIST:
                    self.auth_plugin_list = dpb.get_string()
                elif tag == DPBItem.TRUSTED_AUTH:
                    self.trusted_auth = True
                elif tag == DPBItem.USER_NAME:
                    self.user = dpb.get_string(encoding=_py_charset)
                elif tag == DPBItem.PASSWORD:
                    self.password = dpb.get_string(encoding=_py_charset)
                elif tag == DPBItem.CONNECT_TIMEOUT:
                    self.timeout = dpb.get_int()
                elif tag == DPBItem.DUMMY_PACKET_INTERVAL:
                    self.dummy_packet_interval = dpb.get_int()
                elif tag == DPBItem.SQL_ROLE_NAME:
                    self.role = dpb.get_string(encoding=_py_charset)
                elif tag == DPBItem.SQL_DIALECT:
                    self.sql_dialect = dpb.get_int()
                elif tag == DPBItem.LC_CTYPE:
                    self.charset = dpb.get_string()
                elif tag == DPBItem.NUM_BUFFERS:
                    self.cache_size = dpb.get_int()
                elif tag == DPBItem.NO_GARBAGE_COLLECT:
                    self.no_gc = bool(dpb.get_int())
                elif tag == DPBItem.UTF8_FILENAME:
                    self.utf8filename = bool(dpb.get_int())
                elif tag == DPBItem.NO_DB_TRIGGERS:
                    self.no_db_triggers = bool(dpb.get_int())
                elif tag == DPBItem.NOLINGER:
                    self.no_linger = bool(dpb.get_int())
                elif tag == DPBItem.DBKEY_SCOPE:
                    self.dbkey_scope = DBKeyScope(dpb.get_int())
                elif tag == DPBItem.PAGE_SIZE:
                    self.page_size = dpb.get_int()
                elif tag == DPBItem.OVERWRITE:
                    self.overwrite = bool(dpb.get_int())
                elif tag == DPBItem.SET_PAGE_BUFFERS:
                    self.db_cache_size = dpb.get_int()
                elif tag == DPBItem.FORCE_WRITE:
                    self.forced_writes = bool(dpb.get_int())
                elif tag == DPBItem.NO_RESERVE:
                    self.reserve_space = not bool(dpb.get_int())
                elif tag == DPBItem.SET_DB_READONLY:
                    self.read_only = bool(dpb.get_int())
                elif tag == DPBItem.SWEEP_INTERVAL:
                    self.sweep_interval = dpb.get_int()
                elif tag == DPBItem.SET_DB_SQL_DIALECT:
                    self.db_sql_dialect = dpb.get_int()
                elif tag == DPBItem.SET_DB_CHARSET:
                    self.db_charset = dpb.get_string()
                elif tag == DPBItem.SESSION_TIME_ZONE:
                    self.session_time_zone = dpb.get_string()
                elif tag == DPBItem.SET_DB_REPLICA:
                    self.set_db_replica = ReplicaMode(dpb.get_int())
                elif tag == DPBItem.SET_BIND:
                    self.set_bind = dpb.get_string()
                elif tag == DPBItem.DECFLOAT_ROUND:
                    self.decfloat_round = DecfloatRound(dpb.get_string())
                elif tag == DPBItem.DECFLOAT_TRAPS:
                    self.decfloat_traps = [DecfloatTraps(v.strip())
                                           for v in dpb.get_string().split(',')]
                elif tag == DPBItem.PARALLEL_WORKERS:
                    self.parallel_workers = dpb.get_int()
                dpb.move_next()
    def get_buffer(self, *, for_create: bool=False) -> bytes:
        """Create DPB from stored information.
        """
        _py_charset: str = CHARSET_MAP.get(self.charset, 'ascii')
        with a.get_api().util.get_xpb_builder(XpbKind.DPB) as dpb:
            if self.config is not None:
                dpb.insert_string(DPBItem.CONFIG, self.config, encoding=_py_charset)
            if self.trusted_auth:
                dpb.insert_tag(DPBItem.TRUSTED_AUTH)
            else:
                if self.user:
                    dpb.insert_string(DPBItem.USER_NAME, self.user, encoding=_py_charset)
                if self.password:
                    dpb.insert_string(DPBItem.PASSWORD, self.password, encoding=_py_charset)
            if self.auth_plugin_list is not None:
                dpb.insert_string(DPBItem.AUTH_PLUGIN_LIST, self.auth_plugin_list)
            if self.timeout is not None:
                dpb.insert_int(DPBItem.CONNECT_TIMEOUT, self.timeout)
            if self.dummy_packet_interval is not None:
                dpb.insert_int(DPBItem.DUMMY_PACKET_INTERVAL, self.dummy_packet_interval)
            if self.role:
                dpb.insert_string(DPBItem.SQL_ROLE_NAME, self.role, encoding=_py_charset)
            if self.sql_dialect:
                dpb.insert_int(DPBItem.SQL_DIALECT, self.sql_dialect)
            if self.charset:
                dpb.insert_string(DPBItem.LC_CTYPE, self.charset)
                if for_create:
                    dpb.insert_string(DPBItem.SET_DB_CHARSET, self.charset)
            if self.cache_size is not None:
                dpb.insert_int(DPBItem.NUM_BUFFERS, self.cache_size)
            if self.no_gc:
                dpb.insert_int(DPBItem.NO_GARBAGE_COLLECT, 1)
            if self.utf8filename:
                dpb.insert_int(DPBItem.UTF8_FILENAME, 1)
            if self.no_db_triggers:
                dpb.insert_int(DPBItem.NO_DB_TRIGGERS, 1)
            if self.no_linger:
                dpb.insert_int(DPBItem.NOLINGER, 1)
            if self.dbkey_scope is not None:
                dpb.insert_int(DPBItem.DBKEY_SCOPE, self.dbkey_scope)
            if self.session_time_zone is not None:
                dpb.insert_string(DPBItem.SESSION_TIME_ZONE, self.session_time_zone)
            if self.set_db_replica is not None:
                dpb.insert_int(DPBItem.SET_DB_REPLICA, self.set_db_replica)
            if self.set_bind is not None:
                dpb.insert_string(DPBItem.SET_BIND, self.set_bind)
            if self.decfloat_round is not None:
                dpb.insert_string(DPBItem.DECFLOAT_ROUND, self.decfloat_round.value)
            if self.decfloat_traps is not None:
                dpb.insert_string(DPBItem.DECFLOAT_TRAPS, ','.join(e.value for e in
                                                                   self.decfloat_traps))
            if self.parallel_workers is not None:
                dpb.insert_int(DPBItem.PARALLEL_WORKERS, self.parallel_workers)
            if for_create:
                if self.page_size is not None:
                    dpb.insert_int(DPBItem.PAGE_SIZE, self.page_size)
                if self.overwrite:
                    dpb.insert_int(DPBItem.OVERWRITE, 1)
                if self.db_cache_size is not None:
                    dpb.insert_int(DPBItem.SET_PAGE_BUFFERS, self.db_cache_size)
                if self.forced_writes is not None:
                    dpb.insert_int(DPBItem.FORCE_WRITE, int(self.forced_writes))
                if self.reserve_space is not None:
                    dpb.insert_int(DPBItem.NO_RESERVE, int(not self.reserve_space))
                if self.read_only:
                    dpb.insert_int(DPBItem.SET_DB_READONLY, 1)
                if self.sweep_interval is not None:
                    dpb.insert_int(DPBItem.SWEEP_INTERVAL, self.sweep_interval)
                if self.db_sql_dialect is not None:
                    dpb.insert_int(DPBItem.SET_DB_SQL_DIALECT, self.db_sql_dialect)
                if self.db_charset is not None:
                    dpb.insert_string(DPBItem.SET_DB_CHARSET, self.db_charset)
            #
            result = dpb.get_buffer()
        return result

auth_plugin_list: str | None instance-attribute

List of authentication plugins override

cache_size: int | None instance-attribute

Page cache size override for database connection

charset: str instance-attribute

Character set for database connection

config: str | None instance-attribute

Configuration override

db_buffers: int | None instance-attribute

Number of pages in database cache [db create only]

db_cache_size: int | None instance-attribute

Database cache size [db create only]

db_charset: str | None instance-attribute

Character set for the database [db create only]

db_sql_dialect: int | None instance-attribute

SQL dialect for the database [db create only]

dbkey_scope: DBKeyScope | None instance-attribute

Scope for RDB$DB_KEY values

decfloat_round: DecfloatRound | None instance-attribute

Set DECFLOAT ROUND [Firebird 4]

decfloat_traps: list[DecfloatTraps] | None instance-attribute

Set DECFLOAT TRAPS [Firebird 4]

dummy_packet_interval: int | None instance-attribute

Dummy packet interval for this database connection

forced_writes: bool | None instance-attribute

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

no_db_triggers: bool instance-attribute

Disable database triggers for database connection

no_gc: bool instance-attribute

Disable garbage collection for database connection

no_linger: bool instance-attribute

Do not use linger for database connection

overwrite: bool instance-attribute

Overwrite existing database [db create only]

page_size: int | None instance-attribute

Database page size [db create only]

parallel_workers: int | None instance-attribute

Number of parallel workers

password: str | None instance-attribute

User password

read_only: bool instance-attribute

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

reserve_space: bool | None instance-attribute

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

role: str | None instance-attribute

User role

session_time_zone: str | None instance-attribute

Session time zone [Firebird 4]

set_bind: str | None instance-attribute

Set BIND [Firebird 4]

set_db_replica: ReplicaMode | None instance-attribute

Set replica mode [Firebird 4]

sql_dialect: int instance-attribute

SQL Dialect for database connection

sweep_interval: int | None instance-attribute

Sweep interval for the database [db create only]

timeout: int | None instance-attribute

Connection timeout

trusted_auth: bool instance-attribute

Use trusted authentication

user: str | None instance-attribute

User name

utf8filename: bool instance-attribute

Database filename passed in UTF8

clear() -> None

Clear all information.

Source code in firebird/driver/core.py
def clear(self) -> None:
    """Clear all information.
    """
    self.config = None
    # Connect
    self.trusted_auth = False
    self.user = None
    self.password = None
    self.role = None
    self.sql_dialect = 3
    self.charset = 'UTF8'
    self.timeout = None
    self.dummy_packet_interval = None
    self.cache_size = None
    self.no_gc = False
    self.no_db_triggers = False
    self.no_linger = False
    self.utf8filename = False
    self.dbkey_scope = None
    self.session_time_zone = None
    self.set_db_replica = None
    self.set_bind = None
    self.decfloat_round = None
    self.decfloat_traps = None
    # For db create
    self.page_size = None
    self.overwrite = False
    self.db_buffers = None
    self.forced_writes = None
    self.reserve_space = None
    self.page_size = None
    self.read_only = False
    self.sweep_interval = None
    self.db_sql_dialect = None
    self.db_charset = None

get_buffer(*, for_create: bool = False) -> bytes

Create DPB from stored information.

Source code in firebird/driver/core.py
def get_buffer(self, *, for_create: bool=False) -> bytes:
    """Create DPB from stored information.
    """
    _py_charset: str = CHARSET_MAP.get(self.charset, 'ascii')
    with a.get_api().util.get_xpb_builder(XpbKind.DPB) as dpb:
        if self.config is not None:
            dpb.insert_string(DPBItem.CONFIG, self.config, encoding=_py_charset)
        if self.trusted_auth:
            dpb.insert_tag(DPBItem.TRUSTED_AUTH)
        else:
            if self.user:
                dpb.insert_string(DPBItem.USER_NAME, self.user, encoding=_py_charset)
            if self.password:
                dpb.insert_string(DPBItem.PASSWORD, self.password, encoding=_py_charset)
        if self.auth_plugin_list is not None:
            dpb.insert_string(DPBItem.AUTH_PLUGIN_LIST, self.auth_plugin_list)
        if self.timeout is not None:
            dpb.insert_int(DPBItem.CONNECT_TIMEOUT, self.timeout)
        if self.dummy_packet_interval is not None:
            dpb.insert_int(DPBItem.DUMMY_PACKET_INTERVAL, self.dummy_packet_interval)
        if self.role:
            dpb.insert_string(DPBItem.SQL_ROLE_NAME, self.role, encoding=_py_charset)
        if self.sql_dialect:
            dpb.insert_int(DPBItem.SQL_DIALECT, self.sql_dialect)
        if self.charset:
            dpb.insert_string(DPBItem.LC_CTYPE, self.charset)
            if for_create:
                dpb.insert_string(DPBItem.SET_DB_CHARSET, self.charset)
        if self.cache_size is not None:
            dpb.insert_int(DPBItem.NUM_BUFFERS, self.cache_size)
        if self.no_gc:
            dpb.insert_int(DPBItem.NO_GARBAGE_COLLECT, 1)
        if self.utf8filename:
            dpb.insert_int(DPBItem.UTF8_FILENAME, 1)
        if self.no_db_triggers:
            dpb.insert_int(DPBItem.NO_DB_TRIGGERS, 1)
        if self.no_linger:
            dpb.insert_int(DPBItem.NOLINGER, 1)
        if self.dbkey_scope is not None:
            dpb.insert_int(DPBItem.DBKEY_SCOPE, self.dbkey_scope)
        if self.session_time_zone is not None:
            dpb.insert_string(DPBItem.SESSION_TIME_ZONE, self.session_time_zone)
        if self.set_db_replica is not None:
            dpb.insert_int(DPBItem.SET_DB_REPLICA, self.set_db_replica)
        if self.set_bind is not None:
            dpb.insert_string(DPBItem.SET_BIND, self.set_bind)
        if self.decfloat_round is not None:
            dpb.insert_string(DPBItem.DECFLOAT_ROUND, self.decfloat_round.value)
        if self.decfloat_traps is not None:
            dpb.insert_string(DPBItem.DECFLOAT_TRAPS, ','.join(e.value for e in
                                                               self.decfloat_traps))
        if self.parallel_workers is not None:
            dpb.insert_int(DPBItem.PARALLEL_WORKERS, self.parallel_workers)
        if for_create:
            if self.page_size is not None:
                dpb.insert_int(DPBItem.PAGE_SIZE, self.page_size)
            if self.overwrite:
                dpb.insert_int(DPBItem.OVERWRITE, 1)
            if self.db_cache_size is not None:
                dpb.insert_int(DPBItem.SET_PAGE_BUFFERS, self.db_cache_size)
            if self.forced_writes is not None:
                dpb.insert_int(DPBItem.FORCE_WRITE, int(self.forced_writes))
            if self.reserve_space is not None:
                dpb.insert_int(DPBItem.NO_RESERVE, int(not self.reserve_space))
            if self.read_only:
                dpb.insert_int(DPBItem.SET_DB_READONLY, 1)
            if self.sweep_interval is not None:
                dpb.insert_int(DPBItem.SWEEP_INTERVAL, self.sweep_interval)
            if self.db_sql_dialect is not None:
                dpb.insert_int(DPBItem.SET_DB_SQL_DIALECT, self.db_sql_dialect)
            if self.db_charset is not None:
                dpb.insert_string(DPBItem.SET_DB_CHARSET, self.db_charset)
        #
        result = dpb.get_buffer()
    return result

parse_buffer(buffer: bytes) -> None

Load information from DPB.

Source code in firebird/driver/core.py
def parse_buffer(self, buffer: bytes) -> None:
    """Load information from DPB.
    """
    _py_charset: str = CHARSET_MAP.get(self.charset, 'ascii')
    self.clear()
    with a.get_api().util.get_xpb_builder(XpbKind.DPB, buffer) as dpb:
        while not dpb.is_eof():
            tag = dpb.get_tag()
            if tag == DPBItem.CONFIG:
                self.config = dpb.get_string(encoding=_py_charset)
            elif tag == DPBItem.AUTH_PLUGIN_LIST:
                self.auth_plugin_list = dpb.get_string()
            elif tag == DPBItem.TRUSTED_AUTH:
                self.trusted_auth = True
            elif tag == DPBItem.USER_NAME:
                self.user = dpb.get_string(encoding=_py_charset)
            elif tag == DPBItem.PASSWORD:
                self.password = dpb.get_string(encoding=_py_charset)
            elif tag == DPBItem.CONNECT_TIMEOUT:
                self.timeout = dpb.get_int()
            elif tag == DPBItem.DUMMY_PACKET_INTERVAL:
                self.dummy_packet_interval = dpb.get_int()
            elif tag == DPBItem.SQL_ROLE_NAME:
                self.role = dpb.get_string(encoding=_py_charset)
            elif tag == DPBItem.SQL_DIALECT:
                self.sql_dialect = dpb.get_int()
            elif tag == DPBItem.LC_CTYPE:
                self.charset = dpb.get_string()
            elif tag == DPBItem.NUM_BUFFERS:
                self.cache_size = dpb.get_int()
            elif tag == DPBItem.NO_GARBAGE_COLLECT:
                self.no_gc = bool(dpb.get_int())
            elif tag == DPBItem.UTF8_FILENAME:
                self.utf8filename = bool(dpb.get_int())
            elif tag == DPBItem.NO_DB_TRIGGERS:
                self.no_db_triggers = bool(dpb.get_int())
            elif tag == DPBItem.NOLINGER:
                self.no_linger = bool(dpb.get_int())
            elif tag == DPBItem.DBKEY_SCOPE:
                self.dbkey_scope = DBKeyScope(dpb.get_int())
            elif tag == DPBItem.PAGE_SIZE:
                self.page_size = dpb.get_int()
            elif tag == DPBItem.OVERWRITE:
                self.overwrite = bool(dpb.get_int())
            elif tag == DPBItem.SET_PAGE_BUFFERS:
                self.db_cache_size = dpb.get_int()
            elif tag == DPBItem.FORCE_WRITE:
                self.forced_writes = bool(dpb.get_int())
            elif tag == DPBItem.NO_RESERVE:
                self.reserve_space = not bool(dpb.get_int())
            elif tag == DPBItem.SET_DB_READONLY:
                self.read_only = bool(dpb.get_int())
            elif tag == DPBItem.SWEEP_INTERVAL:
                self.sweep_interval = dpb.get_int()
            elif tag == DPBItem.SET_DB_SQL_DIALECT:
                self.db_sql_dialect = dpb.get_int()
            elif tag == DPBItem.SET_DB_CHARSET:
                self.db_charset = dpb.get_string()
            elif tag == DPBItem.SESSION_TIME_ZONE:
                self.session_time_zone = dpb.get_string()
            elif tag == DPBItem.SET_DB_REPLICA:
                self.set_db_replica = ReplicaMode(dpb.get_int())
            elif tag == DPBItem.SET_BIND:
                self.set_bind = dpb.get_string()
            elif tag == DPBItem.DECFLOAT_ROUND:
                self.decfloat_round = DecfloatRound(dpb.get_string())
            elif tag == DPBItem.DECFLOAT_TRAPS:
                self.decfloat_traps = [DecfloatTraps(v.strip())
                                       for v in dpb.get_string().split(',')]
            elif tag == DPBItem.PARALLEL_WORKERS:
                self.parallel_workers = dpb.get_int()
            dpb.move_next()

firebird.driver.core.SPB_ATTACH

Helper class to build and parse Service Parameter Buffers (SPB) used when connecting to service manager.

Source code in firebird/driver/core.py
class SPB_ATTACH: # noqa: N801
    """Helper class to build and parse Service Parameter Buffers (SPB) used when connecting
    to service manager.
    """
    def __init__(self, *, user: str | None=None, password: str | None=None, trusted_auth: bool=False,
                 config: str | None=None, auth_plugin_list: str | None=None, expected_db: str | None=None,
                 encoding: str='ascii', errors: str='strict', role: str | None=None):
        self.encoding: str = encoding
        self.errors: str = errors
        self.user: str | None = user
        self.password: str | None = password
        self.trusted_auth: bool = trusted_auth
        self.config: str | None = config
        self.auth_plugin_list: str | None = auth_plugin_list
        self.expected_db: str | None = expected_db
        self.role: str | None = role
    def clear(self) -> None:
        """Clear all information.
        """
        self.user = None
        self.password = None
        self.trusted_auth = False
        self.config = None
        self.expected_db = None
    def parse_buffer(self, buffer: bytes) -> None:
        """Load information from SPB_ATTACH.
        """
        self.clear()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_ATTACH, buffer) as spb:
            while not spb.is_eof():
                tag = spb.get_tag()
                if tag == SPBItem.CONFIG:
                    self.config = spb.get_string(encoding=self.encoding, errors=self.errors)
                elif tag == SPBItem.AUTH_PLUGIN_LIST:
                    self.auth_plugin_list = spb.get_string()
                elif tag == SPBItem.TRUSTED_AUTH:
                    self.trusted_auth = True
                elif tag == SPBItem.USER_NAME:
                    self.user = spb.get_string(encoding=self.encoding, errors=self.errors)
                elif tag == SPBItem.PASSWORD:
                    self.password = spb.get_string(encoding=self.encoding, errors=self.errors)
                elif tag == SPBItem.SQL_ROLE_NAME:
                    self.role = spb.get_string(encoding=self.encoding, errors=self.errors)
                elif tag == SPBItem.EXPECTED_DB:
                    self.expected_db = spb.get_string(encoding=self.encoding, errors=self.errors)
                spb.move_next()
    def get_buffer(self) -> bytes:
        """Create SPB_ATTACH from stored information.
        """
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_ATTACH) as spb:
            if self.config is not None:
                spb.insert_string(SPBItem.CONFIG, self.config, encoding=self.encoding,
                                  errors=self.errors)
            if self.trusted_auth:
                spb.insert_tag(SPBItem.TRUSTED_AUTH)
            else:
                if self.user is not None:
                    spb.insert_string(SPBItem.USER_NAME, self.user, encoding=self.encoding,
                                      errors=self.errors)
                if self.password is not None:
                    spb.insert_string(SPBItem.PASSWORD, self.password,
                                      encoding=self.encoding, errors=self.errors)
            if self.role is not None:
                spb.insert_string(SPBItem.SQL_ROLE_NAME, self.role, encoding=self.encoding,
                                  errors=self.errors)
            if self.auth_plugin_list is not None:
                spb.insert_string(SPBItem.AUTH_PLUGIN_LIST, self.auth_plugin_list)
            if self.expected_db is not None:
                spb.insert_string(SPBItem.EXPECTED_DB, self.expected_db,
                                  encoding=self.encoding, errors=self.errors)
            result = spb.get_buffer()
        return result

clear() -> None

Clear all information.

Source code in firebird/driver/core.py
def clear(self) -> None:
    """Clear all information.
    """
    self.user = None
    self.password = None
    self.trusted_auth = False
    self.config = None
    self.expected_db = None

get_buffer() -> bytes

Create SPB_ATTACH from stored information.

Source code in firebird/driver/core.py
def get_buffer(self) -> bytes:
    """Create SPB_ATTACH from stored information.
    """
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_ATTACH) as spb:
        if self.config is not None:
            spb.insert_string(SPBItem.CONFIG, self.config, encoding=self.encoding,
                              errors=self.errors)
        if self.trusted_auth:
            spb.insert_tag(SPBItem.TRUSTED_AUTH)
        else:
            if self.user is not None:
                spb.insert_string(SPBItem.USER_NAME, self.user, encoding=self.encoding,
                                  errors=self.errors)
            if self.password is not None:
                spb.insert_string(SPBItem.PASSWORD, self.password,
                                  encoding=self.encoding, errors=self.errors)
        if self.role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, self.role, encoding=self.encoding,
                              errors=self.errors)
        if self.auth_plugin_list is not None:
            spb.insert_string(SPBItem.AUTH_PLUGIN_LIST, self.auth_plugin_list)
        if self.expected_db is not None:
            spb.insert_string(SPBItem.EXPECTED_DB, self.expected_db,
                              encoding=self.encoding, errors=self.errors)
        result = spb.get_buffer()
    return result

parse_buffer(buffer: bytes) -> None

Load information from SPB_ATTACH.

Source code in firebird/driver/core.py
def parse_buffer(self, buffer: bytes) -> None:
    """Load information from SPB_ATTACH.
    """
    self.clear()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_ATTACH, buffer) as spb:
        while not spb.is_eof():
            tag = spb.get_tag()
            if tag == SPBItem.CONFIG:
                self.config = spb.get_string(encoding=self.encoding, errors=self.errors)
            elif tag == SPBItem.AUTH_PLUGIN_LIST:
                self.auth_plugin_list = spb.get_string()
            elif tag == SPBItem.TRUSTED_AUTH:
                self.trusted_auth = True
            elif tag == SPBItem.USER_NAME:
                self.user = spb.get_string(encoding=self.encoding, errors=self.errors)
            elif tag == SPBItem.PASSWORD:
                self.password = spb.get_string(encoding=self.encoding, errors=self.errors)
            elif tag == SPBItem.SQL_ROLE_NAME:
                self.role = spb.get_string(encoding=self.encoding, errors=self.errors)
            elif tag == SPBItem.EXPECTED_DB:
                self.expected_db = spb.get_string(encoding=self.encoding, errors=self.errors)
            spb.move_next()

firebird.driver.core.Buffer

Bases: MemoryBuffer

MemoryBuffer with extensions.

Source code in firebird/driver/core.py
class Buffer(MemoryBuffer):
    """MemoryBuffer with extensions.
    """
    def __init__(self, init: int | bytes, size: int | None=None, *,
                 factory: type[BufferFactory]=BytesBufferFactory,
                 max_size: int | UNLIMITED=UNLIMITED, byteorder: ByteOrder=ByteOrder.LITTLE):
        super().__init__(init, size, factory=factory, eof_marker=isc_info_end,
                         max_size=max_size, byteorder=byteorder)
    def seek_last_data(self) -> int:
        """Set the position in buffer to first non-zero byte when searched from
        the end of buffer.
        """
        self.pos = self.last_data
    def get_tag(self) -> int:
        """Read 1 byte number (c_ubyte).
        """
        return self.read_byte()
    def rewind(self) -> None:
        """Set current position in buffer to beginning.
        """
        self.pos = 0
    def is_truncated(self) -> bool:
        """Return True when positioned on `isc_info_truncated` tag.
        """
        return safe_ord(self.raw[self.pos]) == isc_info_truncated

buffer_size: int property

Current allocated buffer size in bytes.

byteorder: ByteOrder instance-attribute

The byte order used to read/write numbers [default: LITTLE].

eof_marker: int instance-attribute

Value that indicates the end of data. Could be None.

factory: BufferFactory instance-attribute

Buffer factory instance used by manager [default: BytesBufferFactory].

last_data: int property

Index of the last non-zero byte in the buffer (-1 if all zeros).

max_size: int | Sentinel instance-attribute

The buffer couldn't grow beyond specified number of bytes [default: UNLIMITED].

pos: int instance-attribute

Current position in buffer, i.e. the next read/writen byte would be at this position.

raw: bytearray instance-attribute

The memory buffer. The actual data type of buffer depends on buffer factory, but it must provide direct acces to cells, slices and length like bytearray.

clear() -> None

Fills the buffer with zeros and resets the position in buffer to zero.

Source code in firebird/base/buffer.py
def clear(self) -> None:
    """Fills the buffer with zeros and resets the position in buffer to zero.
    """
    self.factory.clear(self.raw)
    self.pos = 0

get_raw() -> bytes | bytearray

Return the underlying buffer's content as bytes or bytearray.

Use this method for generic access to the raw buffer content instead of accessing the raw attribute directly, as the type of raw can vary depending on the buffer factory used.

Returns:

Type Description
bytes | bytearray

The raw content of the buffer.

Source code in firebird/base/buffer.py
def get_raw(self) -> bytes | bytearray:
    """Return the underlying buffer's content as [bytes][] or [bytearray][].

    Use this method for generic access to the raw buffer content instead of
    accessing the `raw` attribute directly, as the type of `raw` can vary
    depending on the buffer factory used.

    Returns:
        The raw content of the buffer.
    """
    return self.factory.get_raw(self.raw)

get_tag() -> int

Read 1 byte number (c_ubyte).

Source code in firebird/driver/core.py
def get_tag(self) -> int:
    """Read 1 byte number (c_ubyte).
    """
    return self.read_byte()

is_eof() -> bool

Check if the current position is at or past the end of data.

End of data is defined as being beyond the buffer's current length, or positioned exactly on a byte matching self.eof_marker (if defined).

Returns:

Type Description
bool

True if at end-of-data, False otherwise.

Source code in firebird/base/buffer.py
def is_eof(self) -> bool:
    """Check if the current position is at or past the end of data.

    End of data is defined as being beyond the buffer's current length,
    or positioned exactly on a byte matching `self.eof_marker` (if defined).

    Returns:
        True if at end-of-data, False otherwise.
    """
    if self.pos >= len(self.raw):
        return True
    if self.eof_marker is not None and safe_ord(self.raw[self.pos]) == self.eof_marker:
        return True
    return False

is_truncated() -> bool

Return True when positioned on isc_info_truncated tag.

Source code in firebird/driver/core.py
def is_truncated(self) -> bool:
    """Return True when positioned on `isc_info_truncated` tag.
    """
    return safe_ord(self.raw[self.pos]) == isc_info_truncated

read(size: int = -1) -> bytes

Read specified number of bytes from current position, or all remaining data.

Advances the position by the number of bytes read.

Parameters:

Name Type Description Default
size int

Number of bytes to read. If negative, reads all data from the current position to the end of the buffer.

-1

Returns: The bytes read.

Raises:

Type Description
BufferError

If size requests more bytes than available from the current position.

Source code in firebird/base/buffer.py
def read(self, size: int=-1) -> bytes:
    """Read specified number of bytes from current position, or all remaining data.

    Advances the position by the number of bytes read.

    Arguments:
        size: Number of bytes to read. If negative, reads all data from the
              current position to the end of the buffer.
    Returns:
       The bytes read.

    Raises:
        BufferError: If `size` requests more bytes than available from the current position.
    """
    if size < 0:
        size = self.buffer_size - self.pos
    self._check_space(size)
    result = self.raw[self.pos: self.pos + size]
    self.pos += size
    return result

read_bigint(*, signed: bool = False) -> int

Read 8 byte number (c_ulonglong).

Source code in firebird/base/buffer.py
def read_bigint(self, *, signed: bool=False) -> int:
    """Read 8 byte number (c_ulonglong).
    """
    return self.read_number(8, signed=signed)

read_byte(*, signed: bool = False) -> int

Read 1 byte number (c_ubyte).

Source code in firebird/base/buffer.py
def read_byte(self, *, signed: bool=False) -> int:
    """Read 1 byte number (c_ubyte).
    """
    return self.read_number(1, signed=signed)

read_bytes() -> bytes | bytearray

Read content of binary cluster (2 bytes data length followed by data).

Returns:

Type Description
bytes | bytearray

The bytes read.

Raises:

Type Description
BufferError

If the end of the buffer is reached before end of data.

Source code in firebird/base/buffer.py
def read_bytes(self) -> bytes | bytearray:
    """Read content of binary cluster (2 bytes data length followed by data).


    Returns:
        The bytes read.

    Raises:
        BufferError: If the end of the buffer is reached before end of data.
    """
    return self.read(self.read_short())

read_int(*, signed: bool = False) -> int

Read 4 byte number (c_uint).

Source code in firebird/base/buffer.py
def read_int(self, *, signed: bool=False) -> int:
    """Read 4 byte number (c_uint).
    """
    return self.read_number(4, signed=signed)

read_number(size: int, *, signed: bool = False) -> int

Read a number of size bytes from current position using self.byteorder.

Advances the position by size.

Parameters:

Name Type Description Default
size int

The number of bytes representing the number.

required
signed bool

Whether to interpret the bytes as a signed integer.

False

Returns:

Type Description
int

The integer value read.

Raises:

Type Description
BufferError

When size is specified, but there is not enough bytes to read.

Source code in firebird/base/buffer.py
def read_number(self, size: int, *, signed: bool=False) -> int:
    """Read a number of `size` bytes from current position using `self.byteorder`.

    Advances the position by `size`.

    Arguments:
        size: The number of bytes representing the number.
        signed: Whether to interpret the bytes as a signed integer.

    Returns:
       The integer value read.

    Raises:
        BufferError: When `size` is specified, but there is not enough bytes to read.
    """
    self._check_space(size)
    result = (0).from_bytes(self.raw[self.pos: self.pos + size], self.byteorder.value, signed=signed)
    self.pos += size
    return result

read_pascal_string(*, encoding: str = 'ascii', errors: str = 'strict') -> str

Read Pascal string (1 byte length followed by string data).

Parameters:

Name Type Description Default
encoding str

Encoding to use for decoding.

'ascii'
errors str

Decoding error handling scheme.

'strict'

Returns:

Type Description
str

The decoded string.

Raises:

Type Description
BufferError

If the end of the buffer is reached before end of string.

UnicodeDecodeError

If the read bytes cannot be decoded using encoding.

Source code in firebird/base/buffer.py
def read_pascal_string(self, *, encoding: str='ascii', errors: str='strict') -> str:
    """Read Pascal string (1 byte length followed by string data).

    Arguments:
        encoding: Encoding to use for decoding.
        errors: Decoding error handling scheme.

    Returns:
        The decoded string.

    Raises:
        BufferError: If the end of the buffer is reached before end of string.
        UnicodeDecodeError: If the read bytes cannot be decoded using `encoding`.
    """
    return self.read(self.read_byte()).decode(encoding, errors)

read_short(*, signed: bool = False) -> int

Read 2 byte number (c_ushort).

Source code in firebird/base/buffer.py
def read_short(self, *, signed: bool=False) -> int:
    """Read 2 byte number (c_ushort).
    """
    return self.read_number(2, signed=signed)

read_sized_int(*, signed: bool = False) -> int

Read number cluster (2 byte length followed by data).

Source code in firebird/base/buffer.py
def read_sized_int(self, *, signed: bool=False) -> int:
    """Read number cluster (2 byte length followed by data).
    """
    return self.read_number(self.read_short(), signed=signed)

read_sized_string(*, encoding: str = 'ascii', errors: str = 'strict') -> str

Read sized string (2 byte length followed by data).

Parameters:

Name Type Description Default
encoding str

Encoding to use for decoding.

'ascii'
errors str

Decoding error handling scheme.

'strict'

Returns:

Type Description
str

The decoded string.

Raises:

Type Description
BufferError

If the end of the buffer is reached before end of string.

UnicodeDecodeError

If the read bytes cannot be decoded using encoding.

Source code in firebird/base/buffer.py
def read_sized_string(self, *, encoding: str='ascii', errors: str='strict') -> str:
    """Read sized string (2 byte length followed by data).

    Arguments:
        encoding: Encoding to use for decoding.
        errors: Decoding error handling scheme.

    Returns:
        The decoded string.

    Raises:
        BufferError: If the end of the buffer is reached before end of string.
        UnicodeDecodeError: If the read bytes cannot be decoded using `encoding`.
    """
    return self.read(self.read_short()).decode(encoding, errors)

read_string(*, encoding: str = 'ascii', errors: str = 'strict') -> str

Read bytes until a null terminator (0x00) is found, decode, and return string.

Advances the position past the null terminator.

Parameters:

Name Type Description Default
encoding str

Encoding to use for decoding.

'ascii'
errors str

Decoding error handling scheme.

'strict'

Returns:

Type Description
str

The decoded string (excluding the null terminator).

Raises:

Type Description
BufferError

If the end of the buffer is reached before a null terminator.

UnicodeDecodeError

If the read bytes cannot be decoded using encoding.

Source code in firebird/base/buffer.py
def read_string(self, *, encoding: str='ascii', errors: str='strict') -> str:
    """Read bytes until a null terminator (0x00) is found, decode, and return string.

    Advances the position past the null terminator.

    Arguments:
        encoding: Encoding to use for decoding.
        errors: Decoding error handling scheme.

    Returns:
        The decoded string (excluding the null terminator).

    Raises:
        BufferError: If the end of the buffer is reached before a null terminator.
        UnicodeDecodeError: If the read bytes cannot be decoded using `encoding`.
    """
    i = self.pos
    while i < self.buffer_size and safe_ord(self.raw[i]) != 0:
        i += 1
    result = self.read(i - self.pos).decode(encoding, errors)
    self.pos += 1
    return result

resize(size: int) -> None

Resize buffer to the specified length. Content is preserved up to the minimum of the old and new sizes. New space is uninitialized (depends on factory).

Parameters:

Name Type Description Default
size int

The new size in bytes.

required

Raises:

Type Description
BufferError

On attempt to resize beyond self.max_size.

Source code in firebird/base/buffer.py
def resize(self, size: int) -> None:
    """Resize buffer to the specified length. Content is preserved up to the minimum
    of the old and new sizes. New space is uninitialized (depends on factory).

    Arguments:
        size: The new size in bytes.

    Raises:
        BufferError: On attempt to resize beyond `self.max_size`.
    """
    if self.max_size is not UNLIMITED and self.max_size < size:
        raise BufferError(f"Cannot resize buffer past max. size {self.max_size} bytes")
    self.raw = self.factory.create(self.raw, size)

rewind() -> None

Set current position in buffer to beginning.

Source code in firebird/driver/core.py
def rewind(self) -> None:
    """Set current position in buffer to beginning.
    """
    self.pos = 0

seek_last_data() -> int

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

Source code in firebird/driver/core.py
def seek_last_data(self) -> int:
    """Set the position in buffer to first non-zero byte when searched from
    the end of buffer.
    """
    self.pos = self.last_data

write(data: bytes) -> None

Write raw bytes at the current position and advance position.

Ensures buffer has enough space, resizing if necessary and allowed.

Parameters:

Name Type Description Default
data bytes

The bytes to write.

required

Raises:

Type Description
BufferError

If resizing is needed but exceeds max_size.

Source code in firebird/base/buffer.py
def write(self, data: bytes) -> None:
    """Write raw bytes at the current position and advance position.

    Ensures buffer has enough space, resizing if necessary and allowed.

    Arguments:
        data: The bytes to write.

    Raises:
        BufferError: If resizing is needed but exceeds `max_size`.
    """
    size = len(data)
    self._ensure_space(size)
    self.raw[self.pos:self.pos + size] = data
    self.pos += size

write_bigint(value: int) -> None

Write 8 byte number (c_ulonglong).

Parameters:

Name Type Description Default
value int

The integer value to write.

required

Raises:

Type Description
BufferError

If resizing is needed but exceeds max_size.

Source code in firebird/base/buffer.py
def write_bigint(self, value: int) -> None:
    """Write 8 byte number (c_ulonglong).

    Arguments:
        value: The integer value to write.

    Raises:
        BufferError: If resizing is needed but exceeds `max_size`.
    """
    self.write_number(value, 8)

write_byte(byte: int) -> None

Write one byte.

Source code in firebird/base/buffer.py
def write_byte(self, byte: int) -> None:
    """Write one byte.
    """
    self._ensure_space(1)
    self.raw[self.pos] = byte
    self.pos += 1

write_int(value: int) -> None

Write 4 byte number (c_uint).

Parameters:

Name Type Description Default
value int

The integer value to write.

required

Raises:

Type Description
BufferError

If resizing is needed but exceeds max_size.

Source code in firebird/base/buffer.py
def write_int(self, value: int) -> None:
    """Write 4 byte number (c_uint).

    Arguments:
        value: The integer value to write.

    Raises:
        BufferError: If resizing is needed but exceeds `max_size`.
    """
    self.write_number(value, 4)

write_number(value: int, size: int, *, signed: bool = False) -> None

Write number with specified size (in bytes).

Parameters:

Name Type Description Default
value int

The integer value to write.

required
size int

Value size in bytes.

required
signed bool

Write as signed or unsigned integer.

False

Raises:

Type Description
BufferError

If resizing is needed but exceeds max_size.

Source code in firebird/base/buffer.py
def write_number(self, value: int, size: int, *, signed: bool=False) -> None:
    """Write number with specified size (in bytes).

    Arguments:
        value: The integer value to write.
        size: Value size in bytes.
        signed: Write as signed or unsigned integer.

    Raises:
        BufferError: If resizing is needed but exceeds `max_size`.
    """
    self.write(value.to_bytes(size, self.byteorder.value, signed=signed))

write_pascal_string(value: str, *, encoding: str = 'ascii', errors: str = 'strict') -> None

Write Pascal string (2 byte length followed by data).

Parameters:

Name Type Description Default
value str

The string to write.

required
encoding str

Encoding to use.

'ascii'
errors str

Encoding error handling scheme.

'strict'

Raises:

Type Description
BufferError

If resizing is needed but exceeds max_size.

Source code in firebird/base/buffer.py
def write_pascal_string(self, value: str, *, encoding: str='ascii', errors: str='strict') -> None:
    """Write Pascal string (2 byte length followed by data).

    Arguments:
        value: The string to write.
        encoding: Encoding to use.
        errors: Encoding error handling scheme.

    Raises:
        BufferError: If resizing is needed but exceeds `max_size`.
    """
    value = value.encode(encoding, errors)
    self.write_byte(len(value))
    self.write(value)

write_short(value: int) -> None

Write 2 byte number (c_ushort).

Parameters:

Name Type Description Default
value int

The integer value to write.

required

Raises:

Type Description
BufferError

If resizing is needed but exceeds max_size.

Source code in firebird/base/buffer.py
def write_short(self, value: int) -> None:
    """Write 2 byte number (c_ushort).

    Arguments:
        value: The integer value to write.

    Raises:
        BufferError: If resizing is needed but exceeds `max_size`.
    """
    self.write_number(value, 2)

write_sized_string(value: str, *, encoding: str = 'ascii', errors: str = 'strict') -> None

Write sized string (2 byte length followed by data).

Parameters:

Name Type Description Default
value str

The string to write.

required
encoding str

Encoding to use.

'ascii'
errors str

Encoding error handling scheme.

'strict'

Raises:

Type Description
BufferError

If resizing is needed but exceeds max_size.

Source code in firebird/base/buffer.py
def write_sized_string(self, value: str, *, encoding: str='ascii', errors: str='strict') -> None:
    """Write sized string (2 byte length followed by data).

    Arguments:
        value: The string to write.
        encoding: Encoding to use.
        errors: Encoding error handling scheme.

    Raises:
        BufferError: If resizing is needed but exceeds `max_size`.
    """
    value = value.encode(encoding, errors)
    self.write_short(len(value))
    self.write(value)

write_string(value: str, *, encoding: str = 'ascii', errors: str = 'strict') -> None

Encode string, write bytes followed by a null terminator (0x00).

Parameters:

Name Type Description Default
value str

The string to write.

required
encoding str

Encoding to use.

'ascii'
errors str

Encoding error handling scheme.

'strict'

Raises:

Type Description
BufferError

If resizing is needed but exceeds max_size.

UnicodeEncodeError

If value cannot be encoded using encoding.

Source code in firebird/base/buffer.py
def write_string(self, value: str, *, encoding: str='ascii', errors: str='strict') -> None:
    """Encode string, write bytes followed by a null terminator (0x00).

    Arguments:
        value: The string to write.
        encoding: Encoding to use.
        errors: Encoding error handling scheme.

    Raises:
        BufferError: If resizing is needed but exceeds `max_size`.
        UnicodeEncodeError: If `value` cannot be encoded using `encoding`.
    """
    self.write(value.encode(encoding, errors))
    self.write_byte(0)

firebird.driver.core.CBuffer

Bases: Buffer

ctypes MemoryBuffer with extensions.

Source code in firebird/driver/core.py
class CBuffer(Buffer):
    """ctypes MemoryBuffer with extensions.
    """
    def __init__(self, init: int | bytes, size: int | None=None, *,
                 max_size: int | UNLIMITED=UNLIMITED, byteorder: ByteOrder=ByteOrder.LITTLE):
        super().__init__(init, size, factory=CTypesBufferFactory, max_size=max_size, byteorder=byteorder)

buffer_size: int property

Current allocated buffer size in bytes.

byteorder: ByteOrder instance-attribute

The byte order used to read/write numbers [default: LITTLE].

eof_marker: int instance-attribute

Value that indicates the end of data. Could be None.

factory: BufferFactory instance-attribute

Buffer factory instance used by manager [default: BytesBufferFactory].

last_data: int property

Index of the last non-zero byte in the buffer (-1 if all zeros).

max_size: int | Sentinel instance-attribute

The buffer couldn't grow beyond specified number of bytes [default: UNLIMITED].

pos: int instance-attribute

Current position in buffer, i.e. the next read/writen byte would be at this position.

raw: bytearray instance-attribute

The memory buffer. The actual data type of buffer depends on buffer factory, but it must provide direct acces to cells, slices and length like bytearray.

clear() -> None

Fills the buffer with zeros and resets the position in buffer to zero.

Source code in firebird/base/buffer.py
def clear(self) -> None:
    """Fills the buffer with zeros and resets the position in buffer to zero.
    """
    self.factory.clear(self.raw)
    self.pos = 0

get_raw() -> bytes | bytearray

Return the underlying buffer's content as bytes or bytearray.

Use this method for generic access to the raw buffer content instead of accessing the raw attribute directly, as the type of raw can vary depending on the buffer factory used.

Returns:

Type Description
bytes | bytearray

The raw content of the buffer.

Source code in firebird/base/buffer.py
def get_raw(self) -> bytes | bytearray:
    """Return the underlying buffer's content as [bytes][] or [bytearray][].

    Use this method for generic access to the raw buffer content instead of
    accessing the `raw` attribute directly, as the type of `raw` can vary
    depending on the buffer factory used.

    Returns:
        The raw content of the buffer.
    """
    return self.factory.get_raw(self.raw)

get_tag() -> int

Read 1 byte number (c_ubyte).

Source code in firebird/driver/core.py
def get_tag(self) -> int:
    """Read 1 byte number (c_ubyte).
    """
    return self.read_byte()

is_eof() -> bool

Check if the current position is at or past the end of data.

End of data is defined as being beyond the buffer's current length, or positioned exactly on a byte matching self.eof_marker (if defined).

Returns:

Type Description
bool

True if at end-of-data, False otherwise.

Source code in firebird/base/buffer.py
def is_eof(self) -> bool:
    """Check if the current position is at or past the end of data.

    End of data is defined as being beyond the buffer's current length,
    or positioned exactly on a byte matching `self.eof_marker` (if defined).

    Returns:
        True if at end-of-data, False otherwise.
    """
    if self.pos >= len(self.raw):
        return True
    if self.eof_marker is not None and safe_ord(self.raw[self.pos]) == self.eof_marker:
        return True
    return False

is_truncated() -> bool

Return True when positioned on isc_info_truncated tag.

Source code in firebird/driver/core.py
def is_truncated(self) -> bool:
    """Return True when positioned on `isc_info_truncated` tag.
    """
    return safe_ord(self.raw[self.pos]) == isc_info_truncated

read(size: int = -1) -> bytes

Read specified number of bytes from current position, or all remaining data.

Advances the position by the number of bytes read.

Parameters:

Name Type Description Default
size int

Number of bytes to read. If negative, reads all data from the current position to the end of the buffer.

-1

Returns: The bytes read.

Raises:

Type Description
BufferError

If size requests more bytes than available from the current position.

Source code in firebird/base/buffer.py
def read(self, size: int=-1) -> bytes:
    """Read specified number of bytes from current position, or all remaining data.

    Advances the position by the number of bytes read.

    Arguments:
        size: Number of bytes to read. If negative, reads all data from the
              current position to the end of the buffer.
    Returns:
       The bytes read.

    Raises:
        BufferError: If `size` requests more bytes than available from the current position.
    """
    if size < 0:
        size = self.buffer_size - self.pos
    self._check_space(size)
    result = self.raw[self.pos: self.pos + size]
    self.pos += size
    return result

read_bigint(*, signed: bool = False) -> int

Read 8 byte number (c_ulonglong).

Source code in firebird/base/buffer.py
def read_bigint(self, *, signed: bool=False) -> int:
    """Read 8 byte number (c_ulonglong).
    """
    return self.read_number(8, signed=signed)

read_byte(*, signed: bool = False) -> int

Read 1 byte number (c_ubyte).

Source code in firebird/base/buffer.py
def read_byte(self, *, signed: bool=False) -> int:
    """Read 1 byte number (c_ubyte).
    """
    return self.read_number(1, signed=signed)

read_bytes() -> bytes | bytearray

Read content of binary cluster (2 bytes data length followed by data).

Returns:

Type Description
bytes | bytearray

The bytes read.

Raises:

Type Description
BufferError

If the end of the buffer is reached before end of data.

Source code in firebird/base/buffer.py
def read_bytes(self) -> bytes | bytearray:
    """Read content of binary cluster (2 bytes data length followed by data).


    Returns:
        The bytes read.

    Raises:
        BufferError: If the end of the buffer is reached before end of data.
    """
    return self.read(self.read_short())

read_int(*, signed: bool = False) -> int

Read 4 byte number (c_uint).

Source code in firebird/base/buffer.py
def read_int(self, *, signed: bool=False) -> int:
    """Read 4 byte number (c_uint).
    """
    return self.read_number(4, signed=signed)

read_number(size: int, *, signed: bool = False) -> int

Read a number of size bytes from current position using self.byteorder.

Advances the position by size.

Parameters:

Name Type Description Default
size int

The number of bytes representing the number.

required
signed bool

Whether to interpret the bytes as a signed integer.

False

Returns:

Type Description
int

The integer value read.

Raises:

Type Description
BufferError

When size is specified, but there is not enough bytes to read.

Source code in firebird/base/buffer.py
def read_number(self, size: int, *, signed: bool=False) -> int:
    """Read a number of `size` bytes from current position using `self.byteorder`.

    Advances the position by `size`.

    Arguments:
        size: The number of bytes representing the number.
        signed: Whether to interpret the bytes as a signed integer.

    Returns:
       The integer value read.

    Raises:
        BufferError: When `size` is specified, but there is not enough bytes to read.
    """
    self._check_space(size)
    result = (0).from_bytes(self.raw[self.pos: self.pos + size], self.byteorder.value, signed=signed)
    self.pos += size
    return result

read_pascal_string(*, encoding: str = 'ascii', errors: str = 'strict') -> str

Read Pascal string (1 byte length followed by string data).

Parameters:

Name Type Description Default
encoding str

Encoding to use for decoding.

'ascii'
errors str

Decoding error handling scheme.

'strict'

Returns:

Type Description
str

The decoded string.

Raises:

Type Description
BufferError

If the end of the buffer is reached before end of string.

UnicodeDecodeError

If the read bytes cannot be decoded using encoding.

Source code in firebird/base/buffer.py
def read_pascal_string(self, *, encoding: str='ascii', errors: str='strict') -> str:
    """Read Pascal string (1 byte length followed by string data).

    Arguments:
        encoding: Encoding to use for decoding.
        errors: Decoding error handling scheme.

    Returns:
        The decoded string.

    Raises:
        BufferError: If the end of the buffer is reached before end of string.
        UnicodeDecodeError: If the read bytes cannot be decoded using `encoding`.
    """
    return self.read(self.read_byte()).decode(encoding, errors)

read_short(*, signed: bool = False) -> int

Read 2 byte number (c_ushort).

Source code in firebird/base/buffer.py
def read_short(self, *, signed: bool=False) -> int:
    """Read 2 byte number (c_ushort).
    """
    return self.read_number(2, signed=signed)

read_sized_int(*, signed: bool = False) -> int

Read number cluster (2 byte length followed by data).

Source code in firebird/base/buffer.py
def read_sized_int(self, *, signed: bool=False) -> int:
    """Read number cluster (2 byte length followed by data).
    """
    return self.read_number(self.read_short(), signed=signed)

read_sized_string(*, encoding: str = 'ascii', errors: str = 'strict') -> str

Read sized string (2 byte length followed by data).

Parameters:

Name Type Description Default
encoding str

Encoding to use for decoding.

'ascii'
errors str

Decoding error handling scheme.

'strict'

Returns:

Type Description
str

The decoded string.

Raises:

Type Description
BufferError

If the end of the buffer is reached before end of string.

UnicodeDecodeError

If the read bytes cannot be decoded using encoding.

Source code in firebird/base/buffer.py
def read_sized_string(self, *, encoding: str='ascii', errors: str='strict') -> str:
    """Read sized string (2 byte length followed by data).

    Arguments:
        encoding: Encoding to use for decoding.
        errors: Decoding error handling scheme.

    Returns:
        The decoded string.

    Raises:
        BufferError: If the end of the buffer is reached before end of string.
        UnicodeDecodeError: If the read bytes cannot be decoded using `encoding`.
    """
    return self.read(self.read_short()).decode(encoding, errors)

read_string(*, encoding: str = 'ascii', errors: str = 'strict') -> str

Read bytes until a null terminator (0x00) is found, decode, and return string.

Advances the position past the null terminator.

Parameters:

Name Type Description Default
encoding str

Encoding to use for decoding.

'ascii'
errors str

Decoding error handling scheme.

'strict'

Returns:

Type Description
str

The decoded string (excluding the null terminator).

Raises:

Type Description
BufferError

If the end of the buffer is reached before a null terminator.

UnicodeDecodeError

If the read bytes cannot be decoded using encoding.

Source code in firebird/base/buffer.py
def read_string(self, *, encoding: str='ascii', errors: str='strict') -> str:
    """Read bytes until a null terminator (0x00) is found, decode, and return string.

    Advances the position past the null terminator.

    Arguments:
        encoding: Encoding to use for decoding.
        errors: Decoding error handling scheme.

    Returns:
        The decoded string (excluding the null terminator).

    Raises:
        BufferError: If the end of the buffer is reached before a null terminator.
        UnicodeDecodeError: If the read bytes cannot be decoded using `encoding`.
    """
    i = self.pos
    while i < self.buffer_size and safe_ord(self.raw[i]) != 0:
        i += 1
    result = self.read(i - self.pos).decode(encoding, errors)
    self.pos += 1
    return result

resize(size: int) -> None

Resize buffer to the specified length. Content is preserved up to the minimum of the old and new sizes. New space is uninitialized (depends on factory).

Parameters:

Name Type Description Default
size int

The new size in bytes.

required

Raises:

Type Description
BufferError

On attempt to resize beyond self.max_size.

Source code in firebird/base/buffer.py
def resize(self, size: int) -> None:
    """Resize buffer to the specified length. Content is preserved up to the minimum
    of the old and new sizes. New space is uninitialized (depends on factory).

    Arguments:
        size: The new size in bytes.

    Raises:
        BufferError: On attempt to resize beyond `self.max_size`.
    """
    if self.max_size is not UNLIMITED and self.max_size < size:
        raise BufferError(f"Cannot resize buffer past max. size {self.max_size} bytes")
    self.raw = self.factory.create(self.raw, size)

rewind() -> None

Set current position in buffer to beginning.

Source code in firebird/driver/core.py
def rewind(self) -> None:
    """Set current position in buffer to beginning.
    """
    self.pos = 0

seek_last_data() -> int

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

Source code in firebird/driver/core.py
def seek_last_data(self) -> int:
    """Set the position in buffer to first non-zero byte when searched from
    the end of buffer.
    """
    self.pos = self.last_data

write(data: bytes) -> None

Write raw bytes at the current position and advance position.

Ensures buffer has enough space, resizing if necessary and allowed.

Parameters:

Name Type Description Default
data bytes

The bytes to write.

required

Raises:

Type Description
BufferError

If resizing is needed but exceeds max_size.

Source code in firebird/base/buffer.py
def write(self, data: bytes) -> None:
    """Write raw bytes at the current position and advance position.

    Ensures buffer has enough space, resizing if necessary and allowed.

    Arguments:
        data: The bytes to write.

    Raises:
        BufferError: If resizing is needed but exceeds `max_size`.
    """
    size = len(data)
    self._ensure_space(size)
    self.raw[self.pos:self.pos + size] = data
    self.pos += size

write_bigint(value: int) -> None

Write 8 byte number (c_ulonglong).

Parameters:

Name Type Description Default
value int

The integer value to write.

required

Raises:

Type Description
BufferError

If resizing is needed but exceeds max_size.

Source code in firebird/base/buffer.py
def write_bigint(self, value: int) -> None:
    """Write 8 byte number (c_ulonglong).

    Arguments:
        value: The integer value to write.

    Raises:
        BufferError: If resizing is needed but exceeds `max_size`.
    """
    self.write_number(value, 8)

write_byte(byte: int) -> None

Write one byte.

Source code in firebird/base/buffer.py
def write_byte(self, byte: int) -> None:
    """Write one byte.
    """
    self._ensure_space(1)
    self.raw[self.pos] = byte
    self.pos += 1

write_int(value: int) -> None

Write 4 byte number (c_uint).

Parameters:

Name Type Description Default
value int

The integer value to write.

required

Raises:

Type Description
BufferError

If resizing is needed but exceeds max_size.

Source code in firebird/base/buffer.py
def write_int(self, value: int) -> None:
    """Write 4 byte number (c_uint).

    Arguments:
        value: The integer value to write.

    Raises:
        BufferError: If resizing is needed but exceeds `max_size`.
    """
    self.write_number(value, 4)

write_number(value: int, size: int, *, signed: bool = False) -> None

Write number with specified size (in bytes).

Parameters:

Name Type Description Default
value int

The integer value to write.

required
size int

Value size in bytes.

required
signed bool

Write as signed or unsigned integer.

False

Raises:

Type Description
BufferError

If resizing is needed but exceeds max_size.

Source code in firebird/base/buffer.py
def write_number(self, value: int, size: int, *, signed: bool=False) -> None:
    """Write number with specified size (in bytes).

    Arguments:
        value: The integer value to write.
        size: Value size in bytes.
        signed: Write as signed or unsigned integer.

    Raises:
        BufferError: If resizing is needed but exceeds `max_size`.
    """
    self.write(value.to_bytes(size, self.byteorder.value, signed=signed))

write_pascal_string(value: str, *, encoding: str = 'ascii', errors: str = 'strict') -> None

Write Pascal string (2 byte length followed by data).

Parameters:

Name Type Description Default
value str

The string to write.

required
encoding str

Encoding to use.

'ascii'
errors str

Encoding error handling scheme.

'strict'

Raises:

Type Description
BufferError

If resizing is needed but exceeds max_size.

Source code in firebird/base/buffer.py
def write_pascal_string(self, value: str, *, encoding: str='ascii', errors: str='strict') -> None:
    """Write Pascal string (2 byte length followed by data).

    Arguments:
        value: The string to write.
        encoding: Encoding to use.
        errors: Encoding error handling scheme.

    Raises:
        BufferError: If resizing is needed but exceeds `max_size`.
    """
    value = value.encode(encoding, errors)
    self.write_byte(len(value))
    self.write(value)

write_short(value: int) -> None

Write 2 byte number (c_ushort).

Parameters:

Name Type Description Default
value int

The integer value to write.

required

Raises:

Type Description
BufferError

If resizing is needed but exceeds max_size.

Source code in firebird/base/buffer.py
def write_short(self, value: int) -> None:
    """Write 2 byte number (c_ushort).

    Arguments:
        value: The integer value to write.

    Raises:
        BufferError: If resizing is needed but exceeds `max_size`.
    """
    self.write_number(value, 2)

write_sized_string(value: str, *, encoding: str = 'ascii', errors: str = 'strict') -> None

Write sized string (2 byte length followed by data).

Parameters:

Name Type Description Default
value str

The string to write.

required
encoding str

Encoding to use.

'ascii'
errors str

Encoding error handling scheme.

'strict'

Raises:

Type Description
BufferError

If resizing is needed but exceeds max_size.

Source code in firebird/base/buffer.py
def write_sized_string(self, value: str, *, encoding: str='ascii', errors: str='strict') -> None:
    """Write sized string (2 byte length followed by data).

    Arguments:
        value: The string to write.
        encoding: Encoding to use.
        errors: Encoding error handling scheme.

    Raises:
        BufferError: If resizing is needed but exceeds `max_size`.
    """
    value = value.encode(encoding, errors)
    self.write_short(len(value))
    self.write(value)

write_string(value: str, *, encoding: str = 'ascii', errors: str = 'strict') -> None

Encode string, write bytes followed by a null terminator (0x00).

Parameters:

Name Type Description Default
value str

The string to write.

required
encoding str

Encoding to use.

'ascii'
errors str

Encoding error handling scheme.

'strict'

Raises:

Type Description
BufferError

If resizing is needed but exceeds max_size.

UnicodeEncodeError

If value cannot be encoded using encoding.

Source code in firebird/base/buffer.py
def write_string(self, value: str, *, encoding: str='ascii', errors: str='strict') -> None:
    """Encode string, write bytes followed by a null terminator (0x00).

    Arguments:
        value: The string to write.
        encoding: Encoding to use.
        errors: Encoding error handling scheme.

    Raises:
        BufferError: If resizing is needed but exceeds `max_size`.
        UnicodeEncodeError: If `value` cannot be encoded using `encoding`.
    """
    self.write(value.encode(encoding, errors))
    self.write_byte(0)

Classes

firebird.driver.core.Connection

Connection to the database.

Note

Implements context manager protocol to call .close() automatically.

Source code in firebird/driver/core.py
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
class Connection:
    """Connection to the database.

    Note:
        Implements context manager protocol to call `.close()` automatically.
    """
    # PEP 249 (Python DB API 2.0) extension
    Warning = Warning
    Error = Error
    InterfaceError = InterfaceError
    DatabaseError = DatabaseError
    DataError = DataError
    OperationalError = OperationalError
    IntegrityError = IntegrityError
    InternalError = InternalError
    ProgrammingError = ProgrammingError
    NotSupportedError = NotSupportedError
    def __init__(self, att: iAttachment, dsn: str, dpb: bytes | None=None, sql_dialect: int=3,
                 charset: str | None=None) -> None:
        self._lifecycle = ConnectionLifecycle()
        self._att: iAttachment = att
        self._att._lifecycle = self._lifecycle
        self.__handle: a.FB_API_HANDLE = None
        self.__str: str = f'Connection[{self._get_handle().value}]'
        self.__charset: str = charset
        self.__precision_cache = {}
        self.__sqlsubtype_cache = {}
        self.__ecollectors: list[EventCollector] = []
        self.__dsn: str = dsn
        self.__sql_dialect: int = sql_dialect
        self._encoding: str = CHARSET_MAP.get(charset, 'ascii')
        self._att.encoding = self._encoding
        self._dpb: bytes | None = dpb
        self.default_tpb: bytes = tpb(Isolation.SNAPSHOT)
        "Default TPB for newly created transaction managers"
        self._transactions: list[TransactionManager] = []
        self._statements: list[Statement] = []
        #
        self.__ev: float = None
        self.__info: DatabaseInfoProvider = None
        self._tra_main: TransactionManager = TransactionManager(self, self.default_tpb)
        self._tra_qry: TransactionManager = TransactionManager(self,
                                                               tpb(Isolation.READ_COMMITTED_RECORD_VERSION,
                                                                   access_mode=TraAccessMode.READ))
        # Cursor for internal use
        self._ic = self.query_transaction.cursor()
        self._ic._connection = weakref.proxy(self, self._ic._dead_con)
        # firebird.lib extensions
        self.__schema = None
        self.__monitor = None
        self.__FIREBIRD_LIB__ = None
    def __del__(self):
        if getattr(getattr(self, '_lifecycle', None), 'is_dead', False):
            return
        if not self.is_closed():
            warn("Connection disposed without prior close()", ResourceWarning)
            self._close()
            self._close_internals()
            with contextlib.suppress(DatabaseError):
                self._att.detach()
    def __enter__(self) -> Self:
        return self
    def __exit__(self, exc_type, exc_value, traceback) -> None:
        self.close()
    def __repr__(self):
        return self.__str
    def _get_handle(self) -> a.FB_API_HANDLE:
        if self.__handle is None:
            isc_status = a.ISC_STATUS_ARRAY()
            self.__handle = a.FB_API_HANDLE(0)
            a.get_api().fb_get_database_handle(isc_status, self.__handle, self._att)
            if a.db_api_error(isc_status):  # pragma: no cover
                raise a.exception_from_status(DatabaseError,
                                              isc_status,
                                              "Error in Connection._get_handle:fb_get_database_handle()")
        return self.__handle
    def __stmt_deleted(self, stmt: Statement) -> None:
        self._statements.remove(stmt)
    def _close(self) -> None:
        if self.__schema is not None:
            self.__schema._set_internal(False)
            self.__schema.close()
        if self.__monitor is not None:
            self.__monitor._set_internal(False)
            self.__monitor.close()
        self._ic.close()
        for collector in self.__ecollectors:
            collector.close()
        self.main_transaction._finish(DefaultAction.ROLLBACK)
        self.query_transaction._finish(DefaultAction.ROLLBACK)
        while self._transactions:
            tra = self._transactions.pop(0)
            tra.default_action = DefaultAction.ROLLBACK  # Required by Python DB API 2.0
            tra.close()
        while self._statements:
            s = self._statements.pop()()
            if s is not None:
                s.free()
    def _close_internals(self) -> None:
        self.main_transaction.close()
        self.query_transaction.close()
        if self.__info is not None:
            self.__info._close()
    def _engine_version(self) -> float:
        if self.__ev is None:
            self.__ev = _engine_version_provider.get_engine_version(weakref.ref(self))
        return self.__ev
    def _prepare(self, sql: str, tra: TransactionManager) -> Statement:
        if _commit := not tra.is_active():
            tra.begin()
        stmt = self._att.prepare(tra._tra, sql, self.__sql_dialect)
        result = Statement(self, stmt, sql, self.__sql_dialect)
        self._statements.append(weakref.ref(result, self.__stmt_deleted))
        if _commit:
            tra.commit()
        return result
    def _determine_field_precision(self, meta: ItemMetadata) -> int:
        # This internal method involve database queries using _tra_qry.
        if (not meta.relation) or (not meta.field):
            # Either or both field name and relation name are not provided,
            # so we cannot determine field precision. It's normal situation
            # for example for queries with dynamically computed fields
            return 0
        # Special case for automatic RDB$DB_KEY fields.
        if meta.field in ('DB_KEY', 'RDB$DB_KEY'):
            return 0
        precision = self.__precision_cache.get((meta.relation, meta.field))
        if precision is not None:
            return precision
        # First, try table
        with transaction(self._tra_qry, bypass=True):
            with self._ic.execute("SELECT FIELD_SPEC.RDB$FIELD_PRECISION"
                                   " FROM RDB$FIELDS FIELD_SPEC,"
                                   " RDB$RELATION_FIELDS REL_FIELDS"
                                   " WHERE"
                                   " FIELD_SPEC.RDB$FIELD_NAME ="
                                   " REL_FIELDS.RDB$FIELD_SOURCE"
                                   " AND REL_FIELDS.RDB$RELATION_NAME = ?"
                                   " AND REL_FIELDS.RDB$FIELD_NAME = ?",
                                   (meta.relation, meta.field)):
                result = self._ic.fetchone()
            if result is None:
                # Next, try stored procedure output parameter
                with self._ic.execute("SELECT FIELD_SPEC.RDB$FIELD_PRECISION"
                                       " FROM RDB$FIELDS FIELD_SPEC,"
                                       " RDB$PROCEDURE_PARAMETERS REL_FIELDS"
                                       " WHERE"
                                       " FIELD_SPEC.RDB$FIELD_NAME ="
                                       " REL_FIELDS.RDB$FIELD_SOURCE"
                                       " AND RDB$PROCEDURE_NAME = ?"
                                       " AND RDB$PARAMETER_NAME = ?"
                                       " AND RDB$PARAMETER_TYPE = 1",
                                       (meta.relation, meta.field)):
                    result = self._ic.fetchone()
            if result:
                self.__precision_cache[(meta.relation, meta.field)] = result[0]
                return result[0]
        # We ran out of options
        return 0
    def _get_array_sqlsubtype(self, relation: bytes, column: bytes) -> int | None:
        # This internal method involve database query using _tra_qry.
        subtype = self.__sqlsubtype_cache.get((relation, column))
        if subtype is not None:
            return subtype
        with transaction(self._tra_qry, bypass=True):
            with self._ic.execute("SELECT FIELD_SPEC.RDB$FIELD_SUB_TYPE"
                                   " FROM RDB$FIELDS FIELD_SPEC, RDB$RELATION_FIELDS REL_FIELDS"
                                   " WHERE"
                                   " FIELD_SPEC.RDB$FIELD_NAME = REL_FIELDS.RDB$FIELD_SOURCE"
                                   " AND REL_FIELDS.RDB$RELATION_NAME = ?"
                                   " AND REL_FIELDS.RDB$FIELD_NAME = ?",
                                   (relation, column)):
                result = self._ic.fetchone()
        if result:
            self.__sqlsubtype_cache[(relation, column)] = result[0]
            return result[0]
        return None
    def drop_database(self) -> None:
        """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.

        Important:
            The connection object becomes unusable after this call.

        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.
        """
        self._close()
        self._close_internals()
        try:
            self._att.drop_database()
        finally:
            self._att = None
            for hook in get_callbacks(ConnectionHook.DROPPED, self):
                hook(self)
    def execute_immediate(self, sql: str) -> None:
        """Executes SQL statement.

        Important:

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

        Arguments:
           sql: SQL statement to be executed.
        """
        self.main_transaction.execute_immediate(sql)
    def event_collector(self, event_names: Sequence[str]) -> EventCollector:
        """Create new `EventCollector` instance for this connection.

        Arguments:
            event_names: Sequence of database event names to whom the collector should be subscribed.
        """
        conduit = EventCollector(self._get_handle(), event_names)
        self.__ecollectors.append(conduit)
        return conduit
    def close(self) -> None:
        """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.
        """
        if not self.is_closed():
            retain = False
            try:
                self._close()
            except DatabaseError:
                self._att = None
                raise
            for hook in get_callbacks(ConnectionHook.DETACH_REQUEST, self):
                ret = hook(self)
                if ret and not retain:
                    retain = True
            #
            if not retain:
                try:
                    self._close_internals()
                    self._att.detach()
                finally:
                    self._att = None
                    for hook in get_callbacks(ConnectionHook.CLOSED, self):
                        hook(self)
    def transaction_manager(self, default_tpb: bytes | None=None,
                            default_action: DefaultAction=DefaultAction.COMMIT) -> TransactionManager:
        """Create new `TransactionManager` instance for this connection.

        Arguments:
            default_tpb: Default Transaction parameter buffer.
            default_action: Default action to be performed on implicit transaction end.
        """
        tra = TransactionManager(self, default_tpb or self.default_tpb, default_action)
        self._transactions.append(tra)
        return tra
    def begin(self, tpb: bytes | None=None) -> None:
        """Starts new transaction managed by `.main_transaction`.

        Arguments:
            tpb: Transaction parameter buffer with transaction parameters. If not specified,
                 the `.default_tpb` is used.
        """
        self.main_transaction.begin(tpb)
    def savepoint(self, name: str) -> None:
        """Creates a new savepoint for transaction managed by `.main_transaction`.

        Arguments:
            name: Name for the savepoint
        """
        return self.main_transaction.savepoint(name)
    def commit(self, *, retaining: bool=False) -> None:
        """Commits the transaction managed by `.main_transaction`.

        Arguments:
            retaining: When True, the transaction context is retained after commit.
        """
        self.main_transaction.commit(retaining=retaining)
    def rollback(self, *, retaining: bool=False, savepoint: str | None=None) -> None:
        """Rolls back the transaction managed by `.main_transaction`.

        Arguments:
            retaining: When True, the transaction context is retained after rollback.
            savepoint: When specified, the transaction is rolled back to savepoint with given name.
        """
        self.main_transaction.rollback(retaining=retaining, savepoint=savepoint)
    def cursor(self) -> Cursor:
        """Returns new `Cursor` instance associated with `.main_transaction`.
        """
        return self.main_transaction.cursor()
    def ping(self) -> None:
        """Checks connection status. If test fails the only operation possible
        with connection is to close it.

        Raises:
          DatabaseError: When connection is dead.
        """
        self._att.ping()
    def is_active(self) -> bool:
        """Returns True if `.main_transaction` has active transaction.
        """
        return self._tra_main.is_active()
    def is_closed(self) -> bool:
        """Returns True if connection to the database is closed.

        Important:
            Closed connection SHALL NOT be used anymore.
        """
        return self._att is None
    @property
    def dsn(self) -> str:
        """Connection string.
        """
        return self.__dsn
    @property
    def info(self) -> DatabaseInfoProvider3 | DatabaseInfoProvider:
        """Access to various information about attached database.
        """
        if self.__info is None:
            self.__info = DatabaseInfoProvider(self) if self._engine_version() >= 4.0 \
                else DatabaseInfoProvider3(self)
        return self.__info
    @property
    def charset(self) -> str:
        """Connection character set.
        """
        return self.__charset
    @property
    def sql_dialect(self) -> int:
        """Connection SQL dialect.
        """
        return self.__sql_dialect
    @property
    def main_transaction(self) -> TransactionManager:
        """Main transaction manager for this connection.
        """
        return self._tra_main
    @property
    def query_transaction(self) -> TransactionManager:
        """Transaction manager for Read-committed Read-only query transactions.
        """
        return self._tra_qry
    @property
    def transactions(self) -> list[TransactionManager]:
        """List of all transaction managers associated with connection.

        Note:
            The first two are always `.main_transaction` and `.query_transaction` managers.
        """
        result = [self.main_transaction, self.query_transaction]
        result.extend(self._transactions)
        return result
    @property
    def schema(self) -> 'firebird.lib.schema.Schema': # noqa: UP037, F821
        """Access to database schema. Requires `firebird.lib` package.
        """
        if self.__schema is None:
            import firebird.lib.schema
            self.__schema = firebird.lib.schema.Schema()
            self.__schema.bind(self)
            self.__schema._set_internal(True)
        return self.__schema
    @property
    def monitor(self) -> 'firebird.lib.monitor.Monitor': # noqa: UP037, F821
        """Access to database monitoring tables. Requires `firebird.lib` package.
        """
        if self.__monitor is None:
            import firebird.lib.monitor
            self.__monitor = firebird.lib.monitor.Monitor(self)
            self.__monitor._set_internal(True)
        return self.__monitor

charset: str property

Connection character set.

default_tpb: bytes instance-attribute

Default TPB for newly created transaction managers

dsn: str property

Connection string.

info: DatabaseInfoProvider3 | DatabaseInfoProvider property

Access to various information about attached database.

main_transaction: TransactionManager property

Main transaction manager for this connection.

monitor: 'firebird.lib.monitor.Monitor' property

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

query_transaction: TransactionManager property

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

schema: 'firebird.lib.schema.Schema' property

Access to database schema. Requires firebird.lib package.

sql_dialect: int property

Connection SQL dialect.

transactions: list[TransactionManager] property

List of all transaction managers associated with connection.

Note

The first two are always .main_transaction and .query_transaction managers.

begin(tpb: bytes | None = None) -> None

Starts new transaction managed by .main_transaction.

Parameters:

Name Type Description Default
tpb bytes | None

Transaction parameter buffer with transaction parameters. If not specified, the .default_tpb is used.

None
Source code in firebird/driver/core.py
def begin(self, tpb: bytes | None=None) -> None:
    """Starts new transaction managed by `.main_transaction`.

    Arguments:
        tpb: Transaction parameter buffer with transaction parameters. If not specified,
             the `.default_tpb` is used.
    """
    self.main_transaction.begin(tpb)

close() -> None

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.

Source code in firebird/driver/core.py
def close(self) -> None:
    """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.
    """
    if not self.is_closed():
        retain = False
        try:
            self._close()
        except DatabaseError:
            self._att = None
            raise
        for hook in get_callbacks(ConnectionHook.DETACH_REQUEST, self):
            ret = hook(self)
            if ret and not retain:
                retain = True
        #
        if not retain:
            try:
                self._close_internals()
                self._att.detach()
            finally:
                self._att = None
                for hook in get_callbacks(ConnectionHook.CLOSED, self):
                    hook(self)

commit(*, retaining: bool = False) -> None

Commits the transaction managed by .main_transaction.

Parameters:

Name Type Description Default
retaining bool

When True, the transaction context is retained after commit.

False
Source code in firebird/driver/core.py
def commit(self, *, retaining: bool=False) -> None:
    """Commits the transaction managed by `.main_transaction`.

    Arguments:
        retaining: When True, the transaction context is retained after commit.
    """
    self.main_transaction.commit(retaining=retaining)

cursor() -> Cursor

Returns new Cursor instance associated with .main_transaction.

Source code in firebird/driver/core.py
def cursor(self) -> Cursor:
    """Returns new `Cursor` instance associated with `.main_transaction`.
    """
    return self.main_transaction.cursor()

drop_database() -> None

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

The connection object becomes unusable after this call.

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.

Source code in firebird/driver/core.py
def drop_database(self) -> None:
    """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.

    Important:
        The connection object becomes unusable after this call.

    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.
    """
    self._close()
    self._close_internals()
    try:
        self._att.drop_database()
    finally:
        self._att = None
        for hook in get_callbacks(ConnectionHook.DROPPED, self):
            hook(self)

event_collector(event_names: Sequence[str]) -> EventCollector

Create new EventCollector instance for this connection.

Parameters:

Name Type Description Default
event_names Sequence[str]

Sequence of database event names to whom the collector should be subscribed.

required
Source code in firebird/driver/core.py
def event_collector(self, event_names: Sequence[str]) -> EventCollector:
    """Create new `EventCollector` instance for this connection.

    Arguments:
        event_names: Sequence of database event names to whom the collector should be subscribed.
    """
    conduit = EventCollector(self._get_handle(), event_names)
    self.__ecollectors.append(conduit)
    return conduit

execute_immediate(sql: str) -> None

Executes SQL statement.

Important:

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

Parameters:

Name Type Description Default
sql str

SQL statement to be executed.

required
Source code in firebird/driver/core.py
def execute_immediate(self, sql: str) -> None:
    """Executes SQL statement.

    Important:

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

    Arguments:
       sql: SQL statement to be executed.
    """
    self.main_transaction.execute_immediate(sql)

is_active() -> bool

Returns True if .main_transaction has active transaction.

Source code in firebird/driver/core.py
def is_active(self) -> bool:
    """Returns True if `.main_transaction` has active transaction.
    """
    return self._tra_main.is_active()

is_closed() -> bool

Returns True if connection to the database is closed.

Important

Closed connection SHALL NOT be used anymore.

Source code in firebird/driver/core.py
def is_closed(self) -> bool:
    """Returns True if connection to the database is closed.

    Important:
        Closed connection SHALL NOT be used anymore.
    """
    return self._att is None

ping() -> None

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

Raises:

Type Description
DatabaseError

When connection is dead.

Source code in firebird/driver/core.py
def ping(self) -> None:
    """Checks connection status. If test fails the only operation possible
    with connection is to close it.

    Raises:
      DatabaseError: When connection is dead.
    """
    self._att.ping()

rollback(*, retaining: bool = False, savepoint: str | None = None) -> None

Rolls back the transaction managed by .main_transaction.

Parameters:

Name Type Description Default
retaining bool

When True, the transaction context is retained after rollback.

False
savepoint str | None

When specified, the transaction is rolled back to savepoint with given name.

None
Source code in firebird/driver/core.py
def rollback(self, *, retaining: bool=False, savepoint: str | None=None) -> None:
    """Rolls back the transaction managed by `.main_transaction`.

    Arguments:
        retaining: When True, the transaction context is retained after rollback.
        savepoint: When specified, the transaction is rolled back to savepoint with given name.
    """
    self.main_transaction.rollback(retaining=retaining, savepoint=savepoint)

savepoint(name: str) -> None

Creates a new savepoint for transaction managed by .main_transaction.

Parameters:

Name Type Description Default
name str

Name for the savepoint

required
Source code in firebird/driver/core.py
def savepoint(self, name: str) -> None:
    """Creates a new savepoint for transaction managed by `.main_transaction`.

    Arguments:
        name: Name for the savepoint
    """
    return self.main_transaction.savepoint(name)

transaction_manager(default_tpb: bytes | None = None, default_action: DefaultAction = DefaultAction.COMMIT) -> TransactionManager

Create new TransactionManager instance for this connection.

Parameters:

Name Type Description Default
default_tpb bytes | None

Default Transaction parameter buffer.

None
default_action DefaultAction

Default action to be performed on implicit transaction end.

COMMIT
Source code in firebird/driver/core.py
def transaction_manager(self, default_tpb: bytes | None=None,
                        default_action: DefaultAction=DefaultAction.COMMIT) -> TransactionManager:
    """Create new `TransactionManager` instance for this connection.

    Arguments:
        default_tpb: Default Transaction parameter buffer.
        default_action: Default action to be performed on implicit transaction end.
    """
    tra = TransactionManager(self, default_tpb or self.default_tpb, default_action)
    self._transactions.append(tra)
    return tra

firebird.driver.core.TransactionManager

Transaction manager.

Note

Implements context manager protocol to call .close() automatically.

Source code in firebird/driver/core.py
class TransactionManager:
    """Transaction manager.

    Note:
        Implements context manager protocol to call `.close()` automatically.
    """
    def __init__(self, connection: Connection, default_tpb: bytes,
                 default_action: DefaultAction=DefaultAction.COMMIT):
        self._connection: Callable[[], Connection] = weakref.ref(connection, self.__dead_con)
        self._lifecycle = connection._lifecycle
        self.default_tpb: bytes = default_tpb
        "Default Transaction Parameter Block used to start transaction"
        self.default_action: DefaultAction = default_action
        "Default action (commit/rollback) to be performed when transaction is closed."
        self.__handle: a.FB_API_HANDLE = None
        self.__info: TransactionInfoProvider | TransactionInfoProvider3 = None
        self._cursors: list = []  # Weak references to cursors
        self._tra: iTransaction = None
        self.__closed: bool = False
    def __enter__(self) -> Self:
        self.begin()
        return self
    def __exit__(self, exc_type, exc_value, traceback) -> None:
        self.close()
    def __del__(self):
        if getattr(getattr(self, '_lifecycle', None), 'is_dead', False):
            return
        if any(lifecycle.is_dead for lifecycle in getattr(self, '_lifecycles', ())):
            return
        if self._tra is not None:
            warn("Transaction disposed while active", ResourceWarning)
            self._finish()
    def __dead_con(self, obj: Connection) -> None: # noqa: ARG002
        self._connection = None
    def _close_cursors(self) -> None:
        for cursor in self._cursors:
            c = cursor()
            if c:
                c.close()
    def _cursor_deleted(self, obj: Cursor) -> None:
        self._cursors.remove(obj)
    def _finish(self, default_action: DefaultAction | None=None) -> None:
        try:
            if self._tra is not None:
                if default_action is None:
                    default_action = self.default_action
                if default_action == DefaultAction.COMMIT:
                    self.commit()
                else:
                    self.rollback()
        finally:
            self._tra = None
            self.__handle = None
    def _get_handle(self) -> a.FB_API_HANDLE:
        if self.__handle is None:
            isc_status = a.ISC_STATUS_ARRAY()
            self.__handle = a.FB_API_HANDLE(0)
            a.get_api().fb_get_transaction_handle(isc_status, self.__handle, self._tra)
            if a.db_api_error(isc_status):  # pragma: no cover
                raise a.exception_from_status(DatabaseError,
                                              isc_status,
                                              "Error in TransactionManager._get_handle:fb_get_transaction_handle()")
        return self.__handle
    def close(self) -> None:
        """Close the transaction manager and release all associated resources.

        Implicitly ends the current active transaction according to default_action (if active).

        Important:
            Closed instance SHALL NOT be used anymore.
        """
        if not self.__closed:
            try:
                self._finish()
            finally:
                con = self._connection()
                if con is not None and self in con._transactions:
                    con._transactions.remove(self)
                self._connection = None
                self.__closed = True
                if self.__info is not None:
                    self.__info._close()
    def execute_immediate(self, sql: str) -> None:
        """Executes SQL statement. The statement MUST NOT return any result.

        Arguments:
           sql: SQL statement to be executed.
        """
        if not self.is_active():
            self.begin()
        self._connection()._att.execute(self._tra, sql, self._connection().sql_dialect)
    def begin(self, tpb: bytes | None=None) -> None:
        """Starts new transaction managed by this instance.

        Arguments:
            tpb: Transaction parameter buffer with transaction's parameters. If not specified,
                 the `.default_tpb` is used.
        """
        self._finish()  # Make sure that previous transaction (if any) is ended
        self._tra = self._connection()._att.start_transaction(self.default_tpb if tpb is None
                                                              else tpb)
    def commit(self, *, retaining: bool=False) -> None:
        """Commits the transaction managed by this instance.

        Arguments:
            retaining: When True, the transaction context is retained after commit.
        """
        if retaining:
            self._tra.commit_retaining()
        else:
            self._close_cursors()
            self._tra.commit()
        if not retaining:
            self._tra = None
    def rollback(self, *, retaining: bool=False, savepoint: str | None=None) -> None:
        """Rolls back the transaction managed by this instance.

        Arguments:
            retaining: When True, the transaction context is retained after rollback.
            savepoint: When specified, the transaction is rolled back to savepoint with given name.

        Raises:
            InterfaceError: When both retaining and savepoint parameters are specified.
        """
        if retaining and savepoint:
            raise InterfaceError("Can't rollback to savepoint while retaining context")
        if savepoint:
            self.execute_immediate(f'rollback to {savepoint}')
        else:
            if retaining:
                self._tra.rollback_retaining()
            else:
                self._close_cursors()
                self._tra.rollback()
            if not retaining:
                self._tra = None
    def savepoint(self, name: str) -> None:
        """Creates a new savepoint for transaction managed by this instance.

        Arguments:
            name: Name for the savepoint
        """
        self.execute_immediate(f'SAVEPOINT {name}')
    def cursor(self) -> Cursor:
        """Returns new `Cursor` instance associated with this instance.
        """
        cur = Cursor(self._connection(), self)
        self._cursors.append(weakref.ref(cur, self._cursor_deleted))
        return cur
    def is_active(self) -> bool:
        """Returns True if transaction is active.
        """
        return self._tra is not None
    def is_closed(self) -> bool:
        """Returns True if this transaction manager is closed.
        """
        return self.__closed
    # Properties
    @property
    def info(self) -> TransactionInfoProvider3 | TransactionInfoProvider:
        """Access to various information about active transaction.
        """
        if self.__info is None:
            cls = TransactionInfoProvider if self._connection()._engine_version() >= 4.0 \
                else TransactionInfoProvider3
            self.__info = cls(self._connection()._encoding, self)
        return self.__info
    @property
    def log_context(self) -> Connection:
        "Logging context [connection]."
        if self._connection is None:
            return 'Connection.GC'
        return self._connection()
    @property
    def cursors(self) -> list[Cursor]:
        """Cursors associated with this transaction.
        """
        return [x() for x in self._cursors]

cursors: list[Cursor] property

Cursors associated with this transaction.

default_action: DefaultAction instance-attribute

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

default_tpb: bytes instance-attribute

Default Transaction Parameter Block used to start transaction

info: TransactionInfoProvider3 | TransactionInfoProvider property

Access to various information about active transaction.

log_context: Connection property

Logging context [connection].

begin(tpb: bytes | None = None) -> None

Starts new transaction managed by this instance.

Parameters:

Name Type Description Default
tpb bytes | None

Transaction parameter buffer with transaction's parameters. If not specified, the .default_tpb is used.

None
Source code in firebird/driver/core.py
def begin(self, tpb: bytes | None=None) -> None:
    """Starts new transaction managed by this instance.

    Arguments:
        tpb: Transaction parameter buffer with transaction's parameters. If not specified,
             the `.default_tpb` is used.
    """
    self._finish()  # Make sure that previous transaction (if any) is ended
    self._tra = self._connection()._att.start_transaction(self.default_tpb if tpb is None
                                                          else tpb)

close() -> None

Close the transaction manager and release all associated resources.

Implicitly ends the current active transaction according to default_action (if active).

Important

Closed instance SHALL NOT be used anymore.

Source code in firebird/driver/core.py
def close(self) -> None:
    """Close the transaction manager and release all associated resources.

    Implicitly ends the current active transaction according to default_action (if active).

    Important:
        Closed instance SHALL NOT be used anymore.
    """
    if not self.__closed:
        try:
            self._finish()
        finally:
            con = self._connection()
            if con is not None and self in con._transactions:
                con._transactions.remove(self)
            self._connection = None
            self.__closed = True
            if self.__info is not None:
                self.__info._close()

commit(*, retaining: bool = False) -> None

Commits the transaction managed by this instance.

Parameters:

Name Type Description Default
retaining bool

When True, the transaction context is retained after commit.

False
Source code in firebird/driver/core.py
def commit(self, *, retaining: bool=False) -> None:
    """Commits the transaction managed by this instance.

    Arguments:
        retaining: When True, the transaction context is retained after commit.
    """
    if retaining:
        self._tra.commit_retaining()
    else:
        self._close_cursors()
        self._tra.commit()
    if not retaining:
        self._tra = None

cursor() -> Cursor

Returns new Cursor instance associated with this instance.

Source code in firebird/driver/core.py
def cursor(self) -> Cursor:
    """Returns new `Cursor` instance associated with this instance.
    """
    cur = Cursor(self._connection(), self)
    self._cursors.append(weakref.ref(cur, self._cursor_deleted))
    return cur

execute_immediate(sql: str) -> None

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

Parameters:

Name Type Description Default
sql str

SQL statement to be executed.

required
Source code in firebird/driver/core.py
def execute_immediate(self, sql: str) -> None:
    """Executes SQL statement. The statement MUST NOT return any result.

    Arguments:
       sql: SQL statement to be executed.
    """
    if not self.is_active():
        self.begin()
    self._connection()._att.execute(self._tra, sql, self._connection().sql_dialect)

is_active() -> bool

Returns True if transaction is active.

Source code in firebird/driver/core.py
def is_active(self) -> bool:
    """Returns True if transaction is active.
    """
    return self._tra is not None

is_closed() -> bool

Returns True if this transaction manager is closed.

Source code in firebird/driver/core.py
def is_closed(self) -> bool:
    """Returns True if this transaction manager is closed.
    """
    return self.__closed

rollback(*, retaining: bool = False, savepoint: str | None = None) -> None

Rolls back the transaction managed by this instance.

Parameters:

Name Type Description Default
retaining bool

When True, the transaction context is retained after rollback.

False
savepoint str | None

When specified, the transaction is rolled back to savepoint with given name.

None

Raises:

Type Description
InterfaceError

When both retaining and savepoint parameters are specified.

Source code in firebird/driver/core.py
def rollback(self, *, retaining: bool=False, savepoint: str | None=None) -> None:
    """Rolls back the transaction managed by this instance.

    Arguments:
        retaining: When True, the transaction context is retained after rollback.
        savepoint: When specified, the transaction is rolled back to savepoint with given name.

    Raises:
        InterfaceError: When both retaining and savepoint parameters are specified.
    """
    if retaining and savepoint:
        raise InterfaceError("Can't rollback to savepoint while retaining context")
    if savepoint:
        self.execute_immediate(f'rollback to {savepoint}')
    else:
        if retaining:
            self._tra.rollback_retaining()
        else:
            self._close_cursors()
            self._tra.rollback()
        if not retaining:
            self._tra = None

savepoint(name: str) -> None

Creates a new savepoint for transaction managed by this instance.

Parameters:

Name Type Description Default
name str

Name for the savepoint

required
Source code in firebird/driver/core.py
def savepoint(self, name: str) -> None:
    """Creates a new savepoint for transaction managed by this instance.

    Arguments:
        name: Name for the savepoint
    """
    self.execute_immediate(f'SAVEPOINT {name}')

firebird.driver.core.DistributedTransactionManager

Bases: TransactionManager

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

Note

Implements context manager protocol to call .close() automatically.

Source code in firebird/driver/core.py
class DistributedTransactionManager(TransactionManager):
    """Manages distributed transaction over multiple connections that use two-phase
    commit protocol.

    Note:
        Implements context manager protocol to call `.close()` automatically.
    """
    def __init__(self, connections: Sequence[Connection], default_tpb: bytes | None=None,
                 default_action: DefaultAction=DefaultAction.COMMIT):
        self._connections: list[Connection] = list(connections)
        self._lifecycles = tuple(con._lifecycle for con in self._connections)
        self.default_tpb: bytes = default_tpb if default_tpb is not None else tpb(Isolation.SNAPSHOT)
        self.default_action: DefaultAction = default_action
        self._cursors: list = []  # Weak references to cursors
        self._tra: iTransaction = None
        self._dtc: iDtc = _master.get_dtc()
        self.__closed: bool = False
    def close(self) -> None:
        """Close the distributed transaction manager and release all associated
        resources.

        Important:
            Closed instance SHALL NOT be used anymore.
        """
        if not self.__closed:
            try:
                self._finish()
            finally:
                self._connections.clear()
                self.__closed = True
    def execute_immediate(self, sql: str) -> None:
        """Executes SQL statement on all connections in distributed transaction.
        The statement MUST NOT return any result.

        Arguments:
           sql: SQL statement to be executed.
        """
        if not self.is_active():
            self.begin()
        for connection in self._connections:
            connection._att.execute(self._tra, sql, connection.sql_dialect)
    def begin(self, tpb: bytes | None=None) -> None:
        """Starts new distributed transaction managed by this instance.

        Arguments:
            tpb: Transaction parameter buffer with transaction's parameters. If not specified,
                 the `.default_tpb` is used.
        """
        self._finish()  # Make sure that previous transaction (if any) is ended
        with self._dtc.start_builder() as builder:
            for con in self._connections:
                builder.add_with_tpb(con._att, tpb or self.default_tpb)
            self._tra = builder.start()
    def prepare(self) -> None:
        """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.
        """
        self._tra.prepare()
    def commit(self, *, retaining: bool=False) -> None:
        """Commits the distributed transaction managed by this instance.

        Arguments:
            retaining: When True, the transaction context is retained after commit.
        """
        if retaining:
            self._tra.commit_retaining()
        else:
            self._close_cursors()
            self._tra.commit()
        if not retaining:
            self._tra = None
    def rollback(self, *, retaining: bool=False, savepoint: str | None=None) -> None:
        """Rolls back the distributed transaction managed by this instance.

        Arguments:
            retaining: When True, the transaction context is retained after rollback.
            savepoint: When specified, the transaction is rolled back to savepoint with given name.

        Raises:
            InterfaceError: When both retaining and savepoint parameters are specified.
        """
        if retaining and savepoint:
            raise InterfaceError("Can't rollback to savepoint while retaining context")
        if savepoint:
            self.execute_immediate(f'rollback to {savepoint}')
        else:
            if retaining:
                self._tra.rollback_retaining()
            else:
                self._close_cursors()
                self._tra.rollback()
            if not retaining:
                self._tra = None
    def savepoint(self, name: str) -> None:
        """Creates a new savepoint for distributed transaction managed by this instance.

        Arguments:
            name: Name for the savepoint
        """
        self.execute_immediate(f'SAVEPOINT {name}')
    def cursor(self, connection: Connection) -> Cursor:
        """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.
        """
        if connection not in self._connections:
            raise InterfaceError("Cannot create cursor for connection that does "
                                 "not belong to this distributed transaction")
        cur = Cursor(connection, self)
        self._cursors.append(weakref.ref(cur, self._cursor_deleted))
        return cur

    @property
    def log_context(self) -> Connection:
        return UNDEFINED

cursors: list[Cursor] property

Cursors associated with this transaction.

info: TransactionInfoProvider3 | TransactionInfoProvider property

Access to various information about active transaction.

begin(tpb: bytes | None = None) -> None

Starts new distributed transaction managed by this instance.

Parameters:

Name Type Description Default
tpb bytes | None

Transaction parameter buffer with transaction's parameters. If not specified, the .default_tpb is used.

None
Source code in firebird/driver/core.py
def begin(self, tpb: bytes | None=None) -> None:
    """Starts new distributed transaction managed by this instance.

    Arguments:
        tpb: Transaction parameter buffer with transaction's parameters. If not specified,
             the `.default_tpb` is used.
    """
    self._finish()  # Make sure that previous transaction (if any) is ended
    with self._dtc.start_builder() as builder:
        for con in self._connections:
            builder.add_with_tpb(con._att, tpb or self.default_tpb)
        self._tra = builder.start()

close() -> None

Close the distributed transaction manager and release all associated resources.

Important

Closed instance SHALL NOT be used anymore.

Source code in firebird/driver/core.py
def close(self) -> None:
    """Close the distributed transaction manager and release all associated
    resources.

    Important:
        Closed instance SHALL NOT be used anymore.
    """
    if not self.__closed:
        try:
            self._finish()
        finally:
            self._connections.clear()
            self.__closed = True

commit(*, retaining: bool = False) -> None

Commits the distributed transaction managed by this instance.

Parameters:

Name Type Description Default
retaining bool

When True, the transaction context is retained after commit.

False
Source code in firebird/driver/core.py
def commit(self, *, retaining: bool=False) -> None:
    """Commits the distributed transaction managed by this instance.

    Arguments:
        retaining: When True, the transaction context is retained after commit.
    """
    if retaining:
        self._tra.commit_retaining()
    else:
        self._close_cursors()
        self._tra.commit()
    if not retaining:
        self._tra = None

cursor(connection: Connection) -> Cursor

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

Raises:

Type Description
InterfaceError

When specified connection is not associated with distributed connection manager.

Source code in firebird/driver/core.py
def cursor(self, connection: Connection) -> Cursor:
    """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.
    """
    if connection not in self._connections:
        raise InterfaceError("Cannot create cursor for connection that does "
                             "not belong to this distributed transaction")
    cur = Cursor(connection, self)
    self._cursors.append(weakref.ref(cur, self._cursor_deleted))
    return cur

execute_immediate(sql: str) -> None

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

Parameters:

Name Type Description Default
sql str

SQL statement to be executed.

required
Source code in firebird/driver/core.py
def execute_immediate(self, sql: str) -> None:
    """Executes SQL statement on all connections in distributed transaction.
    The statement MUST NOT return any result.

    Arguments:
       sql: SQL statement to be executed.
    """
    if not self.is_active():
        self.begin()
    for connection in self._connections:
        connection._att.execute(self._tra, sql, connection.sql_dialect)

is_active() -> bool

Returns True if transaction is active.

Source code in firebird/driver/core.py
def is_active(self) -> bool:
    """Returns True if transaction is active.
    """
    return self._tra is not None

is_closed() -> bool

Returns True if this transaction manager is closed.

Source code in firebird/driver/core.py
def is_closed(self) -> bool:
    """Returns True if this transaction manager is closed.
    """
    return self.__closed

prepare() -> None

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.

Source code in firebird/driver/core.py
def prepare(self) -> None:
    """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.
    """
    self._tra.prepare()

rollback(*, retaining: bool = False, savepoint: str | None = None) -> None

Rolls back the distributed transaction managed by this instance.

Parameters:

Name Type Description Default
retaining bool

When True, the transaction context is retained after rollback.

False
savepoint str | None

When specified, the transaction is rolled back to savepoint with given name.

None

Raises:

Type Description
InterfaceError

When both retaining and savepoint parameters are specified.

Source code in firebird/driver/core.py
def rollback(self, *, retaining: bool=False, savepoint: str | None=None) -> None:
    """Rolls back the distributed transaction managed by this instance.

    Arguments:
        retaining: When True, the transaction context is retained after rollback.
        savepoint: When specified, the transaction is rolled back to savepoint with given name.

    Raises:
        InterfaceError: When both retaining and savepoint parameters are specified.
    """
    if retaining and savepoint:
        raise InterfaceError("Can't rollback to savepoint while retaining context")
    if savepoint:
        self.execute_immediate(f'rollback to {savepoint}')
    else:
        if retaining:
            self._tra.rollback_retaining()
        else:
            self._close_cursors()
            self._tra.rollback()
        if not retaining:
            self._tra = None

savepoint(name: str) -> None

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

Parameters:

Name Type Description Default
name str

Name for the savepoint

required
Source code in firebird/driver/core.py
def savepoint(self, name: str) -> None:
    """Creates a new savepoint for distributed transaction managed by this instance.

    Arguments:
        name: Name for the savepoint
    """
    self.execute_immediate(f'SAVEPOINT {name}')

firebird.driver.core.Statement

Prepared SQL statement.

Note

Implements context manager protocol to call .free() automatically.

Source code in firebird/driver/core.py
class Statement:
    """Prepared SQL statement.

    Note:
        Implements context manager protocol to call `.free()` automatically.
    """
    def __init__(self, connection: Connection, stmt: iStatement, sql: str, dialect: int):
        self._connection: Callable[[], Connection] = weakref.ref(connection, self.__dead_con)
        self._lifecycle = connection._lifecycle
        self._dialect: int = dialect
        self.__sql: str = sql
        self._istmt: iStatement = stmt
        self._type: StatementType = stmt.get_type()
        self._flags: StatementFlag = stmt.get_flags()
        self._desc: DESCRIPTION = None
        self.__info: StatementInfoProvider3 | StatementInfoProvider4 | StatementInfoProvider = None
        # Input metadata
        meta = stmt.get_input_metadata()
        self._in_cnt: int = meta.get_count()
        self._in_meta: iMessageMetadata = None
        self._in_buffer: bytes = None
        if self._in_cnt == 0:
            meta.release()
        else:
            self._in_meta = meta
            self._in_buffer = create_string_buffer(meta.get_message_length())
        # Output metadata
        meta = stmt.get_output_metadata()
        self._out_meta: iMessageMetadata = None
        self._out_cnt: int = meta.get_count()
        self._out_buffer: bytes = None
        self._out_desc: list[ItemMetadata] = None
        self._names: list[str] = None
        if self._out_cnt == 0:
            meta.release()
            self._out_desc = []
            self._names = []
        else:
            self._out_meta = meta
            self._out_buffer = create_string_buffer(meta.get_message_length())
            self._out_desc = create_meta_descriptors(meta)
            self._names = [m.field if m.field == m.alias else m.alias for m in self._out_desc]
    def __enter__(self) -> Self:
        return self
    def __exit__(self, exc_type, exc_value, traceback) -> None:
        self.free()
    def __del__(self):
        if getattr(getattr(self, '_lifecycle', None), 'is_dead', False):
            return
        if self._in_meta or self._out_meta or self._istmt:
            warn("Statement disposed without prior free()", ResourceWarning)
            self.free()
    def __dead_con(self, obj: Connection) -> None: # noqa: ARG002
        self._connection = None
    def __get_plan(self, *, detailed: bool) -> str:
        result = self._istmt.get_plan(detailed)
        return result if result is None else result.strip()
    def free(self) -> None:
        """Release the statement and all associated resources.

        Important:
            The statement SHALL NOT be used after call to this method.
        """
        if self._in_meta is not None:
            self._in_meta.release()
            self._in_meta = None
        if self._out_meta is not None:
            self._out_meta.release()
            self._out_meta = None
        if self._istmt is not None:
            self._istmt.free()
            self._istmt = None
    def has_cursor(self) -> bool:
        """Returns True if statement has cursor (can return multiple rows).
        """
        return StatementFlag.HAS_CURSOR in self._flags
    def can_repeat(self) -> bool:
        """Returns True if statement could be executed repeatedly.
        """
        return StatementFlag.REPEAT_EXECUTE in self._flags
    # Properties
    @property
    def log_context(self) -> Connection:
        "Logging context [Connection]"
        if self._connection is None:
            return 'Connection.GC'
        return self._connection()
    @property
    def info(self) -> StatementInfoProvider3 | StatementInfoProvider4 | StatementInfoProvider:
        """Access to various information about statement.
        """
        if self.__info is None:
            version = self._connection()._engine_version()
            if version >= 5.0:
                cls = StatementInfoProvider
            elif version >= 4.0:
                cls = StatementInfoProvider4
            else:
                cls = StatementInfoProvider3
            self.__info = cls(self._connection()._encoding, self)
        return self.__info
    @property
    def plan(self) -> str:
        """Execution plan in classic format.
        """
        return self.__get_plan(detailed=False)
    @property
    def detailed_plan(self) -> str:
        """Execution plan in new format (explained).
        """
        return self.__get_plan(detailed=True)
    @property
    def sql(self) -> str:
        """SQL statement.
        """
        return self.__sql
    @property
    def type(self) -> StatementType:
        """Statement type.
        """
        return self._type
    @property
    def timeout(self) -> int:
        """Statement timeout.
        """
        if self._connection()._engine_version() >= 4.0:
            return self._istmt.get_timeout()
        raise NotSupportedError(f"Statement timeout not supported by engine version {self._connection()._engine_version()}")
    @timeout.setter
    def _timeout(self, value: int) -> None:
        if self._connection()._engine_version() >= 4.0:
            return self._istmt.set_timeout(value)
        raise NotSupportedError(f"Statement timeout not supported by engine version {self._connection()._engine_version()}")

detailed_plan: str property

Execution plan in new format (explained).

info: StatementInfoProvider3 | StatementInfoProvider4 | StatementInfoProvider property

Access to various information about statement.

log_context: Connection property

Logging context [Connection]

plan: str property

Execution plan in classic format.

sql: str property

SQL statement.

timeout: int property

Statement timeout.

type: StatementType property

Statement type.

can_repeat() -> bool

Returns True if statement could be executed repeatedly.

Source code in firebird/driver/core.py
def can_repeat(self) -> bool:
    """Returns True if statement could be executed repeatedly.
    """
    return StatementFlag.REPEAT_EXECUTE in self._flags

free() -> None

Release the statement and all associated resources.

Important

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

Source code in firebird/driver/core.py
def free(self) -> None:
    """Release the statement and all associated resources.

    Important:
        The statement SHALL NOT be used after call to this method.
    """
    if self._in_meta is not None:
        self._in_meta.release()
        self._in_meta = None
    if self._out_meta is not None:
        self._out_meta.release()
        self._out_meta = None
    if self._istmt is not None:
        self._istmt.free()
        self._istmt = None

has_cursor() -> bool

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

Source code in firebird/driver/core.py
def has_cursor(self) -> bool:
    """Returns True if statement has cursor (can return multiple rows).
    """
    return StatementFlag.HAS_CURSOR in self._flags

firebird.driver.core.Cursor

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.

Source code in firebird/driver/core.py
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
class Cursor:
    """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.
    """
    arraysize: int = 1
    "This read/write attribute specifies the number of rows to fetch at a time with\n.fetchmany(). It defaults to 1 meaning to fetch a single row at a time.\n\nRequired by Python DB API 2.0"
    def __init__(self, connection: Connection, transaction: TransactionManager):
        self._connection: Connection = connection
        self._lifecycle = connection._lifecycle
        self._dialect: int = connection.sql_dialect
        self._transaction: TransactionManager = transaction
        self._stmt: Statement = None
        self._encoding: str = connection._encoding
        self._result: iResultSet = None
        self._last_fetch_status: StateResult = None
        self._name: str = None
        self._executed: bool = False
        self._cursor_flags: CursorFlag = CursorFlag.NONE
        self.__output_cache: tuple = None
        self.__internal: bool = False
        self.__blob_readers: set = weakref.WeakSet()
        self.stream_blobs: list[str] = []
        "Names of columns that should be returned as `BlobReader`."
        self.stream_blob_threshold = driver_config.stream_blob_threshold.value
        "BLOBs greater than threshold are returned as `BlobReader` instead of materialized values.\nSet to -1 to disable automatic streaming. Defaults to the value from `driver_config`."
    def __enter__(self) -> Self:
        return self
    def __exit__(self, exc_type, exc_value, traceback) -> None:
        self.close()
    def __del__(self):
        if getattr(getattr(self, '_lifecycle', None), 'is_dead', False):
            return
        if self._result is not None or self._stmt is not None or self.__blob_readers:
            warn("Cursor disposed without prior close()", ResourceWarning)
            self.close()
    def __next__(self):
        if (row := self.fetchone()) is not None:
            return row
        raise StopIteration
    def __iter__(self) -> Self:
        return self
    def _dead_con(self, obj: Connection) -> None: # noqa: ARG002
        self._connection = None
    def _extract_db_array_to_list(self, esize: int, dtype: int, subtype: int,
                                  scale: int, dim: int, dimensions: list[int],
                                  buf: Any, bufpos: int) -> tuple[Any, int]:
        value = []
        if dim == len(dimensions)-1:
            for _ in range(dimensions[dim]):
                if dtype in (a.blr_text, a.blr_text2):
                    val = string_at(buf[bufpos:bufpos+esize], esize)
                    if subtype != 1:   # non OCTETS
                        val = val.decode(self._encoding)
                    # CHAR with multibyte encoding requires special handling
                    if subtype in (4, 69):  # UTF8 and GB18030
                        reallength = esize // 4
                    elif subtype == 3:  # UNICODE_FSS
                        reallength = esize // 3
                    else:
                        reallength = esize
                    val = val[:reallength]
                elif dtype in (a.blr_varying, a.blr_varying2):
                    val = string_at(buf[bufpos:bufpos+esize])
                    if subtype != a.OCTETS:
                        val = val.decode(self._encoding)
                elif dtype in (a.blr_short, a.blr_long, a.blr_int64):
                    val = (0).from_bytes(buf[bufpos:bufpos + esize], 'little', signed=True)
                    if subtype or scale:
                        val = decimal.Decimal(val).scaleb(-abs(scale))
                elif dtype == a.blr_bool:
                    val = (0).from_bytes(buf[bufpos:bufpos + esize], 'little') == 1
                elif dtype == a.blr_float:
                    val = struct.unpack('f', buf[bufpos:bufpos+esize])[0]
                elif dtype in (a.blr_d_float, a.blr_double):
                    val = struct.unpack('d', buf[bufpos:bufpos+esize])[0]
                elif dtype == a.blr_timestamp:
                    val = datetime.datetime.combine(_util.decode_date(buf[bufpos:bufpos+4]),
                                                    _util.decode_time(buf[bufpos+4:bufpos+esize]))
                elif dtype == a.blr_sql_date:
                    val = _util.decode_date(buf[bufpos:bufpos+esize])
                elif dtype == a.blr_sql_time:
                    val = _util.decode_time(buf[bufpos:bufpos+esize])
                elif dtype == a.blr_sql_time_tz:
                    val = _util.decode_time_tz(buf[bufpos:bufpos+esize])
                elif dtype == a.blr_timestamp_tz:
                    val = _util.decode_timestamp_tz(buf[bufpos:bufpos+esize])
                elif dtype == a.blr_int128:
                    val = decimal.Decimal(_util.get_int128().to_str(a.FB_I128.from_buffer_copy(buf[bufpos:bufpos+esize]), scale))
                elif dtype == a.blr_dec64:
                    val = decimal.Decimal(_util.get_decfloat16().to_str(a.FB_DEC16.from_buffer_copy(buf[bufpos:bufpos+esize])))
                elif dtype == a.blr_dec128:
                    val = decimal.Decimal(_util.get_decfloat34().to_str(a.FB_DEC34.from_buffer_copy(buf[bufpos:bufpos+esize])))
                else:  # pragma: no cover
                    raise InterfaceError(f"Unsupported Firebird ARRAY subtype: {dtype}")
                value.append(val)
                bufpos += esize
        else:
            for _ in range(dimensions[dim]):
                (val, bufpos) = self._extract_db_array_to_list(esize, dtype, subtype,
                                                               scale, dim + 1,
                                                               dimensions,
                                                               buf, bufpos)
                value.append(val)
        return (value, bufpos)
    def _copy_list_to_db_array(self, esize: int, dtype: int, subtype: int,
                               scale: int, dim: int, dimensions: list[int],
                               value: Any, buf: Any, bufpos: int) -> None:
        valuebuf = None
        if dtype in (a.blr_text, a.blr_text2):
            valuebuf = create_string_buffer(bytes([0]), esize)
        elif dtype in (a.blr_varying, a.blr_varying2):
            valuebuf = create_string_buffer(bytes([0]), esize)
        elif dtype in (a.blr_short, a.blr_long, a.blr_int64):
            if esize == 2:
                valuebuf = a.ISC_SHORT(0)
            elif esize == 4:
                valuebuf = a.ISC_LONG(0)
            elif esize == 8:
                valuebuf = a.ISC_INT64(0)
            else:  # pragma: no cover
                raise InterfaceError("Unsupported number type")
        elif dtype == a.blr_float:
            valuebuf = create_string_buffer(bytes([0]), esize)
        elif dtype in (a.blr_d_float, a.blr_double):
            valuebuf = create_string_buffer(bytes([0]), esize)
        elif dtype == a.blr_timestamp:
            valuebuf = create_string_buffer(bytes([0]), esize)
        elif dtype == a.blr_sql_date:
            valuebuf = create_string_buffer(bytes([0]), esize)
        elif dtype == a.blr_sql_time:
            valuebuf = create_string_buffer(bytes([0]), esize)
        elif dtype == a.blr_bool:
            valuebuf = create_string_buffer(bytes([0]), esize)
        elif dtype in (a.blr_int128, a.blr_dec64, a.blr_dec128):
            valuebuf = create_string_buffer(bytes([0]), esize)
        elif dtype in (a.blr_sql_time_tz, a.blr_timestamp_tz):
            valuebuf = create_string_buffer(bytes([0]), esize)
        else:  # pragma: no cover
            raise InterfaceError(f"Unsupported Firebird ARRAY subtype: {dtype}")
        self._fill_db_array_buffer(esize, dtype,
                                   subtype, scale,
                                   dim, dimensions,
                                   value, valuebuf,
                                   buf, bufpos)
    def _fill_db_array_buffer(self, esize: int, dtype: int, subtype: int,
                              scale: int, dim: int, dimensions: list[int],
                              value: Any, valuebuf: Any, buf: Any, bufpos: int) -> int:
        if dim == len(dimensions)-1:
            for i in range(dimensions[dim]):
                if dtype in (a.blr_text, a.blr_text2,
                             a.blr_varying, a.blr_varying2):
                    val = value[i]
                    if isinstance(val, str):
                        val = val.encode(self._encoding)
                    if len(val) > esize:
                        raise ValueError(f"ARRAY value of parameter is too long,"
                                         f" expected {esize}, found {len(val)}")
                    valuebuf.value = val
                    memmove(byref(buf, bufpos), valuebuf, esize)
                elif dtype in (a.blr_short, a.blr_long, a.blr_int64):
                    if subtype or scale:
                        val = value[i]
                        if isinstance(val, decimal.Decimal):
                            val = int((val * _ten_to[abs(scale)]).to_integral())
                        elif isinstance(val, int | float):
                            val = int(val * _ten_to[abs(scale)])
                        else:
                            raise TypeError(f'Objects of type {type(val)} are not '
                                            f' acceptable input for'
                                            f' a fixed-point column.')
                        valuebuf.value = val
                    else: # noqa: PLR5501
                        if esize == 2:
                            valuebuf.value = value[i]
                        elif esize == 4:
                            valuebuf.value = value[i]
                        elif esize == 8:
                            valuebuf.value = value[i]
                        else:  # pragma: no cover
                            raise InterfaceError("Unsupported type")
                    memmove(byref(buf, bufpos),
                                   byref(valuebuf),
                                   esize)
                elif dtype == a.blr_bool:
                    valuebuf.value = (1 if value[i] else 0).to_bytes(1, 'little')
                    memmove(byref(buf, bufpos),
                                   byref(valuebuf),
                                   esize)
                elif dtype == a.blr_float:
                    valuebuf.value = struct.pack('f', value[i])
                    memmove(byref(buf, bufpos), valuebuf, esize)
                elif dtype in (a.blr_d_float, a.blr_double):
                    valuebuf.value = struct.pack('d', value[i])
                    memmove(byref(buf, bufpos), valuebuf, esize)
                elif dtype == a.blr_timestamp:
                    valuebuf.value = _encode_timestamp(value[i])
                    memmove(byref(buf, bufpos), valuebuf, esize)
                elif dtype == a.blr_sql_date:
                    valuebuf.value = _util.encode_date(value[i]).to_bytes(4, 'little')
                    memmove(byref(buf, bufpos), valuebuf, esize)
                elif dtype == a.blr_sql_time:
                    valuebuf.value = _util.encode_time(value[i]).to_bytes(4, 'little')
                    memmove(byref(buf, bufpos), valuebuf, esize)
                elif dtype == a.blr_sql_time_tz:
                    valuebuf.value = _util.encode_time_tz(value[i])
                    memmove(byref(buf, bufpos), valuebuf, esize)
                elif dtype == a.blr_timestamp_tz:
                    valuebuf.value = _util.encode_timestamp_tz(value[i])
                    memmove(byref(buf, bufpos), valuebuf, esize)
                elif dtype == a.blr_dec64:
                    memmove(byref(buf, bufpos), byref(_util.get_decfloat16().from_str(str(value[i]))), esize)
                elif dtype == a.blr_dec128:
                    memmove(byref(buf, bufpos), _util.get_decfloat34().from_str(str(value[i])), esize)
                elif dtype == a.blr_int128:
                    memmove(byref(buf, bufpos), _util.get_int128().from_str(str(value[i]), scale), esize)
                else:  # pragma: no cover
                    raise InterfaceError(f"Unsupported Firebird ARRAY subtype: {dtype}")
                bufpos += esize
        else:
            for i in range(dimensions[dim]):
                bufpos = self._fill_db_array_buffer(esize, dtype, subtype,
                                                    scale, dim+1,
                                                    dimensions, value[i],
                                                    valuebuf, buf, bufpos)
        return bufpos
    def _validate_array_value(self, dim: int, dimensions: list[int],
                              value_type: int, sqlsubtype: int,
                              value_scale: int, value: Any) -> bool:
        ok = isinstance(value, list | tuple)
        ok = ok and (len(value) == dimensions[dim])
        if not ok:
            return False
        for i in range(dimensions[dim]):
            if dim == len(dimensions) - 1:
                # leaf: check value type
                if value_type in (a.blr_text, a.blr_text2, a.blr_varying, a.blr_varying2):
                    ok = isinstance(value[i], str)
                elif value_type in (a.blr_short, a.blr_long, a.blr_int64, a.blr_int128):
                    if sqlsubtype or value_scale:
                        ok = isinstance(value[i], decimal.Decimal)
                    else:
                        ok = isinstance(value[i], int)
                elif value_type in (a.blr_dec64, a.blr_dec128):
                    ok = isinstance(value[i], decimal.Decimal)
                elif value_type == a.blr_float:
                    ok = isinstance(value[i], float)
                elif value_type in (a.blr_d_float, a.blr_double):
                    ok = isinstance(value[i], float)
                elif value_type in (a.blr_timestamp, a.blr_timestamp_tz):
                    ok = isinstance(value[i], datetime.datetime)
                elif value_type == a.blr_sql_date:
                    ok = isinstance(value[i], datetime.date)
                elif value_type in (a.blr_sql_time, a.blr_sql_time_tz):
                    ok = isinstance(value[i], datetime.time)
                elif value_type == a.blr_bool:
                    ok = isinstance(value[i], bool)
                else:
                    ok = False
            else:
                # non-leaf: recurse down
                ok = ok and self._validate_array_value(dim + 1, dimensions,
                                                       value_type, sqlsubtype,
                                                       value_scale, value[i])
            if not ok: # Fail early
                return False
        return ok
    def _pack_input(self, meta: iMessageMetadata, buffer: bytes,
                    parameters: Sequence) -> tuple[iMessageMetadata, bytes]:
        in_cnt = meta.get_count()
        if len(parameters) != in_cnt:
            raise InterfaceError(f"Statement parameter sequence contains"
                                 f" {len(parameters)} items,"
                                 f" but exactly {in_cnt} are required")
        #
        buf_size = len(buffer)
        memset(buffer, 0, buf_size)
        # Adjust metadata where needed
        with meta.get_builder() as builder:
            for i in range(in_cnt):
                value = parameters[i]
                if _is_str_param(value, meta.get_type(i)):
                    builder.set_type(i, SQLDataType.TEXT)
                    if not isinstance(value, str | bytes | bytearray):
                        value = str(value)
                    builder.set_length(i, len(value.encode(self._encoding)) if isinstance(value, str) else len(value))
            in_meta = builder.get_metadata()
            new_size = in_meta.get_message_length()
            in_buffer = create_string_buffer(new_size) if buf_size < new_size else buffer
        buf_addr = addressof(in_buffer)
        with in_meta:
            for i in range(in_cnt):
                value = parameters[i]
                datatype = in_meta.get_type(i)
                length = in_meta.get_length(i)
                offset = in_meta.get_offset(i)
                # handle NULL value
                in_buffer[in_meta.get_null_offset(i)] = 1 if value is None else 0
                if value is None:
                    continue
                # store parameter value
                if _is_str_param(value, datatype):
                    # Implicit conversion to string
                    if not isinstance(value, str | bytes | bytearray):
                        value = str(value)
                    if isinstance(value, str) and self._encoding:
                        value = value.encode(self._encoding)
                    if (datatype in (SQLDataType.TEXT, SQLDataType.VARYING)
                        and len(value) > length):
                        raise ValueError(f"Value of parameter ({i}) is too long,"
                                         f" expected {length}, found {len(value)}")
                    memmove(buf_addr + offset, value, len(value))
                elif datatype in (SQLDataType.SHORT, SQLDataType.LONG, SQLDataType.INT64):
                    # It's scalled integer?
                    scale = in_meta.get_scale(i)
                    if in_meta.get_subtype(i) or scale:
                        if isinstance(value, decimal.Decimal):
                            value = int((value * _ten_to[abs(scale)]).to_integral())
                        elif isinstance(value, int | float):
                            value = int(value * _ten_to[abs(scale)])
                        else:
                            raise TypeError(f'Objects of type {type(value)} are not '
                                            f' acceptable input for'
                                            f' a fixed-point column.')
                    _check_integer_range(value, self._dialect, datatype,
                                         in_meta.get_subtype(i), scale)
                    memmove(buf_addr + offset, value.to_bytes(length, 'little', signed=True), length)
                elif datatype == SQLDataType.DATE:
                    memmove(buf_addr + offset, _util.encode_date(value).to_bytes(length, 'little', signed=True), length)
                elif datatype == SQLDataType.TIME:
                    memmove(buf_addr + offset, _util.encode_time(value).to_bytes(length, 'little'), length)
                elif datatype == SQLDataType.TIME_TZ:
                    memmove(buf_addr + offset, _util.encode_time_tz(value), length)
                elif datatype == SQLDataType.TIMESTAMP:
                    memmove(buf_addr + offset, _encode_timestamp(value), length)
                elif datatype == SQLDataType.TIMESTAMP_TZ:
                    memmove(buf_addr + offset, _util.encode_timestamp_tz(value), length)
                elif datatype == SQLDataType.DEC16:
                    memmove(buf_addr + offset, byref(_util.get_decfloat16().from_str(str(value))), length)
                elif datatype == SQLDataType.DEC34:
                    memmove(buf_addr + offset, _util.get_decfloat34().from_str(str(value)), length)
                elif datatype == SQLDataType.INT128:
                    memmove(buf_addr + offset, _util.get_int128().from_str(str(value), in_meta.get_scale(i)), length)
                elif datatype == SQLDataType.FLOAT:
                    memmove(buf_addr + offset, struct.pack('f', value), length)
                elif datatype == SQLDataType.DOUBLE:
                    memmove(buf_addr + offset, struct.pack('d', value), length)
                elif datatype == SQLDataType.BOOLEAN:
                    memmove(buf_addr + offset, (1 if value else 0).to_bytes(length, 'little'), length)
                elif datatype == SQLDataType.BLOB:
                    blobid = a.ISC_QUAD(0, 0)
                    if hasattr(value, 'read'):
                        # It seems we've got file-like object, use stream BLOB
                        blob_buf = _create_blob_buffer()
                        blob: iBlob = self._connection._att.create_blob(self._transaction._tra,
                                                                        blobid, _bpb_stream)
                        try:
                            memmove(buf_addr + offset, addressof(blobid), length)
                            while value_chunk := value.read(MAX_BLOB_SEGMENT_SIZE):
                                blob_buf.raw = value_chunk.encode(self._encoding) if isinstance(value_chunk, str) else value_chunk
                                blob.put_segment(len(value_chunk), blob_buf)
                                memset(blob_buf, 0, MAX_BLOB_SEGMENT_SIZE)
                        finally:
                            blob.close()
                            del blob_buf
                    else:
                        # Non-stream BLOB
                        if isinstance(value, str):
                            if in_meta.get_subtype(i) == 1:
                                value = value.encode(self._encoding)
                            else:
                                raise TypeError('String value is not'
                                                ' acceptable type for'
                                                ' a non-textual BLOB column.')
                        blob_buf = create_string_buffer(value)
                        blob: iBlob = self._connection._att.create_blob(self._transaction._tra,
                                                                        blobid)
                        try:
                            memmove(buf_addr + offset, addressof(blobid), length)
                            total_size = len(value)
                            bytes_written_so_far = 0
                            bytes_to_write_this_time = MAX_BLOB_SEGMENT_SIZE
                            while bytes_written_so_far < total_size:
                                if (total_size - bytes_written_so_far) < MAX_BLOB_SEGMENT_SIZE:
                                    bytes_to_write_this_time = (total_size - bytes_written_so_far)
                                blob.put_segment(bytes_to_write_this_time,
                                                 addressof(blob_buf) + bytes_written_so_far)
                                bytes_written_so_far += bytes_to_write_this_time
                        finally:
                            blob.close()
                            del blob_buf
                elif datatype == SQLDataType.ARRAY:
                    arrayid = a.ISC_QUAD(0, 0)
                    arrayid_ptr = pointer(arrayid)
                    arraydesc = a.ISC_ARRAY_DESC(0)
                    isc_status = a.ISC_STATUS_ARRAY()
                    db_handle = self._connection._get_handle()
                    tr_handle = self._transaction._get_handle()
                    relname = in_meta.get_relation(i).encode(self._encoding)
                    sqlname = in_meta.get_field(i).encode(self._encoding)
                    api = a.get_api()
                    sqlsubtype = self._connection._get_array_sqlsubtype(relname, sqlname)
                    api.isc_array_lookup_bounds(isc_status, db_handle, tr_handle,
                                                relname, sqlname, arraydesc)
                    if a.db_api_error(isc_status):  # pragma: no cover
                        raise a.exception_from_status(DatabaseError,
                                                      isc_status,
                                                      "Error in Cursor._pack_input:isc_array_lookup_bounds()")
                    value_type = arraydesc.array_desc_dtype
                    value_scale = arraydesc.array_desc_scale
                    value_size = arraydesc.array_desc_length
                    if value_type in (a.blr_varying, a.blr_varying2):
                        value_size += 2
                    dimensions = []
                    total_num_elements = 1
                    for dimension in range(arraydesc.array_desc_dimensions):
                        bounds = arraydesc.array_desc_bounds[dimension]
                        dimensions.append((bounds.array_bound_upper + 1) - bounds.array_bound_lower)
                        total_num_elements *= dimensions[dimension]
                    total_size = total_num_elements * value_size
                    # Validate value to make sure it matches the array structure
                    if not self._validate_array_value(0, dimensions, value_type,
                                                      sqlsubtype, value_scale, value):
                        raise ValueError("Incorrect ARRAY field value.")
                    value_buffer = create_string_buffer(total_size)
                    tsize = a.ISC_LONG(total_size)
                    self._copy_list_to_db_array(value_size, value_type,
                                                sqlsubtype, value_scale,
                                                0, dimensions,
                                                value, value_buffer, 0)
                    api.isc_array_put_slice(isc_status, db_handle, tr_handle,
                                            arrayid_ptr, arraydesc,
                                            value_buffer, tsize)
                    if a.db_api_error(isc_status):  # pragma: no cover
                        raise a.exception_from_status(DatabaseError,
                                                      isc_status,
                                                      "Error in Cursor._pack_input:/isc_array_put_slice()")
                    memmove(buf_addr + offset, addressof(arrayid), length)
            #
            in_meta.add_ref() # Everything went just fine, so we keep the metadata past 'with'
        return (in_meta, in_buffer)
    def _unpack_output(self) -> tuple:
        values = []
        buffer = self._stmt._out_buffer
        buf_addr = addressof(buffer)
        for desc in self._stmt._out_desc:
            value: Any = '<NOT_IMPLEMENTED>'
            if ord(buffer[desc.null_offset]) != 0:
                value = None
            else:
                datatype = desc.datatype
                offset = desc.offset
                length = desc.length
                if datatype == SQLDataType.TEXT:
                    value = string_at(buf_addr + offset, length)
                    if desc.charset != a.OCTETS:
                        value = value.decode(self._encoding)
                    # CHAR with multibyte encoding requires special handling
                    if desc.charset in (4, 69):  # UTF8 and GB18030
                        reallength = length // 4
                    elif desc.charset == 3:  # UNICODE_FSS
                        reallength = length // 3
                    else:
                        reallength = length
                    value = value[:reallength]
                elif datatype == SQLDataType.VARYING:
                    size = (0).from_bytes(string_at(buf_addr + offset, 2), 'little')
                    value = string_at(buf_addr + offset + 2, size)
                    if desc.charset != 1:
                        value = value.decode(self._encoding)
                elif datatype == SQLDataType.BOOLEAN:
                    value = bool((0).from_bytes(buffer[offset], 'little'))
                elif datatype in (SQLDataType.SHORT, SQLDataType.LONG, SQLDataType.INT64):
                    value = (0).from_bytes(buffer[offset:offset + length], 'little', signed=True)
                    # It's scalled integer?
                    if desc.subtype or desc.scale:
                        value = decimal.Decimal(value).scaleb(-abs(desc.scale))
                elif datatype == SQLDataType.DATE:
                    value = _util.decode_date(buffer[offset:offset+length])
                elif datatype == SQLDataType.TIME:
                    value = _util.decode_time(buffer[offset:offset+length])
                elif datatype == SQLDataType.TIME_TZ:
                    value = _util.decode_time_tz(buffer[offset:offset+length])
                elif datatype == SQLDataType.TIMESTAMP:
                    value = datetime.datetime.combine(_util.decode_date(buffer[offset:offset+4]),
                                                      _util.decode_time(buffer[offset+4:offset+length]))
                elif datatype == SQLDataType.TIMESTAMP_TZ:
                    value = _util.decode_timestamp_tz(buffer[offset:offset+length])
                elif datatype == SQLDataType.INT128:
                    value = decimal.Decimal(_util.get_int128().to_str(a.FB_I128.from_buffer_copy(buffer[offset:offset+length]), desc.scale))
                elif datatype == SQLDataType.DEC16:
                    value = decimal.Decimal(_util.get_decfloat16().to_str(a.FB_DEC16.from_buffer_copy(buffer[offset:offset+length])))
                elif datatype == SQLDataType.DEC34:
                    value = decimal.Decimal(_util.get_decfloat34().to_str(a.FB_DEC34.from_buffer_copy(buffer[offset:offset+length])))
                elif datatype == SQLDataType.FLOAT:
                    value = struct.unpack('f', buffer[offset:offset+length])[0]
                elif datatype == SQLDataType.DOUBLE:
                    value = struct.unpack('d', buffer[offset:offset+length])[0]
                elif datatype == SQLDataType.BLOB:
                    val = buffer[offset:offset+length]
                    blobid = a.ISC_QUAD((0).from_bytes(val[:4], 'little'),
                                        (0).from_bytes(val[4:], 'little'))
                    blob = self._connection._att.open_blob(self._transaction._tra, blobid)
                    # Get BLOB total length and max. size of segment
                    blob_length = blob.get_info2(BlobInfoCode.TOTAL_LENGTH)
                    segment_size = blob.get_info2(BlobInfoCode.MAX_SEGMENT)
                    # Check if stream BLOB is requested instead materialized one
                    if ((self.stream_blobs and (desc.alias if desc.alias != desc.field else desc.field) in self.stream_blobs)
                        or (self.stream_blob_threshold != -1 and blob_length > self.stream_blob_threshold)):
                        # Stream BLOB
                        value = BlobReader(blob, blobid, desc.subtype, blob_length,
                                           segment_size, self._encoding, self)
                        self.__blob_readers.add(value)
                    else:
                        # Materialized BLOB
                        try:
                            # Load BLOB
                            blob_value = create_string_buffer(blob_length)
                            bytes_read = 0
                            bytes_actually_read = a.Cardinal(0)
                            while bytes_read < blob_length:
                                blob.get_segment(min(segment_size, blob_length - bytes_read),
                                                 byref(blob_value, bytes_read),
                                                 bytes_actually_read)
                                bytes_read += bytes_actually_read.value
                            # Finalize value
                            value = blob_value.raw
                            if desc.subtype == 1:
                                value = value.decode(self._encoding)
                        finally:
                            blob.close()
                            del blob_value
                elif datatype == SQLDataType.ARRAY:
                    value = []
                    val = buffer[offset:offset+length]
                    arrayid = a.ISC_QUAD((0).from_bytes(val[:4], 'little'),
                                         (0).from_bytes(val[4:], 'little'))
                    arraydesc = a.ISC_ARRAY_DESC(0)
                    isc_status = a.ISC_STATUS_ARRAY()
                    db_handle = self._connection._get_handle()
                    tr_handle = self._transaction._get_handle()
                    relname = desc.relation.encode(self._encoding)
                    sqlname = desc.field.encode(self._encoding)
                    api = a.get_api()
                    sqlsubtype = self._connection._get_array_sqlsubtype(relname, sqlname)
                    api.isc_array_lookup_bounds(isc_status, db_handle, tr_handle,
                                                relname, sqlname, arraydesc)
                    if a.db_api_error(isc_status):  # pragma: no cover
                        raise a.exception_from_status(DatabaseError,
                                                      isc_status,
                                                      "Error in Cursor._unpack_output:isc_array_lookup_bounds()")
                    value_type = arraydesc.array_desc_dtype
                    value_scale = arraydesc.array_desc_scale
                    value_size = arraydesc.array_desc_length
                    if value_type in (a.blr_varying, a.blr_varying2):
                        value_size += 2
                    dimensions = []
                    total_num_elements = 1
                    for dimension in range(arraydesc.array_desc_dimensions):
                        bounds = arraydesc.array_desc_bounds[dimension]
                        dimensions.append((bounds.array_bound_upper + 1) - bounds.array_bound_lower)
                        total_num_elements *= dimensions[dimension]
                    total_size = total_num_elements * value_size
                    value_buffer = create_string_buffer(total_size)
                    tsize = a.ISC_LONG(total_size)
                    api.isc_array_get_slice(isc_status, db_handle, tr_handle,
                                            arrayid, arraydesc,
                                            value_buffer, tsize)
                    if a.db_api_error(isc_status):  # pragma: no cover
                        raise a.exception_from_status(DatabaseError,
                                                      isc_status,
                                                      "Error in Cursor._unpack_output:isc_array_get_slice()")
                    (value, _) = self._extract_db_array_to_list(value_size,
                                                                     value_type,
                                                                     sqlsubtype,
                                                                     value_scale,
                                                                     0, dimensions,
                                                                     value_buffer, 0)
            values.append(value)
        return tuple(values)
    def _fetchone(self) -> tuple | None:
        if self._executed:
            if self._stmt._out_cnt == 0:
                return None
            if self._last_fetch_status == StateResult.NO_DATA:
                return None
            if self.__output_cache is not None:
                result = self.__output_cache
                self._last_fetch_status = StateResult.NO_DATA
                self.__output_cache = None
                return result
            self._last_fetch_status = self._result.fetch_next(self._stmt._out_buffer)
            if self._last_fetch_status == StateResult.OK:
                return self._unpack_output()
            return None
        raise InterfaceError("Cannot fetch from cursor that did not executed a statement.")
    def _execute(self, operation: str | Statement,
                 parameters: Sequence | None=None, flags: CursorFlag=CursorFlag.NONE) -> None:
        if not self._transaction.is_active():
            self._transaction.begin()
        if isinstance(operation, Statement):
            if operation._connection() is not self._connection:
                raise InterfaceError('Cannot execute Statement that was created by different Connection.')
            self.close()
            self._stmt = operation
            self.__internal = False
        elif self._stmt is not None and self._stmt.sql == operation:
            # We should execute the same SQL string again
            self._clear()
        else:
            self.close()
            self._stmt = self._connection._prepare(operation, self._transaction)
            self.__internal = True
        self._cursor_flags = flags
        in_meta = None
        # Execute the statement
        try:
            if self._stmt._in_cnt > 0:
                in_meta, self._stmt._in_buffer = self._pack_input(self._stmt._in_meta,
                                                                  self._stmt._in_buffer,
                                                                  parameters)
            if self._stmt.has_cursor():
                # Statement returns multiple rows
                self._result = self._stmt._istmt.open_cursor(self._transaction._tra,
                                                            in_meta, self._stmt._in_buffer,
                                                            self._stmt._out_meta,
                                                            flags)
            else:
                # Statement may return single row
                self._stmt._istmt.execute(self._transaction._tra, in_meta,
                                         self._stmt._in_buffer,
                                         self._stmt._out_meta, self._stmt._out_buffer)
                if self._stmt._out_buffer is not None:
                    self.__output_cache = self._unpack_output()
            self._executed = True
            self._last_fetch_status = None
        finally:
            if in_meta is not None:
                in_meta.release()
    def _clear(self) -> None:
        if self._result is not None:
            if self._stmt is not None and self._stmt._istmt is not None:
                self._result.close()
            else:
                # Statement was already freed; the result set is invalidated
                # at the Firebird API level, so we must not call close() on it.
                # Also prevent __del__ from calling release() on the invalid interface.
                self._result._refcnt = 0
            self._result = None
        self._name = None
        self._last_fetch_status = None
        self._executed = False
        self.__output_cache = None
        while self.__blob_readers:
            self.__blob_readers.pop().close()
    def callproc(self, proc_name: str, parameters: Sequence | None=None) -> None:
        """Executes a stored procedure with the given name.

        Arguments:
            proc_name: Stored procedure name.
            parameters: 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.
        """
        params = [] if parameters is None else parameters
        sql = ('EXECUTE PROCEDURE ' + proc_name + ' '
               + ','.join('?' * len(params)))
        self.execute(sql, params)
    def call_procedure(self, proc_name: str, parameters: Sequence | None=None) -> tuple | None:
        """Executes a stored procedure with the given name.

        Arguments:
            proc_name: Stored procedure name.
            parameters: Sequence of parameters. Must contain one entry for each argument
                        that the procedure expects.

        Returns:
            None or tuple with values returned by stored procedure.
        """
        self.callproc(proc_name, parameters)
        return self.fetchone() if self._stmt._out_cnt > 0 else None
    def set_cursor_name(self, name: str) -> None:
        """Sets name for the SQL cursor.

        Arguments:
            name: Cursor name.
        """
        if not self._executed:
            raise InterfaceError("Cannot set name for cursor has not yet "
                                 "executed a statement")
        if self._name:
            raise InterfaceError("Cursor's name has already been declared in"
                                 " context of currently executed statement")
        self._stmt._istmt.set_cursor_name(name)
        self._name = name
    def prepare(self, operation: str) -> Statement:
        """Creates prepared statement for repeated execution.

        Arguments:
            operation: SQL command.
        """
        return self._connection._prepare(operation, self._transaction)
    def open(self, operation: str | Statement, parameters: Sequence[Any] | None=None) -> Cursor:
        """Executes SQL command or prepared `Statement` as scrollable.

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

        Arguments:
            operation: SQL command or prepared `Statement`.
            parameters: Sequence of parameters. Must contain one entry for each argument
                        that the operation expects.

        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.
        """
        self._execute(operation, parameters, CursorFlag.SCROLLABLE)
    def execute(self, operation: str | Statement, parameters: Sequence[Any] | None=None) -> Cursor:
        """Executes SQL command or prepared `Statement`.

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

        Arguments:
            operation: SQL command or prepared `Statement`.
            parameters: Sequence of parameters. Must contain one entry for each argument
                        that the operation expects.

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

        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.
        """
        self._execute(operation, parameters)
        return self
    def executemany(self, operation: str | Statement,
                    seq_of_parameters: Sequence[Sequence[Any]]) -> None:
        """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.

        Arguments:
            operation: SQL command or prepared `Statement`.
            seq_of_parameters: 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 effective as direct use of prepared `Statement`
            and calling `execute` in a loop directly in application.
        """
        for parameters in seq_of_parameters:
            self.execute(operation, parameters)
    def close(self) -> None:
        """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.
        """
        self._clear()
        if self._stmt is not None:
            if self.__internal:
                self._stmt.free()
            self._stmt = None
    def fetchone(self) -> tuple:
        """Fetch the next row of a query result set.
        """
        if self._stmt:
            return self._fetchone()
        raise InterfaceError("Cannot fetch from cursor that did not executed a statement.")
    def fetchmany(self, size: int | None=None) -> list[tuple]:
        """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.

        Arguments:
            size: The number of rows to fetch.
        """
        if size is None:
            size = self.arraysize
        result = []
        for _ in range(size):
            if (row := self.fetchone()) is not None:
                result.append(row)
            else:
                break
        return result
    def fetchall(self) -> list[tuple]:
        """Fetch all remaining rows of a query result set.
        """
        return list(self)
    def fetch_next(self) -> tuple | None:
        """Fetch the next row of a scrollable query result set.

        Returns None if there is no row to be fetched.
        """
        self._last_fetch_status = self._result.fetch_next(self._stmt._out_buffer)
        if self._last_fetch_status == StateResult.OK:
            return self._unpack_output()
        return None
    def fetch_prior(self) -> tuple | None:
        """Fetch the previous row of a scrollable query result set.

        Returns None if there is no row to be fetched.
        """
        self._last_fetch_status = self._result.fetch_prior(self._stmt._out_buffer)
        if self._last_fetch_status == StateResult.OK:
            return self._unpack_output()
        return None
    def fetch_first(self) -> tuple | None:
        """Fetch the first row of a scrollable query result set.

        Returns None if there is no row to be fetched.
        """
        self._last_fetch_status = self._result.fetch_first(self._stmt._out_buffer)
        if self._last_fetch_status == StateResult.OK:
            return self._unpack_output()
        return None
    def fetch_last(self) -> tuple | None:
        """Fetch the last row of a scrollable query result set.

        Returns None if there is no row to be fetched.
        """
        self._last_fetch_status = self._result.fetch_last(self._stmt._out_buffer)
        if self._last_fetch_status == StateResult.OK:
            return self._unpack_output()
        return None
    def fetch_absolute(self, position: int) -> tuple | None:
        """Fetch the row of a scrollable query result set specified by absolute position.

        Returns None if there is no row to be fetched.

        Arguments:
            position: Absolute position number of row in result set.
        """
        self._last_fetch_status = self._result.fetch_absolute(position, self._stmt._out_buffer)
        if self._last_fetch_status == StateResult.OK:
            return self._unpack_output()
        return None
    def fetch_relative(self, offset: int) -> tuple | None:
        """Fetch the row of a scrollable query result set specified by relative position.

        Returns None if there is no row to be fetched.

        Arguments:
            offset: Relative position number of row in result set. Negative value refers
                    to previous row, positive to next row.
        """
        self._last_fetch_status = self._result.fetch_relative(offset, self._stmt._out_buffer)
        if self._last_fetch_status == StateResult.OK:
            return self._unpack_output()
        return None
    def setinputsizes(self, sizes: Sequence[type]) -> None:
        """Required by Python DB API 2.0, but pointless for Firebird, so it does nothing.
        """
    def setoutputsize(self, size: int, column: int | None=None) -> None:
        """Required by Python DB API 2.0, but pointless for Firebird, so it does nothing.
        """
    def is_closed(self) -> bool:
        """Returns True if cursor is closed.
        """
        return self._stmt is None
    def is_eof(self) -> bool:
        """Returns True is scrollable cursor is positioned at the end.
        """
        return self._result.is_eof()
    def is_bof(self) -> bool:
        """Returns True is scrollable cursor is positioned at the beginning.
        """
        return self._result.is_bof()
    def to_dict(self, row: tuple, into: dict | None=None) -> dict:
        """Returns row tuple as dictionary with field names as keys. Returns new dictionary
        if `into` argument is not provided, otherwise returns `into` dictionary updated
        with row data.

        Arguments:
            row:  Row data returned by fetch_* method.
            into: Dictionary that should be updated with row data.
        """
        if into is None:
            into = dict(zip(self._stmt._names, row, strict=True))
        else:
            into.update(zip(self._stmt._names, row, strict=True))
        return into
    # Properties
    @property
    def connection(self) -> Connection:
        """Connection associated with cursor.
        """
        return self._connection
    @property
    def log_context(self) -> Connection:
        "Logging context [Connection"
        return self._connection
    @property
    def statement(self) -> Statement:
        """Executed `Statement` or None if cursor does not executed a statement yet.
        """
        return self._stmt
    @property
    def description(self) -> tuple[DESCRIPTION]:
        """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)
        """
        if self._stmt is None:
            return None
        if self._stmt._desc is None:
            desc = []
            for meta in self._stmt._out_desc:
                scale = meta.scale
                precision = 0
                if meta.datatype in (SQLDataType.TEXT, SQLDataType.VARYING):
                    vtype = str
                    if meta.subtype in (4, 69):  # UTF8 and GB18030
                        dispsize = meta.length // 4
                    elif meta.subtype == 3:  # UNICODE_FSS
                        dispsize = meta.length // 3
                    else:
                        dispsize = meta.length
                elif (meta.datatype in (SQLDataType.SHORT, SQLDataType.LONG, SQLDataType.INT64)
                      and (meta.subtype or meta.scale)):
                    vtype = decimal.Decimal
                    precision = self._connection._determine_field_precision(meta)
                    dispsize = 20
                elif meta.datatype == SQLDataType.SHORT:
                    vtype = int
                    dispsize = 6
                elif meta.datatype == SQLDataType.LONG:
                    vtype = int
                    dispsize = 11
                elif meta.datatype == SQLDataType.INT64:
                    vtype = int
                    dispsize = 20
                elif meta.datatype in (SQLDataType.FLOAT, SQLDataType.D_FLOAT, SQLDataType.DOUBLE,
                                       SQLDataType.DEC16, SQLDataType.DEC34):
                    # Special case, dialect 1 DOUBLE/FLOAT
                    # could be Fixed point
                    if (self._stmt._dialect < 3) and meta.scale:
                        vtype = decimal.Decimal
                        precision = self._connection._determine_field_precision(meta)
                    else:
                        vtype = float
                    dispsize = 17
                elif meta.datatype == SQLDataType.BLOB:
                    vtype = str if meta.subtype == 1 else bytes
                    scale = meta.subtype
                    dispsize = 0
                elif meta.datatype in (SQLDataType.TIMESTAMP, SQLDataType.TIMESTAMP_TZ, SQLDataType.TIMESTAMP_TZ_EX):
                    vtype = datetime.datetime
                    dispsize = 22
                elif meta.datatype == SQLDataType.DATE:
                    vtype = datetime.date
                    dispsize = 10
                elif meta.datatype in (SQLDataType.TIME, SQLDataType.TIME_TZ, SQLDataType.TIME_TZ_EX):
                    vtype = datetime.time
                    dispsize = 11
                elif meta.datatype == SQLDataType.ARRAY:
                    vtype = list
                    dispsize = -1
                elif meta.datatype == SQLDataType.BOOLEAN:
                    vtype = bool
                    dispsize = 5
                else:
                    vtype = None
                    dispsize = -1
                desc.append((meta.field if meta.field == meta.alias else meta.alias,
                             vtype, dispsize, meta.length, precision,
                             scale, meta.nullable))
            self._stmt._desc = tuple(desc) if desc else None
        return self._stmt._desc
    @property
    def affected_rows(self) -> 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.
        """
        if self._stmt is None:
            return -1
        rows: dict[ReqInfoCode, int] = self._stmt.info.get_info(StmtInfoCode.RECORDS)
        code: ReqInfoCode = None
        if self._stmt.type in (StatementType.SELECT, StatementType.SELECT_FOR_UPD):
            code = ReqInfoCode.SELECT_COUNT
        elif self._stmt.type == StatementType.UPDATE:
            code = ReqInfoCode.UPDATE_COUNT
        elif self._stmt.type == StatementType.INSERT:
            code = ReqInfoCode.INSERT_COUNT
        elif self._stmt.type == StatementType.DELETE:
            code = ReqInfoCode.DELETE_COUNT
        else:
            return -1
        return rows[code]
    rowcount = affected_rows
    @property
    def transaction(self) -> TransactionManager:
        """Transaction manager associated with cursor.
        """
        return self._transaction
    @property
    def name(self) -> str:
        """Name set for cursor.
        """
        return self._name

affected_rows: int property

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

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

Note

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

arraysize: int class-attribute instance-attribute

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

connection: Connection property

Connection associated with cursor.

description: tuple[DESCRIPTION] property

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)

log_context: Connection property

Logging context [Connection

name: str property

Name set for cursor.

statement: Statement property

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

stream_blob_threshold instance-attribute

BLOBs greater than threshold are returned as BlobReader instead of materialized values. Set to -1 to disable automatic streaming. Defaults to the value from driver_config.

stream_blobs: list[str] instance-attribute

Names of columns that should be returned as BlobReader.

transaction: TransactionManager property

Transaction manager associated with cursor.

call_procedure(proc_name: str, parameters: Sequence | None = None) -> tuple | None

Executes a stored procedure with the given name.

Parameters:

Name Type Description Default
proc_name str

Stored procedure name.

required
parameters Sequence | None

Sequence of parameters. Must contain one entry for each argument that the procedure expects.

None

Returns:

Type Description
tuple | None

None or tuple with values returned by stored procedure.

Source code in firebird/driver/core.py
def call_procedure(self, proc_name: str, parameters: Sequence | None=None) -> tuple | None:
    """Executes a stored procedure with the given name.

    Arguments:
        proc_name: Stored procedure name.
        parameters: Sequence of parameters. Must contain one entry for each argument
                    that the procedure expects.

    Returns:
        None or tuple with values returned by stored procedure.
    """
    self.callproc(proc_name, parameters)
    return self.fetchone() if self._stmt._out_cnt > 0 else None

callproc(proc_name: str, parameters: Sequence | None = None) -> None

Executes a stored procedure with the given name.

Parameters:

Name Type Description Default
proc_name str

Stored procedure name.

required
parameters Sequence | None

Sequence of parameters. Must contain one entry for each argument that the procedure expects.

None
Note

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

Source code in firebird/driver/core.py
def callproc(self, proc_name: str, parameters: Sequence | None=None) -> None:
    """Executes a stored procedure with the given name.

    Arguments:
        proc_name: Stored procedure name.
        parameters: 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.
    """
    params = [] if parameters is None else parameters
    sql = ('EXECUTE PROCEDURE ' + proc_name + ' '
           + ','.join('?' * len(params)))
    self.execute(sql, params)

close() -> None

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.

Source code in firebird/driver/core.py
def close(self) -> None:
    """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.
    """
    self._clear()
    if self._stmt is not None:
        if self.__internal:
            self._stmt.free()
        self._stmt = None

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

Executes SQL command or prepared Statement.

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

Parameters:

Name Type Description Default
operation str | Statement

SQL command or prepared Statement.

required
parameters Sequence[Any] | None

Sequence of parameters. Must contain one entry for each argument that the operation expects.

None

Returns:

Type Description
Cursor

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.

Source code in firebird/driver/core.py
def execute(self, operation: str | Statement, parameters: Sequence[Any] | None=None) -> Cursor:
    """Executes SQL command or prepared `Statement`.

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

    Arguments:
        operation: SQL command or prepared `Statement`.
        parameters: Sequence of parameters. Must contain one entry for each argument
                    that the operation expects.

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

    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.
    """
    self._execute(operation, parameters)
    return self

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

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:

Name Type Description Default
operation str | Statement

SQL command or prepared Statement.

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

required
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 effective as direct use of prepared Statement and calling execute in a loop directly in application.

Source code in firebird/driver/core.py
def executemany(self, operation: str | Statement,
                seq_of_parameters: Sequence[Sequence[Any]]) -> None:
    """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.

    Arguments:
        operation: SQL command or prepared `Statement`.
        seq_of_parameters: 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 effective as direct use of prepared `Statement`
        and calling `execute` in a loop directly in application.
    """
    for parameters in seq_of_parameters:
        self.execute(operation, parameters)

fetch_absolute(position: int) -> tuple | None

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

Returns None if there is no row to be fetched.

Parameters:

Name Type Description Default
position int

Absolute position number of row in result set.

required
Source code in firebird/driver/core.py
def fetch_absolute(self, position: int) -> tuple | None:
    """Fetch the row of a scrollable query result set specified by absolute position.

    Returns None if there is no row to be fetched.

    Arguments:
        position: Absolute position number of row in result set.
    """
    self._last_fetch_status = self._result.fetch_absolute(position, self._stmt._out_buffer)
    if self._last_fetch_status == StateResult.OK:
        return self._unpack_output()
    return None

fetch_first() -> tuple | None

Fetch the first row of a scrollable query result set.

Returns None if there is no row to be fetched.

Source code in firebird/driver/core.py
def fetch_first(self) -> tuple | None:
    """Fetch the first row of a scrollable query result set.

    Returns None if there is no row to be fetched.
    """
    self._last_fetch_status = self._result.fetch_first(self._stmt._out_buffer)
    if self._last_fetch_status == StateResult.OK:
        return self._unpack_output()
    return None

fetch_last() -> tuple | None

Fetch the last row of a scrollable query result set.

Returns None if there is no row to be fetched.

Source code in firebird/driver/core.py
def fetch_last(self) -> tuple | None:
    """Fetch the last row of a scrollable query result set.

    Returns None if there is no row to be fetched.
    """
    self._last_fetch_status = self._result.fetch_last(self._stmt._out_buffer)
    if self._last_fetch_status == StateResult.OK:
        return self._unpack_output()
    return None

fetch_next() -> tuple | None

Fetch the next row of a scrollable query result set.

Returns None if there is no row to be fetched.

Source code in firebird/driver/core.py
def fetch_next(self) -> tuple | None:
    """Fetch the next row of a scrollable query result set.

    Returns None if there is no row to be fetched.
    """
    self._last_fetch_status = self._result.fetch_next(self._stmt._out_buffer)
    if self._last_fetch_status == StateResult.OK:
        return self._unpack_output()
    return None

fetch_prior() -> tuple | None

Fetch the previous row of a scrollable query result set.

Returns None if there is no row to be fetched.

Source code in firebird/driver/core.py
def fetch_prior(self) -> tuple | None:
    """Fetch the previous row of a scrollable query result set.

    Returns None if there is no row to be fetched.
    """
    self._last_fetch_status = self._result.fetch_prior(self._stmt._out_buffer)
    if self._last_fetch_status == StateResult.OK:
        return self._unpack_output()
    return None

fetch_relative(offset: int) -> tuple | None

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

Returns None if there is no row to be fetched.

Parameters:

Name Type Description Default
offset int

Relative position number of row in result set. Negative value refers to previous row, positive to next row.

required
Source code in firebird/driver/core.py
def fetch_relative(self, offset: int) -> tuple | None:
    """Fetch the row of a scrollable query result set specified by relative position.

    Returns None if there is no row to be fetched.

    Arguments:
        offset: Relative position number of row in result set. Negative value refers
                to previous row, positive to next row.
    """
    self._last_fetch_status = self._result.fetch_relative(offset, self._stmt._out_buffer)
    if self._last_fetch_status == StateResult.OK:
        return self._unpack_output()
    return None

fetchall() -> list[tuple]

Fetch all remaining rows of a query result set.

Source code in firebird/driver/core.py
def fetchall(self) -> list[tuple]:
    """Fetch all remaining rows of a query result set.
    """
    return list(self)

fetchmany(size: int | None = None) -> list[tuple]

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:

Name Type Description Default
size int | None

The number of rows to fetch.

None
Source code in firebird/driver/core.py
def fetchmany(self, size: int | None=None) -> list[tuple]:
    """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.

    Arguments:
        size: The number of rows to fetch.
    """
    if size is None:
        size = self.arraysize
    result = []
    for _ in range(size):
        if (row := self.fetchone()) is not None:
            result.append(row)
        else:
            break
    return result

fetchone() -> tuple

Fetch the next row of a query result set.

Source code in firebird/driver/core.py
def fetchone(self) -> tuple:
    """Fetch the next row of a query result set.
    """
    if self._stmt:
        return self._fetchone()
    raise InterfaceError("Cannot fetch from cursor that did not executed a statement.")

is_bof() -> bool

Returns True is scrollable cursor is positioned at the beginning.

Source code in firebird/driver/core.py
def is_bof(self) -> bool:
    """Returns True is scrollable cursor is positioned at the beginning.
    """
    return self._result.is_bof()

is_closed() -> bool

Returns True if cursor is closed.

Source code in firebird/driver/core.py
def is_closed(self) -> bool:
    """Returns True if cursor is closed.
    """
    return self._stmt is None

is_eof() -> bool

Returns True is scrollable cursor is positioned at the end.

Source code in firebird/driver/core.py
def is_eof(self) -> bool:
    """Returns True is scrollable cursor is positioned at the end.
    """
    return self._result.is_eof()

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

Executes SQL command or prepared Statement as scrollable.

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

Parameters:

Name Type Description Default
operation str | Statement

SQL command or prepared Statement.

required
parameters Sequence[Any] | None

Sequence of parameters. Must contain one entry for each argument that the operation expects.

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

Source code in firebird/driver/core.py
def open(self, operation: str | Statement, parameters: Sequence[Any] | None=None) -> Cursor:
    """Executes SQL command or prepared `Statement` as scrollable.

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

    Arguments:
        operation: SQL command or prepared `Statement`.
        parameters: Sequence of parameters. Must contain one entry for each argument
                    that the operation expects.

    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.
    """
    self._execute(operation, parameters, CursorFlag.SCROLLABLE)

prepare(operation: str) -> Statement

Creates prepared statement for repeated execution.

Parameters:

Name Type Description Default
operation str

SQL command.

required
Source code in firebird/driver/core.py
def prepare(self, operation: str) -> Statement:
    """Creates prepared statement for repeated execution.

    Arguments:
        operation: SQL command.
    """
    return self._connection._prepare(operation, self._transaction)

set_cursor_name(name: str) -> None

Sets name for the SQL cursor.

Parameters:

Name Type Description Default
name str

Cursor name.

required
Source code in firebird/driver/core.py
def set_cursor_name(self, name: str) -> None:
    """Sets name for the SQL cursor.

    Arguments:
        name: Cursor name.
    """
    if not self._executed:
        raise InterfaceError("Cannot set name for cursor has not yet "
                             "executed a statement")
    if self._name:
        raise InterfaceError("Cursor's name has already been declared in"
                             " context of currently executed statement")
    self._stmt._istmt.set_cursor_name(name)
    self._name = name

setinputsizes(sizes: Sequence[type]) -> None

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

Source code in firebird/driver/core.py
def setinputsizes(self, sizes: Sequence[type]) -> None:
    """Required by Python DB API 2.0, but pointless for Firebird, so it does nothing.
    """

setoutputsize(size: int, column: int | None = None) -> None

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

Source code in firebird/driver/core.py
def setoutputsize(self, size: int, column: int | None=None) -> None:
    """Required by Python DB API 2.0, but pointless for Firebird, so it does nothing.
    """

to_dict(row: tuple, into: dict | None = None) -> dict

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

Parameters:

Name Type Description Default
row tuple

Row data returned by fetch_* method.

required
into dict | None

Dictionary that should be updated with row data.

None
Source code in firebird/driver/core.py
def to_dict(self, row: tuple, into: dict | None=None) -> dict:
    """Returns row tuple as dictionary with field names as keys. Returns new dictionary
    if `into` argument is not provided, otherwise returns `into` dictionary updated
    with row data.

    Arguments:
        row:  Row data returned by fetch_* method.
        into: Dictionary that should be updated with row data.
    """
    if into is None:
        into = dict(zip(self._stmt._names, row, strict=True))
    else:
        into.update(zip(self._stmt._names, row, strict=True))
    return into

firebird.driver.core.Server

Represents connection to Firebird Service Manager.

Note

Implements context manager protocol to call .close() automatically.

Source code in firebird/driver/core.py
class Server:
    """Represents connection to Firebird Service Manager.

    Note:
        Implements context manager protocol to call `.close()` automatically.
    """
    def __init__(self, svc: iService, spb: bytes, host: str, encoding: str,
                 encoding_errors: str):
        self._svc: iService = svc
        self.spb: bytes = spb
        "Service Parameter Buffer (SPB) used to connect the service manager"
        self.host: str = host
        "Server host"
        self.mode: SrvInfoCode = SrvInfoCode.TO_EOF
        "Service output mode (line or eof)"
        self.query_timeout: int = INFINITE_TIMEOUT
        "Timeout in seconds for server output queries; -1 waits indefinitely"
        self.response: CBuffer = CBuffer(USHRT_MAX)
        "Response buffer used to communicate with service"
        self._eof: bool = False
        self.__line_buffer: list[str] = []
        self.__decoder: codecs.IncrementalDecoder | None = None
        self.encoding: str = encoding
        "Encoding used for text data exchange with server"
        self.encoding_errors: str = encoding_errors
        "Handler used for encoding errors. See: `codecs#error-handlers`"
        #
        self.__ev: float = None
        self.__info: ServerInfoProvider = None
        self.__dbsvc: ServerDbServices | ServerDbServices3 | ServerDbServices4 = None
        self.__trace: ServerTraceServices = None
        self.__user: ServerUserServices = None
    def __enter__(self) -> Self:
        return self
    def __exit__(self, exc_type, exc_value, traceback) -> None:
        self.close()
    def __del__(self):
        if self._svc is not None:
            warn("Server disposed without prior close()", ResourceWarning)
            self.close()
    def __next__(self):
        if (line := self.readline()) is not None:
            return line
        raise StopIteration
    def __iter__(self):
        return self
    def __str__(self):
        return f'Server[v{self.info.version}@{self.host.replace(":service_mgr","")}]'
    def _engine_version(self) -> float:
        if self.__ev is None:
            self.__ev = _engine_version_provider.get_engine_version(weakref.ref(self))
        return self.__ev
    def _reset_output(self) -> None:
        self._eof = False
        self.__line_buffer.clear()
        self.__decoder = None
    def _make_request(self, timeout: int) -> bytes:
        if timeout == -1:
            return None
        return b''.join([SrvInfoCode.TIMEOUT.value.to_bytes(1, 'little'),
                         (2).to_bytes(2, 'little'),
                         timeout.to_bytes(2, 'little')])
    def _fetch_complex_info(self, request: bytes, timeout: int=INFINITE_TIMEOUT) -> None:
        send = self._make_request(timeout)
        self.response.clear()
        self._svc.query(send, request, self.response.raw)
        if self.response.is_truncated():  # pragma: no cover
            raise InterfaceError("Requested data can't fint into largest possible buffer")
    def _fetch_line(self, timeout: int=INFINITE_TIMEOUT) -> str | None: # noqa: ARG002
        self._fetch_complex_info(bytes([SrvInfoCode.LINE]))
        result = None
        while not self.response.is_eof():
            tag = self.response.get_tag()
            if tag == SrvInfoCode.TIMEOUT:
                return None
            if tag == SrvInfoCode.LINE:
                result = self.response.read_sized_string(encoding=self.encoding)
        if self.response.get_tag() != isc_info_end:  # pragma: no cover
            raise InterfaceError("Malformed result buffer (missing isc_info_end item)")
        return result
    def _query_output(self, timeout: int) -> str | Sentinel:
        self.response.clear()
        self._svc.query(self._make_request(timeout), bytes([self.mode]), self.response.raw)
        if (tag := self.response.get_tag()) == isc_info_svc_timeout:
            return TIMEOUT
        if tag != self.mode:  # pragma: no cover
            raise InterfaceError(f"Service responded with error code: {tag}")
        if self.__decoder is None:
            self.__decoder = codecs.getincrementaldecoder(self.encoding)(self.encoding_errors)
        # The service fills responses by size, so one can end inside a multi-byte character.
        # The incremental decoder keeps those bytes until the next response completes it.
        return self.__decoder.decode(self.response.read_bytes())
    def _flush_output(self) -> str:
        """Decode bytes left from an unfinished character at the end of output or of a line."""
        return self.__decoder.decode(b'', final=True)
    def _read_output(self, *, init: str='') -> bool:
        """Fetch output into the line buffer; return True if the query timed out."""
        data = self._query_output(self.query_timeout)
        if data is TIMEOUT:
            self.__line_buffer = init.splitlines(keepends=True)
            return True
        tag = self.response.get_tag()
        timed_out = tag == isc_info_svc_timeout
        if self.mode is SrvInfoCode.TO_EOF:
            self._eof = tag == isc_info_end
            if self._eof:
                data += self._flush_output()
        else: # LINE mode
            while tag == isc_info_truncated:
                part = self._query_output(self.query_timeout)
                if part is TIMEOUT:
                    timed_out = True
                    break
                data += part
                tag = self.response.get_tag()
                timed_out = tag == isc_info_svc_timeout
            if not timed_out and tag != isc_info_end:  # pragma: no cover
                raise InterfaceError("Malformed result buffer (missing isc_info_end item)")
            if not timed_out:
                data += self._flush_output()
                self._eof = not data
        init += data
        if data and self.mode is SrvInfoCode.LINE and not timed_out:
            init += '\n'
        self.__line_buffer = init.splitlines(keepends=True)
        return timed_out
    def _read_all_binary_output(self, *, timeout: int=INFINITE_TIMEOUT) -> bytes:
        send = self._make_request(timeout)
        result = []
        eof = False
        while not eof:
            self.response.clear()
            self._svc.query(send, bytes([SrvInfoCode.TO_EOF]), self.response.raw)
            if (tag := self.response.get_tag()) != SrvInfoCode.TO_EOF:  # pragma: no cover
                raise InterfaceError(f"Service responded with error code: {tag}")
            result.append(self.response.read_bytes())
            eof = self.response.get_tag() == isc_info_end
        return b''.join(result)
    def _read_next_binary_output(self, *, timeout: int=INFINITE_TIMEOUT) -> bytes:
        result = None
        if not self._eof:
            send = self._make_request(timeout)
            self.response.clear()
            self._svc.query(send, bytes([SrvInfoCode.TO_EOF]), self.response.raw)
            if (tag := self.response.get_tag()) != SrvInfoCode.TO_EOF:  # pragma: no cover
                raise InterfaceError(f"Service responded with error code: {tag}")
            result = self.response.read_bytes()
            self._eof = self.response.get_tag() == isc_info_end
        return result
    def is_running(self) -> bool:
        """Returns True if service is running.

        Note:
           Some services like `~.ServerDbServices.backup()` or `~.ServerDbServices.sweep()`
           may take time to comlete, so they're called asynchronously. Until they're finished,
           no other async service could be started.
        """
        return self.info.get_info(SrvInfoCode.RUNNING) > 0
    def readline_timed(self, timeout: int) -> str | Sentinel | None:
        """Get next line of textual output from last service query.

        Arguments:
          timeout: Time in seconds to wait for output.

        Returns:
          Line of service output, `None` for EOF or `.TIMEOUT` sentinel for expired timeout.
        """
        self.response.clear()
        self._svc.query(self._make_request(timeout), bytes([SrvInfoCode.LINE]), self.response.raw)
        if (tag := self.response.get_tag()) != SrvInfoCode.LINE:  # pragma: no cover
            raise InterfaceError(f"Service responded with error code: {tag}")
        data = self.response.read_sized_string(encoding=self.encoding, errors=self.encoding_errors)
        if self.response.get_tag() == SrvInfoCode.TIMEOUT:
            return TIMEOUT
        # read_sized_string() returns lines ending with '\r ' (CR + space).
        # Strip the trailing space to get proper '\r' line endings.
        if data and data.endswith('\r '):
            data = data[:-1]  # Remove space, keep '\r'
        return data if data else None
    def readline(self) -> str | Sentinel | None:
        """Get next line of textual output from last service query.

        Returns:
          Line of service output, `.TIMEOUT` if the query timed out, or `None` for EOF.

        Important:
          With the default `.query_timeout` this method blocks until output is available.
        """
        while True:
            # Only the last buffered piece can be an incomplete line; earlier ones ended on
            # another `splitlines()` boundary (e.g. a bare '\r' inside SQL text).
            if self.__line_buffer and (len(self.__line_buffer) > 1
                                       or self.__line_buffer[0].endswith('\n') or self._eof):
                return self.__line_buffer.pop(0)
            if self._eof:
                return None
            pending = self.__line_buffer.pop(0) if self.__line_buffer else ''
            if self._read_output(init=pending):
                return TIMEOUT
    def readlines(self) -> list[str]:
        """Get remaining output lines, omitting any timeout signals.
        """
        return [line for line in self if line is not TIMEOUT]
    def wait(self) -> None:
        """Wait until running service completes, i.e. stops sending data.
        """
        while self.is_running():
            for _ in self:
                pass
    def close(self) -> None:
        """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.
        """
        if self.__info is not None:
            self.__info._close()
            self.__info = None
        if self.__dbsvc is not None:
            self.__dbsvc._close()
            self.__dbsvc = None
        if self.__trace is not None:
            self.__trace._close()
            self.__trace = None
        if self.__user is not None:
            self.__user._close()
            self.__user = None
        if self._svc is not None:
            # try..finally is necessary to shield from crashed server
            # Otherwise close() will be called from __del__ which may crash Python
            try:
                self._svc.detach()
            finally:
                self._svc = None
    # Properties
    @property
    def info(self) -> ServerInfoProvider:
        """Access to various information about attached server.
        """
        if self.__info is None:
            self.__info = ServerInfoProvider(self.encoding, self)
        return self.__info
    @property
    def database(self) -> ServerDbServices4 | ServerDbServices3 | ServerDbServices:
        """Access to various database-related actions and services.
        """
        if self.__dbsvc is None:
            if self._engine_version() >= FB50:
                cls = ServerDbServices
            elif self._engine_version() == FB40:
                cls = ServerDbServices4
            else:
                cls = ServerDbServices3
            self.__dbsvc = cls(self)
        return self.__dbsvc
    @property
    def trace(self) -> ServerTraceServices:
        """Access to various database-related actions and services.
        """
        if self.__trace is None:
            self.__trace = ServerTraceServices(self)
        return self.__trace
    @property
    def user(self) -> ServerUserServices:
        """Access to various user-related actions and services.
        """
        if self.__user is None:
            self.__user = ServerUserServices(self)
        return self.__user

database: ServerDbServices4 | ServerDbServices3 | ServerDbServices property

Access to various database-related actions and services.

encoding: str instance-attribute

Encoding used for text data exchange with server

encoding_errors: str instance-attribute

Handler used for encoding errors. See: codecs#error-handlers

host: str instance-attribute

Server host

info: ServerInfoProvider property

Access to various information about attached server.

mode: SrvInfoCode instance-attribute

Service output mode (line or eof)

query_timeout: int instance-attribute

Timeout in seconds for server output queries; -1 waits indefinitely

response: CBuffer instance-attribute

Response buffer used to communicate with service

spb: bytes instance-attribute

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

trace: ServerTraceServices property

Access to various database-related actions and services.

user: ServerUserServices property

Access to various user-related actions and services.

close() -> None

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.

Source code in firebird/driver/core.py
def close(self) -> None:
    """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.
    """
    if self.__info is not None:
        self.__info._close()
        self.__info = None
    if self.__dbsvc is not None:
        self.__dbsvc._close()
        self.__dbsvc = None
    if self.__trace is not None:
        self.__trace._close()
        self.__trace = None
    if self.__user is not None:
        self.__user._close()
        self.__user = None
    if self._svc is not None:
        # try..finally is necessary to shield from crashed server
        # Otherwise close() will be called from __del__ which may crash Python
        try:
            self._svc.detach()
        finally:
            self._svc = None

is_running() -> bool

Returns True if service is running.

Note

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

Source code in firebird/driver/core.py
def is_running(self) -> bool:
    """Returns True if service is running.

    Note:
       Some services like `~.ServerDbServices.backup()` or `~.ServerDbServices.sweep()`
       may take time to comlete, so they're called asynchronously. Until they're finished,
       no other async service could be started.
    """
    return self.info.get_info(SrvInfoCode.RUNNING) > 0

readline() -> str | Sentinel | None

Get next line of textual output from last service query.

Returns:

Type Description
str | Sentinel | None

Line of service output, .TIMEOUT if the query timed out, or None for EOF.

Important

With the default .query_timeout this method blocks until output is available.

Source code in firebird/driver/core.py
def readline(self) -> str | Sentinel | None:
    """Get next line of textual output from last service query.

    Returns:
      Line of service output, `.TIMEOUT` if the query timed out, or `None` for EOF.

    Important:
      With the default `.query_timeout` this method blocks until output is available.
    """
    while True:
        # Only the last buffered piece can be an incomplete line; earlier ones ended on
        # another `splitlines()` boundary (e.g. a bare '\r' inside SQL text).
        if self.__line_buffer and (len(self.__line_buffer) > 1
                                   or self.__line_buffer[0].endswith('\n') or self._eof):
            return self.__line_buffer.pop(0)
        if self._eof:
            return None
        pending = self.__line_buffer.pop(0) if self.__line_buffer else ''
        if self._read_output(init=pending):
            return TIMEOUT

readline_timed(timeout: int) -> str | Sentinel | None

Get next line of textual output from last service query.

Parameters:

Name Type Description Default
timeout int

Time in seconds to wait for output.

required

Returns:

Type Description
str | Sentinel | None

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

Source code in firebird/driver/core.py
def readline_timed(self, timeout: int) -> str | Sentinel | None:
    """Get next line of textual output from last service query.

    Arguments:
      timeout: Time in seconds to wait for output.

    Returns:
      Line of service output, `None` for EOF or `.TIMEOUT` sentinel for expired timeout.
    """
    self.response.clear()
    self._svc.query(self._make_request(timeout), bytes([SrvInfoCode.LINE]), self.response.raw)
    if (tag := self.response.get_tag()) != SrvInfoCode.LINE:  # pragma: no cover
        raise InterfaceError(f"Service responded with error code: {tag}")
    data = self.response.read_sized_string(encoding=self.encoding, errors=self.encoding_errors)
    if self.response.get_tag() == SrvInfoCode.TIMEOUT:
        return TIMEOUT
    # read_sized_string() returns lines ending with '\r ' (CR + space).
    # Strip the trailing space to get proper '\r' line endings.
    if data and data.endswith('\r '):
        data = data[:-1]  # Remove space, keep '\r'
    return data if data else None

readlines() -> list[str]

Get remaining output lines, omitting any timeout signals.

Source code in firebird/driver/core.py
def readlines(self) -> list[str]:
    """Get remaining output lines, omitting any timeout signals.
    """
    return [line for line in self if line is not TIMEOUT]

wait() -> None

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

Source code in firebird/driver/core.py
def wait(self) -> None:
    """Wait until running service completes, i.e. stops sending data.
    """
    while self.is_running():
        for _ in self:
            pass

firebird.driver.core.ServerServiceProvider

Base class for server service providers.

Source code in firebird/driver/core.py
class ServerServiceProvider:
    """Base class for server service providers.
    """
    def __init__(self, server: Server):
        self._srv: Server = weakref.ref(server)
    def _close(self) -> None:
        self._srv = None

firebird.driver.core.ServerDbServices3

Bases: ServerServiceProvider

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

Source code in firebird/driver/core.py
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
class ServerDbServices3(ServerServiceProvider):
    """Database-related actions and services [Firebird 3+].
    """
    def get_statistics(self, *, database: FILESPEC,
                       flags: SrvStatFlag=SrvStatFlag.DEFAULT, role: str | None=None,
                       tables: Sequence[str] | None=None, callback: CB_OUTPUT_LINE | None=None) -> None:
        """Return database statistics produced by gstat utility. **(ASYNC service)**

        Arguments:
            database: Database specification or alias.
            flags: Flags indicating which statistics shall be collected.
            role: SQL ROLE name passed to gstat.
            tables: List of database tables whose statistics are to be collected.
            callback: Function to call back with each output line.
        """
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.DB_STATS)
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            spb.insert_int(SPBItem.OPTIONS, flags)
            if role is not None:
                spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
            if tables is not None:
                for table in tables:
                    spb.insert_string(64, table, encoding=self._srv().encoding) # isc_spb_sts_table = 64
            self._srv()._svc.start(spb.get_buffer())
        if callback:
            for line in self._srv():
                callback(line)
    def backup(self, *, database: FILESPEC, backup: FILESPEC | Sequence[FILESPEC],
               backup_file_sizes: Sequence[int]=(),
               flags: SrvBackupFlag=SrvBackupFlag.NONE, role: str | None=None,
               callback: CB_OUTPUT_LINE | None=None, stats: str | None=None,
               verbose: bool=False, verbint: int | None=None, skip_data: str | None=None,
               include_data: str | None=None, keyholder: str | None=None, keyname: str | None=None,
               crypt: str | None=None, parallel_workers: int | None=None) -> None:
        """Request logical (GBAK) database backup. **(ASYNC service)**

        Arguments:
            database: Database file specification or alias.
            backup: Backup filespec, or list of backup file specifications.
            backup_file_sizes: List of file sizes for backup files.
            flags: Backup options.
            role: SQL ROLE name passed to gbak.
            callback: Function to call back with each output line.
            stats: Backup statistic options (TDWR).
            verbose: Whether output should be verbose or not.
            verbint: Verbose information with explicit interval (number of records)
            skip_data: String with table names whose data should be excluded from backup.
            include_data: String with table names whose data should be included into backup [Firebird 4].
            keyholder: Keyholder name [Firebird 4].
            keyname: Key name [Firebird 4]
            crypt: Encryption specification [Firebird 4]
            parallel_workers: Number of parallel workers [Firebird 5]
        """
        if isinstance(backup, str | Path):
            backup = [backup]
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.BACKUP)
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            for filename, size in itertools.zip_longest(backup, backup_file_sizes):
                spb.insert_string(SrvBackupOption.FILE, str(filename), encoding=self._srv().encoding)
                if size is not None:
                    spb.insert_int(SrvBackupOption.LENGTH, size)
            if role is not None:
                spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
            if skip_data is not None:
                spb.insert_string(SrvBackupOption.SKIP_DATA, skip_data)
            if include_data is not None:
                spb.insert_string(SrvBackupOption.INCLUDE_DATA, include_data)
            if keyholder is not None:
                spb.insert_string(SrvBackupOption.KEYHOLDER, keyholder)
            if keyname is not None:
                spb.insert_string(SrvBackupOption.KEYNAME, keyname)
            if crypt is not None:
                spb.insert_string(SrvBackupOption.CRYPT, crypt)
            if parallel_workers is not None:
                spb.insert_int(SrvBackupOption.PARALLEL_WORKERS, parallel_workers)
            spb.insert_int(SPBItem.OPTIONS, flags)
            if verbose:
                spb.insert_tag(SPBItem.VERBOSE)
            if verbint is not None:
                spb.insert_int(SPBItem.VERBINT, verbint)
            if stats:
                spb.insert_string(SrvBackupOption.STAT, stats)
            self._srv()._svc.start(spb.get_buffer())
        if callback:
            for line in self._srv():
                callback(line)
    def restore(self, *, backup: FILESPEC | Sequence[FILESPEC],
                database: FILESPEC | Sequence[FILESPEC],
                db_file_pages: Sequence[int]=(),
                flags: SrvRestoreFlag=SrvRestoreFlag.CREATE, role: str | None=None,
                callback: CB_OUTPUT_LINE | None=None, stats: str | None=None,
                verbose: bool=False, verbint: int | None=None, skip_data: str | None=None,
                page_size: int | None=None, buffers: int | None=None,
                access_mode: DbAccessMode=DbAccessMode.READ_WRITE, include_data: str | None=None,
                keyholder: str | None=None, keyname: str | None=None, crypt: str | None=None,
                replica_mode: ReplicaMode | None=None, parallel_workers: int | None=None) -> None:
        """Request database restore from logical (GBAK) backup. **(ASYNC service)**

        Arguments:
            backup: Backup filespec, or list of backup file specifications.
            database: Database specification or alias, or list of those.
            db_file_pages: List of database file sizes (in pages).
            flags: Restore options.
            role: SQL ROLE name passed to gbak.
            callback: Function to call back with each output line.
            stats: Restore statistic options (TDWR).
            verbose: Whether output should be verbose or not.
            verbint: Verbose information with explicit interval (number of records)
            skip_data: String with table names whose data should be excluded from restore.
            page_size: Page size for restored database.
            buffers: Cache size for restored database.
            access_mode: Restored database access mode (R/W or R/O).
            include_data: String with table names whose data should be included into backup [Firebird 4].
            keyholder: Keyholder name [Firebird 4].
            keyname: Key name [Firebird 4]
            crypt: Encryption specification [Firebird 4]
            replica_mode: Replica mode for restored database [Firebird 4]
            parallel_workers: Number of parallel workers [Firebird 5]
        """
        if isinstance(backup, str | Path):
            backup = [backup]
        if isinstance(database, str | Path):
            database = [database]
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.RESTORE)
            for filename in backup:
                spb.insert_string(SrvRestoreOption.FILE, str(filename), encoding=self._srv().encoding)
            for filename, size in itertools.zip_longest(database, db_file_pages):
                spb.insert_string(SPBItem.DBNAME, str(filename), encoding=self._srv().encoding)
                if size is not None:
                    spb.insert_int(SrvRestoreOption.LENGTH, size)
            if role is not None:
                spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
            if page_size is not None:
                spb.insert_int(SrvRestoreOption.PAGE_SIZE, page_size)
            if buffers is not None:
                spb.insert_int(SrvRestoreOption.BUFFERS, buffers)
            spb.insert_bytes(SrvRestoreOption.ACCESS_MODE, bytes([access_mode]))
            if skip_data is not None:
                spb.insert_string(SrvRestoreOption.SKIP_DATA, skip_data, encoding=self._srv().encoding)
            if include_data is not None:
                spb.insert_string(SrvRestoreOption.INCLUDE_DATA, include_data, encoding=self._srv().encoding)
            if keyholder is not None:
                spb.insert_string(SrvRestoreOption.KEYHOLDER, keyholder)
            if keyname is not None:
                spb.insert_string(SrvRestoreOption.KEYNAME, keyname)
            if crypt is not None:
                spb.insert_string(SrvRestoreOption.CRYPT, crypt)
            if replica_mode is not None:
                spb.insert_int(SrvRestoreOption.REPLICA_MODE, replica_mode.value)
            if parallel_workers is not None:
                spb.insert_int(SrvRestoreOption.PARALLEL_WORKERS, parallel_workers)
            spb.insert_int(SPBItem.OPTIONS, flags)
            if verbose:
                spb.insert_tag(SPBItem.VERBOSE)
            if verbint is not None:
                spb.insert_int(SPBItem.VERBINT, verbint)
            if stats:
                spb.insert_string(SrvRestoreOption.STAT, stats)
            self._srv()._svc.start(spb.get_buffer())
        if callback:
            for line in self._srv():
                callback(line)
    def local_backup(self, *, database: FILESPEC, backup_stream: BinaryIO,
                     flags: SrvBackupFlag=SrvBackupFlag.NONE, role: str | None=None,
                     skip_data: str | None=None, include_data: str | None=None, keyholder: str | None=None,
                     keyname: str | None=None, crypt: str | None=None) -> None:
        """Request logical (GBAK) database backup into local byte stream. **(SYNC service)**

        Arguments:
            database: Database specification or alias.
            backup_stream: Binary stream to which the backup is to be written.
            flags: Backup options.
            role: SQL ROLE name passed to gbak.
            skip_data: String with table names whose data should be excluded from backup.
            include_data: String with table names whose data should be included into backup [Firebird 4].
            keyholder: Keyholder name [Firebird 4].
            keyname: Key name [Firebird 4]
            crypt: Encryption specification [Firebird 4]
        """
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.BACKUP)
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            spb.insert_string(SrvBackupOption.FILE, 'stdout')
            spb.insert_int(SPBItem.OPTIONS, flags)
            if role is not None:
                spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
            if skip_data is not None:
                spb.insert_string(SrvBackupOption.SKIP_DATA, skip_data,
                                  encoding=self._srv().encoding)
            if include_data is not None:
                spb.insert_string(SrvBackupOption.INCLUDE_DATA, include_data,
                                  encoding=self._srv().encoding)
            if keyholder is not None:
                spb.insert_string(SrvBackupOption.KEYHOLDER, keyholder)
            if keyname is not None:
                spb.insert_string(SrvBackupOption.KEYNAME, keyname)
            if crypt is not None:
                spb.insert_string(SrvBackupOption.CRYPT, crypt)
            self._srv()._svc.start(spb.get_buffer())
        while not self._srv()._eof:
            backup_stream.write(self._srv()._read_next_binary_output())
    def local_restore(self, *, backup_stream: BinaryIO,
                      database: FILESPEC | Sequence[FILESPEC],
                      db_file_pages: Sequence[int]=(),
                      flags: SrvRestoreFlag=SrvRestoreFlag.CREATE, role: str | None=None,
                      skip_data: str | None=None, page_size: int | None=None, buffers: int | None=None,
                      access_mode: DbAccessMode=DbAccessMode.READ_WRITE,
                      include_data: str | None=None, keyholder: str | None=None, keyname: str | None=None,
                      crypt: str | None=None, replica_mode: ReplicaMode | None=None) -> None:
        """Request database restore from logical (GBAK) backup stored in local byte stream.
        **(SYNC service)**

        Arguments:
            backup_stream: Binary stream with the backup.
            database: Database specification or alias, or list of those.
            db_file_pages: List of database file sizes (in pages).
            flags: Restore options.
            role: SQL ROLE name passed to gbak.
            skip_data: String with table names whose data should be excluded from restore.
            page_size: Page size for restored database.
            buffers: Cache size for restored database.
            access_mode: Restored database access mode (R/W or R/O).
            include_data: String with table names whose data should be included into backup [Firebird 4].
            keyholder: Keyholder name [Firebird 4].
            keyname: Key name [Firebird 4]
            crypt: Encryption specification [Firebird 4]
            replica_mode: Replica mode for restored database [Firebird 4]
        """
        if isinstance(database, str | Path):
            database = [database]
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.RESTORE)
            spb.insert_string(SrvRestoreOption.FILE, 'stdin')
            for filename, size in itertools.zip_longest(database, db_file_pages):
                spb.insert_string(SPBItem.DBNAME, str(filename), encoding=self._srv().encoding)
                if size is not None:
                    spb.insert_int(SrvRestoreOption.LENGTH, size)
            if page_size is not None:
                spb.insert_int(SrvRestoreOption.PAGE_SIZE, page_size)
            if buffers is not None:
                spb.insert_int(SrvRestoreOption.BUFFERS, buffers)
            spb.insert_bytes(SrvRestoreOption.ACCESS_MODE, bytes([access_mode]))
            if skip_data is not None:
                spb.insert_string(SrvRestoreOption.SKIP_DATA, skip_data,
                                  encoding=self._srv().encoding)
            if include_data is not None:
                spb.insert_string(SrvRestoreOption.INCLUDE_DATA, include_data,
                                  encoding=self._srv().encoding)
            if keyholder is not None:
                spb.insert_string(SrvRestoreOption.KEYHOLDER, keyholder)
            if keyname is not None:
                spb.insert_string(SrvRestoreOption.KEYNAME, keyname)
            if crypt is not None:
                spb.insert_string(SrvRestoreOption.CRYPT, crypt)
            if replica_mode is not None:
                spb.insert_int(SrvRestoreOption.REPLICA_MODE, replica_mode.value)
            spb.insert_int(SPBItem.OPTIONS, flags)
            if role is not None:
                spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
            self._srv()._svc.start(spb.get_buffer())
        #
        request_length = 0
        line = ''
        keep_going = True
        while keep_going:
            no_data = False
            self._srv().response.clear()
            if request_length > 0:
                request_length = min([request_length, 65500])
                raw = backup_stream.read(request_length)
                send = b''.join([SrvInfoCode.LINE.to_bytes(1, 'little'),
                                 len(raw).to_bytes(2, 'little'), raw,
                                 isc_info_end.to_bytes(1, 'little')])
            else:
                send = None
            self._srv()._svc.query(send, bytes([SrvInfoCode.STDIN, SrvInfoCode.LINE]),
                                   self._srv().response.raw)
            tag = self._srv().response.get_tag()
            while tag != isc_info_end:
                if tag == SrvInfoCode.STDIN:
                    request_length = self._srv().response.read_int()
                elif tag == SrvInfoCode.LINE:
                    line = self._srv().response.read_sized_string(encoding=self._srv().encoding)
                elif tag == isc_info_data_not_ready:
                    no_data = True
                else:  # pragma: no cover
                    raise InterfaceError(f"Service responded with error code: {tag}")
                tag = self._srv().response.get_tag()
            keep_going = no_data or request_length != 0 or line
    def nbackup(self, *, database: FILESPEC, backup: FILESPEC, level: int=0,
                direct: bool | None=None, flags: SrvNBackupFlag=SrvNBackupFlag.NONE,
                role: str | None=None, guid: str | None=None) -> None:
        """Perform physical (NBACKUP) database backup. **(SYNC service)**

        Arguments:
            database: Database specification or alias.
            backup: Backup file specification.
            level: Backup level.
            direct: Direct I/O override.
            flags: Backup options.
            role: SQL ROLE name passed to nbackup.
            guid: Database backup GUID.

        Important:
            Parameters `level` and `guid` are mutually exclusive. If `guid` is specified,
            then `level` value is ignored.
        """
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.NBAK)
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            spb.insert_string(SrvNBackupOption.FILE, str(backup), encoding=self._srv().encoding)
            if guid is not None:
                spb.insert_string(SrvNBackupOption.GUID, guid)
            else:
                spb.insert_int(SrvNBackupOption.LEVEL, level)
            if direct is not None:
                spb.insert_string(SrvNBackupOption.DIRECT, 'ON' if direct else 'OFF')
            if role is not None:
                spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
            spb.insert_int(SPBItem.OPTIONS, flags)
            self._srv()._svc.start(spb.get_buffer())
        self._srv().wait()
    def nrestore(self, *, backups: Sequence[FILESPEC], database: FILESPEC,
                 direct: bool=False, flags: SrvNBackupFlag=SrvNBackupFlag.NONE,
                 role: str | None=None) -> None:
        """Perform restore from physical (NBACKUP) database backup.  **(SYNC service)**

        Arguments:
            backups: Backup file(s) specification.
            database: Database specification or alias.
            direct: Direct I/O override.
            flags: Restore options.
            role: SQL ROLE name passed to nbackup.
        """
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.NREST)
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            for backup in backups:
                spb.insert_string(SrvNBackupOption.FILE, str(backup), encoding=self._srv().encoding)
            if direct is not None:
                spb.insert_string(SrvNBackupOption.DIRECT, 'ON' if direct else 'OFF')
            if role is not None:
                spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
            spb.insert_int(SPBItem.OPTIONS, flags)
            self._srv()._svc.start(spb.get_buffer())
        self._srv().wait()
    def set_default_cache_size(self, *, database: FILESPEC, size: int, role: str | None=None) -> None:
        """Set individual page cache size for database.

        Arguments:
            database: Database specification or alias.
            size: New value.
            role: SQL ROLE name passed to gfix.
        """
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.PROPERTIES)
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            if role is not None:
                spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
            spb.insert_int(SrvPropertiesOption.PAGE_BUFFERS, size)
            self._srv()._svc.start(spb.get_buffer())
        self._srv().wait()
    def set_sweep_interval(self, *, database: FILESPEC, interval: int, role: str | None=None) -> None:
        """Set database sweep interval.

        Arguments:
            database: Database specification or alias.
            interval: New value.
            role: SQL ROLE name passed to gfix.
        """
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.PROPERTIES)
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            if role is not None:
                spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
            spb.insert_int(SrvPropertiesOption.SWEEP_INTERVAL, interval)
            self._srv()._svc.start(spb.get_buffer())
        self._srv().wait()
    def set_space_reservation(self, *, database: FILESPEC, mode: DbSpaceReservation,
                              role: str | None=None) -> None:
        """Set space reservation for database.

        Arguments:
            database: Database specification or alias.
            mode: New value.
            role: SQL ROLE name passed to gfix.
        """
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.PROPERTIES)
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            if role is not None:
                spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
            spb.insert_bytes(SrvPropertiesOption.RESERVE_SPACE,
                             bytes([mode]))
            self._srv()._svc.start(spb.get_buffer())
        self._srv().wait()
    def set_write_mode(self, *, database: FILESPEC, mode: DbWriteMode, role: str | None=None) -> None:
        """Set database write mode (SYNC/ASYNC).

        Arguments:
            database: Database specification or alias.
            mode: New value.
            role: SQL ROLE name passed to gfix.
        """
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.PROPERTIES)
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            if role is not None:
                spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
            spb.insert_bytes(SrvPropertiesOption.WRITE_MODE,
                             bytes([mode]))
            self._srv()._svc.start(spb.get_buffer())
        self._srv().wait()
    def set_access_mode(self, *, database: FILESPEC, mode: DbAccessMode, role: str | None=None) -> None:
        """Set database access mode (R/W or R/O).

        Arguments:
            database: Database specification or alias.
            mode: New value.
            role: SQL ROLE name passed to gfix.
        """
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.PROPERTIES)
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            if role is not None:
                spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
            spb.insert_bytes(SrvPropertiesOption.ACCESS_MODE, bytes([mode]))
            self._srv()._svc.start(spb.get_buffer())
        self._srv().wait()
    def set_sql_dialect(self, *, database: FILESPEC, dialect: int, role: str | None=None) -> None:
        """Set database SQL dialect.

        Arguments:
            database: Database specification or alias.
            dialect: New value.
            role: SQL ROLE name passed to gfix.
        """
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.PROPERTIES)
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            if role is not None:
                spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
            spb.insert_int(SrvPropertiesOption.SET_SQL_DIALECT, dialect)
            self._srv()._svc.start(spb.get_buffer())
        self._srv().wait()
    def activate_shadow(self, *, database: FILESPEC, role: str | None=None) -> None:
        """Activate database shadow.

        Arguments:
            database: Database specification or alias.
            role: SQL ROLE name passed to gfix.
        """
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.PROPERTIES)
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            if role is not None:
                spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
            spb.insert_int(SPBItem.OPTIONS, SrvPropertiesFlag.ACTIVATE)
            self._srv()._svc.start(spb.get_buffer())
        self._srv().wait()
    def no_linger(self, *, database: FILESPEC, role: str | None=None) -> None:
        """Set one-off override for database linger.

        Arguments:
            database: Database specification or alias.
            role: SQL ROLE name passed to gfix.
        """
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.PROPERTIES)
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            if role is not None:
                spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
            spb.insert_int(SPBItem.OPTIONS, SrvPropertiesFlag.NOLINGER)
            self._srv()._svc.start(spb.get_buffer())
        self._srv().wait()
    def shutdown(self, *, database: FILESPEC, mode: ShutdownMode,
                 method: ShutdownMethod, timeout: int, role: str | None=None) -> None:
        """Database shutdown.

        Arguments:
            database: Database specification or alias.
            mode: Shutdown mode.
            method: Shutdown method.
            timeout: Timeout for shutdown.
            role: SQL ROLE name passed to gfix.
        """
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.PROPERTIES)
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            if role is not None:
                spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
            spb.insert_bytes(SrvPropertiesOption.SHUTDOWN_MODE, bytes([mode]))
            spb.insert_int(method, timeout)
            self._srv()._svc.start(spb.get_buffer())
        self._srv().wait()
    def bring_online(self, *, database: FILESPEC, mode: OnlineMode=OnlineMode.NORMAL,
                     role: str | None=None) -> None:
        """Bring previously shut down database back online.

        Arguments:
            database: Database specification or alias.
            mode: Online mode.
            role: SQL ROLE name passed to gfix.
        """
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.PROPERTIES)
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            if role is not None:
                spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
            spb.insert_bytes(SrvPropertiesOption.ONLINE_MODE, bytes([mode]))
            self._srv()._svc.start(spb.get_buffer())
        self._srv().wait()
    def sweep(self, *, database: FILESPEC, role: str | None=None, parallel_workers: int | None=None) -> None:
        """Perform database sweep operation.

        Arguments:
            database: Database specification or alias.
            role: SQL ROLE name passed to gfix.
            parallel_workers: Number of parallel workers [Firebird 5]
        """
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.REPAIR)
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            if role is not None:
                spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
            if parallel_workers is not None:
                spb.insert_int(SrvRepairOption.PARALLEL_WORKERS, parallel_workers)
            spb.insert_int(SPBItem.OPTIONS, SrvRepairFlag.SWEEP_DB)
            self._srv()._svc.start(spb.get_buffer())
        self._srv().wait()
    def repair(self, *, database: FILESPEC, flags: SrvRepairFlag=SrvRepairFlag.REPAIR,
               role: str | None=None) -> None:
        """Perform database repair operation.  **(SYNC service)**

        Arguments:
            database: Database specification or alias.
            flags: Repair flags.
            role: SQL ROLE name passed to gfix.
        """
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.REPAIR)
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            if role is not None:
                spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
            spb.insert_int(SPBItem.OPTIONS, flags)
            self._srv()._svc.start(spb.get_buffer())
        self._srv().wait()
    def validate(self, *, database: FILESPEC, include_table: str | None=None,
                 exclude_table: str | None=None, include_index: str | None=None,
                 exclude_index: str | None=None, lock_timeout: int | None=None,
                 role: str | None=None, callback: CB_OUTPUT_LINE | None=None) -> None:
        """Perform database validation. **(ASYNC service)**

        Arguments:
            database: Database specification or alias.
            include_table: Regex pattern for table names to include in validation run.
            exclude_table: Regex pattern for table names to exclude in validation run.
            include_index: Regex pattern for index names to include in validation run.
            exclude_index: Regex pattern for index names to exclude in validation run.
            lock_timeout: Lock timeout (seconds), used to acquire locks for table to validate,
                default is 10 secs. 0 is no-wait, -1 is infinite wait.
            role: SQL ROLE name passed to gfix.
            callback: Function to call back with each output line.
        """
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.VALIDATE)
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            if include_table is not None:
                spb.insert_string(SrvValidateOption.INCLUDE_TABLE, include_table,
                                  encoding=self._srv().encoding)
            if exclude_table is not None:
                spb.insert_string(SrvValidateOption.EXCLUDE_TABLE, exclude_table,
                                  encoding=self._srv().encoding)
            if include_index is not None:
                spb.insert_string(SrvValidateOption.INCLUDE_INDEX, include_index,
                                  encoding=self._srv().encoding)
            if exclude_index is not None:
                spb.insert_string(SrvValidateOption.EXCLUDE_INDEX, exclude_index,
                                  encoding=self._srv().encoding)
            if lock_timeout is not None:
                spb.insert_int(SrvValidateOption.LOCK_TIMEOUT, lock_timeout)
            if role is not None:
                spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
            self._srv()._svc.start(spb.get_buffer())
        if callback:
            for line in self._srv():
                callback(line)
    def get_limbo_transaction_ids(self, *, database: FILESPEC) -> list[int]: # noqa: ARG002
        """Returns list of transactions in limbo.

        Arguments:
            database: Database specification or alias.
        """
        raise NotSupportedError("Feature not yet implemented")
        #with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            #spb.insert_tag(ServerAction .REPAIR)
            #spb.insert_string(SPBItem.DBNAME, str(database))
            #spb.insert_int(SPBItem.OPTIONS, SrvRepairFlag.LIST_LIMBO_TRANS)
            #self._srv()._svc.start(spb.get_buffer())
        #self._srv()._reset_output()
        #self._srv()._fetch_complex_info(bytes([SrvInfoCode.LIMBO_TRANS]))
        #trans_ids = []
        #while not self._srv().response.is_eof():
            #tag = self._srv().response.get_tag()
            #if tag == SrvInfoCode.TIMEOUT:
                #return None
            #if tag == SrvInfoCode.LIMBO_TRANS:
                #size = self._srv().response.read_short()
                #while not self._srv().response.is_eof() and self._srv().response.pos < size:
                    #tag = self._srv().response.get_tag()
                    #if tag == SrvRepairOption.TRA_HOST_SITE:
                        #site = self._srv().response.get_string()
                    #elif tag == SrvRepairOption.TRA_STATE:
                        #tag = self._srv().response.get_tag()
                        #if tag == SrvRepairOption.TRA_STATE_LIMBO:
                            #state = TransactionState.LIMBO
                        #elif tag == SrvRepairOption.TRA_STATE_COMMIT:
                            #state = TransactionState.COMMIT
                        #elif tag == SrvRepairOption.TRA_STATE_ROLLBACK:
                            #state = TransactionState.ROLLBACK
                        #elif tag == SrvRepairOption.TRA_STATE_UNKNOWN:
                            #state = TransactionState.UNKNOWN
                        #else:
                            #raise InterfaceError(f"Unknown transaction state {tag}")
                    #elif tag == SrvRepairOption.TRA_REMOTE_SITE:
                        #remote_site = self._srv().response.get_string()
                    #elif tag == SrvRepairOption.TRA_DB_PATH:
                        #db_path = self._srv().response.get_string()
                    #elif tag == SrvRepairOption.TRA_ADVISE:
                        #tag = self._srv().response.get_tag()
                        #if tag == SrvRepairOption.TRA_ADVISE_COMMIT:
                            #advise = TransactionState.COMMIT
                        #elif tag == SrvRepairOption.TRA_ADVISE_ROLLBACK:
                            #advise = TransactionState.ROLLBACK
                        #elif tag == SrvRepairOption.TRA_ADVISE_UNKNOWN:
                            #advise = TransactionState.UNKNOWN
                        #else:
                            #raise InterfaceError(f"Unknown transaction state {tag}")
                    #elif tag == SrvRepairOption.MULTI_TRA_ID:
                        #multi_id = self._srv().response.get_int()
                    #elif tag == SrvRepairOption.SINGLE_TRA_ID:
                        #single_id = self._srv().response.get_int()
                    #elif tag == SrvRepairOption.TRA_ID:
                        #tra_id = self._srv().response.get_int()
                    #elif tag == SrvRepairOption.MULTI_TRA_ID_64:
                        #multi_id = self._srv().response.get_int64()
                    #elif tag == SrvRepairOption.SINGLE_TRA_ID_64:
                        #single_id = self._srv().response.get_int64()
                    #elif tag == SrvRepairOption.TRA_ID_64:
                        #tra_id = self._srv().response.get_int64()
                    #else:
                        #raise InterfaceError(f"Unknown transaction state {tag}")
                    #trans_ids.append(None)
        #if self._srv().response.get_tag() != isc_info_end:
            #raise InterfaceError("Malformed result buffer (missing isc_info_end item)")
        #return trans_ids
    def commit_limbo_transaction(self, *, database: FILESPEC, transaction_id: int) -> None:
        """Resolve limbo transaction with commit.

        Arguments:
            database: Database specification or alias.
            transaction_id: ID of Transaction to resolve.
        """
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.REPAIR)
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            if transaction_id <= USHRT_MAX:
                spb.insert_int(SrvRepairOption.COMMIT_TRANS, transaction_id)
            else:
                spb.insert_bigint(SrvRepairOption.COMMIT_TRANS_64, transaction_id)
            self._srv()._svc.start(spb.get_buffer())
        self._srv()._read_all_binary_output()
    def rollback_limbo_transaction(self, *, database: FILESPEC, transaction_id: int) -> None:
        """Resolve limbo transaction with rollback.

        Arguments:
            database: Database specification or alias.
            transaction_id: ID of Transaction to resolve.
        """
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.REPAIR)
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            if transaction_id <= USHRT_MAX:
                spb.insert_int(SrvRepairOption.ROLLBACK_TRANS, transaction_id)
            else:
                spb.insert_bigint(SrvRepairOption.ROLLBACK_TRANS_64, transaction_id)
            self._srv()._svc.start(spb.get_buffer())
        self._srv()._read_all_binary_output()

activate_shadow(*, database: FILESPEC, role: str | None = None) -> None

Activate database shadow.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
role str | None

SQL ROLE name passed to gfix.

None
Source code in firebird/driver/core.py
def activate_shadow(self, *, database: FILESPEC, role: str | None=None) -> None:
    """Activate database shadow.

    Arguments:
        database: Database specification or alias.
        role: SQL ROLE name passed to gfix.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.PROPERTIES)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_int(SPBItem.OPTIONS, SrvPropertiesFlag.ACTIVATE)
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

backup(*, database: FILESPEC, backup: FILESPEC | Sequence[FILESPEC], backup_file_sizes: Sequence[int] = (), flags: SrvBackupFlag = SrvBackupFlag.NONE, role: str | None = None, callback: CB_OUTPUT_LINE | None = None, stats: str | None = None, verbose: bool = False, verbint: int | None = None, skip_data: str | None = None, include_data: str | None = None, keyholder: str | None = None, keyname: str | None = None, crypt: str | None = None, parallel_workers: int | None = None) -> None

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

Parameters:

Name Type Description Default
database FILESPEC

Database file specification or alias.

required
backup FILESPEC | Sequence[FILESPEC]

Backup filespec, or list of backup file specifications.

required
backup_file_sizes Sequence[int]

List of file sizes for backup files.

()
flags SrvBackupFlag

Backup options.

NONE
role str | None

SQL ROLE name passed to gbak.

None
callback CB_OUTPUT_LINE | None

Function to call back with each output line.

None
stats str | None

Backup statistic options (TDWR).

None
verbose bool

Whether output should be verbose or not.

False
verbint int | None

Verbose information with explicit interval (number of records)

None
skip_data str | None

String with table names whose data should be excluded from backup.

None
include_data str | None

String with table names whose data should be included into backup [Firebird 4].

None
keyholder str | None

Keyholder name [Firebird 4].

None
keyname str | None

Key name [Firebird 4]

None
crypt str | None

Encryption specification [Firebird 4]

None
parallel_workers int | None

Number of parallel workers [Firebird 5]

None
Source code in firebird/driver/core.py
def backup(self, *, database: FILESPEC, backup: FILESPEC | Sequence[FILESPEC],
           backup_file_sizes: Sequence[int]=(),
           flags: SrvBackupFlag=SrvBackupFlag.NONE, role: str | None=None,
           callback: CB_OUTPUT_LINE | None=None, stats: str | None=None,
           verbose: bool=False, verbint: int | None=None, skip_data: str | None=None,
           include_data: str | None=None, keyholder: str | None=None, keyname: str | None=None,
           crypt: str | None=None, parallel_workers: int | None=None) -> None:
    """Request logical (GBAK) database backup. **(ASYNC service)**

    Arguments:
        database: Database file specification or alias.
        backup: Backup filespec, or list of backup file specifications.
        backup_file_sizes: List of file sizes for backup files.
        flags: Backup options.
        role: SQL ROLE name passed to gbak.
        callback: Function to call back with each output line.
        stats: Backup statistic options (TDWR).
        verbose: Whether output should be verbose or not.
        verbint: Verbose information with explicit interval (number of records)
        skip_data: String with table names whose data should be excluded from backup.
        include_data: String with table names whose data should be included into backup [Firebird 4].
        keyholder: Keyholder name [Firebird 4].
        keyname: Key name [Firebird 4]
        crypt: Encryption specification [Firebird 4]
        parallel_workers: Number of parallel workers [Firebird 5]
    """
    if isinstance(backup, str | Path):
        backup = [backup]
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.BACKUP)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        for filename, size in itertools.zip_longest(backup, backup_file_sizes):
            spb.insert_string(SrvBackupOption.FILE, str(filename), encoding=self._srv().encoding)
            if size is not None:
                spb.insert_int(SrvBackupOption.LENGTH, size)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        if skip_data is not None:
            spb.insert_string(SrvBackupOption.SKIP_DATA, skip_data)
        if include_data is not None:
            spb.insert_string(SrvBackupOption.INCLUDE_DATA, include_data)
        if keyholder is not None:
            spb.insert_string(SrvBackupOption.KEYHOLDER, keyholder)
        if keyname is not None:
            spb.insert_string(SrvBackupOption.KEYNAME, keyname)
        if crypt is not None:
            spb.insert_string(SrvBackupOption.CRYPT, crypt)
        if parallel_workers is not None:
            spb.insert_int(SrvBackupOption.PARALLEL_WORKERS, parallel_workers)
        spb.insert_int(SPBItem.OPTIONS, flags)
        if verbose:
            spb.insert_tag(SPBItem.VERBOSE)
        if verbint is not None:
            spb.insert_int(SPBItem.VERBINT, verbint)
        if stats:
            spb.insert_string(SrvBackupOption.STAT, stats)
        self._srv()._svc.start(spb.get_buffer())
    if callback:
        for line in self._srv():
            callback(line)

bring_online(*, database: FILESPEC, mode: OnlineMode = OnlineMode.NORMAL, role: str | None = None) -> None

Bring previously shut down database back online.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
mode OnlineMode

Online mode.

NORMAL
role str | None

SQL ROLE name passed to gfix.

None
Source code in firebird/driver/core.py
def bring_online(self, *, database: FILESPEC, mode: OnlineMode=OnlineMode.NORMAL,
                 role: str | None=None) -> None:
    """Bring previously shut down database back online.

    Arguments:
        database: Database specification or alias.
        mode: Online mode.
        role: SQL ROLE name passed to gfix.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.PROPERTIES)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_bytes(SrvPropertiesOption.ONLINE_MODE, bytes([mode]))
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

commit_limbo_transaction(*, database: FILESPEC, transaction_id: int) -> None

Resolve limbo transaction with commit.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
transaction_id int

ID of Transaction to resolve.

required
Source code in firebird/driver/core.py
def commit_limbo_transaction(self, *, database: FILESPEC, transaction_id: int) -> None:
    """Resolve limbo transaction with commit.

    Arguments:
        database: Database specification or alias.
        transaction_id: ID of Transaction to resolve.
    """
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.REPAIR)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if transaction_id <= USHRT_MAX:
            spb.insert_int(SrvRepairOption.COMMIT_TRANS, transaction_id)
        else:
            spb.insert_bigint(SrvRepairOption.COMMIT_TRANS_64, transaction_id)
        self._srv()._svc.start(spb.get_buffer())
    self._srv()._read_all_binary_output()

get_limbo_transaction_ids(*, database: FILESPEC) -> list[int]

Returns list of transactions in limbo.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
Source code in firebird/driver/core.py
def get_limbo_transaction_ids(self, *, database: FILESPEC) -> list[int]: # noqa: ARG002
    """Returns list of transactions in limbo.

    Arguments:
        database: Database specification or alias.
    """
    raise NotSupportedError("Feature not yet implemented")

get_statistics(*, database: FILESPEC, flags: SrvStatFlag = SrvStatFlag.DEFAULT, role: str | None = None, tables: Sequence[str] | None = None, callback: CB_OUTPUT_LINE | None = None) -> None

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

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
flags SrvStatFlag

Flags indicating which statistics shall be collected.

DEFAULT
role str | None

SQL ROLE name passed to gstat.

None
tables Sequence[str] | None

List of database tables whose statistics are to be collected.

None
callback CB_OUTPUT_LINE | None

Function to call back with each output line.

None
Source code in firebird/driver/core.py
def get_statistics(self, *, database: FILESPEC,
                   flags: SrvStatFlag=SrvStatFlag.DEFAULT, role: str | None=None,
                   tables: Sequence[str] | None=None, callback: CB_OUTPUT_LINE | None=None) -> None:
    """Return database statistics produced by gstat utility. **(ASYNC service)**

    Arguments:
        database: Database specification or alias.
        flags: Flags indicating which statistics shall be collected.
        role: SQL ROLE name passed to gstat.
        tables: List of database tables whose statistics are to be collected.
        callback: Function to call back with each output line.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.DB_STATS)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        spb.insert_int(SPBItem.OPTIONS, flags)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        if tables is not None:
            for table in tables:
                spb.insert_string(64, table, encoding=self._srv().encoding) # isc_spb_sts_table = 64
        self._srv()._svc.start(spb.get_buffer())
    if callback:
        for line in self._srv():
            callback(line)

local_backup(*, database: FILESPEC, backup_stream: BinaryIO, flags: SrvBackupFlag = SrvBackupFlag.NONE, role: str | None = None, skip_data: str | None = None, include_data: str | None = None, keyholder: str | None = None, keyname: str | None = None, crypt: str | None = None) -> None

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

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
backup_stream BinaryIO

Binary stream to which the backup is to be written.

required
flags SrvBackupFlag

Backup options.

NONE
role str | None

SQL ROLE name passed to gbak.

None
skip_data str | None

String with table names whose data should be excluded from backup.

None
include_data str | None

String with table names whose data should be included into backup [Firebird 4].

None
keyholder str | None

Keyholder name [Firebird 4].

None
keyname str | None

Key name [Firebird 4]

None
crypt str | None

Encryption specification [Firebird 4]

None
Source code in firebird/driver/core.py
def local_backup(self, *, database: FILESPEC, backup_stream: BinaryIO,
                 flags: SrvBackupFlag=SrvBackupFlag.NONE, role: str | None=None,
                 skip_data: str | None=None, include_data: str | None=None, keyholder: str | None=None,
                 keyname: str | None=None, crypt: str | None=None) -> None:
    """Request logical (GBAK) database backup into local byte stream. **(SYNC service)**

    Arguments:
        database: Database specification or alias.
        backup_stream: Binary stream to which the backup is to be written.
        flags: Backup options.
        role: SQL ROLE name passed to gbak.
        skip_data: String with table names whose data should be excluded from backup.
        include_data: String with table names whose data should be included into backup [Firebird 4].
        keyholder: Keyholder name [Firebird 4].
        keyname: Key name [Firebird 4]
        crypt: Encryption specification [Firebird 4]
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.BACKUP)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        spb.insert_string(SrvBackupOption.FILE, 'stdout')
        spb.insert_int(SPBItem.OPTIONS, flags)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        if skip_data is not None:
            spb.insert_string(SrvBackupOption.SKIP_DATA, skip_data,
                              encoding=self._srv().encoding)
        if include_data is not None:
            spb.insert_string(SrvBackupOption.INCLUDE_DATA, include_data,
                              encoding=self._srv().encoding)
        if keyholder is not None:
            spb.insert_string(SrvBackupOption.KEYHOLDER, keyholder)
        if keyname is not None:
            spb.insert_string(SrvBackupOption.KEYNAME, keyname)
        if crypt is not None:
            spb.insert_string(SrvBackupOption.CRYPT, crypt)
        self._srv()._svc.start(spb.get_buffer())
    while not self._srv()._eof:
        backup_stream.write(self._srv()._read_next_binary_output())

local_restore(*, backup_stream: BinaryIO, database: FILESPEC | Sequence[FILESPEC], db_file_pages: Sequence[int] = (), flags: SrvRestoreFlag = SrvRestoreFlag.CREATE, role: str | None = None, skip_data: str | None = None, page_size: int | None = None, buffers: int | None = None, access_mode: DbAccessMode = DbAccessMode.READ_WRITE, include_data: str | None = None, keyholder: str | None = None, keyname: str | None = None, crypt: str | None = None, replica_mode: ReplicaMode | None = None) -> None

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

Parameters:

Name Type Description Default
backup_stream BinaryIO

Binary stream with the backup.

required
database FILESPEC | Sequence[FILESPEC]

Database specification or alias, or list of those.

required
db_file_pages Sequence[int]

List of database file sizes (in pages).

()
flags SrvRestoreFlag

Restore options.

CREATE
role str | None

SQL ROLE name passed to gbak.

None
skip_data str | None

String with table names whose data should be excluded from restore.

None
page_size int | None

Page size for restored database.

None
buffers int | None

Cache size for restored database.

None
access_mode DbAccessMode

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

READ_WRITE
include_data str | None

String with table names whose data should be included into backup [Firebird 4].

None
keyholder str | None

Keyholder name [Firebird 4].

None
keyname str | None

Key name [Firebird 4]

None
crypt str | None

Encryption specification [Firebird 4]

None
replica_mode ReplicaMode | None

Replica mode for restored database [Firebird 4]

None
Source code in firebird/driver/core.py
def local_restore(self, *, backup_stream: BinaryIO,
                  database: FILESPEC | Sequence[FILESPEC],
                  db_file_pages: Sequence[int]=(),
                  flags: SrvRestoreFlag=SrvRestoreFlag.CREATE, role: str | None=None,
                  skip_data: str | None=None, page_size: int | None=None, buffers: int | None=None,
                  access_mode: DbAccessMode=DbAccessMode.READ_WRITE,
                  include_data: str | None=None, keyholder: str | None=None, keyname: str | None=None,
                  crypt: str | None=None, replica_mode: ReplicaMode | None=None) -> None:
    """Request database restore from logical (GBAK) backup stored in local byte stream.
    **(SYNC service)**

    Arguments:
        backup_stream: Binary stream with the backup.
        database: Database specification or alias, or list of those.
        db_file_pages: List of database file sizes (in pages).
        flags: Restore options.
        role: SQL ROLE name passed to gbak.
        skip_data: String with table names whose data should be excluded from restore.
        page_size: Page size for restored database.
        buffers: Cache size for restored database.
        access_mode: Restored database access mode (R/W or R/O).
        include_data: String with table names whose data should be included into backup [Firebird 4].
        keyholder: Keyholder name [Firebird 4].
        keyname: Key name [Firebird 4]
        crypt: Encryption specification [Firebird 4]
        replica_mode: Replica mode for restored database [Firebird 4]
    """
    if isinstance(database, str | Path):
        database = [database]
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.RESTORE)
        spb.insert_string(SrvRestoreOption.FILE, 'stdin')
        for filename, size in itertools.zip_longest(database, db_file_pages):
            spb.insert_string(SPBItem.DBNAME, str(filename), encoding=self._srv().encoding)
            if size is not None:
                spb.insert_int(SrvRestoreOption.LENGTH, size)
        if page_size is not None:
            spb.insert_int(SrvRestoreOption.PAGE_SIZE, page_size)
        if buffers is not None:
            spb.insert_int(SrvRestoreOption.BUFFERS, buffers)
        spb.insert_bytes(SrvRestoreOption.ACCESS_MODE, bytes([access_mode]))
        if skip_data is not None:
            spb.insert_string(SrvRestoreOption.SKIP_DATA, skip_data,
                              encoding=self._srv().encoding)
        if include_data is not None:
            spb.insert_string(SrvRestoreOption.INCLUDE_DATA, include_data,
                              encoding=self._srv().encoding)
        if keyholder is not None:
            spb.insert_string(SrvRestoreOption.KEYHOLDER, keyholder)
        if keyname is not None:
            spb.insert_string(SrvRestoreOption.KEYNAME, keyname)
        if crypt is not None:
            spb.insert_string(SrvRestoreOption.CRYPT, crypt)
        if replica_mode is not None:
            spb.insert_int(SrvRestoreOption.REPLICA_MODE, replica_mode.value)
        spb.insert_int(SPBItem.OPTIONS, flags)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        self._srv()._svc.start(spb.get_buffer())
    #
    request_length = 0
    line = ''
    keep_going = True
    while keep_going:
        no_data = False
        self._srv().response.clear()
        if request_length > 0:
            request_length = min([request_length, 65500])
            raw = backup_stream.read(request_length)
            send = b''.join([SrvInfoCode.LINE.to_bytes(1, 'little'),
                             len(raw).to_bytes(2, 'little'), raw,
                             isc_info_end.to_bytes(1, 'little')])
        else:
            send = None
        self._srv()._svc.query(send, bytes([SrvInfoCode.STDIN, SrvInfoCode.LINE]),
                               self._srv().response.raw)
        tag = self._srv().response.get_tag()
        while tag != isc_info_end:
            if tag == SrvInfoCode.STDIN:
                request_length = self._srv().response.read_int()
            elif tag == SrvInfoCode.LINE:
                line = self._srv().response.read_sized_string(encoding=self._srv().encoding)
            elif tag == isc_info_data_not_ready:
                no_data = True
            else:  # pragma: no cover
                raise InterfaceError(f"Service responded with error code: {tag}")
            tag = self._srv().response.get_tag()
        keep_going = no_data or request_length != 0 or line

nbackup(*, database: FILESPEC, backup: FILESPEC, level: int = 0, direct: bool | None = None, flags: SrvNBackupFlag = SrvNBackupFlag.NONE, role: str | None = None, guid: str | None = None) -> None

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

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
backup FILESPEC

Backup file specification.

required
level int

Backup level.

0
direct bool | None

Direct I/O override.

None
flags SrvNBackupFlag

Backup options.

NONE
role str | None

SQL ROLE name passed to nbackup.

None
guid str | None

Database backup GUID.

None
Important

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

Source code in firebird/driver/core.py
def nbackup(self, *, database: FILESPEC, backup: FILESPEC, level: int=0,
            direct: bool | None=None, flags: SrvNBackupFlag=SrvNBackupFlag.NONE,
            role: str | None=None, guid: str | None=None) -> None:
    """Perform physical (NBACKUP) database backup. **(SYNC service)**

    Arguments:
        database: Database specification or alias.
        backup: Backup file specification.
        level: Backup level.
        direct: Direct I/O override.
        flags: Backup options.
        role: SQL ROLE name passed to nbackup.
        guid: Database backup GUID.

    Important:
        Parameters `level` and `guid` are mutually exclusive. If `guid` is specified,
        then `level` value is ignored.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.NBAK)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        spb.insert_string(SrvNBackupOption.FILE, str(backup), encoding=self._srv().encoding)
        if guid is not None:
            spb.insert_string(SrvNBackupOption.GUID, guid)
        else:
            spb.insert_int(SrvNBackupOption.LEVEL, level)
        if direct is not None:
            spb.insert_string(SrvNBackupOption.DIRECT, 'ON' if direct else 'OFF')
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_int(SPBItem.OPTIONS, flags)
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

no_linger(*, database: FILESPEC, role: str | None = None) -> None

Set one-off override for database linger.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
role str | None

SQL ROLE name passed to gfix.

None
Source code in firebird/driver/core.py
def no_linger(self, *, database: FILESPEC, role: str | None=None) -> None:
    """Set one-off override for database linger.

    Arguments:
        database: Database specification or alias.
        role: SQL ROLE name passed to gfix.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.PROPERTIES)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_int(SPBItem.OPTIONS, SrvPropertiesFlag.NOLINGER)
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

nrestore(*, backups: Sequence[FILESPEC], database: FILESPEC, direct: bool = False, flags: SrvNBackupFlag = SrvNBackupFlag.NONE, role: str | None = None) -> None

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

Parameters:

Name Type Description Default
backups Sequence[FILESPEC]

Backup file(s) specification.

required
database FILESPEC

Database specification or alias.

required
direct bool

Direct I/O override.

False
flags SrvNBackupFlag

Restore options.

NONE
role str | None

SQL ROLE name passed to nbackup.

None
Source code in firebird/driver/core.py
def nrestore(self, *, backups: Sequence[FILESPEC], database: FILESPEC,
             direct: bool=False, flags: SrvNBackupFlag=SrvNBackupFlag.NONE,
             role: str | None=None) -> None:
    """Perform restore from physical (NBACKUP) database backup.  **(SYNC service)**

    Arguments:
        backups: Backup file(s) specification.
        database: Database specification or alias.
        direct: Direct I/O override.
        flags: Restore options.
        role: SQL ROLE name passed to nbackup.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.NREST)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        for backup in backups:
            spb.insert_string(SrvNBackupOption.FILE, str(backup), encoding=self._srv().encoding)
        if direct is not None:
            spb.insert_string(SrvNBackupOption.DIRECT, 'ON' if direct else 'OFF')
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_int(SPBItem.OPTIONS, flags)
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

repair(*, database: FILESPEC, flags: SrvRepairFlag = SrvRepairFlag.REPAIR, role: str | None = None) -> None

Perform database repair operation. (SYNC service)

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
flags SrvRepairFlag

Repair flags.

REPAIR
role str | None

SQL ROLE name passed to gfix.

None
Source code in firebird/driver/core.py
def repair(self, *, database: FILESPEC, flags: SrvRepairFlag=SrvRepairFlag.REPAIR,
           role: str | None=None) -> None:
    """Perform database repair operation.  **(SYNC service)**

    Arguments:
        database: Database specification or alias.
        flags: Repair flags.
        role: SQL ROLE name passed to gfix.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.REPAIR)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_int(SPBItem.OPTIONS, flags)
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

restore(*, backup: FILESPEC | Sequence[FILESPEC], database: FILESPEC | Sequence[FILESPEC], db_file_pages: Sequence[int] = (), flags: SrvRestoreFlag = SrvRestoreFlag.CREATE, role: str | None = None, callback: CB_OUTPUT_LINE | None = None, stats: str | None = None, verbose: bool = False, verbint: int | None = None, skip_data: str | None = None, page_size: int | None = None, buffers: int | None = None, access_mode: DbAccessMode = DbAccessMode.READ_WRITE, include_data: str | None = None, keyholder: str | None = None, keyname: str | None = None, crypt: str | None = None, replica_mode: ReplicaMode | None = None, parallel_workers: int | None = None) -> None

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

Parameters:

Name Type Description Default
backup FILESPEC | Sequence[FILESPEC]

Backup filespec, or list of backup file specifications.

required
database FILESPEC | Sequence[FILESPEC]

Database specification or alias, or list of those.

required
db_file_pages Sequence[int]

List of database file sizes (in pages).

()
flags SrvRestoreFlag

Restore options.

CREATE
role str | None

SQL ROLE name passed to gbak.

None
callback CB_OUTPUT_LINE | None

Function to call back with each output line.

None
stats str | None

Restore statistic options (TDWR).

None
verbose bool

Whether output should be verbose or not.

False
verbint int | None

Verbose information with explicit interval (number of records)

None
skip_data str | None

String with table names whose data should be excluded from restore.

None
page_size int | None

Page size for restored database.

None
buffers int | None

Cache size for restored database.

None
access_mode DbAccessMode

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

READ_WRITE
include_data str | None

String with table names whose data should be included into backup [Firebird 4].

None
keyholder str | None

Keyholder name [Firebird 4].

None
keyname str | None

Key name [Firebird 4]

None
crypt str | None

Encryption specification [Firebird 4]

None
replica_mode ReplicaMode | None

Replica mode for restored database [Firebird 4]

None
parallel_workers int | None

Number of parallel workers [Firebird 5]

None
Source code in firebird/driver/core.py
def restore(self, *, backup: FILESPEC | Sequence[FILESPEC],
            database: FILESPEC | Sequence[FILESPEC],
            db_file_pages: Sequence[int]=(),
            flags: SrvRestoreFlag=SrvRestoreFlag.CREATE, role: str | None=None,
            callback: CB_OUTPUT_LINE | None=None, stats: str | None=None,
            verbose: bool=False, verbint: int | None=None, skip_data: str | None=None,
            page_size: int | None=None, buffers: int | None=None,
            access_mode: DbAccessMode=DbAccessMode.READ_WRITE, include_data: str | None=None,
            keyholder: str | None=None, keyname: str | None=None, crypt: str | None=None,
            replica_mode: ReplicaMode | None=None, parallel_workers: int | None=None) -> None:
    """Request database restore from logical (GBAK) backup. **(ASYNC service)**

    Arguments:
        backup: Backup filespec, or list of backup file specifications.
        database: Database specification or alias, or list of those.
        db_file_pages: List of database file sizes (in pages).
        flags: Restore options.
        role: SQL ROLE name passed to gbak.
        callback: Function to call back with each output line.
        stats: Restore statistic options (TDWR).
        verbose: Whether output should be verbose or not.
        verbint: Verbose information with explicit interval (number of records)
        skip_data: String with table names whose data should be excluded from restore.
        page_size: Page size for restored database.
        buffers: Cache size for restored database.
        access_mode: Restored database access mode (R/W or R/O).
        include_data: String with table names whose data should be included into backup [Firebird 4].
        keyholder: Keyholder name [Firebird 4].
        keyname: Key name [Firebird 4]
        crypt: Encryption specification [Firebird 4]
        replica_mode: Replica mode for restored database [Firebird 4]
        parallel_workers: Number of parallel workers [Firebird 5]
    """
    if isinstance(backup, str | Path):
        backup = [backup]
    if isinstance(database, str | Path):
        database = [database]
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.RESTORE)
        for filename in backup:
            spb.insert_string(SrvRestoreOption.FILE, str(filename), encoding=self._srv().encoding)
        for filename, size in itertools.zip_longest(database, db_file_pages):
            spb.insert_string(SPBItem.DBNAME, str(filename), encoding=self._srv().encoding)
            if size is not None:
                spb.insert_int(SrvRestoreOption.LENGTH, size)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        if page_size is not None:
            spb.insert_int(SrvRestoreOption.PAGE_SIZE, page_size)
        if buffers is not None:
            spb.insert_int(SrvRestoreOption.BUFFERS, buffers)
        spb.insert_bytes(SrvRestoreOption.ACCESS_MODE, bytes([access_mode]))
        if skip_data is not None:
            spb.insert_string(SrvRestoreOption.SKIP_DATA, skip_data, encoding=self._srv().encoding)
        if include_data is not None:
            spb.insert_string(SrvRestoreOption.INCLUDE_DATA, include_data, encoding=self._srv().encoding)
        if keyholder is not None:
            spb.insert_string(SrvRestoreOption.KEYHOLDER, keyholder)
        if keyname is not None:
            spb.insert_string(SrvRestoreOption.KEYNAME, keyname)
        if crypt is not None:
            spb.insert_string(SrvRestoreOption.CRYPT, crypt)
        if replica_mode is not None:
            spb.insert_int(SrvRestoreOption.REPLICA_MODE, replica_mode.value)
        if parallel_workers is not None:
            spb.insert_int(SrvRestoreOption.PARALLEL_WORKERS, parallel_workers)
        spb.insert_int(SPBItem.OPTIONS, flags)
        if verbose:
            spb.insert_tag(SPBItem.VERBOSE)
        if verbint is not None:
            spb.insert_int(SPBItem.VERBINT, verbint)
        if stats:
            spb.insert_string(SrvRestoreOption.STAT, stats)
        self._srv()._svc.start(spb.get_buffer())
    if callback:
        for line in self._srv():
            callback(line)

rollback_limbo_transaction(*, database: FILESPEC, transaction_id: int) -> None

Resolve limbo transaction with rollback.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
transaction_id int

ID of Transaction to resolve.

required
Source code in firebird/driver/core.py
def rollback_limbo_transaction(self, *, database: FILESPEC, transaction_id: int) -> None:
    """Resolve limbo transaction with rollback.

    Arguments:
        database: Database specification or alias.
        transaction_id: ID of Transaction to resolve.
    """
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.REPAIR)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if transaction_id <= USHRT_MAX:
            spb.insert_int(SrvRepairOption.ROLLBACK_TRANS, transaction_id)
        else:
            spb.insert_bigint(SrvRepairOption.ROLLBACK_TRANS_64, transaction_id)
        self._srv()._svc.start(spb.get_buffer())
    self._srv()._read_all_binary_output()

set_access_mode(*, database: FILESPEC, mode: DbAccessMode, role: str | None = None) -> None

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

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
mode DbAccessMode

New value.

required
role str | None

SQL ROLE name passed to gfix.

None
Source code in firebird/driver/core.py
def set_access_mode(self, *, database: FILESPEC, mode: DbAccessMode, role: str | None=None) -> None:
    """Set database access mode (R/W or R/O).

    Arguments:
        database: Database specification or alias.
        mode: New value.
        role: SQL ROLE name passed to gfix.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.PROPERTIES)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_bytes(SrvPropertiesOption.ACCESS_MODE, bytes([mode]))
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

set_default_cache_size(*, database: FILESPEC, size: int, role: str | None = None) -> None

Set individual page cache size for database.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
size int

New value.

required
role str | None

SQL ROLE name passed to gfix.

None
Source code in firebird/driver/core.py
def set_default_cache_size(self, *, database: FILESPEC, size: int, role: str | None=None) -> None:
    """Set individual page cache size for database.

    Arguments:
        database: Database specification or alias.
        size: New value.
        role: SQL ROLE name passed to gfix.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.PROPERTIES)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_int(SrvPropertiesOption.PAGE_BUFFERS, size)
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

set_space_reservation(*, database: FILESPEC, mode: DbSpaceReservation, role: str | None = None) -> None

Set space reservation for database.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
mode DbSpaceReservation

New value.

required
role str | None

SQL ROLE name passed to gfix.

None
Source code in firebird/driver/core.py
def set_space_reservation(self, *, database: FILESPEC, mode: DbSpaceReservation,
                          role: str | None=None) -> None:
    """Set space reservation for database.

    Arguments:
        database: Database specification or alias.
        mode: New value.
        role: SQL ROLE name passed to gfix.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.PROPERTIES)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_bytes(SrvPropertiesOption.RESERVE_SPACE,
                         bytes([mode]))
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

set_sql_dialect(*, database: FILESPEC, dialect: int, role: str | None = None) -> None

Set database SQL dialect.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
dialect int

New value.

required
role str | None

SQL ROLE name passed to gfix.

None
Source code in firebird/driver/core.py
def set_sql_dialect(self, *, database: FILESPEC, dialect: int, role: str | None=None) -> None:
    """Set database SQL dialect.

    Arguments:
        database: Database specification or alias.
        dialect: New value.
        role: SQL ROLE name passed to gfix.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.PROPERTIES)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_int(SrvPropertiesOption.SET_SQL_DIALECT, dialect)
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

set_sweep_interval(*, database: FILESPEC, interval: int, role: str | None = None) -> None

Set database sweep interval.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
interval int

New value.

required
role str | None

SQL ROLE name passed to gfix.

None
Source code in firebird/driver/core.py
def set_sweep_interval(self, *, database: FILESPEC, interval: int, role: str | None=None) -> None:
    """Set database sweep interval.

    Arguments:
        database: Database specification or alias.
        interval: New value.
        role: SQL ROLE name passed to gfix.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.PROPERTIES)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_int(SrvPropertiesOption.SWEEP_INTERVAL, interval)
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

set_write_mode(*, database: FILESPEC, mode: DbWriteMode, role: str | None = None) -> None

Set database write mode (SYNC/ASYNC).

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
mode DbWriteMode

New value.

required
role str | None

SQL ROLE name passed to gfix.

None
Source code in firebird/driver/core.py
def set_write_mode(self, *, database: FILESPEC, mode: DbWriteMode, role: str | None=None) -> None:
    """Set database write mode (SYNC/ASYNC).

    Arguments:
        database: Database specification or alias.
        mode: New value.
        role: SQL ROLE name passed to gfix.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.PROPERTIES)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_bytes(SrvPropertiesOption.WRITE_MODE,
                         bytes([mode]))
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

shutdown(*, database: FILESPEC, mode: ShutdownMode, method: ShutdownMethod, timeout: int, role: str | None = None) -> None

Database shutdown.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
mode ShutdownMode

Shutdown mode.

required
method ShutdownMethod

Shutdown method.

required
timeout int

Timeout for shutdown.

required
role str | None

SQL ROLE name passed to gfix.

None
Source code in firebird/driver/core.py
def shutdown(self, *, database: FILESPEC, mode: ShutdownMode,
             method: ShutdownMethod, timeout: int, role: str | None=None) -> None:
    """Database shutdown.

    Arguments:
        database: Database specification or alias.
        mode: Shutdown mode.
        method: Shutdown method.
        timeout: Timeout for shutdown.
        role: SQL ROLE name passed to gfix.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.PROPERTIES)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_bytes(SrvPropertiesOption.SHUTDOWN_MODE, bytes([mode]))
        spb.insert_int(method, timeout)
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

sweep(*, database: FILESPEC, role: str | None = None, parallel_workers: int | None = None) -> None

Perform database sweep operation.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
role str | None

SQL ROLE name passed to gfix.

None
parallel_workers int | None

Number of parallel workers [Firebird 5]

None
Source code in firebird/driver/core.py
def sweep(self, *, database: FILESPEC, role: str | None=None, parallel_workers: int | None=None) -> None:
    """Perform database sweep operation.

    Arguments:
        database: Database specification or alias.
        role: SQL ROLE name passed to gfix.
        parallel_workers: Number of parallel workers [Firebird 5]
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.REPAIR)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        if parallel_workers is not None:
            spb.insert_int(SrvRepairOption.PARALLEL_WORKERS, parallel_workers)
        spb.insert_int(SPBItem.OPTIONS, SrvRepairFlag.SWEEP_DB)
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

validate(*, database: FILESPEC, include_table: str | None = None, exclude_table: str | None = None, include_index: str | None = None, exclude_index: str | None = None, lock_timeout: int | None = None, role: str | None = None, callback: CB_OUTPUT_LINE | None = None) -> None

Perform database validation. (ASYNC service)

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
include_table str | None

Regex pattern for table names to include in validation run.

None
exclude_table str | None

Regex pattern for table names to exclude in validation run.

None
include_index str | None

Regex pattern for index names to include in validation run.

None
exclude_index str | None

Regex pattern for index names to exclude in validation run.

None
lock_timeout int | None

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

None
role str | None

SQL ROLE name passed to gfix.

None
callback CB_OUTPUT_LINE | None

Function to call back with each output line.

None
Source code in firebird/driver/core.py
def validate(self, *, database: FILESPEC, include_table: str | None=None,
             exclude_table: str | None=None, include_index: str | None=None,
             exclude_index: str | None=None, lock_timeout: int | None=None,
             role: str | None=None, callback: CB_OUTPUT_LINE | None=None) -> None:
    """Perform database validation. **(ASYNC service)**

    Arguments:
        database: Database specification or alias.
        include_table: Regex pattern for table names to include in validation run.
        exclude_table: Regex pattern for table names to exclude in validation run.
        include_index: Regex pattern for index names to include in validation run.
        exclude_index: Regex pattern for index names to exclude in validation run.
        lock_timeout: Lock timeout (seconds), used to acquire locks for table to validate,
            default is 10 secs. 0 is no-wait, -1 is infinite wait.
        role: SQL ROLE name passed to gfix.
        callback: Function to call back with each output line.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.VALIDATE)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if include_table is not None:
            spb.insert_string(SrvValidateOption.INCLUDE_TABLE, include_table,
                              encoding=self._srv().encoding)
        if exclude_table is not None:
            spb.insert_string(SrvValidateOption.EXCLUDE_TABLE, exclude_table,
                              encoding=self._srv().encoding)
        if include_index is not None:
            spb.insert_string(SrvValidateOption.INCLUDE_INDEX, include_index,
                              encoding=self._srv().encoding)
        if exclude_index is not None:
            spb.insert_string(SrvValidateOption.EXCLUDE_INDEX, exclude_index,
                              encoding=self._srv().encoding)
        if lock_timeout is not None:
            spb.insert_int(SrvValidateOption.LOCK_TIMEOUT, lock_timeout)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        self._srv()._svc.start(spb.get_buffer())
    if callback:
        for line in self._srv():
            callback(line)

firebird.driver.core.ServerDbServices

Bases: ServerDbServices4

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

Source code in firebird/driver/core.py
class ServerDbServices(ServerDbServices4):
    """Database-related actions and services [Firebird 5+].
    """
    def upgrade(self, *, database: FILESPEC) -> bytes:
        """Perform database ODS upgrade operation.  **(SYNC service)**

        Arguments:
            database: Database specification or alias.
        """
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.REPAIR)
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            spb.insert_int(SPBItem.OPTIONS, SrvRepairFlag.UPGRADE_DB)
            self._srv()._svc.start(spb.get_buffer())
        self._srv().wait()

activate_shadow(*, database: FILESPEC, role: str | None = None) -> None

Activate database shadow.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
role str | None

SQL ROLE name passed to gfix.

None
Source code in firebird/driver/core.py
def activate_shadow(self, *, database: FILESPEC, role: str | None=None) -> None:
    """Activate database shadow.

    Arguments:
        database: Database specification or alias.
        role: SQL ROLE name passed to gfix.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.PROPERTIES)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_int(SPBItem.OPTIONS, SrvPropertiesFlag.ACTIVATE)
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

backup(*, database: FILESPEC, backup: FILESPEC | Sequence[FILESPEC], backup_file_sizes: Sequence[int] = (), flags: SrvBackupFlag = SrvBackupFlag.NONE, role: str | None = None, callback: CB_OUTPUT_LINE | None = None, stats: str | None = None, verbose: bool = False, verbint: int | None = None, skip_data: str | None = None, include_data: str | None = None, keyholder: str | None = None, keyname: str | None = None, crypt: str | None = None, parallel_workers: int | None = None) -> None

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

Parameters:

Name Type Description Default
database FILESPEC

Database file specification or alias.

required
backup FILESPEC | Sequence[FILESPEC]

Backup filespec, or list of backup file specifications.

required
backup_file_sizes Sequence[int]

List of file sizes for backup files.

()
flags SrvBackupFlag

Backup options.

NONE
role str | None

SQL ROLE name passed to gbak.

None
callback CB_OUTPUT_LINE | None

Function to call back with each output line.

None
stats str | None

Backup statistic options (TDWR).

None
verbose bool

Whether output should be verbose or not.

False
verbint int | None

Verbose information with explicit interval (number of records)

None
skip_data str | None

String with table names whose data should be excluded from backup.

None
include_data str | None

String with table names whose data should be included into backup [Firebird 4].

None
keyholder str | None

Keyholder name [Firebird 4].

None
keyname str | None

Key name [Firebird 4]

None
crypt str | None

Encryption specification [Firebird 4]

None
parallel_workers int | None

Number of parallel workers [Firebird 5]

None
Source code in firebird/driver/core.py
def backup(self, *, database: FILESPEC, backup: FILESPEC | Sequence[FILESPEC],
           backup_file_sizes: Sequence[int]=(),
           flags: SrvBackupFlag=SrvBackupFlag.NONE, role: str | None=None,
           callback: CB_OUTPUT_LINE | None=None, stats: str | None=None,
           verbose: bool=False, verbint: int | None=None, skip_data: str | None=None,
           include_data: str | None=None, keyholder: str | None=None, keyname: str | None=None,
           crypt: str | None=None, parallel_workers: int | None=None) -> None:
    """Request logical (GBAK) database backup. **(ASYNC service)**

    Arguments:
        database: Database file specification or alias.
        backup: Backup filespec, or list of backup file specifications.
        backup_file_sizes: List of file sizes for backup files.
        flags: Backup options.
        role: SQL ROLE name passed to gbak.
        callback: Function to call back with each output line.
        stats: Backup statistic options (TDWR).
        verbose: Whether output should be verbose or not.
        verbint: Verbose information with explicit interval (number of records)
        skip_data: String with table names whose data should be excluded from backup.
        include_data: String with table names whose data should be included into backup [Firebird 4].
        keyholder: Keyholder name [Firebird 4].
        keyname: Key name [Firebird 4]
        crypt: Encryption specification [Firebird 4]
        parallel_workers: Number of parallel workers [Firebird 5]
    """
    if isinstance(backup, str | Path):
        backup = [backup]
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.BACKUP)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        for filename, size in itertools.zip_longest(backup, backup_file_sizes):
            spb.insert_string(SrvBackupOption.FILE, str(filename), encoding=self._srv().encoding)
            if size is not None:
                spb.insert_int(SrvBackupOption.LENGTH, size)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        if skip_data is not None:
            spb.insert_string(SrvBackupOption.SKIP_DATA, skip_data)
        if include_data is not None:
            spb.insert_string(SrvBackupOption.INCLUDE_DATA, include_data)
        if keyholder is not None:
            spb.insert_string(SrvBackupOption.KEYHOLDER, keyholder)
        if keyname is not None:
            spb.insert_string(SrvBackupOption.KEYNAME, keyname)
        if crypt is not None:
            spb.insert_string(SrvBackupOption.CRYPT, crypt)
        if parallel_workers is not None:
            spb.insert_int(SrvBackupOption.PARALLEL_WORKERS, parallel_workers)
        spb.insert_int(SPBItem.OPTIONS, flags)
        if verbose:
            spb.insert_tag(SPBItem.VERBOSE)
        if verbint is not None:
            spb.insert_int(SPBItem.VERBINT, verbint)
        if stats:
            spb.insert_string(SrvBackupOption.STAT, stats)
        self._srv()._svc.start(spb.get_buffer())
    if callback:
        for line in self._srv():
            callback(line)

bring_online(*, database: FILESPEC, mode: OnlineMode = OnlineMode.NORMAL, role: str | None = None) -> None

Bring previously shut down database back online.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
mode OnlineMode

Online mode.

NORMAL
role str | None

SQL ROLE name passed to gfix.

None
Source code in firebird/driver/core.py
def bring_online(self, *, database: FILESPEC, mode: OnlineMode=OnlineMode.NORMAL,
                 role: str | None=None) -> None:
    """Bring previously shut down database back online.

    Arguments:
        database: Database specification or alias.
        mode: Online mode.
        role: SQL ROLE name passed to gfix.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.PROPERTIES)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_bytes(SrvPropertiesOption.ONLINE_MODE, bytes([mode]))
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

commit_limbo_transaction(*, database: FILESPEC, transaction_id: int) -> None

Resolve limbo transaction with commit.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
transaction_id int

ID of Transaction to resolve.

required
Source code in firebird/driver/core.py
def commit_limbo_transaction(self, *, database: FILESPEC, transaction_id: int) -> None:
    """Resolve limbo transaction with commit.

    Arguments:
        database: Database specification or alias.
        transaction_id: ID of Transaction to resolve.
    """
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.REPAIR)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if transaction_id <= USHRT_MAX:
            spb.insert_int(SrvRepairOption.COMMIT_TRANS, transaction_id)
        else:
            spb.insert_bigint(SrvRepairOption.COMMIT_TRANS_64, transaction_id)
        self._srv()._svc.start(spb.get_buffer())
    self._srv()._read_all_binary_output()

get_limbo_transaction_ids(*, database: FILESPEC) -> list[int]

Returns list of transactions in limbo.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
Source code in firebird/driver/core.py
def get_limbo_transaction_ids(self, *, database: FILESPEC) -> list[int]: # noqa: ARG002
    """Returns list of transactions in limbo.

    Arguments:
        database: Database specification or alias.
    """
    raise NotSupportedError("Feature not yet implemented")

get_statistics(*, database: FILESPEC, flags: SrvStatFlag = SrvStatFlag.DEFAULT, role: str | None = None, tables: Sequence[str] | None = None, callback: CB_OUTPUT_LINE | None = None) -> None

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

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
flags SrvStatFlag

Flags indicating which statistics shall be collected.

DEFAULT
role str | None

SQL ROLE name passed to gstat.

None
tables Sequence[str] | None

List of database tables whose statistics are to be collected.

None
callback CB_OUTPUT_LINE | None

Function to call back with each output line.

None
Source code in firebird/driver/core.py
def get_statistics(self, *, database: FILESPEC,
                   flags: SrvStatFlag=SrvStatFlag.DEFAULT, role: str | None=None,
                   tables: Sequence[str] | None=None, callback: CB_OUTPUT_LINE | None=None) -> None:
    """Return database statistics produced by gstat utility. **(ASYNC service)**

    Arguments:
        database: Database specification or alias.
        flags: Flags indicating which statistics shall be collected.
        role: SQL ROLE name passed to gstat.
        tables: List of database tables whose statistics are to be collected.
        callback: Function to call back with each output line.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.DB_STATS)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        spb.insert_int(SPBItem.OPTIONS, flags)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        if tables is not None:
            for table in tables:
                spb.insert_string(64, table, encoding=self._srv().encoding) # isc_spb_sts_table = 64
        self._srv()._svc.start(spb.get_buffer())
    if callback:
        for line in self._srv():
            callback(line)

local_backup(*, database: FILESPEC, backup_stream: BinaryIO, flags: SrvBackupFlag = SrvBackupFlag.NONE, role: str | None = None, skip_data: str | None = None, include_data: str | None = None, keyholder: str | None = None, keyname: str | None = None, crypt: str | None = None) -> None

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

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
backup_stream BinaryIO

Binary stream to which the backup is to be written.

required
flags SrvBackupFlag

Backup options.

NONE
role str | None

SQL ROLE name passed to gbak.

None
skip_data str | None

String with table names whose data should be excluded from backup.

None
include_data str | None

String with table names whose data should be included into backup [Firebird 4].

None
keyholder str | None

Keyholder name [Firebird 4].

None
keyname str | None

Key name [Firebird 4]

None
crypt str | None

Encryption specification [Firebird 4]

None
Source code in firebird/driver/core.py
def local_backup(self, *, database: FILESPEC, backup_stream: BinaryIO,
                 flags: SrvBackupFlag=SrvBackupFlag.NONE, role: str | None=None,
                 skip_data: str | None=None, include_data: str | None=None, keyholder: str | None=None,
                 keyname: str | None=None, crypt: str | None=None) -> None:
    """Request logical (GBAK) database backup into local byte stream. **(SYNC service)**

    Arguments:
        database: Database specification or alias.
        backup_stream: Binary stream to which the backup is to be written.
        flags: Backup options.
        role: SQL ROLE name passed to gbak.
        skip_data: String with table names whose data should be excluded from backup.
        include_data: String with table names whose data should be included into backup [Firebird 4].
        keyholder: Keyholder name [Firebird 4].
        keyname: Key name [Firebird 4]
        crypt: Encryption specification [Firebird 4]
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.BACKUP)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        spb.insert_string(SrvBackupOption.FILE, 'stdout')
        spb.insert_int(SPBItem.OPTIONS, flags)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        if skip_data is not None:
            spb.insert_string(SrvBackupOption.SKIP_DATA, skip_data,
                              encoding=self._srv().encoding)
        if include_data is not None:
            spb.insert_string(SrvBackupOption.INCLUDE_DATA, include_data,
                              encoding=self._srv().encoding)
        if keyholder is not None:
            spb.insert_string(SrvBackupOption.KEYHOLDER, keyholder)
        if keyname is not None:
            spb.insert_string(SrvBackupOption.KEYNAME, keyname)
        if crypt is not None:
            spb.insert_string(SrvBackupOption.CRYPT, crypt)
        self._srv()._svc.start(spb.get_buffer())
    while not self._srv()._eof:
        backup_stream.write(self._srv()._read_next_binary_output())

local_restore(*, backup_stream: BinaryIO, database: FILESPEC | Sequence[FILESPEC], db_file_pages: Sequence[int] = (), flags: SrvRestoreFlag = SrvRestoreFlag.CREATE, role: str | None = None, skip_data: str | None = None, page_size: int | None = None, buffers: int | None = None, access_mode: DbAccessMode = DbAccessMode.READ_WRITE, include_data: str | None = None, keyholder: str | None = None, keyname: str | None = None, crypt: str | None = None, replica_mode: ReplicaMode | None = None) -> None

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

Parameters:

Name Type Description Default
backup_stream BinaryIO

Binary stream with the backup.

required
database FILESPEC | Sequence[FILESPEC]

Database specification or alias, or list of those.

required
db_file_pages Sequence[int]

List of database file sizes (in pages).

()
flags SrvRestoreFlag

Restore options.

CREATE
role str | None

SQL ROLE name passed to gbak.

None
skip_data str | None

String with table names whose data should be excluded from restore.

None
page_size int | None

Page size for restored database.

None
buffers int | None

Cache size for restored database.

None
access_mode DbAccessMode

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

READ_WRITE
include_data str | None

String with table names whose data should be included into backup [Firebird 4].

None
keyholder str | None

Keyholder name [Firebird 4].

None
keyname str | None

Key name [Firebird 4]

None
crypt str | None

Encryption specification [Firebird 4]

None
replica_mode ReplicaMode | None

Replica mode for restored database [Firebird 4]

None
Source code in firebird/driver/core.py
def local_restore(self, *, backup_stream: BinaryIO,
                  database: FILESPEC | Sequence[FILESPEC],
                  db_file_pages: Sequence[int]=(),
                  flags: SrvRestoreFlag=SrvRestoreFlag.CREATE, role: str | None=None,
                  skip_data: str | None=None, page_size: int | None=None, buffers: int | None=None,
                  access_mode: DbAccessMode=DbAccessMode.READ_WRITE,
                  include_data: str | None=None, keyholder: str | None=None, keyname: str | None=None,
                  crypt: str | None=None, replica_mode: ReplicaMode | None=None) -> None:
    """Request database restore from logical (GBAK) backup stored in local byte stream.
    **(SYNC service)**

    Arguments:
        backup_stream: Binary stream with the backup.
        database: Database specification or alias, or list of those.
        db_file_pages: List of database file sizes (in pages).
        flags: Restore options.
        role: SQL ROLE name passed to gbak.
        skip_data: String with table names whose data should be excluded from restore.
        page_size: Page size for restored database.
        buffers: Cache size for restored database.
        access_mode: Restored database access mode (R/W or R/O).
        include_data: String with table names whose data should be included into backup [Firebird 4].
        keyholder: Keyholder name [Firebird 4].
        keyname: Key name [Firebird 4]
        crypt: Encryption specification [Firebird 4]
        replica_mode: Replica mode for restored database [Firebird 4]
    """
    if isinstance(database, str | Path):
        database = [database]
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.RESTORE)
        spb.insert_string(SrvRestoreOption.FILE, 'stdin')
        for filename, size in itertools.zip_longest(database, db_file_pages):
            spb.insert_string(SPBItem.DBNAME, str(filename), encoding=self._srv().encoding)
            if size is not None:
                spb.insert_int(SrvRestoreOption.LENGTH, size)
        if page_size is not None:
            spb.insert_int(SrvRestoreOption.PAGE_SIZE, page_size)
        if buffers is not None:
            spb.insert_int(SrvRestoreOption.BUFFERS, buffers)
        spb.insert_bytes(SrvRestoreOption.ACCESS_MODE, bytes([access_mode]))
        if skip_data is not None:
            spb.insert_string(SrvRestoreOption.SKIP_DATA, skip_data,
                              encoding=self._srv().encoding)
        if include_data is not None:
            spb.insert_string(SrvRestoreOption.INCLUDE_DATA, include_data,
                              encoding=self._srv().encoding)
        if keyholder is not None:
            spb.insert_string(SrvRestoreOption.KEYHOLDER, keyholder)
        if keyname is not None:
            spb.insert_string(SrvRestoreOption.KEYNAME, keyname)
        if crypt is not None:
            spb.insert_string(SrvRestoreOption.CRYPT, crypt)
        if replica_mode is not None:
            spb.insert_int(SrvRestoreOption.REPLICA_MODE, replica_mode.value)
        spb.insert_int(SPBItem.OPTIONS, flags)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        self._srv()._svc.start(spb.get_buffer())
    #
    request_length = 0
    line = ''
    keep_going = True
    while keep_going:
        no_data = False
        self._srv().response.clear()
        if request_length > 0:
            request_length = min([request_length, 65500])
            raw = backup_stream.read(request_length)
            send = b''.join([SrvInfoCode.LINE.to_bytes(1, 'little'),
                             len(raw).to_bytes(2, 'little'), raw,
                             isc_info_end.to_bytes(1, 'little')])
        else:
            send = None
        self._srv()._svc.query(send, bytes([SrvInfoCode.STDIN, SrvInfoCode.LINE]),
                               self._srv().response.raw)
        tag = self._srv().response.get_tag()
        while tag != isc_info_end:
            if tag == SrvInfoCode.STDIN:
                request_length = self._srv().response.read_int()
            elif tag == SrvInfoCode.LINE:
                line = self._srv().response.read_sized_string(encoding=self._srv().encoding)
            elif tag == isc_info_data_not_ready:
                no_data = True
            else:  # pragma: no cover
                raise InterfaceError(f"Service responded with error code: {tag}")
            tag = self._srv().response.get_tag()
        keep_going = no_data or request_length != 0 or line

nbackup(*, database: FILESPEC, backup: FILESPEC, level: int = 0, direct: bool | None = None, flags: SrvNBackupFlag = SrvNBackupFlag.NONE, role: str | None = None, guid: str | None = None) -> None

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

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
backup FILESPEC

Backup file specification.

required
level int

Backup level.

0
direct bool | None

Direct I/O override.

None
flags SrvNBackupFlag

Backup options.

NONE
role str | None

SQL ROLE name passed to nbackup.

None
guid str | None

Database backup GUID.

None
Important

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

Source code in firebird/driver/core.py
def nbackup(self, *, database: FILESPEC, backup: FILESPEC, level: int=0,
            direct: bool | None=None, flags: SrvNBackupFlag=SrvNBackupFlag.NONE,
            role: str | None=None, guid: str | None=None) -> None:
    """Perform physical (NBACKUP) database backup. **(SYNC service)**

    Arguments:
        database: Database specification or alias.
        backup: Backup file specification.
        level: Backup level.
        direct: Direct I/O override.
        flags: Backup options.
        role: SQL ROLE name passed to nbackup.
        guid: Database backup GUID.

    Important:
        Parameters `level` and `guid` are mutually exclusive. If `guid` is specified,
        then `level` value is ignored.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.NBAK)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        spb.insert_string(SrvNBackupOption.FILE, str(backup), encoding=self._srv().encoding)
        if guid is not None:
            spb.insert_string(SrvNBackupOption.GUID, guid)
        else:
            spb.insert_int(SrvNBackupOption.LEVEL, level)
        if direct is not None:
            spb.insert_string(SrvNBackupOption.DIRECT, 'ON' if direct else 'OFF')
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_int(SPBItem.OPTIONS, flags)
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

nfix_database(*, database: FILESPEC, role: str | None = None, flags: SrvNBackupFlag = SrvNBackupFlag.NONE) -> None

Fixup database after filesystem copy.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
role str | None

SQL ROLE name passed to nbackup.

None
flags SrvNBackupFlag

Backup options.

NONE
Source code in firebird/driver/core.py
def nfix_database(self, *, database: FILESPEC, role: str | None=None,
                  flags: SrvNBackupFlag=SrvNBackupFlag.NONE) -> None:
    """Fixup database after filesystem copy.

    Arguments:
        database: Database specification or alias.
        role: SQL ROLE name passed to nbackup.
        flags: Backup options.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_tag(ServerAction.NFIX)
        spb.insert_int(SPBItem.OPTIONS, flags)
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

no_linger(*, database: FILESPEC, role: str | None = None) -> None

Set one-off override for database linger.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
role str | None

SQL ROLE name passed to gfix.

None
Source code in firebird/driver/core.py
def no_linger(self, *, database: FILESPEC, role: str | None=None) -> None:
    """Set one-off override for database linger.

    Arguments:
        database: Database specification or alias.
        role: SQL ROLE name passed to gfix.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.PROPERTIES)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_int(SPBItem.OPTIONS, SrvPropertiesFlag.NOLINGER)
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

nrestore(*, backups: Sequence[FILESPEC], database: FILESPEC, direct: bool = False, flags: SrvNBackupFlag = SrvNBackupFlag.NONE, role: str | None = None) -> None

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

Parameters:

Name Type Description Default
backups Sequence[FILESPEC]

Backup file(s) specification.

required
database FILESPEC

Database specification or alias.

required
direct bool

Direct I/O override.

False
flags SrvNBackupFlag

Restore options.

NONE
role str | None

SQL ROLE name passed to nbackup.

None
Source code in firebird/driver/core.py
def nrestore(self, *, backups: Sequence[FILESPEC], database: FILESPEC,
             direct: bool=False, flags: SrvNBackupFlag=SrvNBackupFlag.NONE,
             role: str | None=None) -> None:
    """Perform restore from physical (NBACKUP) database backup.  **(SYNC service)**

    Arguments:
        backups: Backup file(s) specification.
        database: Database specification or alias.
        direct: Direct I/O override.
        flags: Restore options.
        role: SQL ROLE name passed to nbackup.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.NREST)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        for backup in backups:
            spb.insert_string(SrvNBackupOption.FILE, str(backup), encoding=self._srv().encoding)
        if direct is not None:
            spb.insert_string(SrvNBackupOption.DIRECT, 'ON' if direct else 'OFF')
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_int(SPBItem.OPTIONS, flags)
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

repair(*, database: FILESPEC, flags: SrvRepairFlag = SrvRepairFlag.REPAIR, role: str | None = None) -> None

Perform database repair operation. (SYNC service)

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
flags SrvRepairFlag

Repair flags.

REPAIR
role str | None

SQL ROLE name passed to gfix.

None
Source code in firebird/driver/core.py
def repair(self, *, database: FILESPEC, flags: SrvRepairFlag=SrvRepairFlag.REPAIR,
           role: str | None=None) -> None:
    """Perform database repair operation.  **(SYNC service)**

    Arguments:
        database: Database specification or alias.
        flags: Repair flags.
        role: SQL ROLE name passed to gfix.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.REPAIR)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_int(SPBItem.OPTIONS, flags)
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

restore(*, backup: FILESPEC | Sequence[FILESPEC], database: FILESPEC | Sequence[FILESPEC], db_file_pages: Sequence[int] = (), flags: SrvRestoreFlag = SrvRestoreFlag.CREATE, role: str | None = None, callback: CB_OUTPUT_LINE | None = None, stats: str | None = None, verbose: bool = False, verbint: int | None = None, skip_data: str | None = None, page_size: int | None = None, buffers: int | None = None, access_mode: DbAccessMode = DbAccessMode.READ_WRITE, include_data: str | None = None, keyholder: str | None = None, keyname: str | None = None, crypt: str | None = None, replica_mode: ReplicaMode | None = None, parallel_workers: int | None = None) -> None

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

Parameters:

Name Type Description Default
backup FILESPEC | Sequence[FILESPEC]

Backup filespec, or list of backup file specifications.

required
database FILESPEC | Sequence[FILESPEC]

Database specification or alias, or list of those.

required
db_file_pages Sequence[int]

List of database file sizes (in pages).

()
flags SrvRestoreFlag

Restore options.

CREATE
role str | None

SQL ROLE name passed to gbak.

None
callback CB_OUTPUT_LINE | None

Function to call back with each output line.

None
stats str | None

Restore statistic options (TDWR).

None
verbose bool

Whether output should be verbose or not.

False
verbint int | None

Verbose information with explicit interval (number of records)

None
skip_data str | None

String with table names whose data should be excluded from restore.

None
page_size int | None

Page size for restored database.

None
buffers int | None

Cache size for restored database.

None
access_mode DbAccessMode

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

READ_WRITE
include_data str | None

String with table names whose data should be included into backup [Firebird 4].

None
keyholder str | None

Keyholder name [Firebird 4].

None
keyname str | None

Key name [Firebird 4]

None
crypt str | None

Encryption specification [Firebird 4]

None
replica_mode ReplicaMode | None

Replica mode for restored database [Firebird 4]

None
parallel_workers int | None

Number of parallel workers [Firebird 5]

None
Source code in firebird/driver/core.py
def restore(self, *, backup: FILESPEC | Sequence[FILESPEC],
            database: FILESPEC | Sequence[FILESPEC],
            db_file_pages: Sequence[int]=(),
            flags: SrvRestoreFlag=SrvRestoreFlag.CREATE, role: str | None=None,
            callback: CB_OUTPUT_LINE | None=None, stats: str | None=None,
            verbose: bool=False, verbint: int | None=None, skip_data: str | None=None,
            page_size: int | None=None, buffers: int | None=None,
            access_mode: DbAccessMode=DbAccessMode.READ_WRITE, include_data: str | None=None,
            keyholder: str | None=None, keyname: str | None=None, crypt: str | None=None,
            replica_mode: ReplicaMode | None=None, parallel_workers: int | None=None) -> None:
    """Request database restore from logical (GBAK) backup. **(ASYNC service)**

    Arguments:
        backup: Backup filespec, or list of backup file specifications.
        database: Database specification or alias, or list of those.
        db_file_pages: List of database file sizes (in pages).
        flags: Restore options.
        role: SQL ROLE name passed to gbak.
        callback: Function to call back with each output line.
        stats: Restore statistic options (TDWR).
        verbose: Whether output should be verbose or not.
        verbint: Verbose information with explicit interval (number of records)
        skip_data: String with table names whose data should be excluded from restore.
        page_size: Page size for restored database.
        buffers: Cache size for restored database.
        access_mode: Restored database access mode (R/W or R/O).
        include_data: String with table names whose data should be included into backup [Firebird 4].
        keyholder: Keyholder name [Firebird 4].
        keyname: Key name [Firebird 4]
        crypt: Encryption specification [Firebird 4]
        replica_mode: Replica mode for restored database [Firebird 4]
        parallel_workers: Number of parallel workers [Firebird 5]
    """
    if isinstance(backup, str | Path):
        backup = [backup]
    if isinstance(database, str | Path):
        database = [database]
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.RESTORE)
        for filename in backup:
            spb.insert_string(SrvRestoreOption.FILE, str(filename), encoding=self._srv().encoding)
        for filename, size in itertools.zip_longest(database, db_file_pages):
            spb.insert_string(SPBItem.DBNAME, str(filename), encoding=self._srv().encoding)
            if size is not None:
                spb.insert_int(SrvRestoreOption.LENGTH, size)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        if page_size is not None:
            spb.insert_int(SrvRestoreOption.PAGE_SIZE, page_size)
        if buffers is not None:
            spb.insert_int(SrvRestoreOption.BUFFERS, buffers)
        spb.insert_bytes(SrvRestoreOption.ACCESS_MODE, bytes([access_mode]))
        if skip_data is not None:
            spb.insert_string(SrvRestoreOption.SKIP_DATA, skip_data, encoding=self._srv().encoding)
        if include_data is not None:
            spb.insert_string(SrvRestoreOption.INCLUDE_DATA, include_data, encoding=self._srv().encoding)
        if keyholder is not None:
            spb.insert_string(SrvRestoreOption.KEYHOLDER, keyholder)
        if keyname is not None:
            spb.insert_string(SrvRestoreOption.KEYNAME, keyname)
        if crypt is not None:
            spb.insert_string(SrvRestoreOption.CRYPT, crypt)
        if replica_mode is not None:
            spb.insert_int(SrvRestoreOption.REPLICA_MODE, replica_mode.value)
        if parallel_workers is not None:
            spb.insert_int(SrvRestoreOption.PARALLEL_WORKERS, parallel_workers)
        spb.insert_int(SPBItem.OPTIONS, flags)
        if verbose:
            spb.insert_tag(SPBItem.VERBOSE)
        if verbint is not None:
            spb.insert_int(SPBItem.VERBINT, verbint)
        if stats:
            spb.insert_string(SrvRestoreOption.STAT, stats)
        self._srv()._svc.start(spb.get_buffer())
    if callback:
        for line in self._srv():
            callback(line)

rollback_limbo_transaction(*, database: FILESPEC, transaction_id: int) -> None

Resolve limbo transaction with rollback.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
transaction_id int

ID of Transaction to resolve.

required
Source code in firebird/driver/core.py
def rollback_limbo_transaction(self, *, database: FILESPEC, transaction_id: int) -> None:
    """Resolve limbo transaction with rollback.

    Arguments:
        database: Database specification or alias.
        transaction_id: ID of Transaction to resolve.
    """
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.REPAIR)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if transaction_id <= USHRT_MAX:
            spb.insert_int(SrvRepairOption.ROLLBACK_TRANS, transaction_id)
        else:
            spb.insert_bigint(SrvRepairOption.ROLLBACK_TRANS_64, transaction_id)
        self._srv()._svc.start(spb.get_buffer())
    self._srv()._read_all_binary_output()

set_access_mode(*, database: FILESPEC, mode: DbAccessMode, role: str | None = None) -> None

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

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
mode DbAccessMode

New value.

required
role str | None

SQL ROLE name passed to gfix.

None
Source code in firebird/driver/core.py
def set_access_mode(self, *, database: FILESPEC, mode: DbAccessMode, role: str | None=None) -> None:
    """Set database access mode (R/W or R/O).

    Arguments:
        database: Database specification or alias.
        mode: New value.
        role: SQL ROLE name passed to gfix.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.PROPERTIES)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_bytes(SrvPropertiesOption.ACCESS_MODE, bytes([mode]))
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

set_default_cache_size(*, database: FILESPEC, size: int, role: str | None = None) -> None

Set individual page cache size for database.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
size int

New value.

required
role str | None

SQL ROLE name passed to gfix.

None
Source code in firebird/driver/core.py
def set_default_cache_size(self, *, database: FILESPEC, size: int, role: str | None=None) -> None:
    """Set individual page cache size for database.

    Arguments:
        database: Database specification or alias.
        size: New value.
        role: SQL ROLE name passed to gfix.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.PROPERTIES)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_int(SrvPropertiesOption.PAGE_BUFFERS, size)
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

set_replica_mode(*, database: FILESPEC, mode: ReplicaMode, role: str | None = None) -> None

Manage replica database.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
mode ReplicaMode

New replication mode.

required
role str | None

SQL ROLE name passed to gfix.

None
Source code in firebird/driver/core.py
def set_replica_mode(self, *, database: FILESPEC, mode: ReplicaMode, role: str | None=None) -> None:
    """Manage replica database.

    Arguments:
        database: Database specification or alias.
        mode: New replication mode.
        role: SQL ROLE name passed to gfix.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.PROPERTIES)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_bytes(SrvPropertiesOption.REPLICA_MODE, bytes([mode]))
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

set_space_reservation(*, database: FILESPEC, mode: DbSpaceReservation, role: str | None = None) -> None

Set space reservation for database.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
mode DbSpaceReservation

New value.

required
role str | None

SQL ROLE name passed to gfix.

None
Source code in firebird/driver/core.py
def set_space_reservation(self, *, database: FILESPEC, mode: DbSpaceReservation,
                          role: str | None=None) -> None:
    """Set space reservation for database.

    Arguments:
        database: Database specification or alias.
        mode: New value.
        role: SQL ROLE name passed to gfix.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.PROPERTIES)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_bytes(SrvPropertiesOption.RESERVE_SPACE,
                         bytes([mode]))
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

set_sql_dialect(*, database: FILESPEC, dialect: int, role: str | None = None) -> None

Set database SQL dialect.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
dialect int

New value.

required
role str | None

SQL ROLE name passed to gfix.

None
Source code in firebird/driver/core.py
def set_sql_dialect(self, *, database: FILESPEC, dialect: int, role: str | None=None) -> None:
    """Set database SQL dialect.

    Arguments:
        database: Database specification or alias.
        dialect: New value.
        role: SQL ROLE name passed to gfix.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.PROPERTIES)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_int(SrvPropertiesOption.SET_SQL_DIALECT, dialect)
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

set_sweep_interval(*, database: FILESPEC, interval: int, role: str | None = None) -> None

Set database sweep interval.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
interval int

New value.

required
role str | None

SQL ROLE name passed to gfix.

None
Source code in firebird/driver/core.py
def set_sweep_interval(self, *, database: FILESPEC, interval: int, role: str | None=None) -> None:
    """Set database sweep interval.

    Arguments:
        database: Database specification or alias.
        interval: New value.
        role: SQL ROLE name passed to gfix.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.PROPERTIES)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_int(SrvPropertiesOption.SWEEP_INTERVAL, interval)
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

set_write_mode(*, database: FILESPEC, mode: DbWriteMode, role: str | None = None) -> None

Set database write mode (SYNC/ASYNC).

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
mode DbWriteMode

New value.

required
role str | None

SQL ROLE name passed to gfix.

None
Source code in firebird/driver/core.py
def set_write_mode(self, *, database: FILESPEC, mode: DbWriteMode, role: str | None=None) -> None:
    """Set database write mode (SYNC/ASYNC).

    Arguments:
        database: Database specification or alias.
        mode: New value.
        role: SQL ROLE name passed to gfix.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.PROPERTIES)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_bytes(SrvPropertiesOption.WRITE_MODE,
                         bytes([mode]))
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

shutdown(*, database: FILESPEC, mode: ShutdownMode, method: ShutdownMethod, timeout: int, role: str | None = None) -> None

Database shutdown.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
mode ShutdownMode

Shutdown mode.

required
method ShutdownMethod

Shutdown method.

required
timeout int

Timeout for shutdown.

required
role str | None

SQL ROLE name passed to gfix.

None
Source code in firebird/driver/core.py
def shutdown(self, *, database: FILESPEC, mode: ShutdownMode,
             method: ShutdownMethod, timeout: int, role: str | None=None) -> None:
    """Database shutdown.

    Arguments:
        database: Database specification or alias.
        mode: Shutdown mode.
        method: Shutdown method.
        timeout: Timeout for shutdown.
        role: SQL ROLE name passed to gfix.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.PROPERTIES)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        spb.insert_bytes(SrvPropertiesOption.SHUTDOWN_MODE, bytes([mode]))
        spb.insert_int(method, timeout)
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

sweep(*, database: FILESPEC, role: str | None = None, parallel_workers: int | None = None) -> None

Perform database sweep operation.

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
role str | None

SQL ROLE name passed to gfix.

None
parallel_workers int | None

Number of parallel workers [Firebird 5]

None
Source code in firebird/driver/core.py
def sweep(self, *, database: FILESPEC, role: str | None=None, parallel_workers: int | None=None) -> None:
    """Perform database sweep operation.

    Arguments:
        database: Database specification or alias.
        role: SQL ROLE name passed to gfix.
        parallel_workers: Number of parallel workers [Firebird 5]
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.REPAIR)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        if parallel_workers is not None:
            spb.insert_int(SrvRepairOption.PARALLEL_WORKERS, parallel_workers)
        spb.insert_int(SPBItem.OPTIONS, SrvRepairFlag.SWEEP_DB)
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

upgrade(*, database: FILESPEC) -> bytes

Perform database ODS upgrade operation. (SYNC service)

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
Source code in firebird/driver/core.py
def upgrade(self, *, database: FILESPEC) -> bytes:
    """Perform database ODS upgrade operation.  **(SYNC service)**

    Arguments:
        database: Database specification or alias.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.REPAIR)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        spb.insert_int(SPBItem.OPTIONS, SrvRepairFlag.UPGRADE_DB)
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

validate(*, database: FILESPEC, include_table: str | None = None, exclude_table: str | None = None, include_index: str | None = None, exclude_index: str | None = None, lock_timeout: int | None = None, role: str | None = None, callback: CB_OUTPUT_LINE | None = None) -> None

Perform database validation. (ASYNC service)

Parameters:

Name Type Description Default
database FILESPEC

Database specification or alias.

required
include_table str | None

Regex pattern for table names to include in validation run.

None
exclude_table str | None

Regex pattern for table names to exclude in validation run.

None
include_index str | None

Regex pattern for index names to include in validation run.

None
exclude_index str | None

Regex pattern for index names to exclude in validation run.

None
lock_timeout int | None

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

None
role str | None

SQL ROLE name passed to gfix.

None
callback CB_OUTPUT_LINE | None

Function to call back with each output line.

None
Source code in firebird/driver/core.py
def validate(self, *, database: FILESPEC, include_table: str | None=None,
             exclude_table: str | None=None, include_index: str | None=None,
             exclude_index: str | None=None, lock_timeout: int | None=None,
             role: str | None=None, callback: CB_OUTPUT_LINE | None=None) -> None:
    """Perform database validation. **(ASYNC service)**

    Arguments:
        database: Database specification or alias.
        include_table: Regex pattern for table names to include in validation run.
        exclude_table: Regex pattern for table names to exclude in validation run.
        include_index: Regex pattern for index names to include in validation run.
        exclude_index: Regex pattern for index names to exclude in validation run.
        lock_timeout: Lock timeout (seconds), used to acquire locks for table to validate,
            default is 10 secs. 0 is no-wait, -1 is infinite wait.
        role: SQL ROLE name passed to gfix.
        callback: Function to call back with each output line.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.VALIDATE)
        spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if include_table is not None:
            spb.insert_string(SrvValidateOption.INCLUDE_TABLE, include_table,
                              encoding=self._srv().encoding)
        if exclude_table is not None:
            spb.insert_string(SrvValidateOption.EXCLUDE_TABLE, exclude_table,
                              encoding=self._srv().encoding)
        if include_index is not None:
            spb.insert_string(SrvValidateOption.INCLUDE_INDEX, include_index,
                              encoding=self._srv().encoding)
        if exclude_index is not None:
            spb.insert_string(SrvValidateOption.EXCLUDE_INDEX, exclude_index,
                              encoding=self._srv().encoding)
        if lock_timeout is not None:
            spb.insert_int(SrvValidateOption.LOCK_TIMEOUT, lock_timeout)
        if role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, role, encoding=self._srv().encoding)
        self._srv()._svc.start(spb.get_buffer())
    if callback:
        for line in self._srv():
            callback(line)

firebird.driver.core.ServerUserServices

Bases: ServerServiceProvider

User-related actions and services.

Source code in firebird/driver/core.py
class ServerUserServices(ServerServiceProvider):
    """User-related actions and services.
    """
    def __fetch_users(self, data: Buffer) -> list[UserInfo]:
        users = []
        user = {}
        while not data.is_eof():
            tag = data.get_tag()
            if tag == SrvUserOption.USER_NAME:
                if user:
                    users.append(UserInfo(**user))
                    user.clear()
                user['user_name'] = data.read_sized_string(encoding=self._srv().encoding)
            elif tag == SrvUserOption.USER_ID:
                user['user_id'] = data.read_int()
            elif tag == SrvUserOption.GROUP_ID:
                user['group_id'] = data.read_int()
            elif tag == SrvUserOption.PASSWORD:  # pragma: no cover
                user['password'] = data.read_bytes()
            elif tag == SrvUserOption.GROUP_NAME:  # pragma: no cover
                user['group_name'] = data.read_sized_string(encoding=self._srv().encoding)
            elif tag == SrvUserOption.FIRST_NAME:
                user['first_name'] = data.read_sized_string(encoding=self._srv().encoding)
            elif tag == SrvUserOption.MIDDLE_NAME:
                user['middle_name'] = data.read_sized_string(encoding=self._srv().encoding)
            elif tag == SrvUserOption.LAST_NAME:
                user['last_name'] = data.read_sized_string(encoding=self._srv().encoding)
            elif tag == SrvUserOption.ADMIN:
                user['admin'] = bool(data.read_int())
            else:  # pragma: no cover
                raise InterfaceError(f"Unrecognized result clumplet: {tag}")
        if user:
            users.append(UserInfo(**user))
        return users
    def get_all(self, *, database: FILESPEC | None=None, sql_role: str | None=None) -> list[UserInfo]:
        """Get information about users.

        Arguments:
            database: Database specification or alias.
            sql_role: SQL role name.
        """
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.DISPLAY_USER_ADM)
            if database is not None:
                spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            if sql_role is not None:
                spb.insert_string(SPBItem.SQL_ROLE_NAME, sql_role,
                                  encoding=self._srv().encoding)
            self._srv()._svc.start(spb.get_buffer())
        return self.__fetch_users(Buffer(self._srv()._read_all_binary_output()))
    def get(self, user_name: str, *, database: FILESPEC | None=None, sql_role: str | None=None) -> UserInfo | None:
        """Get information about user.

        Arguments:
            user_name: User name.
            database: Database specification or alias.
            sql_role: SQL role name.
        """
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.DISPLAY_USER_ADM)
            if database is not None:
                spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            spb.insert_string(SrvUserOption.USER_NAME, user_name, encoding=self._srv().encoding)
            if sql_role is not None:
                spb.insert_string(SPBItem.SQL_ROLE_NAME, sql_role, encoding=self._srv().encoding)
            self._srv()._svc.start(spb.get_buffer())
        users = self.__fetch_users(Buffer(self._srv()._read_all_binary_output()))
        return users[0] if users else None
    def add(self, *, user_name: str, password: str, user_id: int | None=None,
                 group_id: int | None=None, first_name: str | None=None, middle_name: str | None=None,
                 last_name: str | None=None, admin: bool | None=None, database: FILESPEC | None=None,
                 sql_role: str | None=None) -> None:
        """Add new user.

        Arguments:
            user_name: User name.
            password: User password.
            user_id: User ID.
            group_id: Group ID.
            first_name: User's first name.
            middle_name: User's middle name.
            last_name: User's last name.
            admin: Admin flag.
            database: Database specification or alias.
            sql_role: SQL role name.
        """
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.ADD_USER)
            if database is not None:
                spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            spb.insert_string(SrvUserOption.USER_NAME, user_name, encoding=self._srv().encoding)
            if sql_role is not None:
                spb.insert_string(SPBItem.SQL_ROLE_NAME, sql_role, encoding=self._srv().encoding)
            spb.insert_string(SrvUserOption.PASSWORD, password,
                              encoding=self._srv().encoding)
            if user_id is not None:
                spb.insert_int(SrvUserOption.USER_ID, user_id)
            if group_id is not None:
                spb.insert_int(SrvUserOption.GROUP_ID, group_id)
            if first_name is not None:
                spb.insert_string(SrvUserOption.FIRST_NAME, first_name,
                                  encoding=self._srv().encoding)
            if middle_name is not None:
                spb.insert_string(SrvUserOption.MIDDLE_NAME, middle_name,
                                  encoding=self._srv().encoding)
            if last_name is not None:
                spb.insert_string(SrvUserOption.LAST_NAME, last_name,
                                  encoding=self._srv().encoding)
            if admin is not None:
                spb.insert_int(SrvUserOption.ADMIN, 1 if admin else 0)
            self._srv()._svc.start(spb.get_buffer())
        self._srv().wait()
    def update(self, user_name: str, *, password: str | None=None,
                    user_id: int | None=None, group_id: int | None=None,
                    first_name: str | None=None, middle_name: str | None=None,
                    last_name: str | None=None, admin: bool | None=None, database: FILESPEC | None=None) -> None:
        """Update user information.

        Arguments:
            user_name: User name.
            password: User password.
            user_id: User ID.
            group_id: Group ID.
            first_name: User's first name.
            middle_name: User's middle name.
            last_name: User's last name.
            admin: Admin flag.
        """
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.MODIFY_USER)
            spb.insert_string(SrvUserOption.USER_NAME, user_name,
                              encoding=self._srv().encoding)
            if database is not None:
                spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            if password is not None:
                spb.insert_string(SrvUserOption.PASSWORD, password,
                                  encoding=self._srv().encoding)
            if user_id is not None:
                spb.insert_int(SrvUserOption.USER_ID, user_id)
            if group_id is not None:
                spb.insert_int(SrvUserOption.GROUP_ID, group_id)
            if first_name is not None:
                spb.insert_string(SrvUserOption.FIRST_NAME, first_name,
                                  encoding=self._srv().encoding)
            if middle_name is not None:
                spb.insert_string(SrvUserOption.MIDDLE_NAME, middle_name,
                                  encoding=self._srv().encoding)
            if last_name is not None:
                spb.insert_string(SrvUserOption.LAST_NAME, last_name,
                                  encoding=self._srv().encoding)
            if admin is not None:
                spb.insert_int(SrvUserOption.ADMIN, 1 if admin else 0)
            self._srv()._svc.start(spb.get_buffer())
        self._srv().wait()
    def delete(self, user_name: str, *, database: FILESPEC | None=None, sql_role: str | None=None) -> None:
        """Delete user.

        Arguments:
            user_name: User name.
            database: Database specification or alias.
            sql_role: SQL role name.
        """
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.DELETE_USER)
            spb.insert_string(SrvUserOption.USER_NAME, user_name, encoding=self._srv().encoding)
            if database is not None:
                spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
            if sql_role is not None:
                spb.insert_string(SPBItem.SQL_ROLE_NAME, sql_role, encoding=self._srv().encoding)
            self._srv()._svc.start(spb.get_buffer())
        self._srv().wait()
    def exists(self, user_name: str, *, database: FILESPEC | None=None, sql_role: str | None=None) -> bool:
        """Returns True if user exists.

        Arguments:
            user_name: User name.
            database: Database specification or alias.
            sql_role: SQL role name.
        """
        return self.get(user_name, database=database, sql_role=sql_role) is not None

add(*, user_name: str, password: str, user_id: int | None = None, group_id: int | None = None, first_name: str | None = None, middle_name: str | None = None, last_name: str | None = None, admin: bool | None = None, database: FILESPEC | None = None, sql_role: str | None = None) -> None

Add new user.

Parameters:

Name Type Description Default
user_name str

User name.

required
password str

User password.

required
user_id int | None

User ID.

None
group_id int | None

Group ID.

None
first_name str | None

User's first name.

None
middle_name str | None

User's middle name.

None
last_name str | None

User's last name.

None
admin bool | None

Admin flag.

None
database FILESPEC | None

Database specification or alias.

None
sql_role str | None

SQL role name.

None
Source code in firebird/driver/core.py
def add(self, *, user_name: str, password: str, user_id: int | None=None,
             group_id: int | None=None, first_name: str | None=None, middle_name: str | None=None,
             last_name: str | None=None, admin: bool | None=None, database: FILESPEC | None=None,
             sql_role: str | None=None) -> None:
    """Add new user.

    Arguments:
        user_name: User name.
        password: User password.
        user_id: User ID.
        group_id: Group ID.
        first_name: User's first name.
        middle_name: User's middle name.
        last_name: User's last name.
        admin: Admin flag.
        database: Database specification or alias.
        sql_role: SQL role name.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.ADD_USER)
        if database is not None:
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        spb.insert_string(SrvUserOption.USER_NAME, user_name, encoding=self._srv().encoding)
        if sql_role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, sql_role, encoding=self._srv().encoding)
        spb.insert_string(SrvUserOption.PASSWORD, password,
                          encoding=self._srv().encoding)
        if user_id is not None:
            spb.insert_int(SrvUserOption.USER_ID, user_id)
        if group_id is not None:
            spb.insert_int(SrvUserOption.GROUP_ID, group_id)
        if first_name is not None:
            spb.insert_string(SrvUserOption.FIRST_NAME, first_name,
                              encoding=self._srv().encoding)
        if middle_name is not None:
            spb.insert_string(SrvUserOption.MIDDLE_NAME, middle_name,
                              encoding=self._srv().encoding)
        if last_name is not None:
            spb.insert_string(SrvUserOption.LAST_NAME, last_name,
                              encoding=self._srv().encoding)
        if admin is not None:
            spb.insert_int(SrvUserOption.ADMIN, 1 if admin else 0)
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

delete(user_name: str, *, database: FILESPEC | None = None, sql_role: str | None = None) -> None

Delete user.

Parameters:

Name Type Description Default
user_name str

User name.

required
database FILESPEC | None

Database specification or alias.

None
sql_role str | None

SQL role name.

None
Source code in firebird/driver/core.py
def delete(self, user_name: str, *, database: FILESPEC | None=None, sql_role: str | None=None) -> None:
    """Delete user.

    Arguments:
        user_name: User name.
        database: Database specification or alias.
        sql_role: SQL role name.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.DELETE_USER)
        spb.insert_string(SrvUserOption.USER_NAME, user_name, encoding=self._srv().encoding)
        if database is not None:
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if sql_role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, sql_role, encoding=self._srv().encoding)
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

exists(user_name: str, *, database: FILESPEC | None = None, sql_role: str | None = None) -> bool

Returns True if user exists.

Parameters:

Name Type Description Default
user_name str

User name.

required
database FILESPEC | None

Database specification or alias.

None
sql_role str | None

SQL role name.

None
Source code in firebird/driver/core.py
def exists(self, user_name: str, *, database: FILESPEC | None=None, sql_role: str | None=None) -> bool:
    """Returns True if user exists.

    Arguments:
        user_name: User name.
        database: Database specification or alias.
        sql_role: SQL role name.
    """
    return self.get(user_name, database=database, sql_role=sql_role) is not None

get(user_name: str, *, database: FILESPEC | None = None, sql_role: str | None = None) -> UserInfo | None

Get information about user.

Parameters:

Name Type Description Default
user_name str

User name.

required
database FILESPEC | None

Database specification or alias.

None
sql_role str | None

SQL role name.

None
Source code in firebird/driver/core.py
def get(self, user_name: str, *, database: FILESPEC | None=None, sql_role: str | None=None) -> UserInfo | None:
    """Get information about user.

    Arguments:
        user_name: User name.
        database: Database specification or alias.
        sql_role: SQL role name.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.DISPLAY_USER_ADM)
        if database is not None:
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        spb.insert_string(SrvUserOption.USER_NAME, user_name, encoding=self._srv().encoding)
        if sql_role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, sql_role, encoding=self._srv().encoding)
        self._srv()._svc.start(spb.get_buffer())
    users = self.__fetch_users(Buffer(self._srv()._read_all_binary_output()))
    return users[0] if users else None

get_all(*, database: FILESPEC | None = None, sql_role: str | None = None) -> list[UserInfo]

Get information about users.

Parameters:

Name Type Description Default
database FILESPEC | None

Database specification or alias.

None
sql_role str | None

SQL role name.

None
Source code in firebird/driver/core.py
def get_all(self, *, database: FILESPEC | None=None, sql_role: str | None=None) -> list[UserInfo]:
    """Get information about users.

    Arguments:
        database: Database specification or alias.
        sql_role: SQL role name.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.DISPLAY_USER_ADM)
        if database is not None:
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if sql_role is not None:
            spb.insert_string(SPBItem.SQL_ROLE_NAME, sql_role,
                              encoding=self._srv().encoding)
        self._srv()._svc.start(spb.get_buffer())
    return self.__fetch_users(Buffer(self._srv()._read_all_binary_output()))

update(user_name: str, *, password: str | None = None, user_id: int | None = None, group_id: int | None = None, first_name: str | None = None, middle_name: str | None = None, last_name: str | None = None, admin: bool | None = None, database: FILESPEC | None = None) -> None

Update user information.

Parameters:

Name Type Description Default
user_name str

User name.

required
password str | None

User password.

None
user_id int | None

User ID.

None
group_id int | None

Group ID.

None
first_name str | None

User's first name.

None
middle_name str | None

User's middle name.

None
last_name str | None

User's last name.

None
admin bool | None

Admin flag.

None
Source code in firebird/driver/core.py
def update(self, user_name: str, *, password: str | None=None,
                user_id: int | None=None, group_id: int | None=None,
                first_name: str | None=None, middle_name: str | None=None,
                last_name: str | None=None, admin: bool | None=None, database: FILESPEC | None=None) -> None:
    """Update user information.

    Arguments:
        user_name: User name.
        password: User password.
        user_id: User ID.
        group_id: Group ID.
        first_name: User's first name.
        middle_name: User's middle name.
        last_name: User's last name.
        admin: Admin flag.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.MODIFY_USER)
        spb.insert_string(SrvUserOption.USER_NAME, user_name,
                          encoding=self._srv().encoding)
        if database is not None:
            spb.insert_string(SPBItem.DBNAME, str(database), encoding=self._srv().encoding)
        if password is not None:
            spb.insert_string(SrvUserOption.PASSWORD, password,
                              encoding=self._srv().encoding)
        if user_id is not None:
            spb.insert_int(SrvUserOption.USER_ID, user_id)
        if group_id is not None:
            spb.insert_int(SrvUserOption.GROUP_ID, group_id)
        if first_name is not None:
            spb.insert_string(SrvUserOption.FIRST_NAME, first_name,
                              encoding=self._srv().encoding)
        if middle_name is not None:
            spb.insert_string(SrvUserOption.MIDDLE_NAME, middle_name,
                              encoding=self._srv().encoding)
        if last_name is not None:
            spb.insert_string(SrvUserOption.LAST_NAME, last_name,
                              encoding=self._srv().encoding)
        if admin is not None:
            spb.insert_int(SrvUserOption.ADMIN, 1 if admin else 0)
        self._srv()._svc.start(spb.get_buffer())
    self._srv().wait()

firebird.driver.core.ServerTraceServices

Bases: ServerServiceProvider

Trace session actions and services.

Source code in firebird/driver/core.py
class ServerTraceServices(ServerServiceProvider):
    """Trace session actions and services.
    """
    def __action(self, action: ServerAction, label: str, session_id: int) -> str:
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(action)
            spb.insert_int(SrvTraceOption.ID, session_id)
            self._srv()._svc.start(spb.get_buffer())
        response = self._srv()._fetch_line()
        if not response.startswith(f"Trace session ID {session_id} {label}"):  # pragma: no cover
            # response should contain the error message
            raise DatabaseError(response)
        return response
    def start(self, *, config: str, name: str | None=None, plugins: str | list[str] | None=None) -> int:
        """Start new trace session. **(ASYNC service)**

        Arguments:
            config: Trace session configuration.
            name: Trace session name.
            plugins: Plugins to use for the session (only for FIREBIRD 6+)

        Returns:
            Trace session ID.
        """
        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.TRACE_START)
            if name is not None:
                spb.insert_string(SrvTraceOption.NAME, name)
            if plugins is not None:
                if isinstance(plugins, list):
                    plugins = ",".join(plugins)
                spb.insert_string(SrvTraceOption.PLUGINS, plugins)

            spb.insert_string(SrvTraceOption.CONFIG, config, encoding=self._srv().encoding)
            self._srv()._svc.start(spb.get_buffer())
        response = self._srv()._fetch_line()
        if response.startswith('Trace session ID'):
            return int(response.split()[3])
        # pragma: no cover
        # response should contain the error message
        raise DatabaseError(response)
    def stop(self, *, session_id: int) -> str:
        """Stop trace session.

        Arguments:
            session_id: Trace session ID.

        Returns:
           Text message 'Trace session ID <x> stopped'.
        """
        return self.__action(ServerAction.TRACE_STOP, 'stopped', session_id)
    def suspend(self, *, session_id: int) -> str:
        """Suspend trace session.

        Arguments:
            session_id: Trace session ID.

        Returns:
           Text message 'Trace session ID <x> paused'.
        """
        return self.__action(ServerAction.TRACE_SUSPEND, 'paused', session_id)
    def resume(self, *, session_id: int) -> str:
        """Resume trace session.

        Arguments:
            session_id: Trace session ID.

        Returns:
           Text message 'Trace session ID <x> resumed'.
        """
        return self.__action(ServerAction.TRACE_RESUME, 'resumed', session_id)
    @property
    def sessions(self) -> dict[int, TraceSession]:
        """Dictionary with active trace sessions.
        """
        def store():
            if current:
                session = TraceSession(**current)
                result[session.id] = session
                current.clear()

        self._srv()._reset_output()
        with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
            spb.insert_tag(ServerAction.TRACE_LIST)
            self._srv()._svc.start(spb.get_buffer())
        result = {}
        current = {}
        for line in self._srv():
            if not line.strip():
                store()
            elif line.startswith('Session ID:'):
                store()
                current['id'] = int(line.split(':')[1].strip())
            elif line.lstrip().startswith('name:'):
                current['name'] = line.split(':')[1].strip()
            elif line.lstrip().startswith('user:'):
                current['user'] = line.split(':')[1].strip()
            elif line.lstrip().startswith('date:'):
                current['timestamp'] = datetime.datetime.strptime(
                    line.split(':', 1)[1].strip(),
                    '%Y-%m-%d %H:%M:%S')
            elif line.lstrip().startswith('flags:'):
                current['flags'] = line.split(':')[1].strip().split(',')
            elif line.lstrip().startswith('plugins:'):
                current['plugins'] = line.split(':')[1].strip().split(',')
            else:  # pragma: no cover
                raise InterfaceError(f"Unexpected line in trace session list: {line}")
        store()
        return result

sessions: dict[int, TraceSession] property

Dictionary with active trace sessions.

resume(*, session_id: int) -> str

Resume trace session.

Parameters:

Name Type Description Default
session_id int

Trace session ID.

required

Returns:

Type Description
str

Text message 'Trace session ID resumed'.

Source code in firebird/driver/core.py
def resume(self, *, session_id: int) -> str:
    """Resume trace session.

    Arguments:
        session_id: Trace session ID.

    Returns:
       Text message 'Trace session ID <x> resumed'.
    """
    return self.__action(ServerAction.TRACE_RESUME, 'resumed', session_id)

start(*, config: str, name: str | None = None, plugins: str | list[str] | None = None) -> int

Start new trace session. (ASYNC service)

Parameters:

Name Type Description Default
config str

Trace session configuration.

required
name str | None

Trace session name.

None
plugins str | list[str] | None

Plugins to use for the session (only for FIREBIRD 6+)

None

Returns:

Type Description
int

Trace session ID.

Source code in firebird/driver/core.py
def start(self, *, config: str, name: str | None=None, plugins: str | list[str] | None=None) -> int:
    """Start new trace session. **(ASYNC service)**

    Arguments:
        config: Trace session configuration.
        name: Trace session name.
        plugins: Plugins to use for the session (only for FIREBIRD 6+)

    Returns:
        Trace session ID.
    """
    self._srv()._reset_output()
    with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb:
        spb.insert_tag(ServerAction.TRACE_START)
        if name is not None:
            spb.insert_string(SrvTraceOption.NAME, name)
        if plugins is not None:
            if isinstance(plugins, list):
                plugins = ",".join(plugins)
            spb.insert_string(SrvTraceOption.PLUGINS, plugins)

        spb.insert_string(SrvTraceOption.CONFIG, config, encoding=self._srv().encoding)
        self._srv()._svc.start(spb.get_buffer())
    response = self._srv()._fetch_line()
    if response.startswith('Trace session ID'):
        return int(response.split()[3])
    # pragma: no cover
    # response should contain the error message
    raise DatabaseError(response)

stop(*, session_id: int) -> str

Stop trace session.

Parameters:

Name Type Description Default
session_id int

Trace session ID.

required

Returns:

Type Description
str

Text message 'Trace session ID stopped'.

Source code in firebird/driver/core.py
def stop(self, *, session_id: int) -> str:
    """Stop trace session.

    Arguments:
        session_id: Trace session ID.

    Returns:
       Text message 'Trace session ID <x> stopped'.
    """
    return self.__action(ServerAction.TRACE_STOP, 'stopped', session_id)

suspend(*, session_id: int) -> str

Suspend trace session.

Parameters:

Name Type Description Default
session_id int

Trace session ID.

required

Returns:

Type Description
str

Text message 'Trace session ID paused'.

Source code in firebird/driver/core.py
def suspend(self, *, session_id: int) -> str:
    """Suspend trace session.

    Arguments:
        session_id: Trace session ID.

    Returns:
       Text message 'Trace session ID <x> paused'.
    """
    return self.__action(ServerAction.TRACE_SUSPEND, 'paused', session_id)

firebird.driver.core.InfoProvider

Bases: ABC

Abstract base class for embedded information providers.

Attributes:

Name Type Description
response CBuffer

Internal buffer for response packet acquired via Firebird API.

request Buffer

Internal buffer for information request packet needed by Firebird API.

Source code in firebird/driver/core.py
class InfoProvider(ABC):
    """Abstract base class for embedded information providers.

    Attributes:
        response (CBuffer): Internal buffer for response packet acquired via Firebird API.
        request (Buffer): Internal buffer for information request packet needed by Firebird API.
    """
    def __init__(self, charset: str, buffer_size: int=256):
        self._charset: str = charset
        self.response: CBuffer = CBuffer(buffer_size)
        self.request: Buffer = Buffer(10)
        self._cache: dict = {}
    def _raise_not_supported(self) -> None:
        raise NotSupportedError("Requested functionality is not supported by used Firebird version.")
    @abstractmethod
    def _close(self) -> None:
        """Close the information source.
        """
    @abstractmethod
    def _acquire(self, request: bytes) -> None:
        """Acquire information specified by parameter. Information must be stored in
        `response` buffer.

        Arguments:
            request: Data specifying the required information.
        """
    def _get_data(self, request: bytes, max_size: int=SHRT_MAX) -> None:
        """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.

        Arguments:
            request: Data specifying the required information.
            max_size: Maximum response size.

        Raises:
            InterfaceError: If information cannot be successfuly stored into buffer
                of `max_size`, or response is ivalid.
        """
        while True:
            self._acquire(request)
            if self.response.is_truncated():
                if (buf_size := len(self.response.raw)) < max_size:
                    buf_size = min(buf_size * 2, max_size)
                    self.response.resize(buf_size)
                    continue
                raise InterfaceError("Response too large")  # pragma: no cover
            break
        self.response.seek_last_data()
        if not self.response.is_eof():  # pragma: no cover
            raise InterfaceError("Invalid response format")
        self.response.rewind()

firebird.driver.core.DatabaseInfoProvider3

Bases: InfoProvider

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

Information can be accessed either via specific properties (preferred) or the lower-level get_info() method.

Important

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

Source code in firebird/driver/core.py
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
class DatabaseInfoProvider3(InfoProvider):
    """Provides access to information about attached database [Firebird 3+].

    Information can be accessed either via specific properties (preferred) or the lower-level
    `get_info()` method.

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

    """
    def __init__(self, connection: Connection):
        super().__init__(connection._encoding)
        self._con: Connection = weakref.ref(connection)
        self._handlers: dict[DbInfoCode, Callable] = \
            {DbInfoCode.DB_ID: self.__db_id,
             DbInfoCode.READS: self.response.read_sized_int,
             DbInfoCode.WRITES: self.response.read_sized_int,
             DbInfoCode.FETCHES: self.response.read_sized_int,
             DbInfoCode.MARKS: self.response.read_sized_int,
             DbInfoCode.IMPLEMENTATION_OLD: self.__implementation_old,
             DbInfoCode.VERSION: self._version_string,
             DbInfoCode.BASE_LEVEL: self.__base_level,
             DbInfoCode.PAGE_SIZE: self.response.read_sized_int,
             DbInfoCode.NUM_BUFFERS: self.response.read_sized_int,
             DbInfoCode.LIMBO: self.__tra_limbo,
             DbInfoCode.CURRENT_MEMORY: self.response.read_sized_int,
             DbInfoCode.MAX_MEMORY: self.response.read_sized_int,
             DbInfoCode.ALLOCATION: self.response.read_sized_int,
             DbInfoCode.ATTACHMENT_ID: self.response.read_sized_int,
             DbInfoCode.READ_SEQ_COUNT: self.__tbl_perf_count,
             DbInfoCode.READ_IDX_COUNT: self.__tbl_perf_count,
             DbInfoCode.INSERT_COUNT: self.__tbl_perf_count,
             DbInfoCode.UPDATE_COUNT: self.__tbl_perf_count,
             DbInfoCode.DELETE_COUNT: self.__tbl_perf_count,
             DbInfoCode.BACKOUT_COUNT: self.__tbl_perf_count,
             DbInfoCode.PURGE_COUNT: self.__tbl_perf_count,
             DbInfoCode.EXPUNGE_COUNT: self.__tbl_perf_count,
             DbInfoCode.SWEEP_INTERVAL: self.response.read_sized_int,
             DbInfoCode.ODS_VERSION: self.response.read_sized_int,
             DbInfoCode.ODS_MINOR_VERSION: self.response.read_sized_int,
             DbInfoCode.NO_RESERVE: self.response.read_sized_int,
             DbInfoCode.FORCED_WRITES: self.response.read_sized_int,
             DbInfoCode.USER_NAMES: self.__user_names,
             DbInfoCode.PAGE_ERRORS: self.response.read_sized_int,
             DbInfoCode.RECORD_ERRORS: self.response.read_sized_int,
             DbInfoCode.BPAGE_ERRORS: self.response.read_sized_int,
             DbInfoCode.DPAGE_ERRORS: self.response.read_sized_int,
             DbInfoCode.IPAGE_ERRORS: self.response.read_sized_int,
             DbInfoCode.PPAGE_ERRORS: self.response.read_sized_int,
             DbInfoCode.TPAGE_ERRORS: self.response.read_sized_int,
             DbInfoCode.SET_PAGE_BUFFERS: self.response.read_sized_int,
             DbInfoCode.DB_SQL_DIALECT: self.response.read_sized_int,
             DbInfoCode.DB_READ_ONLY: self.response.read_sized_int,
             DbInfoCode.DB_SIZE_IN_PAGES: self.response.read_sized_int,
             DbInfoCode.ATT_CHARSET: self.response.read_sized_int,
             DbInfoCode.DB_CLASS: self.response.read_sized_int,
             DbInfoCode.FIREBIRD_VERSION: self._version_string,
             DbInfoCode.OLDEST_TRANSACTION: self.response.read_sized_int,
             DbInfoCode.OLDEST_ACTIVE: self.response.read_sized_int,
             DbInfoCode.OLDEST_SNAPSHOT: self.response.read_sized_int,
             DbInfoCode.NEXT_TRANSACTION: self.response.read_sized_int,
             DbInfoCode.DB_PROVIDER: self.response.read_sized_int,
             DbInfoCode.ACTIVE_TRANSACTIONS: self.__tra_active,
             DbInfoCode.ACTIVE_TRAN_COUNT: self.response.read_sized_int,
             DbInfoCode.CREATION_DATE: self.__creation_date,
             DbInfoCode.DB_FILE_SIZE: self.response.read_sized_int,
             DbInfoCode.PAGE_CONTENTS: self.response.read_bytes,
             DbInfoCode.IMPLEMENTATION: self.__implementation,
             DbInfoCode.PAGE_WARNS: self.response.read_sized_int,
             DbInfoCode.RECORD_WARNS: self.response.read_sized_int,
             DbInfoCode.BPAGE_WARNS: self.response.read_sized_int,
             DbInfoCode.DPAGE_WARNS: self.response.read_sized_int,
             DbInfoCode.IPAGE_WARNS: self.response.read_sized_int,
             DbInfoCode.PPAGE_WARNS: self.response.read_sized_int,
             DbInfoCode.TPAGE_WARNS: self.response.read_sized_int,
             DbInfoCode.PIP_ERRORS: self.response.read_sized_int,
             DbInfoCode.PIP_WARNS: self.response.read_sized_int,
             DbInfoCode.PAGES_USED: self.response.read_sized_int,
             DbInfoCode.PAGES_FREE: self.response.read_sized_int,
             DbInfoCode.CONN_FLAGS: self.__con_state,
             DbInfoCode.CRYPT_KEY: self._single_info_string,
             DbInfoCode.CRYPT_STATE: self.__crypt_state,
             }
        # Value convertors
        self._convertors: dict[DbInfoCode, Callable] = \
            {DbInfoCode.DB_PROVIDER: DbProvider,
             DbInfoCode.DB_CLASS: DbClass,
             DbInfoCode.NO_RESERVE: self.__conv_space_reservation,
             DbInfoCode.FORCED_WRITES: self.__conv_write_mode,
             DbInfoCode.DB_READ_ONLY: self.__conv_access_mode,
            }
        # Page size
        self.__page_size = self.get_info(DbInfoCode.PAGE_SIZE)  # prefetch it
        # Get Firebird engine version
        self.__version = _engine_version_provider.get_server_version(self._con)
        x = self.__version.split('.')
        self.__engine_version = float(f'{x[0]}.{x[1]}')
    def __base_level(self) -> int:
        self.response.read_short() # cluster length
        self.response.read_byte() # number of codes
        return self.response.read_byte() # should be always 6 for Firebird
    def __conv_space_reservation(self, value: int) -> DbSpaceReservation:
        return DbSpaceReservation.USE_FULL if value else DbSpaceReservation.RESERVE
    def __conv_write_mode(self, value: int) -> DbWriteMode:
        return DbWriteMode.SYNC if value else DbWriteMode.ASYNC
    def __conv_access_mode(self, value: int) -> DbAccessMode:
        return DbAccessMode.READ_ONLY if value else DbAccessMode.READ_WRITE
    def __db_id(self) -> list[str]:
        result = []
        self.response.read_short()  # Cluster length
        count = self.response.read_byte()
        while count > 0:
            result.append(self.response.read_pascal_string(encoding=self._charset))
            count -= 1
        return result
    def __implementation(self) -> tuple[ImpData]:
        result = []
        self.response.read_short() # Cluster length
        seqences = self.response.read_byte()  # Cluster length
        while seqences:
            result.append(ImpData(ImpCPU(self.response.read_byte()),
                                  ImpOS(self.response.read_byte()),
                                  ImpCompiler(self.response.read_byte()),
                                  ImpFlags(self.response.read_byte()),
                                  DbClass(self.response.read_byte()),
                                  self.response.read_byte()))
            seqences -= 1
        return tuple(result)
    def __implementation_old(self) -> tuple[ImpDataOld]:
        result = []
        self.response.read_short() # Cluster length
        seqences = self.response.read_byte()  # Cluster length
        while seqences:
            result.append(ImpDataOld(Implementation(self.response.read_byte()),
                                     DbClass(self.response.read_byte())))
            seqences -= 1
        return tuple(result)
    def _version_string(self) -> str:
        self.response.read_short()  # Cluster length
        result = []
        count = self.response.read_byte() # number of strings
        for _ in range(count):
            result.append(self.response.read_pascal_string())
        return '\n'.join(result)
    def _single_info_string(self) -> str:
        return self.response.read_sized_string()
    def __user_names(self) -> dict[str, str]:
        self.response.rewind() # necessary to process names separated by info tag
        usernames = []
        while not self.response.is_eof():
            self.response.get_tag() # DbInfoCode.USER_NAMES
            self.response.read_short()  # cluster length
            usernames.append(self.response.read_pascal_string(encoding=self._charset))
        # The client-exposed return value is a dictionary mapping
        # username -> number of connections by that user.
        result = {}
        for name in usernames:
            result[name] = result.get(name, 0) + 1
        return result
    def __tra_active(self) -> list[int]:
        result = []
        while not self.response.is_eof():
            self.response.get_tag()  # DbInfoCode.ACTIVE_TRANSACTIONS
            result.append(self.response.read_sized_int())
        return result
    def __tra_limbo(self) -> list[int]:
        result = []
        while not self.response.is_eof():
            self.response.get_tag()  # DbInfoCode.LIMBO
            result.append(self.response.read_sized_int())
        return result
    def __crypt_state(self) -> EncryptionFlag:
        return EncryptionFlag(self.response.read_sized_int())
    def __con_state(self) -> ConnectionFlag:
        return ConnectionFlag(self.response.read_sized_int())
    def __tbl_perf_count(self) -> dict[int, int]:
        result = {}
        clen = self.response.read_short()  # Cluster length
        while clen > 0:
            relation_id = self.response.read_short()
            result[relation_id] = self.response.read_int()
            clen -= 6
        return result
    def __creation_date(self) -> datetime.datetime:
        value = self.response.read_bytes()
        return datetime.datetime.combine(_util.decode_date(value[:4]),
                                         _util.decode_time(value[4:]))
    def _close(self) -> None:
        """Drops the association with attached database.
        """
        self._con = None
    def _acquire(self, request: bytes) -> None:
        """Acquires information from associated attachment. Information is stored in native
        format in `response` buffer.

        Arguments:
            request: Data specifying the required information.
        """
        self._con()._att.get_info(request, self.response.raw)
    def supports(self, code: DbInfoCode) -> bool:
        """Returns True if specified info code is supported by this InfoProvider.

        Arguments:
            code: Info code.
        """
        return code in self._handlers
    def get_info(self, info_code: DbInfoCode, page_number: int | None=None) -> Any:
        """Returns requested information from associated attachment.

        Arguments:
            info_code: A code specifying the required information.
            page_number: A page number for `DbInfoCode.PAGE_CONTENTS` request. Ignored for other requests.

        Returns:
            The data type of returned value depends on information required.

        Note:
            Info codes that return stable values are cached on first call, so subsequent calls do not
            access the server. These codes are: `CREATION_DATE`, `DB_CLASS`, `DB_PROVIDER`,
            `DB_SQL_DIALECT`, `ODS_MINOR_VERSION`, `ODS_VERSION`, `PAGE_SIZE`, `VERSION`,
            `FIREBIRD_VERSION`, `IMPLEMENTATION_OLD`, `IMPLEMENTATION`, `DB_ID`, `BASE_LEVEL`,
            and `ATTACHMENT_ID`.
        """
        if info_code in self._cache:
            return self._cache[info_code]
        if info_code not in self._handlers:
            raise NotSupportedError(f"Info code {info_code} not supported by engine version {self.__engine_version}")
        self.response.clear()
        request = bytes([info_code])
        if info_code == DbInfoCode.PAGE_CONTENTS:
            request += (4).to_bytes(2, 'little')
            request += page_number.to_bytes(4, 'little')
            if len(self.response.raw) < self.page_size + 10:
                self.response.resize(self.page_size + 10)
        self._get_data(request)
        tag = self.response.get_tag()
        if request[0] != tag:
            if info_code in (DbInfoCode.ACTIVE_TRANSACTIONS, DbInfoCode.LIMBO):
                # isc_info_active_transactions and isc_info_limbo with no transactions to
                # report returns empty buffer and does not follow this rule
                pass
            elif tag == isc_info_error:  # pragma: no cover
                raise InterfaceError("An error response was received")
            else:  # pragma: no cover
                raise InterfaceError(f"Result code does not match request code {info_code}")
        #
        if info_code in (DbInfoCode.ACTIVE_TRANSACTIONS, DbInfoCode.LIMBO):
            # we'll rewind back, otherwise it will break the repeating cluster processing
            self.response.rewind()
        result = self._handlers[info_code]()
        if info_code in self._convertors:
            result = self._convertors[info_code](result)
        # cache
        if info_code in (DbInfoCode.CREATION_DATE, DbInfoCode.DB_CLASS, DbInfoCode.DB_PROVIDER,
                         DbInfoCode.DB_SQL_DIALECT, DbInfoCode.ODS_MINOR_VERSION,
                         DbInfoCode.ODS_VERSION, DbInfoCode.PAGE_SIZE, DbInfoCode.VERSION,
                         DbInfoCode.FIREBIRD_VERSION, DbInfoCode.IMPLEMENTATION_OLD,
                         DbInfoCode.IMPLEMENTATION, DbInfoCode.DB_ID, DbInfoCode.BASE_LEVEL,
                         DbInfoCode.ATTACHMENT_ID):
            self._cache[info_code] = result
        return result
    # Functions
    def get_page_content(self, page_number: int) -> bytes:
        """Returns content of single database page.

        Arguments:
           page_number: Sequence number of database page to be fetched from server.
        """
        return self.get_info(DbInfoCode.PAGE_CONTENTS, page_number)
    def get_active_transaction_ids(self) -> list[int]:
        """Returns list of IDs of active transactions.
        """
        return self.get_info(DbInfoCode.ACTIVE_TRANSACTIONS)
    def get_active_transaction_count(self) -> int:
        """Returns number of active transactions.
        """
        return self.get_info(DbInfoCode.ACTIVE_TRAN_COUNT)
    def get_table_access_stats(self) -> list[TableAccessStats]:
        """Returns actual table access statistics.
        """
        tables = {}
        info_codes = [DbInfoCode.READ_SEQ_COUNT, DbInfoCode.READ_IDX_COUNT,
                      DbInfoCode.INSERT_COUNT, DbInfoCode.UPDATE_COUNT,
                      DbInfoCode.DELETE_COUNT, DbInfoCode.BACKOUT_COUNT,
                      DbInfoCode.PURGE_COUNT, DbInfoCode.EXPUNGE_COUNT]
        #stats = self.get_info(info_codes)
        for info_code in info_codes:
            stat: Mapping = self.get_info(info_code)
            for table, count in stat.items():
                tables.setdefault(table, dict.fromkeys(info_codes))[info_code] = count
        return [TableAccessStats(table, **{_i2name[code]:count
                                           for code, count in tables[table].items()})
                for table in tables]
    def is_compressed(self) -> bool:
        """Returns True if connection to the server uses data compression.
        """
        return ConnectionFlag.COMPRESSED in ConnectionFlag(self.get_info(DbInfoCode.CONN_FLAGS))
    def is_encrypted(self) -> bool:
        """Returns True if connection to the server uses data encryption.
        """
        return ConnectionFlag.ENCRYPTED in ConnectionFlag(self.get_info(DbInfoCode.CONN_FLAGS))
    # Properties
    @property
    def id(self) -> int:
        """Attachment ID.
        """
        return self.get_info(DbInfoCode.ATTACHMENT_ID)
    @property
    def charset(self) -> str:
        """Database character set.
        """
        if -1 not in self._cache:
            with transaction(self._con()._tra_qry, bypass=True):
                with self._con()._ic.execute("SELECT RDB$CHARACTER_SET_NAME FROM RDB$DATABASE"):
                    self._cache[-1] = self._con()._ic.fetchone()[0].strip()
        return self._cache[-1]
    @property
    def page_size(self) -> int:
        """Page size (in bytes).
        """
        return self.__page_size
    @property
    def sql_dialect(self) -> int:
        """SQL dialect used by connected database.
        """
        return self.get_info(DbInfoCode.DB_SQL_DIALECT)
    @property
    def name(self) -> str:
        """Database name (filename or alias).
        """
        return self.get_info(DbInfoCode.DB_ID)[0]
    @property
    def site(self) -> str:
        """Database site name.
        """
        return self.get_info(DbInfoCode.DB_ID)[1]
    @property
    def server_version(self) -> str:
        """Firebird server version (compatible with InterBase version).
        """
        return self.get_info(DbInfoCode.VERSION)
    @property
    def firebird_version(self) -> str:
        """Firebird server version.
        """
        return self.get_info(DbInfoCode.FIREBIRD_VERSION)
    @property
    def implementation(self) -> tuple[ImpData]:
        """Implementation (new format).
        """
        return self.get_info(DbInfoCode.IMPLEMENTATION)
    @property
    def provider(self) -> DbProvider:
        """Database Provider.
        """
        return self.get_info(DbInfoCode.DB_PROVIDER)
    @property
    def db_class(self) -> DbClass:
        """Database Class.
        """
        return self.get_info(DbInfoCode.DB_CLASS)
    @property
    def creation_date(self) -> datetime.date:
        """Date when database was created.
        """
        return self.get_info(DbInfoCode.CREATION_DATE)
    @property
    def ods(self) -> float:
        """Database On-Disk Structure version (<major>.<minor>).
        """
        return float(f'{self.ods_version}.{self.ods_minor_version}')
    @property
    def ods_version(self) -> int:
        """Database On-Disk Structure MAJOR version.
        """
        return self.get_info(DbInfoCode.ODS_VERSION)
    @property
    def ods_minor_version(self) -> int:
        """Database On-Disk Structure MINOR version.
        """
        return self.get_info(DbInfoCode.ODS_MINOR_VERSION)
    @property
    def page_cache_size(self) -> int:
        """Size of page cache used by connection.
        """
        return self.get_info(DbInfoCode.NUM_BUFFERS)
    @property
    def pages_allocated(self) -> int:
        """Number of pages allocated for database.
        """
        return self.get_info(DbInfoCode.ALLOCATION)
    @property
    def size_in_pages(self) -> int:
        """Database size in pages.
        """
        return self.get_info(DbInfoCode.DB_SIZE_IN_PAGES)
    @property
    def pages_used(self) -> int:
        """Number of database pages in active use.
        """
        return self.get_info(DbInfoCode.PAGES_USED)
    @property
    def pages_free(self) -> int:
        """Number of free allocated pages in database.
        """
        return self.get_info(DbInfoCode.PAGES_FREE)
    @property
    def sweep_interval(self) -> int:
        """Sweep interval.
        """
        return self.get_info(DbInfoCode.SWEEP_INTERVAL)
    @property
    def space_reservation(self) -> DbSpaceReservation:
        """Data page space usage (USE_FULL or RESERVE).
        """
        return self.get_info(DbInfoCode.NO_RESERVE)
    @property
    def write_mode(self) -> DbWriteMode:
        """Database write mode (SYNC or ASYNC).
        """
        return self.get_info(DbInfoCode.FORCED_WRITES)
    @property
    def access_mode(self) -> DbAccessMode:
        """Database access mode (READ_ONLY or READ_WRITE).
        """
        return self.get_info(DbInfoCode.DB_READ_ONLY)
    @property
    def reads(self) -> int:
        """Current I/O statistics - Reads from disk to page cache.
        """
        return self.get_info(DbInfoCode.READS)
    @property
    def fetches(self) -> int:
        """Current I/O statistics - Fetches from page cache.
        """
        return self.get_info(DbInfoCode.FETCHES)
    @property
    def cache_hit_ratio(self) -> float:
        """Cache hit ratio = 1 - (reads / fetches).
        """
        return (1 - (self.reads / self.fetches)) if self.fetches else 1.0
    @property
    def writes(self) -> int:
        """Current I/O statistics - Writes from page cache to disk.
        """
        return self.get_info(DbInfoCode.WRITES)
    @property
    def marks(self) -> int:
        """Current I/O statistics - Writes to page in cache.
        """
        return self.get_info(DbInfoCode.MARKS)
    @property
    def current_memory(self) -> int:
        """Total amount of memory curretly used by database engine.
        """
        return self.get_info(DbInfoCode.CURRENT_MEMORY)
    @property
    def max_memory(self) -> int:
        """Max. total amount of memory so far used by database engine.
        """
        return self.get_info(DbInfoCode.MAX_MEMORY)
    @property
    def oit(self) -> int:
        """ID of Oldest Interesting Transaction.
        """
        return self.get_info(DbInfoCode.OLDEST_TRANSACTION)
    @property
    def oat(self) -> int:
        """ID of Oldest Active Transaction.
        """
        return self.get_info(DbInfoCode.OLDEST_ACTIVE)
    @property
    def ost(self) -> int:
        """ID of Oldest Snapshot Transaction.
        """
        return self.get_info(DbInfoCode.OLDEST_SNAPSHOT)
    @property
    def next_transaction(self) -> int:
        """ID for next transaction.
        """
        return self.get_info(DbInfoCode.NEXT_TRANSACTION)
    @property
    def version(self) -> str:
        """Firebird version as SEMVER string.
        """
        return self.__version
    @property
    def engine_version(self) -> float:
        """Firebird version as <major>.<minor> float number.
        """
        return self.__engine_version

access_mode: DbAccessMode property

Database access mode (READ_ONLY or READ_WRITE).

cache_hit_ratio: float property

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

charset: str property

Database character set.

creation_date: datetime.date property

Date when database was created.

current_memory: int property

Total amount of memory curretly used by database engine.

db_class: DbClass property

Database Class.

engine_version: float property

Firebird version as . float number.

fetches: int property

Current I/O statistics - Fetches from page cache.

firebird_version: str property

Firebird server version.

id: int property

Attachment ID.

implementation: tuple[ImpData] property

Implementation (new format).

marks: int property

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

max_memory: int property

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

name: str property

Database name (filename or alias).

next_transaction: int property

ID for next transaction.

oat: int property

ID of Oldest Active Transaction.

ods: float property

Database On-Disk Structure version (.).

ods_minor_version: int property

Database On-Disk Structure MINOR version.

ods_version: int property

Database On-Disk Structure MAJOR version.

oit: int property

ID of Oldest Interesting Transaction.

ost: int property

ID of Oldest Snapshot Transaction.

page_cache_size: int property

Size of page cache used by connection.

page_size: int property

Page size (in bytes).

pages_allocated: int property

Number of pages allocated for database.

pages_free: int property

Number of free allocated pages in database.

pages_used: int property

Number of database pages in active use.

provider: DbProvider property

Database Provider.

reads: int property

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

server_version: str property

Firebird server version (compatible with InterBase version).

site: str property

Database site name.

size_in_pages: int property

Database size in pages.

space_reservation: DbSpaceReservation property

Data page space usage (USE_FULL or RESERVE).

sql_dialect: int property

SQL dialect used by connected database.

sweep_interval: int property

Sweep interval.

version: str property

Firebird version as SEMVER string.

write_mode: DbWriteMode property

Database write mode (SYNC or ASYNC).

writes: int property

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

get_active_transaction_count() -> int

Returns number of active transactions.

Source code in firebird/driver/core.py
def get_active_transaction_count(self) -> int:
    """Returns number of active transactions.
    """
    return self.get_info(DbInfoCode.ACTIVE_TRAN_COUNT)

get_active_transaction_ids() -> list[int]

Returns list of IDs of active transactions.

Source code in firebird/driver/core.py
def get_active_transaction_ids(self) -> list[int]:
    """Returns list of IDs of active transactions.
    """
    return self.get_info(DbInfoCode.ACTIVE_TRANSACTIONS)

get_info(info_code: DbInfoCode, page_number: int | None = None) -> Any

Returns requested information from associated attachment.

Parameters:

Name Type Description Default
info_code DbInfoCode

A code specifying the required information.

required
page_number int | None

A page number for DbInfoCode.PAGE_CONTENTS request. Ignored for other requests.

None

Returns:

Type Description
Any

The data type of returned value depends on information required.

Note

Info codes that return stable values are cached on first call, so subsequent calls do not access the server. These codes are: CREATION_DATE, DB_CLASS, DB_PROVIDER, DB_SQL_DIALECT, ODS_MINOR_VERSION, ODS_VERSION, PAGE_SIZE, VERSION, FIREBIRD_VERSION, IMPLEMENTATION_OLD, IMPLEMENTATION, DB_ID, BASE_LEVEL, and ATTACHMENT_ID.

Source code in firebird/driver/core.py
def get_info(self, info_code: DbInfoCode, page_number: int | None=None) -> Any:
    """Returns requested information from associated attachment.

    Arguments:
        info_code: A code specifying the required information.
        page_number: A page number for `DbInfoCode.PAGE_CONTENTS` request. Ignored for other requests.

    Returns:
        The data type of returned value depends on information required.

    Note:
        Info codes that return stable values are cached on first call, so subsequent calls do not
        access the server. These codes are: `CREATION_DATE`, `DB_CLASS`, `DB_PROVIDER`,
        `DB_SQL_DIALECT`, `ODS_MINOR_VERSION`, `ODS_VERSION`, `PAGE_SIZE`, `VERSION`,
        `FIREBIRD_VERSION`, `IMPLEMENTATION_OLD`, `IMPLEMENTATION`, `DB_ID`, `BASE_LEVEL`,
        and `ATTACHMENT_ID`.
    """
    if info_code in self._cache:
        return self._cache[info_code]
    if info_code not in self._handlers:
        raise NotSupportedError(f"Info code {info_code} not supported by engine version {self.__engine_version}")
    self.response.clear()
    request = bytes([info_code])
    if info_code == DbInfoCode.PAGE_CONTENTS:
        request += (4).to_bytes(2, 'little')
        request += page_number.to_bytes(4, 'little')
        if len(self.response.raw) < self.page_size + 10:
            self.response.resize(self.page_size + 10)
    self._get_data(request)
    tag = self.response.get_tag()
    if request[0] != tag:
        if info_code in (DbInfoCode.ACTIVE_TRANSACTIONS, DbInfoCode.LIMBO):
            # isc_info_active_transactions and isc_info_limbo with no transactions to
            # report returns empty buffer and does not follow this rule
            pass
        elif tag == isc_info_error:  # pragma: no cover
            raise InterfaceError("An error response was received")
        else:  # pragma: no cover
            raise InterfaceError(f"Result code does not match request code {info_code}")
    #
    if info_code in (DbInfoCode.ACTIVE_TRANSACTIONS, DbInfoCode.LIMBO):
        # we'll rewind back, otherwise it will break the repeating cluster processing
        self.response.rewind()
    result = self._handlers[info_code]()
    if info_code in self._convertors:
        result = self._convertors[info_code](result)
    # cache
    if info_code in (DbInfoCode.CREATION_DATE, DbInfoCode.DB_CLASS, DbInfoCode.DB_PROVIDER,
                     DbInfoCode.DB_SQL_DIALECT, DbInfoCode.ODS_MINOR_VERSION,
                     DbInfoCode.ODS_VERSION, DbInfoCode.PAGE_SIZE, DbInfoCode.VERSION,
                     DbInfoCode.FIREBIRD_VERSION, DbInfoCode.IMPLEMENTATION_OLD,
                     DbInfoCode.IMPLEMENTATION, DbInfoCode.DB_ID, DbInfoCode.BASE_LEVEL,
                     DbInfoCode.ATTACHMENT_ID):
        self._cache[info_code] = result
    return result

get_page_content(page_number: int) -> bytes

Returns content of single database page.

Parameters:

Name Type Description Default
page_number int

Sequence number of database page to be fetched from server.

required
Source code in firebird/driver/core.py
def get_page_content(self, page_number: int) -> bytes:
    """Returns content of single database page.

    Arguments:
       page_number: Sequence number of database page to be fetched from server.
    """
    return self.get_info(DbInfoCode.PAGE_CONTENTS, page_number)

get_table_access_stats() -> list[TableAccessStats]

Returns actual table access statistics.

Source code in firebird/driver/core.py
def get_table_access_stats(self) -> list[TableAccessStats]:
    """Returns actual table access statistics.
    """
    tables = {}
    info_codes = [DbInfoCode.READ_SEQ_COUNT, DbInfoCode.READ_IDX_COUNT,
                  DbInfoCode.INSERT_COUNT, DbInfoCode.UPDATE_COUNT,
                  DbInfoCode.DELETE_COUNT, DbInfoCode.BACKOUT_COUNT,
                  DbInfoCode.PURGE_COUNT, DbInfoCode.EXPUNGE_COUNT]
    #stats = self.get_info(info_codes)
    for info_code in info_codes:
        stat: Mapping = self.get_info(info_code)
        for table, count in stat.items():
            tables.setdefault(table, dict.fromkeys(info_codes))[info_code] = count
    return [TableAccessStats(table, **{_i2name[code]:count
                                       for code, count in tables[table].items()})
            for table in tables]

is_compressed() -> bool

Returns True if connection to the server uses data compression.

Source code in firebird/driver/core.py
def is_compressed(self) -> bool:
    """Returns True if connection to the server uses data compression.
    """
    return ConnectionFlag.COMPRESSED in ConnectionFlag(self.get_info(DbInfoCode.CONN_FLAGS))

is_encrypted() -> bool

Returns True if connection to the server uses data encryption.

Source code in firebird/driver/core.py
def is_encrypted(self) -> bool:
    """Returns True if connection to the server uses data encryption.
    """
    return ConnectionFlag.ENCRYPTED in ConnectionFlag(self.get_info(DbInfoCode.CONN_FLAGS))

supports(code: DbInfoCode) -> bool

Returns True if specified info code is supported by this InfoProvider.

Parameters:

Name Type Description Default
code DbInfoCode

Info code.

required
Source code in firebird/driver/core.py
def supports(self, code: DbInfoCode) -> bool:
    """Returns True if specified info code is supported by this InfoProvider.

    Arguments:
        code: Info code.
    """
    return code in self._handlers

firebird.driver.core.DatabaseInfoProvider

Bases: DatabaseInfoProvider3

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

Information can be accessed either via specific properties (preferred) or the lower-level get_info() method.

Important

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

Source code in firebird/driver/core.py
class DatabaseInfoProvider(DatabaseInfoProvider3):
    """Provides access to information about attached database [Firebird 4+].

    Information can be accessed either via specific properties (preferred) or the lower-level
    `get_info()` method.

    Important:
       Do NOT create instances of this class directly! Use `Connection.info` property to