firebird.lib.schema

Globals

firebird.lib.schema.SCRIPT_DEFAULT_ORDER

Default order of sections for DDL script generation via get_metadata_ddl().

Enums

class firebird.lib.schema.FieldType(value)[source]

Bases: IntEnum

Firebird field type codes.

BLOB = 261
BLOB_ID = 45
BOOLEAN = 23
CSTRING = 40
DATE = 12
DEC16 = 24
DEC34 = 25
DOUBLE = 27
FLOAT = 10
INT128 = 26
INT64 = 16
LONG = 8
NONE = 0
QUAD = 9
SHORT = 7
TEXT = 14
TIME = 13
TIMESTAMP = 35
TIMESTAMP_TZ = 29
TIMESTAMP_TZ_EX = 31
TIME_TZ = 28
TIME_TZ_EX = 30
VARYING = 37
class firebird.lib.schema.FieldSubType(value)[source]

Bases: IntEnum

Field sub-types.

ACL = 3
BINARY = 0
BLR = 2
DEBUG_INFORMATION = 9
DECIMAL = 2
EXTERNAL_FILE_DESCRIPTION = 8
FORMAT = 6
NUMERIC = 1
RANGES = 4
SUMMARY = 5
TEXT = 1
TRANSACTION_DESCRIPTION = 7
class firebird.lib.schema.ObjectType(value)[source]

Bases: IntEnum

Dependent type codes.

Changed in version 1.4.0: - PACKAGE renamed to PACKAGE_HEADER, added values 20-37

BLOB_FILTER = 16
CHARACTER_SET = 11
CHARSETS = 31
CHECK = 4
COLLATION = 17
COLLATIONS = 32
COLUMN = 9
DATABASE = 21
DOMAIN = 3
DOMAINS = 28
EXCEPTION = 7
EXCEPTIONS = 29
FILTERS = 33
FUNCTIONS = 25
GENERATOR = 14
GENERATORS = 27
INDEX = 10
INDEX_CONDITION = 37
INDEX_EXPR = 6
JOBS = 34
PACKAGES = 26
PACKAGE_BODY = 19
PACKAGE_HEADER = 18
PRIVILEGE = 20
PROCEDURE = 5
PROCEDURES = 24
RELATIONS = 22
ROLE = 13
ROLES = 30
TABLE = 0
TABLESPACE = 35
TABLESPACES = 36
TRIGGER = 2
UDF = 15
USER = 8
USER_GROUP = 12
VIEW = 1
VIEWS = 23
class firebird.lib.schema.IndexType(value)[source]

Bases: Enum

Index ordering.

ASCENDING = 'ASCENDING'
DESCENDING = 'DESCENDING'
class firebird.lib.schema.Mechanism(value)[source]

Bases: IntEnum

Mechanism codes.

BY_ISC_DESCRIPTOR = 3
BY_REFERENCE = 1
BY_REFERENCE_WITH_NULL = 5
BY_SCALAR_ARRAY_DESCRIPTOR = 4
BY_VALUE = 0
BY_VMS_DESCRIPTOR = 2
class firebird.lib.schema.TransactionState(value)[source]

Bases: IntEnum

Transaction state codes.

COMMITTED = 2
LIMBO = 1
ROLLED_BACK = 3
class firebird.lib.schema.SystemFlag(value)[source]

Bases: IntEnum

System flag codes.

CHECK_CONSTRAINT = 3
IDENTITY_GENERATOR = 6
QLI = 2
REFERENTIAL_CONSTRAINT = 4
SYSTEM = 1
USER = 0
VIEW_CHECK = 5
class firebird.lib.schema.RelationType(value)[source]

Bases: IntEnum

Relation type codes.

EXTERNAL = 2
GLOBAL_TEMPORARY_DELETE = 5
GLOBAL_TEMPORARY_PRESERVE = 4
PERSISTENT = 0
VIEW = 1
VIRTUAL = 3
class firebird.lib.schema.ProcedureType(value)[source]

Bases: IntEnum

Procedure type codes.

EXECUTABLE = 2
LEGACY = 0
SELECTABLE = 1
class firebird.lib.schema.ParameterMechanism(value)[source]

Bases: IntEnum

Parameter mechanism type codes.

NORMAL = 0
TYPE_OF = 1
class firebird.lib.schema.TypeFrom(value)[source]

Bases: IntEnum

Source of parameter datatype codes.

DATATYPE = 0
DOMAIN = 1
TYPE_OF_COLUMN = 3
TYPE_OF_DOMAIN = 2
class firebird.lib.schema.ParameterType(value)[source]

Bases: IntEnum

Parameter type codes.

INPUT = 0
OUTPUT = 1
class firebird.lib.schema.IdentityType(value)[source]

Bases: IntEnum

Identity type codes.

ALWAYS = 0
BY_DEFAULT = 1
class firebird.lib.schema.GrantOption(value)[source]

Bases: IntEnum

Grant option codes.

ADMIN_OPTION = 2
GRANT_OPTION = 1
NONE = 0
class firebird.lib.schema.PageType(value)[source]

Bases: IntEnum

Page type codes.

BLOB = 8
DATA = 5
GENERATOR = 9
HEADER = 1
INDEX_BUCKET = 7
INDEX_ROOT = 6
PAGE_INVENTORY = 2
POINTER = 4
SCN_INVENTORY = 10
TRANSACTION_INVENTORY = 3
class firebird.lib.schema.MapTo(value)[source]

Bases: IntEnum

Map to type codes.

ROLE = 1
USER = 0
class firebird.lib.schema.TriggerType(value)[source]

Bases: IntEnum

Trigger type codes.

DB = 8192
DDL = 16384
DML = 0
class firebird.lib.schema.DDLTrigger(value)[source]

Bases: IntEnum

DDL trigger type codes.

ALTER_CHARACTER_SET = 39
ALTER_DOMAIN = 23
ALTER_EXCEPTION = 17
ALTER_FUNCTION = 8
ALTER_INDEX = 29
ALTER_MAPPING = 46
ALTER_PACKAGE = 41
ALTER_PROCEDURE = 5
ALTER_ROLE = 26
ALTER_SEQUENCE = 32
ALTER_TABLE = 2
ALTER_TRIGGER = 11
ALTER_USER = 35
ALTER_VIEW = 20
ANY = 4611686018427375615
CREATE_COLLATION = 37
CREATE_DOMAIN = 22
CREATE_EXCEPTION = 16
CREATE_FUNCTION = 7
CREATE_INDEX = 28
CREATE_MAPPING = 45
CREATE_PACKAGE = 40
CREATE_PACKAGE_BODY = 43
CREATE_PROCEDURE = 4
CREATE_ROLE = 25
CREATE_SEQUENCE = 31
CREATE_TABLE = 1
CREATE_TRIGGER = 10
CREATE_USER = 34
CREATE_VIEW = 19
DROP_COLLATION = 38
DROP_DOMAIN = 24
DROP_EXCEPTION = 18
DROP_FUNCTION = 9
DROP_INDEX = 30
DROP_MAPPING = 47
DROP_PACKAGE = 42
DROP_PACKAGE_BODY = 44
DROP_PROCEDURE = 6
DROP_ROLE = 27
DROP_SEQUENCE = 33
DROP_TABLE = 3
DROP_TRIGGER = 12
DROP_USER = 36
DROP_VIEW = 21
class firebird.lib.schema.DBTrigger(value)[source]

Bases: IntEnum

Database trigger type codes.

CONNECT = 0
DISCONNECT = 1
TRANSACTION_COMMIT = 3
TRANSACTION_ROLLBACK = 4
TRANSACTION_START = 2
class firebird.lib.schema.TriggerTime(value)[source]

Bases: IntEnum

Trigger action time codes.

AFTER = 1
BEFORE = 0
class firebird.lib.schema.ConstraintType(value)[source]

Bases: Enum

Contraint type codes.

CHECK = 'CHECK'
FOREIGN_KEY = 'FOREIGN KEY'
NOT_NULL = 'NOT NULL'
PRIMARY_KEY = 'PRIMARY KEY'
UNIQUE = 'UNIQUE'
class firebird.lib.schema.Section(value)[source]

Bases: Enum

DDL script sections. Used by Schema.get_metadata_ddl().

CHARACTER_SETS = 2
CHECK_CONSTRAINTS = 13
COLLATIONS = 1
COMMENTS = 23
DOMAINS = 6
EXCEPTIONS = 5
FOREIGN_CONSTRAINTS = 14
FUNCTION_BODIES = 19
FUNCTION_DEFS = 8
GENERATORS = 4
GRANTS = 22
INDEX_ACTIVATIONS = 27
INDEX_DEACTIVATIONS = 26
INDICES = 15
PACKAGE_BODIES = 17
PACKAGE_DEFS = 7
PRIMARY_KEYS = 11
PROCEDURE_BODIES = 18
PROCEDURE_DEFS = 9
ROLES = 21
SET_GENERATORS = 25
SHADOWS = 24
TABLES = 10
TRIGGERS = 20
TRIGGER_ACTIVATIONS = 29
TRIGGER_DEACTIVATIONS = 28
UDFS = 3
UNIQUE_CONSTRAINTS = 12
VIEWS = 16
class firebird.lib.schema.Category(value)[source]

Bases: Enum

Schema information collection categories.

BACKUP_HISTORY = 20
CHARACTER_SETS = 11
COLLATIONS = 10
CONSTRAINTS = 9
DEPENDENCIES = 5
DOMAINS = 3
EXCEPTIONS = 12
FILES = 15
FILTERS = 21
FUNCTIONS = 14
GENERATORS = 6
INDICES = 4
PACKAGES = 19
PRIVILEGES = 17
PROCEDURES = 8
ROLES = 13
SEQUENCES = 6
SHADOWS = 16
TABLES = 1
TRIGGERS = 7
USERS = 18
VIEWS = 2
class firebird.lib.schema.Privacy(value)[source]

Bases: IntEnum

Privacy flag codes.

PRIVATE = 1
PUBLIC = 0
class firebird.lib.schema.Legacy(value)[source]

Bases: IntEnum

Legacy flag codes.

LEGACY_STYLE = 1
NEW_STYLE = 0
class firebird.lib.schema.PrivilegeCode(value)[source]

Bases: Enum

Priviledge codes.

ALTER = 'L'
CREATE = 'C'
DELETE = 'D'
DROP = 'O'
EXECUTE = 'X'
INSERT = 'I'
MEMBERSHIP = 'M'
REFERENCES = 'R'
SELECT = 'S'
UPDATE = 'U'
USAGE = 'G'

Flags

class firebird.lib.schema.ShadowFlag(value)[source]

Bases: IntFlag

Shadow file flags.

_generate_next_value_(start, count, last_values)

Generate the next value when not given.

name: the name of the member start: the initial start value or None count: the number of existing members last_values: the last value assigned or None

CONDITIONAL = 16
INACTIVE = 2
MANUAL = 4
class firebird.lib.schema.DMLTrigger(value)[source]

Bases: IntFlag

DML trigger type codes.

_generate_next_value_(start, count, last_values)

Generate the next value when not given.

name: the name of the member start: the initial start value or None count: the number of existing members last_values: the last value assigned or None

DELETE = 4
INSERT = 1
UPDATE = 2
class firebird.lib.schema.CollationFlag(value)[source]

Bases: IntFlag

Collation attribute flags.

_generate_next_value_(start, count, last_values)

Generate the next value when not given.

name: the name of the member start: the initial start value or None count: the number of existing members last_values: the last value assigned or None

ACCENT_INSENSITIVE = 4
CASE_INSENSITIVE = 2
NONE = 0
PAD_SPACE = 1

Functions

firebird.lib.schema.get_grants(privileges: list[Privilege], grantors: list[str] | None = None) list[str][source]

Get list of minimal set of SQL GRANT statamenets necessary to grant specified privileges.

Parameters:
Keyword Arguments:

grantors – list of standard grantor names. Generates GRANTED BY clause for privileges granted by user that’s not in list.

Return type:

list[str]

Classes

class firebird.lib.schema.Visitable[source]

Bases: object

Base class for Visitor Pattern support.

accept(visitor: Visitor) None[source]

Accepts a Visitor object as part of the Visitor design pattern.

Calls the visit() method on the provided visitor object, passing this SchemaItem instance (self) as the argument.

Parameters:

visitor (Visitor) – An object implementing the Visitor interface.

Return type:

None

class firebird.lib.schema.Visitor[source]

Bases: object

Base class for Visitor Pattern visitors.

Descendants may implement methods to handle individual object types that follow naming pattern visit_[class_name]. Calls default_action() if appropriate special method is not defined.

Important

This implementation uses Python Method Resolution Order (__mro__) to find special handling method, so special method for given class is used also for its decendants.

Example:

class Node(object): pass
class A(Node): pass
class B(Node): pass
class C(A,B): pass

class MyVisitor(object):
    def default_action(self, obj):
        print('default_action ', obj.__class__.__name__)

    def visit_b(self, obj):
        print('visit_b ', obj.__class__.__name__)


a = A()
b = B()
c = C()
visitor = MyVisitor()
visitor.visit(a)
visitor.visit(b)
visitor.visit(c)

Will create output:

default_action A
visit_b B
visit_b C
default_action(obj: Visitable) None[source]

Default handler for visited objects.

Parameters:

obj (Visitable) – Object to be handled.

Return type:

None

Note

Default implementation does nothing!

visit(obj: Visitable) Any[source]

Dispatch to method that handles obj.

Parameters:

obj (Visitable) – Object to be handled by visitor.

Return type:

Any

First traverses the obj.__mro__ to try find method with name following visit_ pattern and calls it with obj. Otherwise it calls default_action().

class firebird.lib.schema.Schema[source]

Bases: Visitable

Provides access to and represents the metadata of a Firebird database.

This class serves as the main entry point for exploring the database schema. It connects to a database (typically obtained via Connection.schema) and provides access to various schema elements like tables, views, procedures, domains, etc., by querying the RDB$ system tables using an internal, read-committed transaction.

Key Behaviors:

  • Lazy Loading: Metadata collections (like tables, procedures) are fetched from the database only when their corresponding property (e.g., schema.tables, schema.procedures) is first accessed after binding or clearing the cache.

  • Object Representation: Schema elements are represented by instances of SchemaItem subclasses (e.g., Table, Procedure, Domain), offering properties to access details and methods like get_sql_for() to generate DDL.

  • Caching: Fetched metadata is cached internally. Use clear() or reload() to refresh the cache.

  • Binding & Lifecycle: An instance must be bound to a live Connection using the bind() method (this is done automatically when accessed via Connection.schema). It should be closed using close() (or via a with statement) to release resources when no longer needed.

Configuration options control certain behaviors like SQL identifier quoting. Internal maps are populated during binding to translate system codes (e.g., for object types, field types) into meaningful enums or names.

bind(connection: Connection) Self[source]

Binds this Schema instance to a live database connection.

This method establishes the connection, creates an internal cursor for querying system tables, fetches basic database attributes (ODS version, owner, default charset), determines reserved keywords, and populates internal enum/code mappings from RDB$TYPES.

Note

This method is primarily for internal use. Users typically access a bound Schema instance via Connection.schema. Calling bind() on an already bound or embedded schema may raise an Error.

Parameters:

connection (Connection) – The Connection instance to bind to.

Returns:

The bound Schema instance (self).

Raises:

Error – If called on an embedded schema instance.

Return type:

Self

clear() None[source]

Clears all cached metadata collections (tables, views, etc.).

Does not affect the binding to the connection or basic database attributes (like ODS version). Metadata will be reloaded from the database on the next access to a relevant property. Also commits the internal transaction if active.

Return type:

None

close() None[source]

Closes the internal cursor and transaction, detaching from the connection.

After closing, the schema object cannot be used to fetch further metadata. Attempting to access unloaded properties will raise an Error.

Raises:

Error – If attempting to close an embedded schema instance (obtained via Connection.schema).

Return type:

None

get_charset_by_id(charset_id: int) CharacterSet[source]

Retrieves a CharacterSet object by its ID.

Parameters:

charset_id (int) – The numeric ID of the character set (RDB$CHARACTER_SET_ID).

Returns:

The matching CharacterSet instance, or None if not found or not loaded.

Return type:

CharacterSet

get_collation_by_id(charset_id: int, collation_id: int) Collation[source]

Retrieves a Collation object by its character set ID and collation ID.

Parameters:
  • charset_id (int) – The numeric ID of the character set (RDB$CHARACTER_SET_ID).

  • collation_id (int) – The numeric ID of the collation within the character set (RDB$COLLATION_ID).

Returns:

The matching Collation instance, or None if not found or not loaded.

Return type:

Collation

get_item(name: str, itype: ObjectType, subname: str | None = None) SchemaItem[source]

Retrieves a specific database object by its type and name(s).

Parameters:
  • name (str) – The primary name of the database object (e.g., table name, procedure name).

  • itype (ObjectType) – The ObjectType enum value specifying the type of object to retrieve.

  • subname (str | None) – An optional secondary name, typically used for columns (itype=ObjectType.COLUMN) where name is the table/view name and subname is the column name.

Returns:

An instance of a SchemaItem subclass (e.g., Table, Procedure), a UserInfo instance (for itype=ObjectType.USER), or None if the object is not found.

Return type:

SchemaItem

get_metadata_ddl(*, sections=[Section.COLLATIONS, Section.CHARACTER_SETS, Section.UDFS, Section.GENERATORS, Section.EXCEPTIONS, Section.DOMAINS, Section.PACKAGE_DEFS, Section.FUNCTION_DEFS, Section.PROCEDURE_DEFS, Section.TABLES, Section.PRIMARY_KEYS, Section.UNIQUE_CONSTRAINTS, Section.CHECK_CONSTRAINTS, Section.FOREIGN_CONSTRAINTS, Section.INDICES, Section.VIEWS, Section.PACKAGE_BODIES, Section.PROCEDURE_BODIES, Section.FUNCTION_BODIES, Section.TRIGGERS, Section.GRANTS, Section.ROLES, Section.COMMENTS, Section.SHADOWS, Section.SET_GENERATORS]) list[str][source]

Generates a list of DDL SQL commands for creating database objects.

Constructs a DDL script based on the schema information cached in this instance.

Parameters:

sections – An iterable of Section enum members specifying which types of database objects to include in the DDL script and the order in which their creation statements should appear. Defaults to SCRIPT_DEFAULT_ORDER.

Returns:

A list of strings, where each string is a single DDL SQL command.

Raises:
  • ValueError – If an unknown section code is provided in the sections list.

  • Error – If required metadata for a requested section has not been loaded yet (e.g., accessing schema.tables might be needed first).

Return type:

list[str]

get_privileges_of(user: str | UserInfo | Table | View | Procedure | Trigger | Role, user_type: ObjectType | None = None) DataList[Privilege][source]

Retrieves a list of all privileges granted to a specific user or database object (grantee).

Parameters:
Returns:

A DataList containing Privilege objects granted to the specified user/object. Returns an empty list if no privileges are found or privileges haven’t been loaded.

