Skip to content

firebird.driver.config

This module defines the configuration system for the firebird-driver. It uses an INI-style format managed via the DriverConfig class, which allows defining settings for the driver itself, default server/database parameters, and named configurations for specific servers and databases.

Configuration can be loaded from files, strings, or dictionaries, and supports environment variable interpolation. The primary interaction point is usually the global driver_config instance.

Classes

firebird.driver.config.DriverConfig

Bases: Config

Main configuration object for the Firebird driver. Holds global settings, default configurations, and lists of registered servers and databases.

Settings loaded from specific server/database sections override those in the db_defaults and server_defaults sections. When reading multiple files, options from later files override those from earlier ones.

Source code in firebird/driver/config.py
class DriverConfig(Config):
    """Main configuration object for the Firebird driver. Holds global settings, default
    configurations, and lists of registered servers and databases.

    Settings loaded from specific server/database sections override those in the `db_defaults`
    and `server_defaults` sections. When reading multiple files, options from later files
    override those from earlier ones.
    """
    def __init__(self, name: str):
        super().__init__(name)
        self.fb_client_library: StrOption = \
            StrOption('fb_client_library', "Path to Firebird client library")
        "Path to Firebird client library"
        self.stream_blob_threshold: IntOption = \
            IntOption('stream_blob_threshold',
                      "BLOB size threshold; larger BLOBs are streamed automatically (-1 disables it).",
                      default=65536)
        "BLOB size threshold. Larger BLOBs are streamed automatically; -1 disables this."
        self.db_defaults: DatabaseConfig = DatabaseConfig('firebird.db.defaults',
                                                          optional=True,
                                                          description="Default database configuration.")
        "Default database configuration ('firebird.db.defaults')"
        self.server_defaults: ServerConfig = ServerConfig('firebird.server.defaults',
                                                          optional=True,
                                                          description="Default server configuration.")
        "Default server configuration ('firebird.server.defaults')"
        self.servers: ConfigListOption = \
            ConfigListOption('servers', ServerConfig, "Registered servers")
        "Registered servers"
        self.databases: ConfigListOption = \
            ConfigListOption('databases', DatabaseConfig, "Registered databases")
        "Registered databases"
    def read(self, filenames: str | Iterable, encoding: str | None=None):
        """Read configuration from a filename or an iterable of filenames.

        Files that cannot be opened are silently ignored; this is
        designed so that you can specify an iterable of potential
        configuration file locations (e.g. current directory, user's
        home directory, systemwide directory), and all existing
        configuration files in the iterable will be read.  A single
        filename may also be given.

        Return list of successfully read files.
        """
        parser = ConfigParser(interpolation=EnvExtendedInterpolation())
        read_ok = parser.read(filenames, encoding)
        if read_ok:
            self.load_config(parser)
        return read_ok
    def read_file(self, f):
        """Read configuration from a file-like object.

        The `f` argument must be iterable, returning one line at a time.
        """
        parser = ConfigParser(interpolation=EnvExtendedInterpolation())
        parser.read_file(f)
        self.load_config(parser)
    def read_string(self, string: str) -> None:
        """Read configuration from a given string.
        """
        parser = ConfigParser(interpolation=EnvExtendedInterpolation())
        parser.read_string(string)
        self.load_config(parser)
    def read_dict(self, dictionary: dict[str, str]) -> None:
        """Read configuration from a dictionary.

        Keys are section names, values are dictionaries with keys and values
        that should be present in the section. If the used dictionary type
        preserves order, sections and their keys will be added in order.

        All types held in the dictionary are converted to strings during
        reading, including section names, option names and keys.
        """
        parser = ConfigParser(interpolation=EnvExtendedInterpolation())
        parser.read_dict(dictionary)
        self.load_config(parser)
    def get_server(self, name: str) -> ServerConfig:
        """Returns server configuration.
        """
        for srv in self.servers.value:
            if srv.name == name:
                return srv
        return None
    def get_database(self, name: str) -> DatabaseConfig:
        """Returns database configuration.
        """
        for db in self.databases.value:
            if db.name == name:
                return db
        return None
    def register_server(self, name: str, config: str | None=None) -> ServerConfig:
        """Register server.

        Arguments:
            name: Server name.
            config: Optional server configuration string in ConfigParser format in [name] section.

        Returns:
           ServerConfig: For newly registered server

        Raises:
            ValueError: If server is already registered.
        """
        if self.get_server(name) is not None:
            raise ValueError(f"Server '{name}' already registered.")
        srv_config = ServerConfig(name)
        self.servers.value.append(srv_config)
        if config:
            parser = ConfigParser(interpolation=EnvExtendedInterpolation())
            parser.read_string(config)
            srv_config.load_config(parser, name)
        return srv_config
    def register_database(self, name: str, config: str | None=None) -> DatabaseConfig:
        """Register database.

        Arguments:
            name: Database name.
            config: Optional database configuration string in ConfigParser format in [name] section.

        Returns:
           DatabaseConfig: For newly registered database

        Raises:
            ValueError: If database is already registered.
        """
        if self.get_database(name) is not None:
            raise ValueError(f"Database '{name}' already registered.")
        db_config = DatabaseConfig(name)
        self.databases.value.append(db_config)
        if config:
            parser = ConfigParser(interpolation=EnvExtendedInterpolation())
            parser.read_string(config)
            db_config.load_config(parser, name)
        return db_config