Raises:

ValueError – If user is a string name and user_type is not provided.

Return type:

DataList[Privilege]

is_keyword(ident: str) bool[source]

Checks if the given identifier is a reserved keyword for the database’s ODS version.

Parameters:

ident (str) – The identifier string to check (case-insensitive comparison).

Returns:

True if the identifier is a reserved keyword, False otherwise.

Return type:

bool

is_multifile() bool[source]

Checks if the database consists of multiple physical files (has secondary files).

Returns:

True if the database has secondary files defined, False otherwise.

Return type:

bool

reload(data: Category | list[Category] | None = None) None[source]

Clears cached metadata for specified categories and commits the internal transaction.

If data is None, clears all cached metadata collections. Otherwise, clears only the collections specified in the data iterable (e.g., [Category.TABLES, Category.VIEWS]). This forces the specified metadata to be reloaded from the database on next access.

Parameters:

data (Category | list[Category] | None) – A specific Category enum member, an iterable of Category members, or None to clear all categories. Defaults to None.

Raises:

Error – If the instance is closed or if an invalid category is provided.

Return type:

None

property all_domains: DataList[Domain]

DataList of all (user + system) Domain objects in the database. Loads lazily.

property all_functions: DataList[Function]

DataList of all (user + system) Function objects in the database. Loads lazily.

property all_generators: DataList[Sequence]

DataList of all (user + system) Sequence objects (generators) in the database. Loads lazily.

property all_indices: DataList[Index]

DataList of all (user + system) Index objects in the database. Loads lazily.

property all_procedures: DataList[Procedure]

DataList of all (user + system) Procedure objects in the database. Loads lazily.

property all_tables: DataList[Table]

DataList of all (user + system) Table objects in the database. Loads lazily.

property all_triggers: DataList[Trigger]

DataList of all (user + system) Trigger objects in the database. Loads lazily.

property all_views: DataList[View]

DataList of all (user + system) View objects in the database. Loads lazily.

property backup_history: DataList[BackupHistory]

DataList of all BackupHistory objects in the database. Loads lazily.

character_set_names: ClassVar[dict[int, str]] = {}

Mapping from character set IDs (RDB$CHARACTER_SET_ID) to names.

property character_sets: DataList[CharacterSet]

DataList of all CharacterSet objects defined in the database. Loads lazily.

property closed: bool

True if the schema object is closed or not bound to a connection.

property collations: DataList[Collation]

DataList of all Collation objects defined in the database. Loads lazily.

property constraints: DataList[Constraint]

DataList of all Constraint objects in the database. Loads lazily.

property default_character_set: CharacterSet

Default CharacterSet for database.

property dependencies: DataList[Dependency]

DataList of all Dependency objects in the database. Loads lazily.

property description: str | None

The database description string from RDB$DATABASE, or None.

deterministic_flags: ClassVar[dict[int, str]] = {}

Mapping from determinism flag codes (RDB$DETERMINISTIC_FLAG) to names.

property domains: DataList[Domain]

DataList of all user-defined Domain objects in the database. Loads lazily.

property exceptions: DataList[DatabaseException]

DataList of all DatabaseException objects defined in the database. Loads lazily.

field_subtypes: ClassVar[dict[int, str]] = {}

Mapping from field sub-type codes (RDB$FIELD_SUB_TYPE) to names.

field_types: ClassVar[dict[int, str]] = {}

Mapping from field type codes (RDB$FIELD_TYPE) to SQL type names.

property files: DataList[DatabaseFile]

DataList of all DatabaseFile objects in the database. Loads lazily.

property filters: DataList[Filter]

DataList of all user-defiend Filter objects in the database. Loads lazily.

function_types: ClassVar[dict[int, str]] = {}

Mapping from function type codes (RDB$FUNCTION_TYPE) to names.

property functions: DataList[Function]

DataList of all user-defined Function objects in the database. Loads lazily.

property generators: DataList[Sequence]

DataList of all user-defined Sequence objects (generators) in the database. Loads lazily.

grant_options: ClassVar[dict[int, str]] = {}

Mapping from grant option codes (RDB$GRANT_OPTION) to names.

identity_type: ClassVar[dict[int, str]] = {}

Mapping from identity type codes (RDB$IDENTITY_TYPE) to names.

index_activity_flags: ClassVar[dict[int, str]] = {}

Mapping from index activity codes (RDB$INDEX_INACTIVE) to names.

index_unique_flags: ClassVar[dict[int, str]] = {}

Mapping from index uniqueness codes (RDB$UNIQUE_FLAG) to names.

property indices: DataList[Index]

DataList of all user-defined Index objects in the database. Loads lazily.

legacy_flags: ClassVar[dict[int, str]] = {}

Mapping from legacy flag codes (RDB$LEGACY_FLAG) to names.

property linger: int | None

Database linger value.

mechanism_types: ClassVar[dict[str, str]] = {}

Mapping from mechanism codes (RDB$MECHANISM) to names.

object_type_codes: ClassVar[dict[str, int]] = {}

Reverse mapping from object type names to codes.

object_types: ClassVar[dict[int, str]] = {}

Mapping from object type codes (RDB$OBJECT_TYPE) to descriptive strings.

ods: float | None

ODS version of the connected database (e.g., 12.0, 13.0).

opt_always_quote: bool = False

If True, always quote database object names in generated SQL, otherwise quote only when necessary (e.g., reserved words, non-standard characters). Defaults to False.

Type:

Configuration option

opt_generator_keyword: str = 'SEQUENCE'

SQL keyword to use for generators/sequences (‘SEQUENCE’ or ‘GENERATOR’). Defaults to ‘SEQUENCE’.

Type:

Configuration option

property owner_name: str | None

The user name of the database owner, or None if not determined.

property packages: DataList[Package]

DataList of all Package objects in the database. Loads lazily.

page_types: ClassVar[dict[int, str]] = {}

Mapping from page type codes (RDB$PAGE_TYPE) to names.

param_type_from: ClassVar[dict[int, str]] = {0: 'DATATYPE', 1: 'DOMAIN', 2: 'TYPE OF DOMAIN', 3: 'TYPE OF COLUMN'}

Mapping from parameter source codes (RDB$PARAMETER_MECHANISM) to descriptive strings.

parameter_mechanism_types: ClassVar[dict[int, str]] = {}

Mapping from parameter mechanism codes (RDB$PARAMETER_MECHANISM) to names.

parameter_types: ClassVar[dict[int, str]] = {}

Mapping from parameter type codes (RDB$PARAMETER_TYPE) to names.

privacy_flags: ClassVar[dict[int, str]] = {}

Mapping from privacy flag codes (RDB$PRIVATE_FLAG) to names.

property privileges: DataList[Privilege]

DataList of all Privilege objects in the database. Loads lazily.

procedure_types: ClassVar[dict[int, str]] = {}

Mapping from procedure type codes (RDB$PROCEDURE_TYPE) to names.

property procedures: DataList[Procedure]

DataList of all user-defined Procedure objects in the database. Loads lazily.

relation_types: ClassVar[dict[int, str]] = {}

Mapping from relation type codes (RDB$RELATION_TYPE) to names.

property roles: DataList[Role]

DataList of all Role objects in the database. Loads lazily.

property security_class: str

Can refer to the security class applied as databasewide access control limits.

property shadows: DataList[Shadow]

DataList of all Shadow objects in the database. Loads lazily.

property sys_domains: DataList[Domain]

DataList of all system Domain objects in the database. Loads lazily.

property sys_functions: DataList[Function]

DataList of all system Function objects in the database. Loads lazily.

property sys_generators: DataList[Sequence]

DataList of all system Sequence objects (generators) in the database. Loads lazily.

property sys_indices: DataList[Index]

DataList of all system Index objects in the database. Loads lazily.

property sys_procedures: DataList[Procedure]

DataList of all system Procedure objects in the database. Loads lazily.

property sys_tables: DataList[Table]

DataList of all system Table objects in the database. Loads lazily.

property sys_triggers: DataList[Trigger]

DataList of all system Trigger objects in the database. Loads lazily.

property sys_views: DataList[View]

DataList of all system View objects in the database. Loads lazily.

system_flag_types: ClassVar[dict[int, str]] = {}

Mapping from system flag codes (RDB$SYSTEM_FLAG) to names.

property tables: DataList[Table]

DataList of all user-defined Table objects in the database. Loads lazily.

transaction_state_types: ClassVar[dict[int, str]] = {}

Mapping from transaction state codes (RDB$TRANSACTION_STATE) to names.

trigger_activity_flags: ClassVar[dict[int, str]] = {}

Mapping from trigger activity codes (RDB$TRIGGER_INACTIVE) to names.

trigger_types: ClassVar[dict[int, str]] = {}

Mapping from trigger type codes (RDB$TRIGGER_TYPE) to names.

property triggers: DataList[Trigger]

DataList of all user-defined Trigger objects in the database. Loads lazily.

property views: DataList[View]

DataList of all user-defined View objects in the database. Loads lazily.

class firebird.lib.schema.SchemaItem(schema: Schema, attributes: dict[str, Any])[source]

Bases: Visitable

Abstract base class for all objects representing elements within a Firebird database schema.

This class provides a common interface and shared functionality for objects like tables, views, procedures, domains, indices, etc. It holds metadata retrieved from the RDB$ system tables and facilitates interaction with the schema structure.

Key Features:

  • Access to the parent Schema instance (via a weak reference).

  • Storage of raw metadata attributes fetched from system tables.

  • Methods for retrieving the object’s name, description, and quoted identifier.

  • Functionality to find dependent and depended-on objects within the schema.

  • A mechanism (get_sql_for()) to generate DDL/DML SQL commands (like CREATE, ALTER, DROP, COMMENT) specific to the object type.

  • Support for the Visitor pattern via the accept() method.

Subclasses typically override methods like _get_name() and implement specific _get_<action>_sql() methods to provide type-specific behavior. Instances are usually created and managed by the parent Schema object.

Parameters:
  • schema (Schema | None) – The parent Schema instance this item belongs to.

  • attributes (dict[str, Any]) – A dictionary containing the raw column names (e.g., ‘RDB$RELATION_NAME’, ‘RDB$SYSTEM_FLAG’) and their corresponding values fetched from the relevant RDB$ system table row for this schema object.

_check_params(params: dict[str, Any], param_names: list[str]) None[source]

Internal helper: Validates keyword arguments passed to get_sql_for.

Checks if all keys in the params dictionary are present in the param_names list of allowed parameters for a specific SQL action.

Parameters:
  • params (dict[str, Any]) – The dictionary of parameters received by the _get_<action>_sql method.

  • param_names (list[str]) – A list of strings representing the allowed parameter names for that action.

Raises:

ValueError – If params contains any key not found in param_names.

Return type:

None

_get_create_or_alter_sql(**params) str[source]

Generates ‘CREATE OR ALTER’ SQL by modifying the ‘CREATE’ SQL. Subclasses can override if needed.

Return type:

str

_get_create_sql(**params) str[source]

Abstract method for generating ‘CREATE’ SQL. Subclasses must implement.

Return type:

str

_get_name() str | None[source]

Internal method: Retrieves the primary name of the schema object.

Subclasses should override this to return the name from the appropriate ‘RDB$…’ attribute (e.g., ‘RDB$RELATION_NAME’, ‘RDB$PROCEDURE_NAME’).

Returns:

The name of the object as a string, or None if the object conceptually lacks a name (though most schema items have one).

Return type:

str | None

_get_quoted_ident(ident: str) str[source]

Internal helper: Returns the identifier, quoted if necessary.

Parameters:

ident (str)

Return type:

str

_get_recreate_sql(**params) str[source]

Generates ‘RECREATE’ SQL by prefixing the ‘CREATE’ SQL. Subclasses can override if ‘RECREATE’ differs more significantly.

Return type:

str

_needs_quoting(ident: str) bool[source]

Internal helper: Determines if an identifier requires double quotes in SQL.

Checks based on Schema.opt_always_quote setting, reserved words (Schema.is_keyword), starting characters, and allowed characters (A-Z, 0-9, _, $).

Returns:

True if the identifier needs quoting, False otherwise. Returns False for empty or None identifiers.

Parameters:

ident (str)

Return type:

bool

_strip_attribute(attr: str) None[source]

Internal helper: Removes leading/trailing whitespace from a string attribute if it exists.

Parameters:

attr (str)

Return type:

None

get_dependencies() DataList[Dependency][source]

Retrieves a list of database objects that this object depends on.

Queries Schema.dependencies based on this object’s name and _type_code.

Returns:

A DataList containing Dependency objects where this item is the dependent object. Returns an empty list if this object has no dependencies or dependencies haven’t been loaded in the parent schema.

Return type:

DataList[Dependency]

get_dependents() DataList[Dependency][source]

Returns list of all database objects that depend on this one.

Return type:

DataList[Dependency]

get_quoted_name() str[source]

Retrieves a list of database objects that depend on this object.

Queries Schema.dependencies based on this object’s name and _type_code.

Returns:

A DataList containing Dependency objects where this item is the depended_on object. Returns an empty list if no dependents are found or dependencies haven’t been loaded in the parent schema.

Return type:

str

get_sql_for(action: str, **params: dict) str[source]

Generates a DDL/DML SQL command for a specified action on this schema object.

Parameters:
  • action (str) – The desired SQL action (e.g., ‘create’, ‘drop’, ‘alter’, ‘comment’). The action must be present (case-insensitively) in the object’s actions list.

  • **params (dict) – Keyword arguments specific to the requested action. These are validated and passed directly to the internal _get_<action>_sql method implemented by the subclass. Consult the specific subclass documentation for available parameters for each action.

Returns:

A string containing the generated SQL command.

Raises:
  • ValueError – If the requested action is not supported for this object type, or if invalid/missing params are provided for the action.

  • NotImplementedError – If the action is listed but the corresponding _get_<action>_sql method is not implemented.

Return type:

str

is_sys_object() bool[source]

Checks if this schema object is a system-defined object.

Typically determined by checking the RDB$SYSTEM_FLAG attribute (> 0). Subclasses may provide more specific logic (e.g., based on name prefixes like ‘RDB$’).

Returns:

True if it’s considered a system object, False otherwise.

Return type:

bool

property actions: list[str]

A list of lowercase action strings (e.g., ‘create’, ‘drop’, ‘alter’) that are supported by the get_sql_for() method for this specific object type.

property description: str | None

The description (comment) associated with this object from RDB$DESCRIPTION, or None if it has no description.

property name: str | None

The primary name of this schema object (e.g., table name, procedure name), or None if the object type does not have a name.

schema: Schema | None = None

Weak reference proxy to the parent Schema instance. Provides access to the overall schema context without creating circular references.

class firebird.lib.schema.Collation(schema: Schema, attributes: dict[str, Any])[source]

Bases: SchemaItem

Represents a specific collation, defining rules for character sorting and comparison.

Collations are always associated with a specific CharacterSet. They determine aspects like case sensitivity, accent sensitivity, and handling of padding spaces during comparisons.

Instances of this class map data primarily from the RDB$COLLATIONS system table. They are typically accessed via Schema.collations or CharacterSet.collations.

Supported SQL actions via get_sql_for():

  • User-defined collations: create, drop, comment.

  • System collations: comment.

Parameters:
  • schema (Schema | None) – The parent Schema instance.

  • attributes (dict[str, Any]) – Raw data dictionary fetched from the RDB$COLLATIONS row.

_get_comment_sql(**params) str[source]

Generates the SQL command to add or remove a COMMENT ON this collation.

Parameters:

**params – Accepts no parameters.

Returns:

The COMMENT ON COLLATION SQL string. Sets comment to NULL if self.description is None, otherwise uses the description text with proper escaping.

Return type:

str

_get_create_sql(**params) str[source]

Generates the SQL command to CREATE this collation.

Constructs the CREATE COLLATION statement including character set, base collation (internal or external), padding, case/accent sensitivity, and specific attributes.

Parameters:

**params – Accepts no parameters.

Returns:

The CREATE COLLATION SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_drop_sql(**params) str[source]

Generates the SQL command to DROP this collation.

Parameters:

**params – Accepts no parameters.

Returns:

The DROP COLLATION SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_name() str[source]

Returns the collation name (RDB$COLLATION_NAME).

Return type:

str

is_based_on_external() bool[source]

Checks if this collation is based on an external definition (e.g., ICU).

Determines this by checking if RDB$BASE_COLLATION_NAME exists but does not correspond to another collation defined within the database schema.

Returns:

True if based on an external collation, False otherwise.

Return type:

bool

property attributes: CollationFlag

A CollationFlag enum value representing the combined attributes (pad space, case/accent sensitivity) defined by RDB$COLLATION_ATTRIBUTES.

property base_collation: Collation | None

The base Collation object this collation derives from, if any.

Returns None if this collation is a primary collation for its character set or if it’s based on an external definition (check is_based_on_external()).

property character_set: CharacterSet

The CharacterSet object this collation belongs to.

property function_name: str

Not currently used.

property id: int

The unique numeric ID (RDB$COLLATION_ID) assigned to this collation within its character set.

property owner_name: str

The user name of the collation’s owner/creator (RDB$OWNER_NAME).

property security_class: str | None

The security class name associated with this collation, if any (RDB$SECURITY_CLASS). Returns None if no specific security class is assigned.

property specific_attributes: str

Locale string or other specific configuration used by the collation engine (e.g., for ICU collations), stored in RDB$SPECIFIC_ATTRIBUTES. Returns None if not applicable.

class firebird.lib.schema.CharacterSet(schema: Schema, attributes: dict[str, Any])[source]

Bases: SchemaItem

Represents a character set defined in the database.

A character set defines how characters are encoded (represented as bytes) and provides a default collation for sorting and comparison if none is explicitly specified.

Instances of this class map data primarily from the RDB$CHARACTER_SETS system table. They are typically accessed via Schema.character_sets.

Supported SQL actions via get_sql_for():

  • alter (keyword argument collation: Collation instance or collation name): Sets the default collation for this character set.

  • comment: Adds or removes a descriptive comment for the character set.

Parameters:
  • schema (Schema | None) – The parent Schema instance.

  • attributes (dict[str, Any]) – Raw data dictionary fetched from the RDB$CHARACTER_SETS row.

_get_alter_sql(**params) str[source]

Generates the SQL command to ALTER this character set.

Currently only supports setting the default collation.

Parameters:

**params

Accepts one keyword argument:

  • collation (Collation | str): The Collation object or the string name of the collation to set as the default for this character set. Required.

Returns:

The ALTER CHARACTER SET SQL string.

Raises:

ValueError – If the required collation parameter is missing or if unexpected parameters are passed.

Return type:

str

_get_comment_sql(**params) str[source]

Generates the SQL command to add or remove a COMMENT ON this character set.

Parameters:

**params – Accepts no parameters.

Returns:

The COMMENT ON CHARACTER SET SQL string. Sets comment to NULL if self.description is None, otherwise uses the description text with proper escaping.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_name() str[source]

Returns the character set name (RDB$CHARACTER_SET_NAME).

Return type:

str

get_collation_by_id(id_: int) Collation | None[source]

Retrieves a specific Collation belonging to this character set by its ID.

Searches the cached collations associated with this character set.

Parameters:
  • id – The numeric ID (RDB$COLLATION_ID) of the collation to find.

  • id_ (int)

Returns:

The matching Collation object, or None if no collation with that ID exists within this character set (or if collations haven’t been loaded).

Return type:

Collation | None

property bytes_per_character: int

The maximum number of bytes required to store a single character in this set (RDB$BYTES_PER_CHARACTER).

property collations: DataList[Collation]

A lazily-loaded DataList of all Collation objects associated with this character set.

property default_collation: Collation

The default Collation object associated with this character set.

Identified by RDB$DEFAULT_COLLATE_NAME. Returns None if the default collation cannot be found (which would indicate a schema inconsistency).

property id: int

The unique numeric ID (RDB$CHARACTER_SET_ID) assigned to this character set.

property owner_name: str

The user name of the character set’s owner/creator (RDB$OWNER_NAME).

property security_class: str | None

The security class name associated with this character set, if any (RDB$SECURITY_CLASS). Returns None if no specific security class is assigned.

class firebird.lib.schema.DatabaseException(schema: Schema, attributes: dict[str, Any])[source]

Bases: SchemaItem

Represents a named database exception, used for raising custom errors in PSQL.

Database exceptions provide a way to signal specific error conditions from stored procedures or triggers using a symbolic name and an associated message text.

Instances of this class map data primarily from the RDB$EXCEPTIONS system table. They are typically accessed via Schema.exceptions.

Supported SQL actions via get_sql_for():

  • User-defined exceptions:

    • create: Creates the exception with its message.

    • recreate: Recreates the exception (drops if exists, then creates).

    • alter (keyword argument message: str): Changes the message text associated with the exception. Required.

    • create_or_alter: Creates the exception or alters it if it already exists.

    • drop: Removes the exception from the database.

    • comment: Adds or removes a descriptive comment for the exception.

  • System exceptions:

    • comment: Adds or removes a descriptive comment.

Parameters:
  • schema (Schema | None) – The parent Schema instance.

  • attributes (dict[str, Any]) – Raw data dictionary fetched from the RDB$EXCEPTIONS row.

_get_alter_sql(**params) str[source]

Generates the SQL command to ALTER this exception’s message.

Parameters:

**params

Accepts one keyword argument:

  • message (str): The new message text for the exception. Required.

Returns:

The ALTER EXCEPTION SQL string with the new message text, properly escaped.

Raises:

ValueError – If the required message parameter is missing, is not a string, or if unexpected parameters are passed.

Return type:

str

_get_comment_sql(**params) str[source]

Generates the SQL command to add or remove a COMMENT ON this exception.

Parameters:

**params – Accepts no parameters.

Returns:

The COMMENT ON EXCEPTION SQL string. Sets comment to NULL if self.description is None, otherwise uses the description text with proper escaping.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_create_sql(**params) str[source]

Generates the SQL command to CREATE this exception.

Parameters:

**params – Accepts no parameters.

Returns:

The CREATE EXCEPTION SQL string, including the message text with single quotes properly escaped.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_drop_sql(**params) str[source]

Generates the SQL command to DROP this exception.

Parameters:

**params – Accepts no parameters.

Returns:

The DROP EXCEPTION SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_name() str[source]

Returns the exception name (RDB$EXCEPTION_NAME).

Return type:

str

property id: int

The system-assigned unique numeric ID (RDB$EXCEPTION_NUMBER) for the exception.

property message: str

The custom message text associated with the exception (RDB$MESSAGE).

property owner_name: str

The user name of the exception’s owner/creator (RDB$OWNER_NAME).

property security_class: str | None

The security class name associated with this exception, if any (RDB$SECURITY_CLASS). Returns None if no specific security class is assigned.

class firebird.lib.schema.Sequence(schema: Schema, attributes: dict[str, Any])[source]

Bases: SchemaItem

Represents a database sequence (historically called generator).

Sequences are used to generate unique, sequential numeric values, often employed for primary key generation or identity columns.

Instances of this class map data primarily from the RDB$GENERATORS system table. They are typically accessed via Schema.generators, Schema.sys_generators, or Schema.all_generators. The current value is retrieved dynamically using the GEN_ID() function.

The SQL keyword used (SEQUENCE or GENERATOR) in generated DDL depends on the Schema.opt_generator_keyword setting.

Supported SQL actions via get_sql_for():

  • User-defined sequences:

    • create (optional keyword args: value: int, increment: int): Creates the sequence, optionally setting START WITH and INCREMENT BY.

    • alter (optional keyword args: value: int, increment: int): Alters the sequence, optionally setting RESTART WITH and/or INCREMENT BY. At least one argument must be provided.

    • drop: Removes the sequence from the database.

    • comment: Adds or removes a descriptive comment for the sequence.

  • System sequences (e.g., for IDENTITY columns):

    • comment: Adds or removes a descriptive comment.

Parameters:
  • schema (Schema | None) – The parent Schema instance.

  • attributes (dict[str, Any]) – Raw data dictionary fetched from the RDB$GENERATORS row.

_get_alter_sql(**params) str[source]

Generates the SQL command to ALTER this sequence/generator.

Uses the keyword specified by Schema.opt_generator_keyword.

Parameters:

**params

Accepts optional keyword arguments:

  • value (int): The value to restart the sequence with (RESTART WITH).

  • increment (int): The new increment step (INCREMENT BY).

At least one of value or increment must be provided.

Returns:

The ALTER SEQUENCE or ALTER GENERATOR SQL string.

Raises:

ValueError – If neither value nor increment is provided, or if unexpected parameters are passed.

Return type:

str

_get_comment_sql(**params) str[source]

Generates the SQL command to add or remove a COMMENT ON this sequence/generator.

Uses the keyword specified by Schema.opt_generator_keyword.

Parameters:

**params – Accepts no parameters.

Returns:

The COMMENT ON SEQUENCE or COMMENT ON GENERATOR SQL string. Sets comment to NULL if self.description is None, otherwise uses the description text with proper escaping.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_create_sql(**params) str[source]

Generates the SQL command to CREATE this sequence/generator.

Uses the keyword specified by Schema.opt_generator_keyword.

Parameters:

**params

Accepts optional keyword arguments:

  • value (int): The initial value (START WITH).

  • increment (int): The increment step (INCREMENT BY).

Returns:

The CREATE SEQUENCE or CREATE GENERATOR SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_drop_sql(**params) str[source]

Generates the SQL command to DROP this sequence/generator.

Uses the keyword specified by Schema.opt_generator_keyword.

Parameters:

**params – Accepts no parameters.

Returns:

The DROP SEQUENCE or DROP GENERATOR SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_name() str[source]

Returns the sequence/generator name (RDB$GENERATOR_NAME).

Return type:

str

is_identity() bool[source]

Checks if this sequence is system-generated for an IDENTITY column.

Determined by checking if RDB$SYSTEM_FLAG has the specific value 6.

Returns:

True if it’s an identity sequence, False otherwise.

Return type:

bool

property id: int

The internal numeric ID (RDB$GENERATOR_ID) assigned to the sequence/generator.

property increment: int

The increment step (INCREMENT BY) defined for the sequence (RDB$GENERATOR_INCREMENT). Returns None if not explicitly set (defaults to 1).

Added in version 1.4.0: Support for reading this attribute (requires Firebird 4.0+). Older versions might return None even if an increment was conceptually set.

property inital_value: int | None

The initial value (START WITH) defined for the sequence (RDB$INITIAL_VALUE). Returns None if not explicitly set (defaults may apply based on DB version).

Added in version 1.4.0: Support for reading this attribute (requires Firebird 4.0+). Older versions might return None even if a start value was conceptually set.

property owner_name: str

The user name of the sequence’s owner/creator (RDB$OWNER_NAME).

property security_class: str | None

The security class name associated with this sequence, if any (RDB$SECURITY_CLASS). Returns None if no specific security class is assigned.

property value: int

The current value of the sequence.

Important

Accessing this property executes SELECT GEN_ID(name, 0) FROM RDB$DATABASE against the database to retrieve the current value. It does not increment the sequence.

Returns:

The current integer value of the sequence.

Raises:

Error – If the schema is closed or the query fails.

class firebird.lib.schema.TableColumn(schema: Schema, table: Table, attributes: dict[str, Any])[source]

Bases: SchemaItem

Represents a column within a database table (Table).

This class holds metadata about a table column, such as its name, data type (derived from its underlying Domain), nullability, default value, collation, position, and whether it’s computed or an identity column.

Instances map data primarily from the RDB$RELATION_FIELDS system table, linking to RDB$FIELDS via RDB$FIELD_SOURCE for domain/type information. They are typically accessed via the Table.columns property.

Supported SQL actions via get_sql_for():

  • User table columns:

    • drop: Generates ALTER TABLE ... DROP COLUMN ....

    • comment: Generates COMMENT ON COLUMN ... IS ....

    • alter (keyword args): Modifies the column definition. Only one type of alteration can be performed per call:

    • name (str): Renames the column (ALTER ... TO ...).

    • position (int): Changes the column’s ordinal position.

    • datatype (str): Changes the column’s data type (ALTER ... TYPE ...). Cannot be used to change between computed/persistent.

    • expression (str): Changes the COMPUTED BY expression. Requires the column to already be computed.

    • restart (int | None): Restarts the sequence associated with an IDENTITY column. Provide an integer for RESTART WITH value, or None for RESTART (uses sequence’s next value). Only applicable to identity columns.

  • System table columns:

    • comment: Adds or removes a descriptive comment.

Parameters:
  • schema (Schema | None) – The parent Schema instance.

  • table (Table) – The parent Table object this column belongs to.

  • attributes (dict[str, Any]) – Raw data dictionary fetched from the RDB$RELATION_FIELDS row.

_get_alter_sql(**params) str[source]

Generates the SQL command to ALTER this table column.

Only one type of alteration (rename, reposition, change type/expression, restart identity) can be performed per call.

Parameters:

**params

Accepts one of the following optional keyword arguments:

  • name (str): The new name for the column.

  • position (int): The new 1-based ordinal position for the column.

  • datatype (str): The new SQL data type definition (e.g., ‘VARCHAR(100)’, ‘INTEGER’). Cannot be used if expression is also provided.

  • expression (str): The new COMPUTED BY (...) expression. Cannot be used if datatype is also provided. Only applicable to computed columns.

  • restart (int | None): Restarts the identity sequence. Provide an integer value for WITH or None to restart without specifying a value. Only applicable to identity columns.

Returns:

The ALTER TABLE ... ALTER COLUMN ... SQL string.

Raises:

ValueError – If multiple alteration types are specified, if attempting invalid alterations (e.g., changing computed to persistent), if required parameters are missing, or if unexpected parameters are passed.

Return type:

str

_get_comment_sql(**params) str[source]

Generates the SQL command to add or remove a COMMENT ON this table column.

Parameters:

**params – Accepts no parameters.

Returns:

The COMMENT ON COLUMN ... IS ... SQL string. Sets comment to NULL if self.description is None, otherwise uses the description text with proper escaping.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_drop_sql(**params) str[source]

Generates the SQL command to DROP this table column.

Parameters:

**params – Accepts no parameters.

Returns:

The ALTER TABLE ... DROP COLUMN ... SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_name() str[source]

Returns the column name (RDB$FIELD_NAME).

Return type:

str

get_computedby() str | None[source]

Returns the COMPUTED BY (...) expression string if this is a computed column.

Returns:

The expression string (without the COMPUTED BY keywords), or None if the column is not computed. Retrieves expression from the underlying domain.

Return type:

str | None

get_dependencies() DataList[Dependency][source]

Retrieves a list of database objects that this column depends on.

This is typically relevant for computed columns, checking Schema.dependencies where this column’s table and name are the dependent reference.

Returns:

A DataList containing Dependency objects where this column is part of the dependent reference.

Return type:

DataList[Dependency]

get_dependents() DataList[Dependency][source]

Retrieves a list of database objects that depend on this specific column.

Searches Schema.dependencies matching the table name (RDB$RELATION_NAME), object type (0 for table), and this column’s name (RDB$FIELD_NAME).

Returns:

A DataList containing Dependency objects where this column is part of the depended_on reference.

Return type:

DataList[Dependency]

has_default() bool[source]

Checks if the column has a DEFAULT value defined.

Based on the presence of RDB$DEFAULT_SOURCE. Note that is_identity() should be checked first, as identity columns may technically have a default source internally but are conceptually different.

Returns:

True if a default value source exists, False otherwise.

Return type:

bool

is_computed() bool[source]

Checks if this column is a computed column (COMPUTED BY).

Returns:

True if the underlying domain has a computed source, False otherwise.

Return type:

bool

is_domain_based() bool[source]

Checks if this column is directly based on a user-defined domain.

Returns:

True if the underlying domain (RDB$FIELD_SOURCE) is not a system object, False otherwise (e.g., based on a system domain or defined inline).

Return type:

bool

is_identity() bool[source]

Checks if this column is an IDENTITY column (GENERATED ... AS IDENTITY).

Determined by checking if RDB$IDENTITY_TYPE is not NULL.

Returns:

True if it’s an identity column, False otherwise.

Return type:

bool

is_nullable() bool[source]

Checks if the column allows NULL values.

Based on the RDB$NULL_FLAG attribute (0 = nullable, 1 = not nullable).

Returns:

True if the column can accept NULL, False otherwise.

Return type:

bool

is_writable() bool[source]

Checks if the column can be directly written to (e.g., not computed).

Based on the RDB$UPDATE_FLAG attribute (1 = writable, 0 = not writable).

Returns:

True if the column is considered writable, False otherwise.

Return type:

bool

property collation: Collation | None

The specific Collation object applied to this column (RDB$COLLATION_ID), if applicable (for character types).

Returns None if the column type does not support collation or if the default collation of the underlying domain/character set is used.

property datatype: str

A string representation of the column’s complete SQL data type definition.

This is derived from the underlying Domain’s datatype property. Example: ‘VARCHAR(100) CHARACTER SET UTF8 COLLATE UNICODE_CI’.

property default: str | None

The DEFAULT value expression string defined for the column (RDB$DEFAULT_SOURCE).

Returns the expression string (e.g., ‘CURRENT_TIMESTAMP’, “‘ACTIVE’”, ‘0’) or None if no default is defined. The leading ‘DEFAULT ‘ keyword is removed.

property domain: Domain

The underlying Domain object that defines this column’s base data type and constraints (RDB$FIELD_SOURCE). May be a system domain or a user domain.

property generator: Sequence | None

The Sequence (generator) associated with this column if it’s an IDENTITY column (RDB$GENERATOR_NAME).

Returns:

The related Sequence object, or None if this is not an identity column or the sequence cannot be found.

property id: int

The internal numeric ID (RDB$FIELD_ID) assigned to the column within the table.

property identity_type: int | None

The type of IDENTITY generation (ALWAYS or BY DEFAULT) specified for the column.

Returns:

An IdentityType enum member if this is an identity column (RDB$IDENTITY_TYPE is not NULL), otherwise None.

property position: int

The 0-based ordinal position (RDB$FIELD_POSITION) of the column within the table row.

property privileges: DataList[Privilege]

A lazily-loaded DataList of specific privileges (SELECT, UPDATE, REFERENCES) granted directly on this column.

property security_class: str | None

The security class name associated with this column, if any (RDB$SECURITY_CLASS). Returns None if no specific security class is assigned.

property table: Table

The parent Table object this column belongs to.

class firebird.lib.schema.Index(schema: Schema, attributes: dict[str, Any])[source]

Bases: SchemaItem

Represents a database index used to speed up data retrieval or enforce constraints.

Indexes can be defined on one or more columns (segment-based) or based on an expression (expression-based). They can be unique or non-unique, ascending or descending, and active or inactive. Indexes are also used internally to enforce PRIMARY KEY, UNIQUE, and FOREIGN KEY constraints.

Instances of this class map data primarily from the RDB$INDICES and RDB$INDEX_SEGMENTS system tables. They are typically accessed via Schema.indices, Schema.sys_indices, Schema.all_indices, or Table.indices.

Supported SQL actions via get_sql_for():

  • User-defined indexes:

    • create: Creates the index (UNIQUE, ASC/DESC, on columns or COMPUTED BY).

    • activate: Activates an inactive index (ALTER INDEX ... ACTIVE).

    • deactivate: Deactivates an active index (ALTER INDEX ... INACTIVE).

    • recompute: Requests recalculation of index statistics (SET STATISTICS INDEX ...).

    • drop: Removes the index from the database.

    • comment: Adds or removes a descriptive comment for the index.

  • System indexes (used for constraints):

    • activate: Activates the index.

    • recompute: Recalculates statistics.

    • comment: Adds or removes a comment.

    • Note: System indexes usually cannot be dropped directly; drop the constraint instead.

Parameters:
  • schema (Schema | None) – The parent Schema instance.

  • attributes (dict[str, Any]) – Raw data dictionary fetched from the RDB$INDICES row.

_get_activate_sql(**params) str[source]

Generates the SQL command to ACTIVATE this index.

Parameters:

**params – Accepts no parameters.

Returns:

The ALTER INDEX ... ACTIVE SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_comment_sql(**params) str[source]

Generates the SQL command to add or remove a COMMENT ON this index.

Parameters:

**params – Accepts no parameters.

Returns:

The COMMENT ON INDEX ... IS ... SQL string. Sets comment to NULL if self.description is None, otherwise uses the description text with proper escaping.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_create_sql(**params) str[source]

Generates the SQL command to CREATE this index.

Handles UNIQUE, ASCENDING/DESCENDING attributes, and segment lists or COMPUTED BY expressions.

Parameters:

**params – Accepts no parameters.

Returns:

The CREATE INDEX SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_deactivate_sql(**params) str[source]

Generates the SQL command to DEACTIVATE this index.

Parameters:

**params – Accepts no parameters.

Returns:

The ALTER INDEX ... INACTIVE SQL string.

Raises:

ValueError – If unexpected parameters are passed or if trying to deactivate a system index enforcing a constraint. (Note: DB might prevent this, this check is for clarity).

Return type:

str

_get_drop_sql(**params) str[source]

Generates the SQL command to DROP this index.

Parameters:

**params – Accepts no parameters.

Returns:

The DROP INDEX ... SQL string.

Raises:

ValueError – If unexpected parameters are passed or if trying to drop a system index enforcing a constraint. (Note: DB prevents this, this check is for clarity).

Return type:

str

_get_name() str[source]

Returns the index name (RDB$INDEX_NAME).

Return type:

str

_get_recompute_sql(**params) str[source]

Generates the SQL command to request recalculation of index statistics.

Parameters:

**params – Accepts no parameters.

Returns:

The SET STATISTICS INDEX ... SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

is_enforcer() bool[source]

Checks if this index is used to enforce a constraint (PK, UK, FK).

Determines this by checking if its name exists as a key in the schema’s internal constraint-to-index map.