configs: list[Config] property

List of nested Config instances associated with this instance.

Includes:

  • Config instances directly assigned as attributes.
  • The Config instance held by any ConfigOption attribute.
  • All Config instances within the list held by any ConfigListOption attribute.

databases: ConfigListOption instance-attribute

Registered databases

db_defaults: DatabaseConfig instance-attribute

Default database configuration ('firebird.db.defaults')

fb_client_library: StrOption instance-attribute

Path to Firebird client library

name: str property

Name associated with Config (default section name).

optional: bool property

Whether config is optional (False) or mandatory (True) for configuration file (see load_config() for details).

options: list[Option] property

List of Option instances directly defined as attributes of this Config instance.

server_defaults: ServerConfig instance-attribute

Default server configuration ('firebird.server.defaults')

servers: ConfigListOption instance-attribute

Registered servers

stream_blob_threshold: IntOption instance-attribute

BLOB size threshold. Larger BLOBs are streamed automatically; -1 disables this.

clear(*, to_default: bool = True) -> None

Clears all owned options and options in owned sub-configs.

Parameters:

Name Type Description Default
to_default bool

If True, sets the option values to defaults, else to None.

True
Source code in firebird/base/config.py
def clear(self, *, to_default: bool=True) -> None:
    """Clears all owned options and options in owned sub-configs.

    Arguments:
        to_default: If True, sets the option values to defaults, else to None.
    """
    for option in self.options:
        option.clear(to_default=to_default)
    for config in self.configs:
        config.clear(to_default=to_default)

get_config(*, plain: bool = False) -> str

Returns string containing text lines suitable for use in configuration file processed with configparser.ConfigParser.

Important

When config is optional and the name is an empty string, it returns empty string.

Parameters:

Name Type Description Default
plain bool

When True, it outputs only the option values. When False, it includes also option descriptions and other helpful information.

False
Source code in firebird/base/config.py
def get_config(self, *, plain: bool=False) -> str:
    """Returns string containing text lines suitable for use in configuration file
    processed with [configparser.ConfigParser][].

    Important:
        When config is optional and the name is an empty string, it returns empty string.

    Arguments:
      plain: When True, it outputs only the option values. When False, it includes also
             option descriptions and other helpful information.
    """
    if self.optional and not self.name:
        return ''
    lines = [f"[{self.name}]\n"]
    if not plain:
        lines.append(';\n')
        for line in self.get_description().strip().splitlines():
            lines.append(f"; {line}\n")
    for option in self.options:
        if not plain:
            lines.append('\n')
        lines.append(option.get_config(plain=plain))
    for config in self.configs:
        if subcfg := config.get_config(plain=plain):
            if not plain:
                lines.append('\n')
            lines.append(subcfg)
    return ''.join(lines)

get_database(name: str) -> DatabaseConfig

Returns database configuration.

Source code in firebird/driver/config.py
def get_database(self, name: str) -> DatabaseConfig:
    """Returns database configuration.
    """
    for db in self.databases.value:
        if db.name == name:
            return db
    return None

get_description() -> str

Configuration description. Can span multiple lines.

Note: If description is not provided on instance creation, class doc string.

Source code in firebird/base/config.py
def get_description(self) -> str:
    """Configuration description. Can span multiple lines.

    Note:  If description is not provided on instance creation, class doc string.
    """
    return '' if self._description is None else self._description

get_server(name: str) -> ServerConfig

Returns server configuration.

Source code in firebird/driver/config.py
def get_server(self, name: str) -> ServerConfig:
    """Returns server configuration.
    """
    for srv in self.servers.value:
        if srv.name == name:
            return srv
    return None

load_config(config: ConfigParser, section: str | None = None) -> None

Update configuration values from a ConfigParser instance.

Parameters:

Name Type Description Default
config ConfigParser

ConfigParser instance containing configuration values.

required
section str | None

Name of the ConfigParser section corresponding to this Config instance. If None, uses self.name.

None
Behavior
  • Reads values for directly owned Option instances from the specified section.
  • Recursively calls load_config on directly owned Config instances using their respective name attribute as the section name.
  • Recursively calls load_config on Config instances referenced by owned ConfigOption and ConfigListOption values, using the section names stored within those options.

Raises:

Type Description
Error

If section does not exist in config and self.optional is False (unless section is DEFAULTSECT). Also wraps underlying ValueError or KeyError from option parsing.

KeyError

Propagated if an invalid section name is used for a nested config.

ValueError

Propagated if an option string cannot be parsed correctly.

Source code in firebird/base/config.py
def load_config(self, config: ConfigParser, section: str | None=None) -> None:
    """Update configuration values from a `ConfigParser` instance.

    Arguments:
        config:  `ConfigParser` instance containing configuration values.
        section: Name of the `ConfigParser` section corresponding to this `Config`
                 instance. If `None`, uses `self.name`.

    Behavior:
        - Reads values for directly owned `Option` instances from the specified `section`.
        - Recursively calls `load_config` on directly owned `Config` instances using
          their respective `name` attribute as the section name.
        - Recursively calls `load_config` on `Config` instances referenced by owned
          `ConfigOption` and `ConfigListOption` values, using the section names
          stored within those options.

    Raises:
        Error: If `section` does not exist in `config` and `self.optional` is `False`
               (unless `section` is `DEFAULTSECT`). Also wraps underlying [ValueError][]
               or [KeyError][] from option parsing.
        KeyError: Propagated if an invalid section name is used for a nested config.
        ValueError: Propagated if an option string cannot be parsed correctly.
    """
    if section is None:
        section = self.name
    if not config.has_section(section):
        if self._optional:
            return
        if section != DEFAULTSECT:
            raise Error(f"Configuration error: section '{section}' not found!")
    try:
        for option in self.options:
            option.load_config(config, section)
        for subcfg in self.configs:
            subcfg.load_config(config)
    except Error:
        raise
    except Exception as exc: # pragma: no cover
        raise Error(f"Configuration error: {exc}") from exc