Returns:

True if the index enforces a constraint, False otherwise.

Return type:

bool

is_expression() bool[source]

Checks if this is an expression-based index (COMPUTED BY).

Determined by checking if RDB$EXPRESSION_SOURCE is not NULL.

Returns:

True if it’s an expression index, False otherwise.

Return type:

bool

is_inactive() bool[source]

Checks if the index is currently inactive (INACTIVE).

Based on the RDB$INDEX_INACTIVE attribute (1 = inactive, 0 = active).

Returns:

True if the index is inactive, False otherwise.

Return type:

bool

is_sys_object() bool[source]

Checks if this index is a system-defined object.

Considers both the RDB$SYSTEM_FLAG and whether the index enforces a constraint and has a system-generated name (like ‘RDB$…’).

Returns:

True if it’s considered a system object, False otherwise.

Return type:

bool

is_unique() bool[source]

Checks if the index enforces uniqueness (UNIQUE).

Based on the RDB$UNIQUE_FLAG attribute (1 = unique, 0 = non-unique).

Returns:

True if the index is unique, False otherwise.

Return type:

bool

property condition: str | None

The partial index condition string (RDB$CONDITION_SOURCE), if defined.

Returns the condition string (typically enclosed in parentheses), or None if this is not a partial index.

Added in version 1.4.0: Requires Firebird 5.0+. Older versions will return None.

property constraint: Constraint | None

The Constraint object (PK, UK, FK) that this index enforces, if any.

Returns None if the index does not enforce a constraint (i.e., it’s purely for performance).

property expression: str | None

The expression string for an expression-based index (RDB$EXPRESSION_SOURCE).

Returns:

The expression string (typically enclosed in parentheses), or None if this is a segment-based index.

property id: int

The internal numeric ID (RDB$INDEX_ID) assigned to the index.

property index_type: IndexType

The index ordering type (IndexType.ASCENDING or IndexType.DESCENDING).

Based on RDB$INDEX_TYPE (NULL or 0 = ascending, 1 = descending).

property partner_index: Index | None

For a FOREIGN KEY index, the associated PRIMARY KEY or UNIQUE key Index it references (RDB$FOREIGN_KEY contains the partner index name).

Returns:

The partner Index object, or None if this is not a foreign key index or the partner index cannot be found.

property segment_names: list[str]

A list of column names that form the segments of this index.

Returns an empty list for expression-based indexes. Fetched lazily from RDB$INDEX_SEGMENTS.

property segment_statistics: list[float]

A list of selectivity statistics for each corresponding segment in segment_names.

Returns an empty list for expression-based indexes or if statistics are unavailable. Fetched lazily from RDB$INDEX_SEGMENTS.

property segments: DataList[TableColumn]

A DataList of the TableColumn objects corresponding to the index segments.

Returns an empty list for expression-based indexes. Uses segment_names to look up columns in the associated Table.

property statistics: float

The latest calculated selectivity statistic for the index (RDB$STATISTICS). Lower values indicate higher selectivity. May be None if statistics haven’t been computed.

property table: Table

The Table object this index is defined on (RDB$RELATION_NAME).

class firebird.lib.schema.ViewColumn(schema: Schema, view: View, attributes: dict[str, Any])[source]

Bases: SchemaItem

Represents a column within a database view (View).

View columns derive their properties (like data type, nullability) from the underlying query’s output columns, which might originate from base tables, other views, or procedure outputs.

Instances primarily map data from RDB$RELATION_FIELDS where the relation type is VIEW. Information about the source column/expression is often limited compared to table columns. They are accessed via the View.columns property.

Supported SQL actions via get_sql_for():

  • comment: Adds or removes a descriptive comment for the view column (COMMENT ON COLUMN view_name.column_name IS ...).

Parameters:
  • schema (Schema | None) – The parent Schema instance.

  • view (View) – The parent View object this column belongs to.

  • attributes (dict[str, Any]) – Raw data dictionary fetched from the RDB$RELATION_FIELDS row (potentially joined with RDB$VIEW_RELATIONS for base info).

_get_comment_sql(**params) str[source]

Generates the SQL command to add or remove a COMMENT ON this view column.

Parameters:

**params – Accepts no parameters.

Returns:

The COMMENT ON COLUMN view_name.column_name IS ... SQL string. Sets comment to NULL if self.description is None, otherwise uses the description text with proper escaping.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_name() str[source]

Returns the view column name (RDB$FIELD_NAME).

Return type:

str

get_dependencies() DataList[Dependency][source]

Retrieves a list of database objects that this view column depends on.

Searches Schema.dependencies where this view column’s view name and column name are the dependent reference (dependent type is 1 for VIEW).

Returns:

A DataList containing Dependency objects where this view column is part of the dependent reference.

Return type:

DataList[Dependency]

get_dependents() DataList[Dependency][source]

Retrieves a list of database objects that depend on this specific view column.

Searches Schema.dependencies matching the view name (RDB$RELATION_NAME), object type (1 for view), and this column’s name (RDB$FIELD_NAME).

Returns:

A DataList containing Dependency objects where this view column is part of the depended_on reference.

Return type:

DataList[Dependency]

is_nullable() bool[source]

Checks if the view column allows NULL values.

Based on the RDB$NULL_FLAG attribute derived from the underlying source or view definition.

Returns:

True if the column can contain NULL, False otherwise.

Return type:

bool

is_writable() bool[source]

Checks if the view column is potentially updatable.

Based on the RDB$UPDATE_FLAG. Note that view updatability also depends on the view definition itself (e.g., joins, aggregates). This flag indicates if the underlying source column could be updated through the view, assuming the view itself is updatable.

Returns:

True if the column source is marked as updatable via the view, False otherwise.

Return type:

bool

property base_field: TableColumn | ViewColumn | ProcedureParameter

The original source column or parameter from the underlying base object.

Identified via RDB$BASE_FIELD (source column name) and BASE_RELATION (source object name). It attempts to find the source in tables, views, or procedures.

Returns:

A TableColumn, ViewColumn, or ProcedureParameter instance representing the ultimate source, or None if the source cannot be determined (e.g., an expression without a direct base column).

Raises:

Error – If the base relation name exists but the corresponding schema object (table/view/procedure) cannot be found.

property collation: Collation | None

The specific Collation object applied to this view column (RDB$COLLATION_ID), if applicable (for character types) and different from the domain default.

Returns None if the column type does not support collation or if the default collation of the underlying domain/character set is used.

property datatype: str

A string representation of the column’s SQL data type definition.

Derived from the underlying Domain’s datatype property. Example: ‘VARCHAR(50) CHARACTER SET UTF8’.

property domain: Domain

The underlying Domain object that defines this column’s base data type and constraints (RDB$FIELD_SOURCE).

property position: int

The 0-based ordinal position (RDB$FIELD_POSITION) of the column within the view’s definition.

property privileges: DataList[Privilege]

A lazily-loaded DataList of privileges (SELECT, UPDATE, REFERENCES) granted specifically on this view column.

Note

In RDB$USER_PRIVILEGES, privileges on view columns are often logged with the subject type as TABLE (0), not VIEW (1). This property accounts for that when filtering.

property security_class: str | None

The security class name associated with this view column, if any (RDB$SECURITY_CLASS). Returns None if no specific security class is assigned.

property view: View

The parent View object this column belongs to.

class firebird.lib.schema.Domain(schema: Schema, attributes: dict[str, Any])[source]

Bases: SchemaItem

Represents an SQL Domain, a reusable definition for data types and constraints.

Domains allow defining a base data type (e.g., VARCHAR(50), DECIMAL(18,4)), along with optional attributes like:

  • NOT NULL constraint

  • DEFAULT value

  • CHECK constraint (validation rule)

  • Collation (for character types)

  • Array dimensions

Table columns and PSQL variables/parameters can then be declared based on a domain, inheriting its properties. This promotes consistency and simplifies schema management.

Instances map data primarily from the RDB$FIELDS system table. They are accessed via Schema.domains, Schema.sys_domains, or Schema.all_domains.

Supported SQL actions via get_sql_for():

  • User-defined domains:

    • create: Creates the domain with its full definition.

    • drop: Removes the domain from the database.

    • comment: Adds or removes a descriptive comment for the domain.

    • alter (keyword args): Modifies the domain definition. Only one type of alteration can be performed per call:

      • name (str): Renames the domain (ALTER DOMAIN ... TO ...).

      • default (str | None): Sets or drops the default value. Provide the default expression string, or None/empty string to DROP DEFAULT.

      • check (str | None): Adds or drops the check constraint. Provide the CHECK (...) expression string (without the CHECK keyword itself), or None/empty string to DROP CONSTRAINT.

      • datatype (str): Changes the base data type (ALTER DOMAIN ... TYPE ...).

  • System domains:

    • comment: Adds or removes a descriptive comment.

Parameters:
  • schema (Schema | None) – The parent Schema instance.

  • attributes (dict[str, Any]) – Raw data dictionary fetched from the RDB$FIELDS row.

_get_alter_sql(**params) str[source]

Generates the SQL command to ALTER this domain.

Only one type of alteration (rename, change default, change check, change type) can be performed per call.

Parameters:

**params

Accepts one of the following optional keyword arguments:

  • name (str): The new name for the domain.

  • default (str | None): The new default value expression, or None/”” to drop the default.

  • check (str | None): The new check constraint expression (inside the parentheses), or None/”” to drop the check constraint.

  • datatype (str): The new base SQL data type definition.

Returns:

The ALTER DOMAIN SQL string.

Raises:

ValueError – If multiple alteration types are specified, if required parameters are missing, or if unexpected parameters are passed.

Return type:

str

_get_comment_sql(**params) str[source]

Generates the SQL command to add or remove a COMMENT ON this domain.

Parameters:

**params – Accepts no parameters.

Returns:

The COMMENT ON DOMAIN SQL string. Sets comment to NULL if self.description is None, otherwise uses the description text with proper escaping.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_create_sql(**params) str[source]

Generates the SQL command to CREATE this domain.

Includes the base data type, default value, nullability, check constraint, and collation, if defined.

Parameters:

**params – Accepts no parameters.

Returns:

The CREATE DOMAIN SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_drop_sql(**params) str[source]

Generates the SQL command to DROP this domain.

Parameters:

**params – Accepts no parameters.

Returns:

The DROP DOMAIN SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_name() str[source]

Returns the domain name (RDB$FIELD_NAME).

Return type:

str

has_default() bool[source]

Checks if the domain has a DEFAULT value defined.

Based on the presence of RDB$DEFAULT_SOURCE.

Returns:

True if a default value source exists, False otherwise.

Return type:

bool

is_array() bool[source]

Checks if the domain defines an array data type.

Based on the presence of RDB$DIMENSIONS.

Returns:

True if the domain defines an array, False otherwise.

Return type:

bool

is_computed() bool[source]

Checks if this domain represents a COMPUTED BY definition.

Based on the presence of RDB$COMPUTED_SOURCE. Note: Domains themselves aren’t directly computed, but columns based on them can inherit this if the domain definition was used implicitly for a computed column type. Generally, user-defined domains should not have this set.

Returns:

True if RDB$COMPUTED_SOURCE has a value, False otherwise.

Return type:

bool

is_nullable() bool[source]

Checks if the domain allows NULL values (i.e., not defined with NOT NULL).

Based on the RDB$NULL_FLAG attribute (0 = nullable, 1 = not nullable).

Returns:

True if the domain allows NULL, False otherwise.

Return type:

bool

is_sys_object() bool[source]

Checks if this domain is a system-defined object.

Considers both the RDB$SYSTEM_FLAG and whether the name starts with ‘RDB$’.

Returns:

True if it’s considered a system object, False otherwise.

Return type:

bool

is_validated() bool[source]

Checks if the domain has a CHECK constraint defined.

Based on the presence of RDB$VALIDATION_SOURCE.

Returns:

True if a check constraint source exists, False otherwise.

Return type:

bool

property character_length: int

Length of character types (CHAR, VARCHAR) in characters, not bytes (RDB$CHARACTER_LENGTH). Returns None for non-character types.

property character_set: CharacterSet | None

The CharacterSet object associated with the domain (RDB$CHARACTER_SET_ID), if applicable (for character/text types). Returns None otherwise.

property collation: Collation | None

The specific Collation object defined for the domain (RDB$COLLATION_ID), if applicable (for character/text types).

Returns None if the domain type does not support collation or if the default collation of the character set is used.

property datatype: str

A string representation of the domain’s complete SQL data type definition.

Combines the base type, length/precision/scale, character set/collation, and array dimensions into a standard SQL type string. Example: DECIMAL(18, 4), VARCHAR(100) CHARACTER SET UTF8 COLLATE UNICODE_CI, INTEGER [1:10].

property default: str | None

The DEFAULT value expression string (RDB$DEFAULT_SOURCE).

Returns the expression string (e.g., ‘CURRENT_TIMESTAMP’, “‘ACTIVE’”, ‘0’) or None if no default is defined. The leading ‘DEFAULT ‘ keyword is removed.

property dimensions: list[tuple[int, int]]

A list of dimension bounds for array domains.

Each tuple in the list represents one dimension (lower_bound, upper_bound). Returns None if the domain is not an array type (RDB$DIMENSIONS is NULL). Fetched lazily by querying RDB$FIELD_DIMENSIONS.

property expression: str | None

The COMPUTED BY (...) expression string, if applicable (RDB$COMPUTED_SOURCE). Typically None for user-defined domains.

property external_length: int

Length of the field if mapped from an external table (RDB$EXTERNAL_LENGTH). Typically 0 or None for regular domains.

property external_scale: int | None

Scale of the field if mapped from an external table (RDB$EXTERNAL_SCALE). Typically 0 or None.

property external_type: FieldType | None

Data type code (FieldType) of the field if mapped from an external table (RDB$EXTERNAL_TYPE). Returns None otherwise.

property field_type: FieldType

The base data type code (FieldType) defined for the domain (RDB$FIELD_TYPE).

property length: int

The defined length of the data type in bytes (RDB$FIELD_LENGTH). Applicable to types like CHAR, VARCHAR, BLOB. May be None.

property owner_name: str

The user name of the domain’s owner/creator (RDB$OWNER_NAME).

property precision: int | None

The precision (total number of digits) for exact numeric types (NUMERIC, DECIMAL) or approximate types (FLOAT, DOUBLE) (RDB$FIELD_PRECISION). Returns None if not applicable.

property scale: int

The scale (number of digits to the right of the decimal point) for NUMERIC or DECIMAL types (RDB$FIELD_SCALE). Stored as a negative number. Returns None for non-exact numeric types.

property security_class: str | None

The security class name associated with this domain, if any (RDB$SECURITY_CLASS). Returns None if no specific security class is assigned.

property segment_length: int | None

Suggested segment size for BLOB types (RDB$SEGMENT_LENGTH). Returns None for non-BLOB types.

property sub_type: int | None

The field sub-type code (RDB$FIELD_SUB_TYPE).

Commonly used for BLOB subtypes (0=binary, 1=text) or NUMERIC/DECIMAL indication (1=numeric, 2=decimal) for exact numeric types. Returns the raw integer if not a standard FieldSubType enum member, or None.

property validation: str | None

The CHECK (...) constraint expression string (RDB$VALIDATION_SOURCE).

Returns the expression part inside the parentheses, or None if no check constraint is defined.

class firebird.lib.schema.Dependency(schema: Schema, attributes: dict[str, Any])[source]

Bases: SchemaItem

Represents a dependency relationship between two database schema objects.

This class maps a single row from the RDB$DEPENDENCIES system table, indicating that one object (dependent) relies on another object (depended_on). Understanding these dependencies is crucial for determining the correct order for DDL operations (e.g., dropping or altering objects).

Instances of this class are typically accessed via Schema.dependencies or by calling get_dependents() or get_dependencies() on other SchemaItem objects.

This class itself does not support any direct SQL actions via get_sql_for().

Parameters:
  • schema (Schema | None) – The parent Schema instance.

  • attributes (dict[str, Any]) – Raw data dictionary fetched from the RDB$DEPENDENCIES row.

_get_name() str | None[source]

Returns a descriptive string representation, not a standard object name.

Dependencies don’t have a unique name in the SQL sense. This returns None as per the base class expectation for unnamed items.

Return type:

str | None

get_dependencies() DataList[source]

Dependencies represent a relationship and do not have dependencies themselves.

Returns:

An empty DataList.

Return type:

DataList

get_dependents() DataList[source]

Dependencies do not have further dependents.

Returns:

An empty DataList.

Return type:

DataList

is_packaged() bool[source]

Checks if this dependency involves an object defined within a PSQL package.

Based on the presence of RDB$PACKAGE_NAME. This usually means the dependent object is inside the package.

Returns:

True if RDB$PACKAGE_NAME has a value, False otherwise.

Return type:

bool

is_sys_object() bool[source]

Indicates that dependency entries themselves are considered system metadata.

Returns:

True always.

Return type:

bool

property depended_on: SchemaItem

The database object that is being depended upon.

Resolves the object based on RDB$DEPENDED_ON_NAME, RDB$DEPENDED_ON_TYPE, and potentially RDB$FIELD_NAME. If field_name is set, this property attempts to return the specific column object; otherwise, it returns the container object (table, view, procedure, etc.).

Returns:

The SchemaItem subclass instance (e.g., Table, Procedure, Domain) or a TableColumn / ViewColumn instance representing the object being depended upon, or None if it cannot be resolved or the type is unhandled.

property depended_on_name: str

The name (RDB$DEPENDED_ON_NAME) of the object being depended upon.

property depended_on_type: ObjectType

The type (ObjectType) of the object being depended upon (RDB$DEPENDED_ON_TYPE).

property dependent: SchemaItem

The database object that has the dependency (the one that relies on something else).

Resolves the object based on RDB$DEPENDENT_NAME and RDB$DEPENDENT_TYPE.

Returns:

The SchemaItem subclass instance (e.g., View, Procedure, Trigger) representing the dependent object, or None if the object cannot be found or the type is currently unhandled.

property dependent_name: str

The name (RDB$DEPENDENT_NAME) of the object that has the dependency.

property dependent_type: ObjectType

The type (ObjectType) of the object that has the dependency (RDB$DEPENDENT_TYPE).

property field_name: str | None

The specific field/column name (RDB$FIELD_NAME) involved in the dependency, if applicable.

This is non-NULL when the dependency relates to a specific column (e.g., a procedure depending on a table column, a view column based on a table column). Returns None if the dependency is on the object as a whole.

property package: Package | None

The Package object involved, if the dependency relates to a packaged object (RDB$PACKAGE_NAME).

This typically means the dependent object is part of this package. Returns None if the dependency does not involve a package.

class firebird.lib.schema.Constraint(schema: Schema, attributes: dict[str, Any])[source]

Bases: SchemaItem

Represents a table or column constraint (PRIMARY KEY, UNIQUE, FOREIGN KEY, CHECK, NOT NULL).

Constraints enforce data integrity rules within the database. They are associated with a specific table and may rely on an underlying index (for PK, UK, FK) or triggers (for CHECK, NOT NULL) for enforcement.

Instances map data primarily from RDB$RELATION_CONSTRAINTS, potentially joined with RDB$REF_CONSTRAINTS (for FK) and RDB$CHECK_CONSTRAINTS (for CHECK). They are typically accessed via Schema.constraints or Table.constraints.

Supported SQL actions via get_sql_for():

  • User-defined constraints (excluding NOT NULL):

    • create: Generates the ALTER TABLE ... ADD CONSTRAINT ... statement. Handles PK, UNIQUE, FK (including rules), and CHECK constraints.

    • drop: Generates the ALTER TABLE ... DROP CONSTRAINT ... statement.

  • System constraints or NOT NULL constraints:

    • No direct SQL actions supported via get_sql_for(). NOT NULL is typically managed as part of the column/domain definition. System constraints (on system tables) generally cannot be modified.

Note

NOT NULL constraints are represented by this class internally when fetched from system tables but do not support create or drop actions here. They are managed via ALTER DOMAIN or ALTER TABLE ... ALTER COLUMN.

Parameters:
  • schema (Schema | None) – The parent Schema instance.

  • attributes (dict[str, Any]) – Raw data dictionary fetched from RDB$RELATION_CONSTRAINTS (potentially joined with other constraint tables).

_get_create_sql(**params) str[source]

Generates the SQL command to ADD this constraint to its table.

Constructs ALTER TABLE ... ADD CONSTRAINT ... syntax for PRIMARY KEY, UNIQUE, FOREIGN KEY, and CHECK constraints.

Parameters:

**params – Accepts no parameters.

Returns:

The ALTER TABLE ... ADD CONSTRAINT ... SQL string.

Raises:
  • ValueError – If unexpected parameters are passed.

  • Error – If called for a NOT NULL or unsupported constraint type, or if required underlying objects (like index or partner constraint) are missing.

Return type:

str

_get_drop_sql(**params) str[source]

Generates the SQL command to DROP this constraint from its table.

Parameters:

**params – Accepts no parameters.

Returns:

The ALTER TABLE ... DROP CONSTRAINT ... SQL string.

Raises:
  • ValueError – If unexpected parameters are passed.

  • Error – If called for a NOT NULL constraint or if the table cannot be found.

Return type:

str

_get_name() str[source]

Returns the constraint name (RDB$CONSTRAINT_NAME).

Return type:

str

is_check() bool[source]

Checks if this is a CHECK constraint.

Returns:

True if constraint_type is ConstraintType.CHECK, False otherwise.

Return type:

bool

is_deferrable() bool[source]

Checks if the constraint is defined as DEFERRABLE.

Based on RDB$DEFERRABLE (‘YES’ or ‘NO’).

Returns:

True if deferrable, False otherwise.

Return type:

bool

is_deferred() bool[source]

Checks if the constraint is defined as INITIALLY DEFERRED.

Based on RDB$INITIALLY_DEFERRED (‘YES’ or ‘NO’). Relevant only if is_deferrable() is True.

Returns:

True if initially deferred, False otherwise.

Return type:

bool

is_fkey() bool[source]

Checks if this is a FOREIGN KEY constraint.

Returns:

True if constraint_type is ConstraintType.FOREIGN_KEY, False otherwise.

Return type:

bool

is_not_null() bool[source]

Checks if this is a NOT NULL constraint.

Returns:

True if constraint_type is ConstraintType.NOT_NULL, False otherwise.

Return type:

bool

is_pkey() bool[source]

Checks if this is a PRIMARY KEY constraint.

Returns:

True if constraint_type is ConstraintType.PRIMARY_KEY, False otherwise.

Return type:

bool

is_sys_object() bool[source]

Checks if this constraint is defined on a system table.

Returns:

True if the associated table is a system object, False otherwise.

Return type:

bool

is_unique() bool[source]

Checks if this is a UNIQUE constraint.

Returns:

True if constraint_type is ConstraintType.UNIQUE, False otherwise.

Return type:

bool

property column_name: str | None

The name of the column it applies to.

Returns None for other constraint types.

Type:

For a NOT NULL constraint

property constraint_type: ConstraintType

The type of the constraint (ConstraintType enum).

Derived from RDB$CONSTRAINT_TYPE (‘PRIMARY KEY’, ‘UNIQUE’, etc.). Returns None if the type string is unrecognized.

property delete_rule: str | None

The action specified for ON DELETE (RDB$DELETE_RULE, e.g., ‘RESTRICT’, ‘CASCADE’, ‘SET NULL’, ‘SET DEFAULT’). Returns None for other constraint types.

Type:

For a FOREIGN KEY constraint

property index: Index | None

The Index object used to enforce the constraint (RDB$INDEX_NAME).

Relevant for PRIMARY KEY, UNIQUE, and FOREIGN KEY constraints. Returns None for CHECK and NOT NULL constraints, or if the index cannot be found.

property match_option: str | None

The match option specified (RDB$MATCH_OPTION). Usually ‘FULL’ or ‘SIMPLE’ (though ‘SIMPLE’ might not be fully supported). Returns None for other constraint types.

Type:

For a FOREIGN KEY constraint

property partner_constraint: Constraint | None

The referenced PRIMARY KEY or UNIQUE Constraint object (RDB$CONST_NAME_UQ).

Returns None for other constraint types or if the partner constraint cannot be found.

Type:

For a FOREIGN KEY constraint

property table: Table

The Table object this constraint is defined on (RDB$RELATION_NAME).

property trigger_names: list[str]

A list of trigger names that enforce it. For a NOT NULL constraint: The name of the single column it applies to. Returns None for other constraint types.

Type:

For a CHECK constraint

property triggers: DataList[Trigger]

A DataList of the Trigger objects that enforce it.

Returns an empty list for other constraint types or if triggers cannot be found.

Type:

For a CHECK constraint

property update_rule: str | None

The action specified for ON UPDATE (RDB$UPDATE_RULE, e.g., ‘RESTRICT’, ‘CASCADE’, ‘SET NULL’, ‘SET DEFAULT’). Returns None for other constraint types.

Type:

For a FOREIGN KEY constraint

class firebird.lib.schema.Table(schema: Schema, attributes: dict[str, Any])[source]

Bases: SchemaItem

Represents a database table, including persistent, global temporary, and external tables.

This class serves as a container for the table’s metadata, including its columns, constraints (primary key, foreign keys, unique, check), indexes, and triggers. It provides methods to generate SQL DDL for creating or dropping the table and its associated objects (partially, constraints/indexes might need separate creation).

Instances map data primarily from the RDB$RELATIONS system table where RDB$VIEW_BLR is NULL. Associated objects like columns, constraints, etc., are fetched from other system tables (RDB$RELATION_FIELDS, RDB$RELATION_CONSTRAINTS, RDB$INDICES, RDB$TRIGGERS).

Access typically occurs via Schema.tables, Schema.sys_tables, or Schema.all_tables.

Supported SQL actions via get_sql_for():

  • User-defined tables:

    • create (optional keyword args: no_pk: bool=False, no_unique: bool=False): Generates CREATE [GLOBAL TEMPORARY] TABLE ... statement. Includes column definitions. Optionally includes inline PRIMARY KEY and UNIQUE constraints unless excluded by no_pk=True or no_unique=True respectively. CHECK and FOREIGN KEY constraints are not included inline by this method.

    • recreate (optional keyword args: no_pk: bool=False, no_unique: bool=False): Generates RECREATE [GLOBAL TEMPORARY] TABLE ... (similar to create).

    • drop: Generates DROP TABLE ....

    • comment: Generates COMMENT ON TABLE ... IS ....

    • insert (optional keyword args: update: bool=False, returning: list[str]=None, matching: list[str]=None): Generates an INSERT or UPDATE OR INSERT statement template with placeholders for all columns. Optionally adds MATCHING and RETURNING clauses.

  • System tables:

    • comment: Adds or removes a descriptive comment.

Parameters:
  • schema (Schema | None) – The parent Schema instance.

  • attributes (dict[str, Any]) – Raw data dictionary fetched from the RDB$RELATIONS row.

_get_comment_sql(**params) str[source]

Generates the SQL command to add or remove a COMMENT ON this table.

Parameters:

**params – Accepts no parameters.

Returns:

The COMMENT ON TABLE ... IS ... SQL string. Sets comment to NULL if self.description is None, otherwise uses the description text with proper escaping.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_create_sql(**params) str[source]

Generates the SQL command to CREATE this table.

Includes column definitions based on their underlying domains or types. Optionally includes inline PRIMARY KEY and UNIQUE constraints. Does not include CHECK or FOREIGN KEY constraints inline; create those separately.

Parameters:

**params

Accepts optional keyword arguments:

  • no_pk (bool): If True, excludes the inline PRIMARY KEY constraint definition (if one exists). Defaults to False.

  • no_unique (bool): If True, excludes inline UNIQUE constraint definitions. Defaults to False.

Returns:

The CREATE [GLOBAL TEMPORARY] TABLE SQL string.

Raises:
  • ValueError – If unexpected parameters are passed.

  • Error – If essential information (like columns) cannot be loaded.

Return type:

str

_get_drop_sql(**params) str[source]

Generates the SQL command to DROP this table.

Parameters:

**params – Accepts no parameters.

Returns:

The DROP TABLE SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_insert_sql(**params) str[source]

Generates an SQL INSERT or UPDATE OR INSERT statement template for this table.

Includes all columns in the column list and corresponding placeholders (?) in the VALUES clause. Optionally adds MATCHING and RETURNING clauses.

Parameters:

**params

Accepts optional keyword arguments:

  • update (bool): If True, generates UPDATE OR INSERT instead of INSERT. Defaults to False.

  • returning (list[str]): A list of column names or expressions to include in the RETURNING clause. Defaults to None.

  • matching (list[str]): A list of column names to include in the MATCHING (...) clause (used with UPDATE OR INSERT). Defaults to None.

Returns:

The generated INSERT or UPDATE OR INSERT SQL statement string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_name() str[source]

Returns the table name (RDB$RELATION_NAME).

Return type:

str

has_fkey() bool[source]

Checks if the table has at least one FOREIGN KEY constraint defined.

Iterates through the table’s constraints.

Returns:

True if any foreign key constraints exist, False otherwise.

Return type:

bool

has_pkey() bool[source]

Checks if the table has a PRIMARY KEY constraint defined.

Iterates through the table’s constraints.

Returns:

True if a primary key constraint exists, False otherwise.

Return type:

bool

is_external() bool[source]

Checks if this table is an External Table.

Based on the presence of the RDB$EXTERNAL_FILE attribute.

Returns:

True if it’s an external table, False otherwise.

Return type:

bool

is_gtt() bool[source]

Checks if this table is a Global Temporary Table (GTT).

Returns:

True if table_type is RelationType.GLOBAL_TEMPORARY_DELETE or RelationType.GLOBAL_TEMPORARY_PRESERVE, False otherwise.

Return type:

bool

is_persistent() bool[source]

Checks if this table is a standard persistent table or an external table.

Excludes views and GTTs.

Returns:

True if table_type is RelationType.PERSISTENT or RelationType.EXTERNAL, False otherwise.

Return type:

bool

property columns: DataList[TableColumn]

A lazily-loaded DataList of all TableColumn objects defined for this table.

Columns are ordered by their position (RDB$FIELD_POSITION). Fetched from RDB$RELATION_FIELDS.

property constraints: DataList[Constraint]

A DataList of all Constraint objects (PK, FK, UK, CHECK) defined for this table.

Filters the main Schema.constraints collection.

property dbkey_length: int

Length of the internal RDB$DB_KEY pseudo-column in bytes (RDB$DBKEY_LENGTH).

property default_class: str

Default security class name (RDB$DEFAULT_CLASS). Usage may vary.

property external_file: str | None

The full path and filename of the external data file (RDB$EXTERNAL_FILE). Returns None if this is not an external table.

property flags: int

Internal flags (RDB$FLAGS) used by the engine. Interpretation may vary.

property foreign_keys: DataList[Constraint]

A DataList of all FOREIGN KEY Constraint objects defined for this table.

property format: int

The internal format version number (RDB$FORMAT) for the table’s record structure.

property id: int

The internal numeric ID (RDB$RELATION_ID) assigned to the table/relation.

property indices: DataList[Index]

A DataList of all Index objects defined for this table.

Filters the main Schema.all_indices collection.

property owner_name: str

The user name of the table’s owner/creator (RDB$OWNER_NAME).

property primary_key: Constraint | None

The PRIMARY KEY Constraint object defined for this table.

Returns:

The Constraint object representing the primary key, or None if no primary key is defined on this table. Finds the first constraint marked as PK.

property privileges: DataList[Privilege]

A DataList of all Privilege objects granted on this table.

Filters the main Schema.privileges collection. Includes privileges granted on the table as a whole, not column-specific privileges (see TableColumn.privileges).

property security_class: str | None

The security class name associated with this table, if any (RDB$SECURITY_CLASS). Used for access control limits. Returns None if not set.

property table_type: RelationType

The type of the relation (RelationType enum).

Derived from RDB$RELATION_TYPE (0=Persistent, 2=External, 4=GTT Preserve, 5=GTT Delete). Views (1) and Virtual (3) are excluded by the table loading logic.

property triggers: DataList[Trigger]

A DataList of all Trigger objects defined for this table.

Filters the main Schema.triggers collection (which contains user triggers). Use Schema.all_triggers if system triggers are needed.

class firebird.lib.schema.View(schema: Schema, attributes: dict[str, Any])[source]

Bases: SchemaItem

Represents a database view, a virtual table based on a stored SQL query.

Views provide a way to simplify complex queries, encapsulate logic, and control data access by presenting a predefined subset or transformation of data from one or more base tables or other views.

Instances map data primarily from the RDB$RELATIONS system table where RDB$VIEW_BLR is NOT NULL. Associated columns are fetched from RDB$RELATION_FIELDS.

Access typically occurs via Schema.views, Schema.sys_views, or Schema.all_views.

Supported SQL actions via get_sql_for():

  • User-defined views:

    • create: Generates CREATE VIEW view_name (col1, ...) AS SELECT ....

      Includes the column list and the view’s query (AS SELECT ...).

    • recreate: Generates RECREATE VIEW ... (similar structure to create).

    • alter (keyword args): Modifies the view definition.

      • columns (str | list[str] | tuple[str], optional): A comma-separated string or list/tuple of new column names for the view definition. If omitted, the existing column list (if any) is generally assumed or derived by the DB.

      • query (str, required): The new SELECT ... statement defining the view.

      • check (bool, optional): If True, adds WITH CHECK OPTION to the view definition. Defaults to False.

    • create_or_alter: Generates CREATE OR ALTER VIEW ... (combines create/alter logic).

    • drop: Generates DROP VIEW ....

    • comment: Generates COMMENT ON VIEW ... IS ....

  • System views:

    • comment: Adds or removes a descriptive comment.

Parameters:
  • schema (Schema | None) – The parent Schema instance.

  • attributes (dict[str, Any]) – Raw data dictionary fetched from the RDB$RELATIONS row.

_get_alter_sql(**params) str[source]

Generates the SQL command to ALTER this view.

Allows changing the column list (optional), the underlying query (required), and adding/removing the WITH CHECK OPTION.

Parameters:

**params

Accepts keyword arguments:

  • columns (str | list[str] | tuple[str], optional): New column list. If provided as list/tuple, names are joined with commas. If omitted, the existing column list structure is often retained or inferred by the DB.

  • query (str, required): The new SELECT ... statement for the view.

  • check (bool, optional): Set to True to add WITH CHECK OPTION. Defaults to False.

Returns:

The ALTER VIEW SQL string.

Raises:

ValueError – If the required query parameter is missing, if parameter types are incorrect, or if unexpected parameters are passed.

Return type:

str

_get_comment_sql(**params) str[source]

Generates the SQL command to add or remove a COMMENT ON this view.

Parameters:

**params – Accepts no parameters.

Returns:

The COMMENT ON VIEW ... IS ... SQL string. Sets comment to NULL if self.description is None, otherwise uses the description text with proper escaping.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_create_sql(**params) str[source]

Generates the SQL command to CREATE this view.

Includes the explicit column list and the AS SELECT ... query definition.

Parameters:

**params – Accepts no parameters.

Returns:

The CREATE VIEW SQL string.

Raises:
  • ValueError – If unexpected parameters are passed.

  • Error – If view columns cannot be loaded.

Return type:

str

_get_drop_sql(**params) str[source]

Generates the SQL command to DROP this view.

Parameters:

**params – Accepts no parameters.

Returns:

The DROP VIEW SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_name() str[source]

Returns the view name (RDB$RELATION_NAME).

Return type:

str

has_checkoption() bool[source]

Checks if the view definition likely includes WITH CHECK OPTION.

Performs a case-insensitive search for “WITH CHECK OPTION” within the view’s SQL source (sql property).

Warning

This is a simple text search and might produce false positives if the text appears within comments or string literals in the view definition.

Returns:

True if the text “WITH CHECK OPTION” is found, False otherwise.

Return type:

bool

property columns: DataList[ViewColumn]

A lazily-loaded DataList of all ViewColumn objects defined for this view.

Columns are ordered by their position (RDB$FIELD_POSITION). Fetched from RDB$RELATION_FIELDS potentially joined with RDB$VIEW_RELATIONS.

property dbkey_length: int

Length of the internal RDB$DB_KEY pseudo-column in bytes (RDB$DBKEY_LENGTH).

property default_class: str | None

Default security class name (RDB$DEFAULT_CLASS). Usage may vary.

property flags: int | None

Internal flags (RDB$FLAGS) used by the engine. Interpretation may vary.

property format: int

The internal format version number (RDB$FORMAT) for the view.

property id: int

The internal numeric ID (RDB$RELATION_ID) assigned to the view/relation.

property owner_name: str

The user name of the view’s owner/creator (RDB$OWNER_NAME).

property privileges: DataList[Privilege]

A DataList of all Privilege objects granted on this view.

Filters the main Schema.privileges collection. Includes privileges granted on the view as a whole. Column-specific privileges are accessed via ViewColumn.privileges.

Note

In RDB$USER_PRIVILEGES, privileges on views are often logged with the subject type as TABLE (0). This property accounts for that when filtering.

property security_class: str | None

The security class name associated with this view, if any (RDB$SECURITY_CLASS). Returns None if no specific security class is assigned.

property sql: str | None

The SELECT statement text that defines the view (RDB$VIEW_SOURCE). Returns None if the source is not available.

property triggers: DataList[Trigger]

A DataList of all user Trigger objects defined for this view.

Filters the main Schema.triggers collection. Use Schema.all_triggers if system triggers are needed.

class firebird.lib.schema.Trigger(schema: Schema, attributes: dict[str, Any])[source]

Bases: SchemaItem

Represents a database trigger, executing PSQL code in response to specific events.