load_proto(proto: ConfigProto) -> None

Deserialize value from ConfigProto message.

Parameters:

Name Type Description Default
proto ConfigProto

Protobuf message that may contains option values and sub-configs.

required
Source code in firebird/base/config.py
def load_proto(self, proto: ConfigProto) -> None:
    """Deserialize value from `ConfigProto` message.

    Arguments:
        proto: Protobuf message that may contains option values and sub-configs.
    """
    for option in self.options:
        option.load_proto(proto)
    for subcfg in self.configs:
        if subcfg.name in proto.configs:
            subcfg.load_proto(proto.configs[subcfg.name])

read(filenames: str | Iterable, encoding: str | None = None)

Read configuration from a filename or an iterable of filenames.

Files that cannot be opened are silently ignored; this is designed so that you can specify an iterable of potential configuration file locations (e.g. current directory, user's home directory, systemwide directory), and all existing configuration files in the iterable will be read. A single filename may also be given.

Return list of successfully read files.

Source code in firebird/driver/config.py
def read(self, filenames: str | Iterable, encoding: str | None=None):
    """Read configuration from a filename or an iterable of filenames.

    Files that cannot be opened are silently ignored; this is
    designed so that you can specify an iterable of potential
    configuration file locations (e.g. current directory, user's
    home directory, systemwide directory), and all existing
    configuration files in the iterable will be read.  A single
    filename may also be given.

    Return list of successfully read files.
    """
    parser = ConfigParser(interpolation=EnvExtendedInterpolation())
    read_ok = parser.read(filenames, encoding)
    if read_ok:
        self.load_config(parser)
    return read_ok

read_dict(dictionary: dict[str, str]) -> None

Read configuration from a dictionary.

Keys are section names, values are dictionaries with keys and values that should be present in the section. If the used dictionary type preserves order, sections and their keys will be added in order.

All types held in the dictionary are converted to strings during reading, including section names, option names and keys.

Source code in firebird/driver/config.py
def read_dict(self, dictionary: dict[str, str]) -> None:
    """Read configuration from a dictionary.

    Keys are section names, values are dictionaries with keys and values
    that should be present in the section. If the used dictionary type
    preserves order, sections and their keys will be added in order.

    All types held in the dictionary are converted to strings during
    reading, including section names, option names and keys.
    """
    parser = ConfigParser(interpolation=EnvExtendedInterpolation())
    parser.read_dict(dictionary)
    self.load_config(parser)

read_file(f)

Read configuration from a file-like object.

The f argument must be iterable, returning one line at a time.

Source code in firebird/driver/config.py
def read_file(self, f):
    """Read configuration from a file-like object.

    The `f` argument must be iterable, returning one line at a time.
    """
    parser = ConfigParser(interpolation=EnvExtendedInterpolation())
    parser.read_file(f)
    self.load_config(parser)

read_string(string: str) -> None

Read configuration from a given string.

Source code in firebird/driver/config.py
def read_string(self, string: str) -> None:
    """Read configuration from a given string.
    """
    parser = ConfigParser(interpolation=EnvExtendedInterpolation())
    parser.read_string(string)
    self.load_config(parser)

register_database(name: str, config: str | None = None) -> DatabaseConfig

Register database.

Parameters:

Name Type Description Default
name str

Database name.

required
config str | None

Optional database configuration string in ConfigParser format in [name] section.

None

Returns:

Name Type Description
DatabaseConfig DatabaseConfig

For newly registered database

Raises:

Type Description
ValueError

If database is already registered.

Source code in firebird/driver/config.py
def register_database(self, name: str, config: str | None=None) -> DatabaseConfig:
    """Register database.

    Arguments:
        name: Database name.
        config: Optional database configuration string in ConfigParser format in [name] section.

    Returns:
       DatabaseConfig: For newly registered database

    Raises:
        ValueError: If database is already registered.
    """
    if self.get_database(name) is not None:
        raise ValueError(f"Database '{name}' already registered.")
    db_config = DatabaseConfig(name)
    self.databases.value.append(db_config)
    if config:
        parser = ConfigParser(interpolation=EnvExtendedInterpolation())
        parser.read_string(config)
        db_config.load_config(parser, name)
    return db_config

register_server(name: str, config: str | None = None) -> ServerConfig

Register server.

Parameters:

Name Type Description Default
name str

Server name.

required
config str | None

Optional server configuration string in ConfigParser format in [name] section.

None

Returns:

Name Type Description
ServerConfig ServerConfig

For newly registered server

Raises:

Type Description
ValueError

If server is already registered.

Source code in firebird/driver/config.py
def register_server(self, name: str, config: str | None=None) -> ServerConfig:
    """Register server.

    Arguments:
        name: Server name.
        config: Optional server configuration string in ConfigParser format in [name] section.

    Returns:
       ServerConfig: For newly registered server

    Raises:
        ValueError: If server is already registered.
    """
    if self.get_server(name) is not None:
        raise ValueError(f"Server '{name}' already registered.")
    srv_config = ServerConfig(name)
    self.servers.value.append(srv_config)
    if config:
        parser = ConfigParser(interpolation=EnvExtendedInterpolation())
        parser.read_string(config)
        srv_config.load_config(parser, name)
    return srv_config

save_proto(proto: ConfigProto) -> None

Serialize value into ConfigProto message.

Parameters:

Name Type Description Default
proto ConfigProto

Protobuf message where option values and sub-configs should be stored.

required
Source code in firebird/base/config.py
def save_proto(self, proto: ConfigProto) -> None:
    """Serialize value into `ConfigProto` message.

    Arguments:
        proto: Protobuf message where option values and sub-configs should be stored.
    """
    for option in self.options:
        option.save_proto(proto)
    for subcfg in self.configs:
        subcfg.save_proto(proto.configs.get_or_create(subcfg.name))

validate() -> None

Recursively validates all directly owned options and sub-configs.

Checks whether
  • all required options have a non-None value.
  • required ConfigOption values have a non-empty section name.
  • required ConfigListOption values have a non-empty list.
  • all options are defined as instance attributes with the same name as option.name.
  • calls validate() on all nested Config instances (direct attributes, values of ConfigOption, and items in ConfigListOption).

Raises:

Type Description
Error

When any validation constraint is violated.

Source code in firebird/base/config.py
def validate(self) -> None:
    """Recursively validates all directly owned options and sub-configs.

    Checks whether:
        - all required options have a non-`None` value.
        - required `ConfigOption` values have a non-empty section name.
        - required `ConfigListOption` values have a non-empty list.
        - all options are defined as instance attributes with the same name as `option.name`.
        - calls `validate()` on all nested `Config` instances (direct attributes,
          values of `ConfigOption`, and items in `ConfigListOption`).

    Raises:
        Error: When any validation constraint is violated.
    """
    for option in self.options:
        option.validate()
        if not hasattr(self, option.name):
            raise Error(f"Option '{option.name}' is not defined as attribute with the same name")

firebird.driver.config.ServerConfig

Bases: Config

Represents configuration options specific to a named Firebird server entry.

Source code in firebird/driver/config.py
class ServerConfig(Config):
    """Represents configuration options specific to a named Firebird server entry.
    """
    def __init__(self, name: str, *, optional: bool=False, description: str | None=None):
        super().__init__(name, optional=optional, description=description)
        self.host: StrOption = \
            StrOption('host', "Server host machine specification")
        "Server host machine specification"
        self.port: StrOption = \
            StrOption('port', "Port used by Firebird server")
        "Port used by Firebird server"
        self.user: StrOption = \
            StrOption('user', "Defaul user name", default=os.environ.get('ISC_USER', None))
        "Defaul user name, default is envar ISC_USER or None if not specified"
        self.password: StrOption = \
            StrOption('password', "Default user password",
                      default=os.environ.get('ISC_PASSWORD', None))
        "Default user password, default is envar ISC_PASSWORD or None if not specified"
        self.config: StrOption = \
            StrOption('config', "Configuration override")
        "Configuration override"
        self.auth_plugin_list: StrOption = \
            StrOption('auth_plugin_list', "List of authentication plugins override")
        "List of authentication plugins override"
        self.trusted_auth: BoolOption = \
            BoolOption('trusted_auth', "Use trusted authentication", default=False)
        "Use trusted authentication, default: False"
        self.encoding: StrOption = \
            StrOption('encoding', "Encoding used for text data exchange with server",
                      default='ascii')
        "Encoding used for text data exchange with server"
        self.encoding_errors: StrOption = \
            StrOption('encoding_errors', "Handler used for encoding errors", default='strict')
        "Handler used for encoding errors. See `codecs error handlers <codecs>` for details."

auth_plugin_list: StrOption instance-attribute

List of authentication plugins override

config: StrOption instance-attribute

Configuration override

configs: list[Config] property

List of nested Config instances associated with this instance.

Includes:

  • Config instances directly assigned as attributes.
  • The Config instance held by any ConfigOption attribute.
  • All Config instances within the list held by any ConfigListOption attribute.

encoding: StrOption instance-attribute

Encoding used for text data exchange with server

encoding_errors: StrOption instance-attribute

Handler used for encoding errors. See codecs error handlers <codecs> for details.

host: StrOption instance-attribute

Server host machine specification

name: str property

Name associated with Config (default section name).

optional: bool property

Whether config is optional (False) or mandatory (True) for configuration file (see load_config() for details).

options: list[Option] property

List of Option instances directly defined as attributes of this Config instance.

password: StrOption instance-attribute

Default user password, default is envar ISC_PASSWORD or None if not specified

port: StrOption instance-attribute

Port used by Firebird server

trusted_auth: BoolOption instance-attribute

Use trusted authentication, default: False

user: StrOption instance-attribute

Defaul user name, default is envar ISC_USER or None if not specified

clear(*, to_default: bool = True) -> None

Clears all owned options and options in owned sub-configs.

Parameters:

Name Type Description Default
to_default bool

If True, sets the option values to defaults, else to None.

True
Source code in firebird/base/config.py
def clear(self, *, to_default: bool=True) -> None:
    """Clears all owned options and options in owned sub-configs.

    Arguments:
        to_default: If True, sets the option values to defaults, else to None.
    """
    for option in self.options:
        option.clear(to_default=to_default)
    for config in self.configs:
        config.clear(to_default=to_default)

get_config(*, plain: bool = False) -> str

Returns string containing text lines suitable for use in configuration file processed with configparser.ConfigParser.

Important

When config is optional and the name is an empty string, it returns empty string.

Parameters:

Name Type Description Default
plain bool

When True, it outputs only the option values. When False, it includes also option descriptions and other helpful information.

False
Source code in firebird/base/config.py
def get_config(self, *, plain: bool=False) -> str:
    """Returns string containing text lines suitable for use in configuration file
    processed with [configparser.ConfigParser][].

    Important:
        When config is optional and the name is an empty string, it returns empty string.

    Arguments:
      plain: When True, it outputs only the option values. When False, it includes also
             option descriptions and other helpful information.
    """
    if self.optional and not self.name:
        return ''
    lines = [f"[{self.name}]\n"]
    if not plain:
        lines.append(';\n')
        for line in self.get_description().strip().splitlines():
            lines.append(f"; {line}\n")
    for option in self.options:
        if not plain:
            lines.append('\n')
        lines.append(option.get_config(plain=plain))
    for config in self.configs:
        if subcfg := config.get_config(plain=plain):
            if not plain:
                lines.append('\n')
            lines.append(subcfg)
    return ''.join(lines)

get_description() -> str

Configuration description. Can span multiple lines.

Note: If description is not provided on instance creation, class doc string.

Source code in firebird/base/config.py
def get_description(self) -> str:
    """Configuration description. Can span multiple lines.

    Note:  If description is not provided on instance creation, class doc string.
    """
    return '' if self._description is None else self._description

load_config(config: ConfigParser, section: str | None = None) -> None

Update configuration values from a ConfigParser instance.

Parameters:

Name Type Description Default
config ConfigParser

ConfigParser instance containing configuration values.

required
section str | None

Name of the ConfigParser section corresponding to this Config instance. If None, uses self.name.

None
Behavior
  • Reads values for directly owned Option instances from the specified section.
  • Recursively calls load_config on directly owned Config instances using their respective name attribute as the section name.
  • Recursively calls load_config on Config instances referenced by owned ConfigOption and ConfigListOption values, using the section names stored within those options.

Raises:

Type Description
Error

If section does not exist in config and self.optional is False (unless section is DEFAULTSECT). Also wraps underlying ValueError or KeyError from option parsing.

KeyError

Propagated if an invalid section name is used for a nested config.

ValueError

Propagated if an option string cannot be parsed correctly.

Source code in firebird/base/config.py
def load_config(self, config: ConfigParser, section: str | None=None) -> None:
    """Update configuration values from a `ConfigParser` instance.

    Arguments:
        config:  `ConfigParser` instance containing configuration values.
        section: Name of the `ConfigParser` section corresponding to this `Config`
                 instance. If `None`, uses `self.name`.

    Behavior:
        - Reads values for directly owned `Option` instances from the specified `section`.
        - Recursively calls `load_config` on directly owned `Config` instances using
          their respective `name` attribute as the section name.
        - Recursively calls `load_config` on `Config` instances referenced by owned
          `ConfigOption` and `ConfigListOption` values, using the section names
          stored within those options.

    Raises:
        Error: If `section` does not exist in `config` and `self.optional` is `False`
               (unless `section` is `DEFAULTSECT`). Also wraps underlying [ValueError][]
               or [KeyError][] from option parsing.
        KeyError: Propagated if an invalid section name is used for a nested config.
        ValueError: Propagated if an option string cannot be parsed correctly.
    """
    if section is None:
        section = self.name
    if not config.has_section(section):
        if self._optional:
            return
        if section != DEFAULTSECT:
            raise Error(f"Configuration error: section '{section}' not found!")
    try:
        for option in self.options:
            option.load_config(config, section)
        for subcfg in self.configs:
            subcfg.load_config(config)
    except Error:
        raise
    except Exception as exc: # pragma: no cover
        raise Error(f"Configuration error: {exc}") from exc

load_proto(proto: ConfigProto) -> None

Deserialize value from ConfigProto message.

Parameters:

Name Type Description Default
proto ConfigProto

Protobuf message that may contains option values and sub-configs.

required
Source code in firebird/base/config.py
def load_proto(self, proto: ConfigProto) -> None:
    """Deserialize value from `ConfigProto` message.

    Arguments:
        proto: Protobuf message that may contains option values and sub-configs.
    """
    for option in self.options:
        option.load_proto(proto)
    for subcfg in self.configs:
        if subcfg.name in proto.configs:
            subcfg.load_proto(proto.configs[subcfg.name])

save_proto(proto: ConfigProto) -> None

Serialize value into ConfigProto message.

Parameters:

Name Type Description Default
proto ConfigProto

Protobuf message where option values and sub-configs should be stored.

required
Source code in firebird/base/config.py
def save_proto(self, proto: ConfigProto) -> None:
    """Serialize value into `ConfigProto` message.

    Arguments:
        proto: Protobuf message where option values and sub-configs should be stored.
    """
    for option in self.options:
        option.save_proto(proto)
    for subcfg in self.configs:
        subcfg.save_proto(proto.configs.get_or_create(subcfg.name))

validate() -> None

Recursively validates all directly owned options and sub-configs.

Checks whether
  • all required options have a non-None value.
  • required ConfigOption values have a non-empty section name.
  • required ConfigListOption values have a non-empty list.
  • all options are defined as instance attributes with the same name as option.name.
  • calls validate() on all nested Config instances (direct attributes, values of ConfigOption, and items in ConfigListOption).

Raises:

Type Description
Error

When any validation constraint is violated.

Source code in firebird/base/config.py
def validate(self) -> None:
    """Recursively validates all directly owned options and sub-configs.

    Checks whether:
        - all required options have a non-`None` value.
        - required `ConfigOption` values have a non-empty section name.
        - required `ConfigListOption` values have a non-empty list.
        - all options are defined as instance attributes with the same name as `option.name`.
        - calls `validate()` on all nested `Config` instances (direct attributes,
          values of `ConfigOption`, and items in `ConfigListOption`).

    Raises:
        Error: When any validation constraint is violated.
    """
    for option in self.options:
        option.validate()
        if not hasattr(self, option.name):
            raise Error(f"Option '{option.name}' is not defined as attribute with the same name")

firebird.driver.config.DatabaseConfig

Bases: Config

Represents configuration options specific to a named Firebird database entry, including connection and creation parameters.

Source code in firebird/driver/config.py
class DatabaseConfig(Config):
    """Represents configuration options specific to a named Firebird database entry, including connection and creation parameters.
    """
    def __init__(self, name: str, *, optional: bool=False, description: str | None=None):
        super().__init__(name, optional=optional, description=description)
        self.server: StrOption = \
            StrOption('server', "Name of server where database is located")
        "Name of server where database is located"
        self.dsn: StrOption = \
            StrOption('dsn', "Database connection string")
        "Database connection string"
        self.database: StrOption = \
            StrOption('database', "Database file specification or alias")
        "Database file specification or alias"
        self.utf8filename: BoolOption = \
            BoolOption('utf8filename', "Specifies whether the database parameter (filename) is encoded in UTF-8 when passed to the server.")
        "Specifies whether the database parameter (filename) is encoded in UTF-8 when passed to the server."
        self.protocol: EnumOption = \
            EnumOption('protocol', NetProtocol, "Network protocol to use for the connection. Value must be a member of the .NetProtocol enum.")
        "Network protocol to use for the connection. Value must be a member of the .NetProtocol enum."
        self.user: StrOption = \
            StrOption('user', "Defaul user name", default=os.environ.get('ISC_USER', None))
        "Defaul user name, default is envar ISC_USER or None if not specified"
        self.password: StrOption = \
            StrOption('password', "Default user password",
                      default=os.environ.get('ISC_PASSWORD', None))
        "Default user password, default is envar ISC_PASSWORD or None if not specified"
        self.trusted_auth: BoolOption = \
            BoolOption('trusted_auth', "Use trusted authentication", default=False)
        "Use trusted authentication, default: False"
        self.role: StrOption = \
            StrOption('role', "User role")
        "User role"
        self.charset: StrOption = \
            StrOption('charset', "Character set for database connection")
        "Character set for database connection"
        self.sql_dialect: IntOption = \
            IntOption('sql_dialect', "SQL Dialect for database connection", default=3)
        "SQL Dialect for database connection, default: 3"
        self.timeout: IntOption = \
            IntOption('timeout', "Connection timeout")
        "Connection timeout"
        self.no_linger: BoolOption = \
            BoolOption('no_linger', "Do not use linger for database connection")
        "Do not use linger for database connection"
        self.cache_size: IntOption = \
            IntOption('cache_size', "Page cache size override for database connection")
        "Page cache size override for database connection"
        self.dummy_packet_interval: IntOption = \
            IntOption('dummy_packet_interval',
                      "Dummy packet interval")
        "Dummy packet interval for this database connection"
        self.config: StrOption = \
            StrOption('config', "Configuration override")
        "Configuration override"
        self.auth_plugin_list: StrOption = \
            StrOption('auth_plugin_list', "List of authentication plugins override")
        "List of authentication plugins override"
        self.session_time_zone: StrOption = \
            StrOption('session_time_zone', "Session time zone")
        "Session time zone [Firebird 4]"
        self.set_bind: StrOption = \
            StrOption('set_bind', "Set BIND - sets up columns coercion rules in session")
        "Set BIND [Firebird 4]"
        self.decfloat_round: EnumOption = \
            EnumOption('decfloat_round', DecfloatRound, "DECFLOAT round mode")
        "Set DECFLOAT ROUND [Firebird 4], value is `.DecfloatRound`"
        self.decfloat_traps: ListOption = \
            ListOption('decfloat_traps', DecfloatTraps,
                       """Specifies which DECFLOAT exceptional conditions should cause a trap
(raise an error) [Firebird 4]. Accepts a list of .DecfloatTraps enum members.""")
        "Specifies which DECFLOAT exceptional conditions should cause a trap (raise an error) [Firebird 4]. Accepts a list of .DecfloatTraps enum members."
        self.parallel_workers = \
            IntOption('parallel_workers', "Number of parallel workers")
        "Number of parallel workers"
        # --- Options specific to Database Creation ---
        self.page_size: IntOption = \
            IntOption('page_size', "Page size to be used for created database.")
        "Database create option. Page size to be used."
        self.forced_writes: BoolOption = \
            BoolOption('forced_writes', "Write mode for created database (True = sync, False = async)")
        "Database create option. Write mode (True = sync/False = async)."
        self.db_charset: StrOption = \
            StrOption('db_charset', "Character set for created database")
        "Database create option. Character set for the database."
        self.db_sql_dialect: IntOption = \
            IntOption('db_sql_dialect', "SQL dialect for created database")
        "Database create option. SQL dialect for the database."
        self.db_cache_size: IntOption = \
            IntOption('db_cache_size', "Page cache size override for created database")
        "Database create option. Page cache size override for database."
        self.sweep_interval: IntOption = \
            IntOption('sweep_interval', "Sweep interval for created database")
        "Database create option. Sweep interval for the database."
        self.reserve_space: BoolOption = \
            BoolOption('reserve_space',
                       "Data page space usage for created database (True = reserve space, False = Use all space)")
        "Database create option. Data page space usage (True = reserve space, False = Use all space)."

auth_plugin_list: StrOption instance-attribute

List of authentication plugins override

cache_size: IntOption instance-attribute

Page cache size override for database connection

charset: StrOption instance-attribute

Character set for database connection

config: StrOption instance-attribute

Configuration override

configs: list[Config] property

List of nested Config instances associated with this instance.

Includes:

  • Config instances directly assigned as attributes.
  • The Config instance held by any ConfigOption attribute.
  • All Config instances within the list held by any ConfigListOption attribute.

database: StrOption instance-attribute

Database file specification or alias

db_cache_size: IntOption instance-attribute

Database create option. Page cache size override for database.

db_charset: StrOption instance-attribute

Database create option. Character set for the database.

db_sql_dialect: IntOption instance-attribute

Database create option. SQL dialect for the database.

decfloat_round: EnumOption instance-attribute

Set DECFLOAT ROUND [Firebird 4], value is .DecfloatRound

decfloat_traps: ListOption instance-attribute

Specifies which DECFLOAT exceptional conditions should cause a trap (raise an error) [Firebird 4]. Accepts a list of .DecfloatTraps enum members.

dsn: StrOption instance-attribute

Database connection string

dummy_packet_interval: IntOption instance-attribute

Dummy packet interval for this database connection

forced_writes: BoolOption instance-attribute

Database create option. Write mode (True = sync/False = async).

name: str property

Name associated with Config (default section name).

no_linger: BoolOption instance-attribute

Do not use linger for database connection

optional: bool property

Whether config is optional (False) or mandatory (True) for configuration file (see load_config() for details).

options: list[Option] property

List of Option instances directly defined as attributes of this Config instance.

page_size: IntOption instance-attribute

Database create option. Page size to be used.

parallel_workers instance-attribute

Number of parallel workers

password: StrOption instance-attribute

Default user password, default is envar ISC_PASSWORD or None if not specified

protocol: EnumOption instance-attribute

Network protocol to use for the connection. Value must be a member of the .NetProtocol enum.

reserve_space: BoolOption instance-attribute

Database create option. Data page space usage (True = reserve space, False = Use all space).

role: StrOption instance-attribute

User role

server: StrOption instance-attribute

Name of server where database is located

session_time_zone: StrOption instance-attribute

Session time zone [Firebird 4]

set_bind: StrOption instance-attribute

Set BIND [Firebird 4]

sql_dialect: IntOption instance-attribute

SQL Dialect for database connection, default: 3

sweep_interval: IntOption instance-attribute

Database create option. Sweep interval for the database.

timeout: IntOption instance-attribute

Connection timeout

trusted_auth: BoolOption instance-attribute

Use trusted authentication, default: False

user: StrOption instance-attribute

Defaul user name, default is envar ISC_USER or None if not specified

utf8filename: BoolOption instance-attribute

Specifies whether the database parameter (filename) is encoded in UTF-8 when passed to the server.

clear(*, to_default: bool = True) -> None

Clears all owned options and options in owned sub-configs.

Parameters:

Name Type Description Default
to_default bool

If True, sets the option values to defaults, else to None.

True
Source code in firebird/base/config.py
def clear(self, *, to_default: bool=True) -> None:
    """Clears all owned options and options in owned sub-configs.

    Arguments:
        to_default: If True, sets the option values to defaults, else to None.
    """
    for option in self.options:
        option.clear(to_default=to_default)
    for config in self.configs:
        config.clear(to_default=to_default)

get_config(*, plain: bool = False) -> str

Returns string containing text lines suitable for use in configuration file processed with configparser.ConfigParser.

Important

When config is optional and the name is an empty string, it returns empty string.

Parameters:

Name Type Description Default
plain bool

When True, it outputs only the option values. When False, it includes also option descriptions and other helpful information.

False
Source code in firebird/base/config.py
def get_config(self, *, plain: bool=False) -> str:
    """Returns string containing text lines suitable for use in configuration file
    processed with [configparser.ConfigParser][].

    Important:
        When config is optional and the name is an empty string, it returns empty string.

    Arguments:
      plain: When True, it outputs only the option values. When False, it includes also
             option descriptions and other helpful information.
    """
    if self.optional and not self.name:
        return ''
    lines = [f"[{self.name}]\n"]
    if not plain:
        lines.append(';\n')
        for line in self.get_description().strip().splitlines():
            lines.append(f"; {line}\n")
    for option in self.options:
        if not plain:
            lines.append('\n')
        lines.append(option.get_config(plain=plain))
    for config in self.configs:
        if subcfg := config.get_config(plain=plain):
            if not plain:
                lines.append('\n')
            lines.append(subcfg)
    return ''.join(lines)

get_description() -> str

Configuration description. Can span multiple lines.

Note: If description is not provided on instance creation, class doc string.

Source code in firebird/base/config.py
def get_description(self) -> str:
    """Configuration description. Can span multiple lines.

    Note:  If description is not provided on instance creation, class doc string.
    """
    return '' if self._description is None else self._description

load_config(config: ConfigParser, section: str | None = None) -> None

Update configuration values from a ConfigParser instance.

Parameters:

Name Type Description Default
config ConfigParser

ConfigParser instance containing configuration values.

required
section str | None

Name of the ConfigParser section corresponding to this Config instance. If None, uses self.name.

None
Behavior
  • Reads values for directly owned Option instances from the specified section.
  • Recursively calls load_config on directly owned Config instances using their respective name attribute as the section name.
  • Recursively calls load_config on Config instances referenced by owned ConfigOption and ConfigListOption values, using the section names stored within those options.

Raises:

Type Description
Error

If section does not exist in config and self.optional is False (unless section is DEFAULTSECT). Also wraps underlying ValueError or KeyError from option parsing.

KeyError

Propagated if an invalid section name is used for a nested config.

ValueError

Propagated if an option string cannot be parsed correctly.

Source code in firebird/base/config.py
def load_config(self, config: ConfigParser, section: str | None=None) -> None:
    """Update configuration values from a `ConfigParser` instance.

    Arguments:
        config:  `ConfigParser` instance containing configuration values.
        section: Name of the `ConfigParser` section corresponding to this `Config`
                 instance. If `None`, uses `self.name`.

    Behavior:
        - Reads values for directly owned `Option` instances from the specified `section`.
        - Recursively calls `load_config` on directly owned `Config` instances using
          their respective `name` attribute as the section name.
        - Recursively calls `load_config` on `Config` instances referenced by owned
          `ConfigOption` and `ConfigListOption` values, using the section names
          stored within those options.

    Raises:
        Error: If `section` does not exist in `config` and `self.optional` is `False`
               (unless `section` is `DEFAULTSECT`). Also wraps underlying [ValueError][]
               or [KeyError][] from option parsing.
        KeyError: Propagated if an invalid section name is used for a nested config.
        ValueError: Propagated if an option string cannot be parsed correctly.
    """
    if section is None:
        section = self.name
    if not config.has_section(section):
        if self._optional:
            return
        if section != DEFAULTSECT:
            raise Error(f"Configuration error: section '{section}' not found!")
    try:
        for option in self.options:
            option.load_config(config, section)
        for subcfg in self.configs:
            subcfg.load_config(config)
    except Error:
        raise
    except Exception as exc: # pragma: no cover
        raise Error(f"Configuration error: {exc}") from exc

load_proto(proto: ConfigProto) -> None

Deserialize value from ConfigProto message.

Parameters:

Name Type Description Default
proto ConfigProto

Protobuf message that may contains option values and sub-configs.

required
Source code in firebird/base/config.py
def load_proto(self, proto: ConfigProto) -> None:
    """Deserialize value from `ConfigProto` message.

    Arguments:
        proto: Protobuf message that may contains option values and sub-configs.
    """
    for option in self.options:
        option.load_proto(proto)
    for subcfg in self.configs:
        if subcfg.name in proto.configs:
            subcfg.load_proto(proto.configs[subcfg.name])

save_proto(proto: ConfigProto) -> None

Serialize value into ConfigProto message.

Parameters:

Name Type Description Default
proto ConfigProto

Protobuf message where option values and sub-configs should be stored.

required
Source code in firebird/base/config.py
def save_proto(self, proto: ConfigProto) -> None:
    """Serialize value into `ConfigProto` message.

    Arguments:
        proto: Protobuf message where option values and sub-configs should be stored.
    """
    for option in self.options:
        option.save_proto(proto)
    for subcfg in self.configs:
        subcfg.save_proto(proto.configs.get_or_create(subcfg.name))

validate() -> None

Recursively validates all directly owned options and sub-configs.

Checks whether
  • all required options have a non-None value.
  • required ConfigOption values have a non-empty section name.
  • required ConfigListOption values have a non-empty list.
  • all options are defined as instance attributes with the same name as option.name.
  • calls validate() on all nested Config instances (direct attributes, values of ConfigOption, and items in ConfigListOption).

Raises:

Type Description
Error

When any validation constraint is violated.

Source code in firebird/base/config.py
def validate(self) -> None:
    """Recursively validates all directly owned options and sub-configs.

    Checks whether:
        - all required options have a non-`None` value.
        - required `ConfigOption` values have a non-empty section name.
        - required `ConfigListOption` values have a non-empty list.
        - all options are defined as instance attributes with the same name as `option.name`.
        - calls `validate()` on all nested `Config` instances (direct attributes,
          values of `ConfigOption`, and items in `ConfigListOption`).

    Raises:
        Error: When any validation constraint is violated.
    """
    for option in self.options:
        option.validate()
        if not hasattr(self, option.name):
            raise Error(f"Option '{option.name}' is not defined as attribute with the same name")

Globals

firebird.driver.config.driver_config: DriverConfig module-attribute

Global driver configuration instance. Load settings from files/strings/dicts into this object before connecting, or modify its attributes directly for programmatic configuration.