Triggers automate actions based on:

  • Data Manipulation Language (DML) events on tables/views (INSERT, UPDATE, DELETE).

  • Database-level events (CONNECT, DISCONNECT, TRANSACTION START/COMMIT/ROLLBACK).

  • Data Definition Language (DDL) events (CREATE/ALTER/DROP of various objects).

Triggers have an activation time (BEFORE or AFTER the event for DML/DDL) and a sequence/position to control execution order among multiple triggers for the same event.

Instances map data primarily from the RDB$TRIGGERS system table. They are accessed via Schema.triggers, Schema.sys_triggers, Schema.all_triggers, or Table.triggers/View.triggers.

Supported SQL actions via get_sql_for():

  • User-defined triggers:

    • create (optional keyword arg inactive: bool=False): Generates CREATE TRIGGER ... statement with full definition (relation/event, time, position, source code). Can create it initially inactive.

    • recreate: Generates RECREATE TRIGGER ....

    • create_or_alter: Generates CREATE OR ALTER TRIGGER ....

    • drop: Generates DROP TRIGGER ....

    • comment: Generates COMMENT ON TRIGGER ... IS ....

    • alter (keyword args): Modifies the trigger definition. Allows changing fire_on (event string), active status, sequence position, declare section (variable declarations), and code (trigger body). At least one parameter must be provided. Trigger type (DML/DB/DDL) cannot be changed via ALTER.

  • System triggers:

    • comment: Adds or removes a descriptive comment.

Parameters:
  • schema (Schema | None) – The parent Schema instance.

  • attributes (dict[str, Any]) – Raw data dictionary fetched from the RDB$TRIGGERS row.

_get_action_type(slot: int) DMLTrigger[source]

Internal helper: Decodes DML trigger type (INSERT/UPDATE/DELETE) from RDB$TRIGGER_TYPE.

Parameters:

slot (int)

Return type:

DMLTrigger

_get_alter_sql(**params) str[source]

Generates the SQL command to ALTER this trigger.

Allows modification of active status, event (within the same type DML/DB/DDL), position, and PSQL source code (declarations and body).

Parameters:

**params

Accepts optional keyword arguments:

  • fire_on (str): The new event specification string (e.g., ‘AFTER INSERT OR UPDATE’, ‘ON CONNECT’). Must be compatible with the existing trigger type (DML/DB/DDL).

  • active (bool): Set to True for ACTIVE, False for INACTIVE.

  • sequence (int): The new execution position.

  • declare (str | list[str] | tuple[str]): New variable declarations (replaces existing). Provided as a single string or list/tuple of lines.

  • code (str | list[str] | tuple[str]): New trigger body code (replaces existing). Provided as a single string or list/tuple of lines. Required if `declare` is provided.

Returns:

The ALTER TRIGGER SQL string.

Raises:

ValueError – If no parameters are provided, if declare is provided without code, if attempting to change trigger type via fire_on, or if unexpected parameters are passed.

Return type:

str

_get_comment_sql(**params) str[source]

Generates the SQL command to add or remove a COMMENT ON this trigger.

Parameters:

**params – Accepts no parameters.

Returns:

The COMMENT ON TRIGGER ... IS ... SQL string. Sets comment to NULL if self.description is None, otherwise uses the description text with proper escaping.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_create_sql(**params) str[source]

Generates the SQL command to CREATE this trigger.

Includes target object (if DML), active status, event type and time, position, and the full PSQL source code.

Parameters:

**params

Accepts one optional keyword argument:

  • inactive (bool): If True, creates the trigger in an INACTIVE state. Defaults to False (creates ACTIVE).

Returns:

The CREATE TRIGGER SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_drop_sql(**params) str[source]

Generates the SQL command to DROP this trigger.

Parameters:

**params – Accepts no parameters.

Returns:

The DROP TRIGGER SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_name() str[source]

Returns the trigger name (RDB$TRIGGER_NAME).

Return type:

str

get_type_as_string() str[source]

Generates a human-readable string describing the trigger’s event and time.

Examples: “AFTER INSERT OR UPDATE”, “ON CONNECT”, “BEFORE ANY DDL STATEMENT”.

Returns:

A string representation of the trigger type, action, and time.

Return type:

str

is_after() bool[source]

Checks if the trigger executes AFTER the event (for DML/DDL triggers).

Returns:

True if it’s an AFTER trigger, False otherwise (BEFORE or DB trigger).

Return type:

bool

is_before() bool[source]

Checks if the trigger executes BEFORE the event (for DML/DDL triggers).

Returns:

True if it’s a BEFORE trigger, False otherwise (AFTER or DB trigger).

Return type:

bool

is_db_trigger() bool[source]

Checks if this is a database-level trigger (ON CONNECT, etc.).

Returns:

True if trigger_type is TriggerType.DB, False otherwise.

Return type:

bool

is_ddl_trigger() bool[source]

Checks if this is a DDL trigger (ON CREATE TABLE, etc.).

Returns:

True if trigger_type is TriggerType.DDL, False otherwise.

Return type:

bool

is_delete() bool[source]

Checks if this is a DML trigger firing on DELETE events.

Returns:

True if it’s a DELETE DML trigger, False otherwise.

Return type:

bool

is_insert() bool[source]

Checks if this is a DML trigger firing on INSERT events.

Returns:

True if it’s an INSERT DML trigger, False otherwise.

Return type:

bool

is_update() bool[source]

Checks if this is a DML trigger firing on UPDATE events.

Returns:

True if it’s an UPDATE DML trigger, False otherwise.

Return type:

bool

property action: DMLTrigger | DBTrigger | DDLTrigger

The specific event that fires the trigger.

Returns:

  • For DML triggers: A DMLTrigger flag combination (e.g., INSERT|UPDATE).

  • For DB triggers: A DBTrigger enum member (e.g., CONNECT).

  • For DDL triggers: A DDLTrigger enum member (e.g., CREATE_TABLE).

Return type:

Depends on trigger type

property active: bool

Indicates if the trigger is currently active and will fire on its defined event.

Based on RDB$TRIGGER_INACTIVE (0 = active, 1 = inactive).

Returns:

True if the trigger is active, False if inactive.

property engine_name: str | None

The name of the external engine used, if this is an external trigger (RDB$ENGINE_NAME). Returns None for standard PSQL triggers.

property entrypoint: str | None

The entry point function name within the external engine’s library, if this is an external trigger (RDB$ENTRYPOINT). Returns None for PSQL triggers.

property flags: int

Internal flags (RDB$FLAGS) used by the engine. Interpretation may vary.

property relation: Table | View | None

The Table or View object this trigger is associated with (RDB$RELATION_NAME).

Returns None for database-level (DB) or DDL triggers.

property sequence: int

The execution sequence (position) number (RDB$TRIGGER_SEQUENCE) of the trigger relative to other triggers for the same event. Lower numbers execute first.

property source: str | None

The PSQL source code of the trigger body (RDB$TRIGGER_SOURCE). Returns None if source is unavailable.

property time: TriggerTime

BEFORE or AFTER).

Type:

The execution time relative to the event (TriggerTime

property trigger_type: TriggerType | None

The broad type of the trigger (DML, DB, or DDL).

Determined by masking the high bits of RDB$TRIGGER_TYPE. Returns None if the type code is unrecognized.

property valid_blr: bool | None

Indicates if the compiled BLR (Binary Language Representation) of the trigger is currently considered valid by the engine (RDB$VALID_BLR).

Returns True if valid, False if invalid, None if the status is unknown or the attribute is missing.

class firebird.lib.schema.ProcedureParameter(schema: Schema, proc: Procedure, attributes: dict[str, Any])[source]

Bases: SchemaItem

Represents an input or output parameter of a stored procedure (Procedure).

This class holds metadata about a single parameter, including its name, data type (derived from a domain, column type, or defined inline), direction (input/output), position, nullability, default value, and collation.

Instances map data primarily from the RDB$PROCEDURE_PARAMETERS system table. They are accessed via the Procedure.input_params or Procedure.output_params properties.

Supported SQL actions via get_sql_for():

  • comment: Adds or removes a descriptive comment for the parameter (COMMENT ON PARAMETER proc_name.param_name IS ...).

Parameters:
  • schema (Schema | None) – The parent Schema instance.

  • proc (Procedure) – The parent Procedure object this parameter belongs to.

  • attributes (dict[str, Any]) – Raw data dictionary fetched from the RDB$PROCEDURE_PARAMETERS row.

_get_comment_sql(**params) str[source]

Generates the SQL command to add or remove a COMMENT ON this parameter.

Parameters:

**params – Accepts no parameters.

Returns:

The COMMENT ON PARAMETER proc_name.param_name IS ... SQL string. Sets comment to NULL if self.description is None, otherwise uses the description text with proper escaping.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_name() str[source]

Returns the parameter name (RDB$PARAMETER_NAME).

Return type:

str

get_sql_definition() str[source]

Generates the SQL string representation of the parameter’s definition.

Used when constructing CREATE PROCEDURE statements. Includes name, data type (handling TYPE OF variants), nullability, collation, and default value (for inputs).

Example: P_ID INTEGER NOT NULL, P_NAME VARCHAR(50) COLLATE WIN1252 = NULL

Returns:

A string suitable for use within CREATE PROCEDURE parameter lists.

Return type:

str

has_default() bool[source]

Checks if the parameter has a DEFAULT value defined.

Based on the presence of RDB$DEFAULT_SOURCE. Only applicable to input parameters.

Returns:

True if a default value source exists, False otherwise.

Return type:

bool

is_input() bool[source]

Checks if this is an INPUT parameter.

Returns:

True if parameter_type is ParameterType.INPUT, False otherwise.

Return type:

bool

is_nullable() bool[source]

Checks if the parameter allows NULL values.

Based on RDB$NULL_FLAG (0 = nullable, 1 = not nullable).

Returns:

True if the parameter allows NULL, False otherwise.

Return type:

bool

is_packaged() bool[source]

Checks if the parameter belongs to a procedure defined within a package.

Based on the presence of RDB$PACKAGE_NAME.

Returns:

True if part of a packaged procedure, False otherwise.

Return type:

bool

property collation: Collation | None

The specific Collation object applied to this parameter (RDB$COLLATION_ID), if applicable (for character types) and different from the domain default.

Returns None if the parameter type does not support collation, if the default collation is used, or if domain info is unavailable.

property column: TableColumn | None

If the parameter type is derived using TYPE OF COLUMN, this property returns the source TableColumn object.

Based on RDB$RELATION_NAME and RDB$FIELD_NAME. Returns None otherwise.

property datatype: str

A string representation of the parameter’s complete SQL data type definition.

Handles derivation from domain (DOMAIN name), column (TYPE OF COLUMN t.c), or base type (INTEGER, VARCHAR(50)).

property default: str | None

The DEFAULT value expression string defined for the parameter (RDB$DEFAULT_SOURCE).

Applies only to input parameters. Returns the expression string (e.g., ‘0’, “‘PENDING’”) or None if no default is defined. The leading ‘= ‘ or ‘DEFAULT ‘ keyword is removed.

property domain: Domain

The underlying Domain object that defines this parameter’s base data type and constraints (RDB$FIELD_SOURCE).

property mechanism: Mechanism | None

The mechanism used for passing the parameter (Mechanism), derived from RDB$PARAMETER_MECHANISM.

Indicates if passed by value or reference, relevant for type determination. Returns None if the mechanism code is unrecognized or missing.

property package: Package | None

The Package object this parameter’s procedure belongs to, if any.

Based on RDB$PACKAGE_NAME. Returns None if the procedure is standalone.

property parameter_type: ParameterType

The direction of the parameter ( INPUT or OUTPUT).

Derived from RDB$PARAMETER_TYPE (0=Input, 1=Output).

property procedure: Procedure

The parent Procedure object this parameter belongs to.

property sequence: int

The 0-based sequence (position) number (RDB$PARAMETER_NUMBER) of the parameter within its input or output list.

property type_from: TypeFrom

Indicates the source of the parameter’s data type definition (TypeFrom).

Determined by RDB$PARAMETER_MECHANISM:

  • BY_VALUE (0) implies DATATYPE or DOMAIN.

  • BY_REFERENCE (1) implies TYPE OF DOMAIN or TYPE OF COLUMN.

class firebird.lib.schema.Procedure(schema: Schema, attributes: dict[str, Any])[source]

Bases: SchemaItem

Represents a stored procedure defined in the database.

Stored procedures encapsulate reusable PSQL logic, accepting input parameters and optionally returning output parameters (for selectable procedures) or single values (legacy functions implemented as procedures). They can be standalone or part of a Package.

Instances map data primarily from the RDB$PROCEDURES system table. Associated parameters are fetched from RDB$PROCEDURE_PARAMETERS. Procedures are accessed via Schema.procedures, Schema.sys_procedures, Schema.all_procedures, or Package.procedures.

Supported SQL actions via get_sql_for():

  • User-defined, standalone procedures:

    • create (optional keyword arg no_code: bool=False): Generates CREATE PROCEDURE ... statement, including parameter definitions and the PSQL source code (unless no_code=True, which generates an empty BEGIN END block).

    • recreate (optional keyword arg no_code: bool=False): Generates RECREATE PROCEDURE ....

    • create_or_alter (optional keyword arg no_code: bool=False): Generates CREATE OR ALTER PROCEDURE ....

    • drop: Generates DROP PROCEDURE ....

    • comment: Generates COMMENT ON PROCEDURE ... IS ....

    • alter (keyword args): Modifies the procedure. Allows changing input/output parameter lists, variable declarations, and code body.

      • input (str | list[str] | tuple[str], optional): New list of input parameter definitions (full SQL like ‘p_id INTEGER’).

      • output (str | list[str] | tuple[str], optional): New list of output parameter definitions (for RETURNS (...)).

      • declare (str | list[str] | tuple[str], optional): New variable declarations.

      • code (str | list[str] | tuple[str], required): New procedure body code.

  • System procedures or packaged procedures:

    • comment: Adds or removes a descriptive comment.

    • Note: Packaged procedures are typically managed via ALTER PACKAGE.

Parameters:
  • schema (Schema | None) – The parent Schema instance.

  • attributes (dict[str, Any]) – Raw data dictionary fetched from the RDB$PROCEDURES row.

_get_alter_sql(**params) str[source]

Generates the SQL command to ALTER this procedure.

Allows modification of input/output parameters, declarations, and code body. The code parameter is required.

Parameters:

**params

Accepts optional keyword arguments:

  • input (str | list[str] | tuple[str], optional): New definition(s) for input parameters (full SQL like ‘p_id INTEGER’). Replaces existing.

  • output (str | list[str] | tuple[str], optional): New definition(s) for output parameters. Replaces existing.

  • declare (str | list[str] | tuple[str], optional): New variable declarations section. Replaces existing.

  • code (str | list[str] | tuple[str], required): The new PSQL code for the procedure body (between BEGIN and END).

Returns:

The ALTER PROCEDURE SQL string.

Raises:

ValueError – If the required code parameter is missing, if parameter types are invalid, or if unexpected parameters are passed.

Return type:

str

_get_comment_sql(**params) str[source]

Generates the SQL command to add or remove a COMMENT ON this procedure.

Parameters:

**params – Accepts no parameters.

Returns:

The COMMENT ON PROCEDURE ... IS ... SQL string. Sets comment to NULL if self.description is None, otherwise uses the description text with proper escaping.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_create_sql(**params) str[source]

Generates the SQL command to CREATE this procedure.

Includes input parameter list (...), output parameter list RETURNS (...) if applicable, and the AS BEGIN ... END block with PSQL source code.

Parameters:

**params

Accepts one optional keyword argument:

  • no_code (bool): If True, generates an empty BEGIN END block instead of the actual procedure source code. Useful for creating procedure headers first. Defaults to False.

Returns:

The CREATE PROCEDURE SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_drop_sql(**params) str[source]

Generates the SQL command to DROP this procedure.

Parameters:

**params – Accepts no parameters.

Returns:

The DROP PROCEDURE SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_name() str[source]

Returns the procedure name (RDB$PROCEDURE_NAME).

Return type:

str

get_param(name: str) ProcedureParameter | None[source]

Retrieves a specific input or output parameter by its name.

Searches output parameters first, then input parameters.

Parameters:

name (str) – The case-sensitive name of the parameter to find.

Returns:

The matching ProcedureParameter object, or None if no parameter with that name exists.

Return type:

ProcedureParameter | None

has_input() bool[source]

Checks if the procedure defines any input parameters.

Based on RDB$PROCEDURE_INPUTS > 0.

Returns:

True if input parameters exist, False otherwise.

Return type:

bool

has_output() bool[source]

Checks if the procedure defines any output parameters (RETURNS).

Based on RDB$PROCEDURE_OUTPUTS > 0.

Returns:

True if output parameters exist, False otherwise.

Return type:

bool

is_packaged() bool[source]

Checks if the procedure is defined within a package.

Based on the presence of RDB$PACKAGE_NAME.

Returns:

True if part of a package, False otherwise.

Return type:

bool

property engine_name: str | None

The name of the external engine used, if this is an external procedure (RDB$ENGINE_NAME). Returns None for standard PSQL procedures.

property entrypoint: str | None

The entry point function name within the external engine’s library, if this is an external procedure (RDB$ENTRYPOINT). Returns None for PSQL procedures.

property id: int

The internal numeric ID (RDB$PROCEDURE_ID) assigned to the procedure.

property input_params: DataList[ProcedureParameter]

A lazily-loaded DataList of the procedure’s input ProcedureParameter objects.

Ordered by position (RDB$PARAMETER_NUMBER). Returns an empty list if the procedure has no input parameters. Fetched from RDB$PROCEDURE_PARAMETERS.

property output_params: DataList[ProcedureParameter]

A lazily-loaded DataList of the procedure’s output ProcedureParameter objects.

Ordered by position (RDB$PARAMETER_NUMBER). Returns an empty list if the procedure has no output parameters (i.e., does not have a RETURNS clause). Fetched from RDB$PROCEDURE_PARAMETERS.

property owner_name: str

The user name of the procedure’s owner/creator (RDB$OWNER_NAME).

property package: Package | None

The Package object this procedure belongs to, if any (RDB$PACKAGE_NAME).

Returns None if the procedure is standalone.

property privacy: Privacy

The privacy flag (PUBLIC or PRIVATE) for packaged procedures.

Derived from RDB$PRIVATE_FLAG. Returns None if not a packaged procedure or flag is missing.

property privileges: DataList[Privilege]

A DataList of EXECUTE Privilege objects granted on this procedure.

Filters the main Schema.privileges collection for this procedure’s name and type (ObjectType.PROCEDURE).

property proc_type: ProcedureType

The type of the procedure (LEGACY, SELECTABLE, EXECUTABLE).

Derived from RDB$PROCEDURE_TYPE. Defaults to LEGACY if the attribute is missing.

property security_class: str | None

The security class name associated with this procedure, if any (RDB$SECURITY_CLASS). Returns None if not set.

property source: str | None

The PSQL source code of the procedure body (RDB$PROCEDURE_SOURCE). Returns None if the source is unavailable.

property valid_blr: bool | None

Indicates if the compiled BLR of the procedure is currently valid (RDB$VALID_BLR).

Returns True if valid, False if invalid, None if status is unknown/missing.

class firebird.lib.schema.Role(schema: Schema, attributes: dict[str, Any])[source]

Bases: SchemaItem

Represents a database role, a named collection of privileges.

Roles simplify privilege management by allowing privileges to be granted to the role, and then the role granted to users or other roles. RDB$ADMIN is a predefined system role.

Instances map data primarily from the RDB$ROLES system table. They are accessed via Schema.roles.

Supported SQL actions via get_sql_for():

  • User-defined roles:

    • create: Generates CREATE ROLE role_name.

    • drop: Generates DROP ROLE role_name.

    • comment: Generates COMMENT ON ROLE role_name IS ....

  • System roles (like RDB$ADMIN):

    • comment: Adds or removes a descriptive comment.

Parameters:
  • schema (Schema | None) – The parent Schema instance.

  • attributes (dict[str, Any]) – Raw data dictionary fetched from the RDB$ROLES row.

_get_comment_sql(**params) str[source]

Generates the SQL command to add or remove a COMMENT ON this role.

Parameters:

**params – Accepts no parameters.

Returns:

The COMMENT ON ROLE ... IS ... SQL string. Sets comment to NULL if self.description is None, otherwise uses the description text with proper escaping.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_create_sql(**params) str[source]

Generates the SQL command to CREATE this role.

Parameters:

**params – Accepts no parameters.

Returns:

The CREATE ROLE SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_drop_sql(**params) str[source]

Generates the SQL command to DROP this role.

Parameters:

**params – Accepts no parameters.

Returns:

The DROP ROLE SQL string.

Raises:
  • ValueError – If unexpected parameters are passed.

  • Error – If attempting to drop a system role.

Return type:

str

_get_name() str[source]

Returns the role name (RDB$ROLE_NAME).

Return type:

str

property owner_name: str

The user name of the role’s owner/creator (RDB$OWNER_NAME).

property privileges: DataList[Privilege]

A DataList of all Privilege objects granted to this role.

Filters the main Schema.privileges collection where this role is the grantee (RDB$USER). This includes object privileges (SELECT, INSERT, etc.) and potentially membership in other roles granted TO this role.

Returns:

A list of privileges held by this role.

property security_class: str | None

The security class name associated with this role, if any (RDB$SECURITY_CLASS). Returns None if not set.

class firebird.lib.schema.FunctionArgument(schema: Schema, function: Function, attributes: dict[str, Any])[source]

Bases: SchemaItem

Represents an argument or the return value of a User-Defined Function (Function).

This class holds metadata about a single function argument/return value, including its name, data type, position, passing mechanism (e.g., by value, by descriptor), and nullability/default value (for PSQL function arguments).

Instances map data primarily from the RDB$FUNCTION_ARGUMENTS system table. They are accessed via the Function.arguments or Function.returns properties.

This class itself does not support any direct SQL actions via get_sql_for(). Its definition is part of the DECLARE EXTERNAL FUNCTION or CREATE FUNCTION statement.

Parameters:
  • schema (Schema | None) – The parent Schema instance.

  • function (Function) – The parent Function object this argument belongs to.

  • attributes (dict[str, Any]) – Raw data dictionary fetched from the RDB$FUNCTION_ARGUMENTS row.

_get_name() str[source]

Returns the argument name (RDB$ARGUMENT_NAME).

Return type:

str

get_sql_definition() str[source]

Generates the SQL string representation of the argument’s definition.

Used when constructing DECLARE EXTERNAL FUNCTION or CREATE FUNCTION statements. Format varies depending on whether it’s an external UDF or a PSQL function, and whether it’s an input argument or the return value.

Examples:

  • External UDF input: INTEGER BY DESCRIPTOR

  • External UDF return: VARCHAR(100) CHARACTER SET WIN1252 BY DESCRIPTOR FREE_IT

  • PSQL function input: P_ID INTEGER NOT NULL = 0

  • PSQL function return: VARCHAR(50) CHARACTER SET UTF8 COLLATE UNICODE_CI

Returns:

A string suitable for use within function DDL statements.

Return type:

str

has_default() bool[source]

Checks if the argument has a DEFAULT value defined (relevant for PSQL function inputs).

Based on the presence of RDB$DEFAULT_SOURCE.

Returns:

True if a default value source exists, False otherwise.

Return type:

bool

is_by_descriptor(*, any_desc: bool = False) bool[source]

Checks if the argument is passed using a descriptor mechanism.

Parameters:

any_desc (bool) – If True, checks for any descriptor type (BY_VMS_DESCRIPTOR, BY_ISC_DESCRIPTOR, BY_SCALAR_ARRAY_DESCRIPTOR). If False (default), specifically checks only for BY_VMS_DESCRIPTOR (legacy).

Returns:

True if the argument uses the specified descriptor mechanism(s), False otherwise.

Return type:

bool

is_by_reference() bool[source]

Checks if the argument is passed by reference (RDB$MECHANISM = 1 or 5).

Includes standard reference and reference with NULL support.

Returns:

True if passed by reference, False otherwise.

Return type:

bool

is_by_value() bool[source]

Checks if the argument is passed by value (RDB$MECHANISM = 0).

Returns:

True if passed by value, False otherwise.

Return type:

bool

is_freeit() bool[source]

Checks if the engine should free memory allocated for a RETURNS BY DESCRIPTOR value.

Indicated by a negative value in RDB$MECHANISM.

Returns:

True if the FREE_IT convention applies, False otherwise.

Return type:

bool

is_nullable() bool[source]

Checks if the argument/return value allows NULL (relevant for PSQL functions).

Based on RDB$NULL_FLAG (0 = nullable, 1 = not nullable).

Returns:

True if NULL is allowed, False otherwise.

Return type:

bool

is_packaged() bool[source]

Checks if the argument belongs to a function defined within a package.

Based on the presence of RDB$PACKAGE_NAME.

Returns:

True if part of a packaged function, False otherwise.

Return type:

bool

is_returning() bool[source]

Checks if this argument represents the function’s return value.

Determined by comparing position with the function’s RDB$RETURN_ARGUMENT.

Returns:

True if this is the return argument/value, False otherwise.

Return type:

bool

is_with_null() bool[source]

Checks if the argument is passed by reference with explicit NULL indicator support (RDB$MECHANISM = 5).

Returns:

True if mechanism is BY_REFERENCE_WITH_NULL, False otherwise.

Return type:

bool

property argument_mechanism: Mechanism | None

The mechanism (Mechanism) used for passing PSQL function parameters (RDB$ARGUMENT_MECHANISM). Returns None for external UDFs or if unknown.

property argument_name: str | None

The explicit name (RDB$ARGUMENT_NAME) of the argument, if defined. Common for PSQL functions, may be None for external UDF arguments.

property character_length: int

Length in characters (RDB$CHARACTER_LENGTH) for CHAR, VARCHAR, CSTRING.

property character_set: CharacterSet | None

The CharacterSet object (RDB$CHARACTER_SET_ID) for character/text types. Returns None otherwise.

property collation: Collation | None

The specific Collation object (RDB$COLLATION_ID) for character types. Returns None if not applicable or using default.

property column: TableColumn | None

The source TableColumn if a PSQL parameter uses TYPE OF COLUMN. Returns None otherwise.

property datatype: str

A string representation of the argument’s complete SQL data type definition.

Handles differences between external UDF types (based on field_type, length, etc.) and PSQL function types (potentially derived from domain or column).

property default: str | None

The DEFAULT value expression string (RDB$DEFAULT_SOURCE) for PSQL input arguments. Returns None if no default or not applicable.

property domain: Domain | None

The underlying Domain object (RDB$FIELD_SOURCE) for PSQL function parameters. Returns None for external UDF arguments or if no domain is associated.

property field_type: FieldType | None

The base data type code (FieldType) of the argument (RDB$FIELD_TYPE).

Returns None if the type code is missing or zero (may occur for PSQL params relying solely on domain/column type).

property function: Function

The parent Function object this argument belongs to.

property length: int

The defined length (RDB$FIELD_LENGTH) in bytes for types like CHAR, VARCHAR, BLOB.

property mechanism: Mechanism | None

The mechanism (Mechanism enum) used for passing the argument.

Derived from the absolute value of RDB$MECHANISM. See is_freeit() for sign meaning. Returns None if the mechanism code is unrecognized or missing.

property package: Package | None

The Package if the function is part of one (RDB$PACKAGE_NAME). Returns None otherwise.

property position: int

The 1-based position (RDB$ARGUMENT_POSITION) of the argument in the function signature (or the return argument position number).

property precision: int | None

The precision (RDB$FIELD_PRECISION) for numeric/decimal/float types. Returns None if not applicable.

property scale: int

Negative number representing the scale of NUMBER and DECIMAL argument.

property sub_type: FieldSubType | None

The field sub-type code (RDB$FIELD_SUB_TYPE).

Returns a FieldSubType enum member (e.g., BINARY, TEXT, NUMERIC, DECIMAL) if recognized, the raw integer code otherwise, or None if missing.

property type_from: TypeFrom | None

Indicates the source (TypeFrom) of a PSQL parameter’s data type definition.

Returns None for external UDF arguments or if the source cannot be determined.

class firebird.lib.schema.Function(schema: Schema, attributes: dict[str, Any])[source]

Bases: SchemaItem

Represents a User-Defined Function (UDF), either external or written in PSQL.

Functions perform calculations or operations and return a single value. They can be:

  • External UDFs: Implemented in an external library (DLL/SO), declared using DECLARE EXTERNAL FUNCTION. Arguments are passed by value, reference, or descriptor.

  • PSQL Functions: Implemented directly in PSQL using CREATE FUNCTION, similar to stored procedures but must return a value via the RETURNS clause. Can be standalone or part of a Package.

Instances map data primarily from the RDB$FUNCTIONS system table. Associated arguments/return values are fetched from RDB$FUNCTION_ARGUMENTS. Functions are accessed via Schema.functions, Schema.sys_functions, Schema.all_functions, or Package.functions.

Supported SQL actions via get_sql_for():

  • External UDFs:

    • declare: Generates DECLARE [EXTERNAL] FUNCTION ... ENTRY_POINT ... MODULE_NAME ....

    • drop: Generates DROP [EXTERNAL] FUNCTION ....

    • comment: Generates COMMENT ON [EXTERNAL] FUNCTION ... IS ....

  • User-defined, standalone PSQL Functions:

    • create (optional keyword arg no_code: bool=False): Generates CREATE FUNCTION ... RETURNS ... AS BEGIN ... END. Includes parameter and return type definitions. Uses empty body if no_code=True.

    • recreate (optional keyword arg no_code: bool=False): Generates RECREATE FUNCTION ....

    • create_or_alter (optional keyword arg no_code: bool=False): Generates CREATE OR ALTER FUNCTION ....

    • drop: Generates DROP FUNCTION ....

    • comment: Generates COMMENT ON FUNCTION ... IS ....

    • alter (keyword args): Modifies the function definition. Requires code.

      • arguments (str | list[str] | tuple[str], optional): New input argument definitions.

      • returns (str, required): New RETURNS definition.

      • declare (str | list[str] | tuple[str], optional): New variable declarations.

      • code (str | list[str] | tuple[str], required): New function body code.

  • System functions or packaged functions:

    • comment: Adds or removes a descriptive comment.

    • Note: Packaged functions are typically managed via ALTER PACKAGE.

Parameters:
  • schema (Schema | None) – The parent Schema instance.

  • attributes (dict[str, Any]) – Raw data dictionary fetched from the RDB$FUNCTIONS row.

_get_alter_sql(**params) str[source]

Generates the SQL command to ALTER this PSQL function.

Allows modification of input parameters, return type, declarations, and code body. Both returns and code parameters are required.

Parameters:

**params

Accepts keyword arguments:

  • arguments (str | list[str] | tuple[str], optional): New definition(s) for input parameters (full SQL like ‘p_id INTEGER’). Replaces existing.

  • returns (str, required): The new return type definition string (e.g., ‘VARCHAR(100) CHARACTER SET UTF8’).

  • declare (str | list[str] | tuple[str], optional): New variable declarations section. Replaces existing.

  • code (str | list[str] | tuple[str], required): The new PSQL code for the function body (between BEGIN and END).

Returns:

The ALTER FUNCTION SQL string.

Raises:
  • ValueError – If required parameters (returns, code) are missing, if parameter types are invalid, or if unexpected parameters are passed.

  • Error – If called on an external UDF.

Return type:

str

_get_comment_sql(**params) str[source]

Generates the SQL command to add or remove a COMMENT ON this function.

Parameters:

**params – Accepts no parameters.

Returns:

The COMMENT ON [EXTERNAL] FUNCTION ... IS ... SQL string. Sets comment to NULL if self.description is None, otherwise uses the description text with proper escaping.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_create_sql(**params) str[source]

Generates the SQL command to CREATE this PSQL function.

Includes input parameter list (...), RETURNS clause, and the AS BEGIN ... END block with PSQL source code.

Parameters:

**params

Accepts one optional keyword argument:

  • no_code (bool): If True, generates an empty BEGIN END block instead of the actual function source code. Defaults to False.

Returns:

The CREATE FUNCTION SQL string.

Raises:
  • ValueError – If unexpected parameters are passed.

  • Error – If called on an external UDF, or if parameters/return type cannot be loaded.

Return type:

str

_get_declare_sql(**params) str[source]

Generates the SQL command to DECLARE this external function (UDF).

Includes input parameter definitions (type, mechanism) and the return value definition (type, mechanism, FREE_IT), plus ENTRY_POINT and MODULE_NAME.

Parameters:

**params – Accepts no parameters.

Returns:

The DECLARE EXTERNAL FUNCTION SQL string.

Raises:
  • ValueError – If unexpected parameters are passed.

  • Error – If called on a non-external (PSQL) function or if arguments/return value cannot be loaded.

Return type:

str

_get_drop_sql(**params) str[source]

Generates the SQL command to DROP this function.

Parameters:

**params – Accepts no parameters.

Returns:

The DROP EXTERNAL FUNCTION or DROP FUNCTION SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_name() str[source]

Returns the function name (RDB$FUNCTION_NAME).

Return type:

str

_load_arguments(mock: dict[str, Any] | None = None) None[source]

Internal helper: Loads function arguments from RDB$FUNCTION_ARGUMENTS.

Parameters:

mock (dict[str, Any] | None)

Return type:

None

has_arguments() bool[source]

Checks if the function defines any input arguments.

Excludes the argument designated as the return value.

Returns:

True if input arguments exist, False otherwise.

Return type:

bool

has_return() bool[source]

Checks if the function is defined to return a value.

Based on the presence of a return argument identified by RDB$RETURN_ARGUMENT.

Returns:

True if a return value/argument exists, False otherwise.

Return type:

bool

has_return_argument() bool[source]

Checks if the function returns its value via one of its input arguments.

This is a legacy mechanism where RDB$RETURN_ARGUMENT points to a non-zero argument position. Modern functions usually return directly (position 0 or implied).

Returns:

True if return is via an input parameter position, False otherwise.

Return type:

bool

is_external() bool[source]

Checks if this is an external UDF (declared with MODULE_NAME).

Returns:

True if module_name is not None/empty, False otherwise (PSQL function).

Return type:

bool

is_packaged() bool[source]

Checks if the function is defined within a package.

Based on the presence of RDB$PACKAGE_NAME.

Returns:

True if part of a package, False otherwise.

Return type:

bool

property arguments: DataList[FunctionArgument]

A lazily-loaded DataList of the function’s input FunctionArgument objects.

Excludes the argument designated as the return value. Ordered by position. Returns an empty list if there are no input arguments.

property deterministic_flag: int | None

Indicates if a PSQL function is declared as deterministic (RDB$DETERMINISTIC_FLAG).

(Introduced in Firebird 4.0). 1 = Deterministic, 0 = Not Deterministic. Returns None if not applicable (external UDF, older FB) or flag is missing.

property engine_mame: str | None

The execution engine name (RDB$ENGINE_NAME), often ‘UDR’ for PSQL functions or None for external UDFs.

property entrypoint: str | None

The function name within the external library (RDB$ENTRYPOINT) for external UDFs. Returns None for PSQL functions.

property id: int

The internal numeric ID (RDB$FUNCTION_ID)

property legacy_flag: Legacy

Indicates if the function uses legacy syntax/behavior (Legacy enum).

Derived from RDB$LEGACY_FLAG.

property module_name: str | None

The external library name (RDB$MODULE_NAME) for external UDFs. Returns None for PSQL functions.

property owner_name: str

The user name of the function’s owner/creator (RDB$OWNER_NAME).

property package: Package | None

The Package object this function belongs to, if any (RDB$PACKAGE_NAME). Returns None if the function is standalone.

property private_flag: Privacy | None

PUBLIC or PRIVATE) for packaged functions.

Derived from RDB$PRIVATE_FLAG. Returns None if not a packaged function.

Type:

The privacy flag (Privacy

property returns: FunctionArgument | None

The FunctionArgument object representing the function’s return value.

This argument is identified by the RDB$RETURN_ARGUMENT field in RDB$FUNCTIONS. Returns None if the function does not return a value or arguments are not loaded. Loads arguments lazily on first access.

property security_class: str | None

The security class name associated with this function (RDB$SECURITY_CLASS). Returns None if not set.

property source: str | None

The PSQL source code (RDB$FUNCTION_SOURCE) for PSQL functions. Returns None for external UDFs.

property valid_blr: bool | None

Indicates if the compiled BLR of the PSQL function is valid (RDB$VALID_BLR). Returns True/False/None. Not applicable to external UDFs.

class firebird.lib.schema.DatabaseFile(schema: Schema, attributes: dict[str, Any])[source]

Bases: SchemaItem

Represents a single physical file belonging to the main database or a shadow.

Firebird databases can span multiple files. The first file is the primary, and subsequent files are secondary (continuation) files. This class holds information about one such file, including its name, sequence number within the database or shadow set, its starting page number, and its length in pages.

Instances map data from the RDB$FILES system table. They are typically accessed via Schema.files (for main database files) or Shadow.files (for shadow files).

This class represents a physical file component and does not support any direct SQL actions via get_sql_for(). Database file management is done through other commands (e.g., ALTER DATABASE ADD FILE, CREATE SHADOW).

Parameters:
  • schema (Schema | None) – The parent Schema instance.

  • attributes (dict[str, Any]) – Raw data dictionary fetched from the RDB$FILES row.

_get_name() str[source]

Returns a synthesized name based on sequence, not a standard object name.

Database files don’t have SQL names. This returns a name like ‘FILE_N’ based on the sequence number for identification purposes within the library.

Returns:

A string like ‘FILE_0’, ‘FILE_1’, etc., or None if sequence is missing.

Return type:

str

is_sys_object() bool[source]

Indicates that database file entries themselves are system metadata.

Returns:

True always.

Return type:

bool

property filename: str

The full operating system path and name of the database file (RDB$FILE_NAME).

property length: str

The allocated length (RDB$FILE_LENGTH) of this file in database pages. A value of 0 often indicates the file can grow automatically.

property sequence: int

The sequence number (RDB$FILE_SEQUENCE) of this file within its set (main database or a specific shadow). Starts from 0 for the primary file.

property start: int

The starting page number (RDB$FILE_START) allocated to this file within the logical database page space.

class firebird.lib.schema.Shadow(schema: Schema, attributes: dict[str, Any])[source]

Bases: SchemaItem

Represents a database shadow, a physical copy of the database for disaster recovery.

Shadows are maintained automatically by the Firebird engine (if AUTO) or manually (if MANUAL). They can be conditional, activating only if the main database becomes unavailable. A shadow can consist of one or more physical files.

Instances primarily map data derived from RDB$FILES where RDB$SHADOW_NUMBER > 0. They are accessed via Schema.shadows.

Supported SQL actions via get_sql_for():

  • create: Generates the CREATE SHADOW shadow_id [AUTO|MANUAL] [CONDITIONAL] FILE '...' [LENGTH N] [FILE '...' STARTING AT P [LENGTH N]] ... statement.

  • drop (optional keyword arg preserve: bool=False): Generates DROP SHADOW shadow_id [PRESERVE FILE]. If preserve is True, adds PRESERVE FILE clause.

Note:

Shadows do not have user-assigned names in SQL; they are identified by their numeric ID.
Parameters:
  • schema (Schema | None) – The parent Schema instance.

  • attributes (dict[str, Any]) – Raw data dictionary containing RDB$SHADOW_NUMBER and RDB$FILE_FLAGS fetched from the RDB$FILES row corresponding to the shadow’s primary file (sequence 0).

_get_create_sql(**params) str[source]

Generates the SQL command to CREATE this shadow.

Includes the shadow ID, AUTO/MANUAL and CONDITIONAL flags, and the definition for all associated physical files (name, length, starting page).

Parameters:

**params – Accepts no parameters.

Returns:

The CREATE SHADOW SQL string.

Raises:
  • ValueError – If unexpected parameters are passed.

  • Error – If the associated shadow files cannot be loaded.

Return type:

str

_get_drop_sql(**params) str[source]

Generates the SQL command to DROP this shadow.

Parameters:

**params

Accepts one optional keyword argument:

  • preserve (bool): If True, adds the PRESERVE FILE clause to prevent the physical shadow files from being deleted by the engine. Defaults to False.

Returns:

The DROP SHADOW SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_name() str[source]

Returns a synthesized name ‘SHADOW_N’, as shadows don’t have SQL names.

Returns:

A string like ‘SHADOW_1’, ‘SHADOW_2’, etc., based on the shadow ID.

Return type:

str

is_conditional() bool[source]

Checks if the shadow is conditional (CONDITIONAL).

Conditional shadows are only activated by the engine if the main database becomes inaccessible. Based on the ShadowFlag.CONDITIONAL flag.

Returns:

True if conditional, False otherwise.

Return type:

bool

is_inactive() bool[source]

Checks if the shadow is currently marked as inactive (INACTIVE).

Based on the ShadowFlag.INACTIVE flag. The engine typically ignores inactive shadows.

Returns:

True if inactive, False if active.

Return type:

bool

is_manual() bool[source]

Checks if the shadow requires manual intervention (MANUAL).

Based on the ShadowFlag.MANUAL flag.

Returns:

True if manual, False if automatic (AUTO).

Return type:

bool

is_sys_object() bool[source]

Indicates that shadows are user-defined objects, not system objects.

Returns:

False always.

Return type:

bool

property files: DataList[DatabaseFile]

A lazily-loaded DataList of the DatabaseFile objects comprising this shadow.

Ordered by sequence number. Fetched from RDB$FILES matching this shadow’s ID.

property flags: ShadowFlag

A ShadowFlag enum value representing the combined flags (INACTIVE, MANUAL, CONDITIONAL) defined by RDB$FILE_FLAGS for this shadow.

property id: int

The numeric ID (RDB$SHADOW_NUMBER) that identifies this shadow set.

class firebird.lib.schema.Privilege(schema: Schema, attributes: dict[str, Any])[source]

Bases: SchemaItem

Represents a single privilege granted on a database object to a user or another object.

This class maps a single row from the RDB$USER_PRIVILEGES system table, detailing:

  • Who granted the privilege (grantor).

  • Who received the privilege (user / grantee).

  • What the privilege is (privilege, e.g., SELECT, INSERT, EXECUTE, MEMBERSHIP).

  • What object the privilege applies to (subject, e.g., Table, Procedure, Role).

  • Optionally, which specific column it applies to (field_name).

  • Whether the grantee can grant this privilege to others (grant_option).

Instances are typically accessed via Schema.privileges or filtered using methods like Schema.get_privileges_of() or properties like Table.privileges.

Supported SQL actions via get_sql_for():

  • grant (optional keyword arg grantors: list[str]=[‘SYSDBA’]): Generates the GRANT ... ON ... TO ... [WITH GRANT/ADMIN OPTION] [GRANTED BY ...] statement. The GRANTED BY clause is added if the actual grantor is not in the grantors list.

  • revoke (optional keyword args: grantors: list[str]=[‘SYSDBA’], grant_option: bool=False): Generates the REVOKE [GRANT/ADMIN OPTION FOR] ... FROM ... [GRANTED BY ...] statement. If grant_option is True, revokes only the grant/admin option, not the privilege itself. The GRANTED BY clause is added if the actual grantor is not in the grantors list.

Parameters:
  • schema (Schema | None) – The parent Schema instance.

  • attributes (dict[str, Any]) – Raw data dictionary fetched from the RDB$USER_PRIVILEGES row.

_get_grant_sql(**params) str[source]

Generates the SQL command to GRANT this specific privilege.

Constructs the GRANT statement including the privilege type (and column if applicable), subject object, grantee, optional WITH GRANT/ADMIN OPTION, and optional GRANTED BY clause.

Parameters:

**params

Accepts one optional keyword argument:

  • grantors (list[str]): A list of user/role names considered standard grantors. If the actual grantor_name of this privilege is not in this list, a GRANTED BY clause will be appended. Defaults to ['SYSDBA'].

Returns:

The GRANT SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_name() str | None[source]

Returns a synthesized name representing the privilege, not a standard object name.

Combines grantee, privilege, and subject for identification within the library. Example: ‘USER1_SELECT_ON_TABLE_T1’

Returns:

A synthesized string identifier, or None if components are missing.

Return type:

str | None

_get_revoke_sql(**params) str[source]

Generates the SQL command to REVOKE this specific privilege.

Constructs the REVOKE statement including the privilege type (and column if applicable), subject object, grantee, optional GRANT/ADMIN OPTION FOR clause, and optional GRANTED BY clause.

Parameters:

**params

Accepts optional keyword arguments:

  • grantors (list[str]): A list of standard grantor names. If the actual grantor_name is not in this list, a GRANTED BY clause will be appended. Defaults to ['SYSDBA'].

  • grant_option (bool): If True, revokes only the ability to grant the privilege (GRANT OPTION FOR or ADMIN OPTION FOR), not the privilege itself. Defaults to False.

Returns:

The REVOKE SQL string.

Raises:

ValueError – If grant_option is True but the privilege was not granted with the grant/admin option, or if unexpected parameters are passed.

Return type:

str

has_grant() bool[source]

Checks if this privilege was granted with the WITH GRANT OPTION or WITH ADMIN OPTION.

Returns:

True if grant/admin option is present, False otherwise.

Return type:

bool

is_delete() bool[source]

Checks if this is a DELETE privilege.

Return type:

bool

is_execute() bool[source]

Checks if this is an EXECUTE privilege (on a procedure or function).

Return type:

bool

is_insert() bool[source]

Checks if this is an INSERT privilege.

Return type:

bool

is_membership() bool[source]

Checks if this represents ROLE membership.

Return type:

bool

is_reference() bool[source]

Checks if this is a REFERENCES privilege (for foreign keys).

Return type:

bool

is_select() bool[source]

Checks if this is a SELECT privilege.

Return type:

bool

is_sys_object() bool[source]

Indicates that privilege entries themselves are system metadata.

Returns:

True always.

Return type:

bool

is_update() bool[source]

Checks if this is an UPDATE privilege.

Return type:

bool

is_usage() bool[source]

Checks if this represents USAGE privilege.

Return type:

bool

property field_name: str

The specific column/field name (RDB$FIELD_NAME) this privilege applies to.

Relevant for column-level SELECT, UPDATE, REFERENCES privileges. Returns None if the privilege applies to the object as a whole.

property grant_option: GrantOption | None

Indicates if the privilege includes the grant/admin option (GrantOption).

Derived from RDB$GRANT_OPTION (0=None, 1=Grant, 2=Admin). Returns None if the option code is unrecognized or missing.

property grantor: UserInfo | None

the user who granted the privilege (RDB$GRANTOR).

Returns:

A UserInfo object representing the grantor, or None if the grantor name is missing.

Type:

The grantor

property grantor_name: str

The user name (RDB$GRANTOR) of the user who granted the privilege.

property privilege: PrivilegeCode

The type of privilege granted (PrivilegeCode enum).

Derived from RDB$PRIVILEGE (‘S’, ‘I’, ‘U’, ‘D’, ‘R’, ‘X’, ‘G’, ‘M’, …).

property subject: Role | Table | View | Procedure | Function

The database object (SchemaItem) on which the privilege is granted.

Resolves based on subject_name and subject_type. May return specific column objects if field_name is set.

Returns:

The specific object (e.g., Table, Procedure, Role, TableColumn), or None if resolution fails.

property subject_name: str

The name (RDB$RELATION_NAME) of the object on which the privilege is granted (e.g., table name, procedure name, role name).

property subject_type: ObjectType

The type (ObjectType) of the object to which the privilege is granted (RDB$OBJECT_TYPE).

property user: UserInfo | Role | Procedure | Trigger | View | None

the user or object receiving the privilege.

Resolves based on RDB$USER (name) and RDB$USER_TYPE.

Returns:

A UserInfo, Role, Procedure, Trigger, or View object representing the grantee, or None if resolution fails.

Type:

The grantee

property user_name: str

The name (RDB$USER) of the grantee (user, role, procedure, etc.).

property user_type: ObjectType

The type (ObjectType) of the grantee (RDB$USER_TYPE).

class firebird.lib.schema.Package(schema: Schema, attributes: dict[str, Any])[source]

Bases: SchemaItem

Represents a PSQL package, a container for related procedures and functions.

Packages provide namespace management, encapsulation, and can define public (accessible outside the package) and private (internal use only) routines. They consist of two parts:

  • Header: Declares public procedures, functions, variables, and types.

  • Body: Contains the implementation (code) for the declared routines, and can also include private declarations and implementations.

Instances map data primarily from the RDB$PACKAGES system table. Contained procedures and functions are linked via RDB$PACKAGE_NAME in their respective system tables (RDB$PROCEDURES, RDB$FUNCTIONS). Packages are accessed via Schema.packages.

Supported SQL actions via get_sql_for():

  • create (keyword argument body: bool=False): Generates CREATE PACKAGE [BODY] ... AS ... END. If body is False (default), creates the package header using self.header. If body is True, creates the package body using self.body.

  • recreate (keyword argument body: bool=False): Generates RECREATE PACKAGE [BODY] .... Same logic as create regarding the body parameter.

  • create_or_alter (keyword argument body: bool=False): Generates CREATE OR ALTER PACKAGE [BODY] .... Same logic as create regarding the body parameter.

  • drop (keyword argument body: bool=False): Generates DROP PACKAGE [BODY] .... If body is False (default), drops the package header (and implicitly the body). If body is True, drops only the package body.

  • comment: Generates COMMENT ON PACKAGE ... IS ....

Note

Altering the contents of a package typically involves using CREATE OR ALTER PACKAGE [BODY] with the complete new source code, rather than a specific ALTER PACKAGE command to modify parts (which is less common in Firebird PSQL).

Parameters:
  • schema (Schema | None) – The parent Schema instance.

  • attributes (dict[str, Any]) – Raw data dictionary fetched from the RDB$PACKAGES row.

_get_alter_sql(**params) str[source]

Generates the SQL command to CREATE the package header or body.

Parameters:

**params

Accepts one optional keyword argument:

  • header (str | list[str]): Source string or list of lines (without line end) for package header. If present, generates ALTER PACKAGE using the value as source. Otherwise it generates ALTER PACKAGE with empty source.

Returns:

The ALTER PACKAGE SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_comment_sql(**params) str[source]

Generates the SQL command to add or remove a COMMENT ON this package.

Parameters:

**params – Accepts no parameters.

Returns:

The COMMENT ON PACKAGE ... IS ... SQL string. Sets comment to NULL if self.description is None, otherwise uses the description text with proper escaping.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_create_sql(**params) str[source]

Generates the SQL command to CREATE the package header or body.

Parameters:

**params

Accepts one optional keyword argument:

  • body (str): If present, generates CREATE PACKAGE BODY using the specified value as body source. If not present, generates CREATE PACKAGE (header) using the header property as source.

Returns:

The CREATE PACKAGE [BODY] SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_drop_sql(**params) str[source]

Generates the SQL command to DROP the package header or body.

Parameters:

**params

Accepts one optional keyword argument:

  • body (bool): If True, generates DROP PACKAGE BODY. If False (default), generates DROP PACKAGE (which drops both header and body).

Returns:

The DROP PACKAGE [BODY] SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_name() str[source]

Returns the package name (RDB$PACKAGE_NAME).

Return type:

str

has_valid_body() bool | None[source]

Checks if the package body is currently marked as valid by the engine.

Based on RDB$VALID_BODY_FLAG. A body might be invalid if the header changed since the body was compiled, or if the body failed compilation.

Returns:

True if the body is valid, False if invalid, None if the status is unknown or the flag is missing.

Return type:

bool | None

property body: str | None

The PSQL source code for the package body (RDB$PACKAGE_BODY_SOURCE). Contains implementations and private declarations. Returns None if unavailable.

property functions: DataList[Function]

A DataList of all Function objects defined within this package.

Filters the main Schema.functions collection based on package name.

property header: str | None

The PSQL source code for the package header (RDB$PACKAGE_HEADER_SOURCE). Contains public declarations. Returns None if unavailable.

property owner_name: str

The user name of the package’s owner/creator (RDB$OWNER_NAME).

property procedures: DataList[Procedure]

A DataList of all Procedure objects defined within this package.

Filters the main Schema.procedures collection based on package name.

property security_class: str | None

The security class name associated with this package, if any (RDB$SECURITY_CLASS). Returns None if not set.

class firebird.lib.schema.BackupHistory(schema: Schema, attributes: dict[str, Any])[source]

Bases: SchemaItem

Represents an entry in the database’s NBackup history log.

Each entry records details about a physical backup operation performed using the nbackup utility, such as the backup level (full or incremental), timestamp, SCN (System Change Number), GUID, and the location of the backup file.

Instances map data from the RDB$BACKUP_HISTORY system table. They are accessed via Schema.backup_history.

This class represents a historical record and does not support any direct SQL actions via get_sql_for(). Backup history is managed implicitly by nbackup operations and potentially explicit DELETE FROM RDB$BACKUP_HISTORY statements (use with caution).

Parameters:
  • schema (Schema | None) – The parent Schema instance.

  • attributes (dict[str, Any]) – Raw data dictionary fetched from the RDB$BACKUP_HISTORY row.

_get_name() str[source]

Returns a synthesized name based on SCN, not a standard object name.

Backup history entries don’t have SQL names. This returns a name like ‘BCKP_SCN_12345’ based on the SCN for identification purposes within the library.

Returns:

A string like ‘BCKP_SCN_12345’, or None if SCN is missing.

Return type:

str

is_sys_object() bool[source]

Indicates that backup history entries themselves are system metadata.

Returns:

True always.

Return type:

bool

property created: datetime

The date and time (RDB$TIMESTAMP) when the backup operation completed.

property filename: str

The full operating system path and filename (RDB$FILE_NAME) of the primary backup file created during this operation.

property guid: str

A unique identifier string (RDB$GUID) associated with the database state at the time of the backup. Used for validating incremental backups.

property id: int

The unique numeric identifier (RDB$BACKUP_ID) assigned by the engine to this backup record.

property level: int

The backup level (RDB$BACKUP_LEVEL). Typically 0 for a full backup, and increasing integers for subsequent incremental backups based on the level 0.

property scn: int

The System Change Number (RDB$SCN) of the database at the time this backup operation started.

class firebird.lib.schema.Filter(schema: Schema, attributes: dict[str, Any])[source]

Bases: SchemaItem

Represents a user-defined BLOB filter, used for transforming BLOB data.

BLOB filters are implemented as external functions residing in shared libraries (DLL/SO). They define a transformation between two BLOB subtypes (e.g., compressing text, encrypting binary data). Filters are declared in the database and can then be used implicitly when reading/writing BLOBs of matching subtypes.

Instances map data from the RDB$FILTERS system table. They are typically accessed via Schema.filters.

Supported SQL actions via get_sql_for():

  • User-defined filters:

    • declare: Generates DECLARE FILTER filter_name ... ENTRY_POINT ... MODULE_NAME ....

    • drop: Generates DROP FILTER filter_name.

    • comment: Generates COMMENT ON FILTER filter_name IS ....

  • System filters (if any exist):

    • comment: Adds or removes a descriptive comment.

Parameters:
  • schema (Schema | None) – The parent Schema instance.

  • attributes (dict[str, Any]) – Raw data dictionary fetched from the RDB$FILTERS row.

_get_comment_sql(**params) str[source]

Generates the SQL command to add or remove a COMMENT ON this BLOB filter.

Parameters:

**params – Accepts no parameters.

Returns:

The COMMENT ON FILTER ... IS ... SQL string. Sets comment to NULL if self.description is None, otherwise uses the description text with proper escaping.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_declare_sql(**params) str[source]

Generates the SQL command to DECLARE this BLOB filter.

Includes the input and output BLOB subtypes, entry point, and module name.

Parameters:

**params – Accepts no parameters.

Returns:

The DECLARE FILTER SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_drop_sql(**params) str[source]

Generates the SQL command to DROP this BLOB filter.

Parameters:

**params – Accepts no parameters.

Returns:

The DROP FILTER SQL string.

Raises:

ValueError – If unexpected parameters are passed.

Return type:

str

_get_name() str[source]

Returns the filter name (stored in RDB$FUNCTION_NAME).

Return type:

str

property entrypoint: str

The exported function name (RDB$ENTRYPOINT) within the external library that implements the filter logic.

property input_sub_type: int

The numeric BLOB subtype (RDB$INPUT_SUB_TYPE) that this filter accepts as input.

property module_name: str

The name (RDB$MODULE_NAME) of the external shared library (DLL/SO) containing the filter’s implementation code.

property output_sub_type: int

The numeric BLOB subtype (RDB$OUTPUT_SUB_TYPE) that this filter produces as output.