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:
IntEnumFirebird 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:
IntEnumField 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:
IntEnumDependent type codes.
Changed in version 1.4.0: -
PACKAGErenamed toPACKAGE_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:
EnumIndex ordering.
- ASCENDING = 'ASCENDING'¶
- DESCENDING = 'DESCENDING'¶
- class firebird.lib.schema.Mechanism(value)[source]¶
Bases:
IntEnumMechanism 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:
IntEnumTransaction state codes.
- COMMITTED = 2¶
- LIMBO = 1¶
- ROLLED_BACK = 3¶
- class firebird.lib.schema.SystemFlag(value)[source]¶
Bases:
IntEnumSystem 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:
IntEnumRelation 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:
IntEnumProcedure type codes.
- EXECUTABLE = 2¶
- LEGACY = 0¶
- SELECTABLE = 1¶
- class firebird.lib.schema.ParameterMechanism(value)[source]¶
Bases:
IntEnumParameter mechanism type codes.
- NORMAL = 0¶
- TYPE_OF = 1¶
- class firebird.lib.schema.TypeFrom(value)[source]¶
Bases:
IntEnumSource of parameter datatype codes.
- DATATYPE = 0¶
- DOMAIN = 1¶
- TYPE_OF_COLUMN = 3¶
- TYPE_OF_DOMAIN = 2¶
- class firebird.lib.schema.ParameterType(value)[source]¶
Bases:
IntEnumParameter type codes.
- INPUT = 0¶
- OUTPUT = 1¶
- class firebird.lib.schema.IdentityType(value)[source]¶
Bases:
IntEnumIdentity type codes.
- ALWAYS = 0¶
- BY_DEFAULT = 1¶
- class firebird.lib.schema.GrantOption(value)[source]¶
Bases:
IntEnumGrant option codes.
- ADMIN_OPTION = 2¶
- GRANT_OPTION = 1¶
- NONE = 0¶
- class firebird.lib.schema.PageType(value)[source]¶
Bases:
IntEnumPage 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:
IntEnumMap to type codes.
- ROLE = 1¶
- USER = 0¶
- class firebird.lib.schema.TriggerType(value)[source]¶
Bases:
IntEnumTrigger type codes.
- DB = 8192¶
- DDL = 16384¶
- DML = 0¶
- class firebird.lib.schema.DDLTrigger(value)[source]¶
Bases:
IntEnumDDL 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:
IntEnumDatabase trigger type codes.
- CONNECT = 0¶
- DISCONNECT = 1¶
- TRANSACTION_COMMIT = 3¶
- TRANSACTION_ROLLBACK = 4¶
- TRANSACTION_START = 2¶
- class firebird.lib.schema.TriggerTime(value)[source]¶
Bases:
IntEnumTrigger action time codes.
- AFTER = 1¶
- BEFORE = 0¶
- class firebird.lib.schema.ConstraintType(value)[source]¶
Bases:
EnumContraint 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:
EnumDDL 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:
EnumSchema 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:
IntEnumPrivacy flag codes.
- PRIVATE = 1¶
- PUBLIC = 0¶
Flags¶
- class firebird.lib.schema.ShadowFlag(value)[source]¶
Bases:
IntFlagShadow 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:
IntFlagDML 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:
IntFlagCollation 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¶
Classes¶
- class firebird.lib.schema.Visitable[source]¶
Bases:
objectBase 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 providedvisitorobject, passing thisSchemaIteminstance (self) as the argument.
- class firebird.lib.schema.Visitor[source]¶
Bases:
objectBase class for Visitor Pattern visitors.
Descendants may implement methods to handle individual object types that follow naming pattern
visit_[class_name]. Callsdefault_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
- class firebird.lib.schema.Schema[source]¶
Bases:
VisitableProvides 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 theRDB$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
SchemaItemsubclasses (e.g.,Table,Procedure,Domain), offering properties to access details and methods likeget_sql_for()to generate DDL.Caching: Fetched metadata is cached internally. Use
clear()orreload()to refresh the cache.Binding & Lifecycle: An instance must be bound to a live
Connectionusing thebind()method (this is done automatically when accessed viaConnection.schema). It should be closed usingclose()(or via awithstatement) 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. Callingbind()on an already bound or embedded schema may raise anError.- Parameters:
connection (Connection) – The
Connectioninstance to bind to.- Returns:
The bound
Schemainstance (self).- Raises:
Error – If called on an embedded schema instance.
- Return type:
- 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
CharacterSetobject by its ID.- Parameters:
charset_id (int) – The numeric ID of the character set (
RDB$CHARACTER_SET_ID).- Returns:
The matching
CharacterSetinstance, orNoneif not found or not loaded.- Return type:
- get_collation_by_id(charset_id: int, collation_id: int) Collation[source]¶
Retrieves a
Collationobject by its character set ID and collation ID.
- 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
ObjectTypeenum value specifying the type of object to retrieve.subname (str | None) – An optional secondary name, typically used for columns (
itype=ObjectType.COLUMN) wherenameis the table/view name andsubnameis the column name.
- Returns:
An instance of a
SchemaItemsubclass (e.g.,Table,Procedure), aUserInfoinstance (foritype=ObjectType.USER), orNoneif the object is not found.- Return type:
- 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
Sectionenum members specifying which types of database objects to include in the DDL script and the order in which their creation statements should appear. Defaults toSCRIPT_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
sectionslist.Error – If required metadata for a requested section has not been loaded yet (e.g., accessing
schema.tablesmight be needed first).
- Return type:
- 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:
user (str | UserInfo | Table | View | Procedure | Trigger | Role) – The grantee, specified either as a string name, a
UserInfoinstance, or aSchemaItemsubclass instance (e.g.,Role,Procedure).user_type (ObjectType | None) – The
ObjectTypeof the grantee. Required ifuseris provided as a string name. Ignored otherwise.
- Returns:
A
DataListcontainingPrivilegeobjects granted to the specified user/object. Returns an empty list if no privileges are found or privileges haven’t been loaded.- Raises:
ValueError – If
useris a string name anduser_typeis not provided.- Return type:
- is_keyword(ident: str) bool[source]¶
Checks if the given identifier is a reserved keyword for the database’s ODS version.
- is_multifile() bool[source]¶
Checks if the database consists of multiple physical files (has secondary files).
- reload(data: Category | list[Category] | None = None) None[source]¶
Clears cached metadata for specified categories and commits the internal transaction.
If
datais None, clears all cached metadata collections. Otherwise, clears only the collections specified in thedataiterable (e.g.,[Category.TABLES, Category.VIEWS]). This forces the specified metadata to be reloaded from the database on next access.
- property all_domains: DataList[Domain]¶
DataListof all (user + system)Domainobjects in the database. Loads lazily.
- property all_functions: DataList[Function]¶
DataListof all (user + system)Functionobjects in the database. Loads lazily.
- property all_generators: DataList[Sequence]¶
DataListof all (user + system)Sequenceobjects (generators) in the database. Loads lazily.
- property all_indices: DataList[Index]¶
DataListof all (user + system)Indexobjects in the database. Loads lazily.
- property all_procedures: DataList[Procedure]¶
DataListof all (user + system)Procedureobjects in the database. Loads lazily.
- property all_tables: DataList[Table]¶
DataListof all (user + system)Tableobjects in the database. Loads lazily.
- property all_triggers: DataList[Trigger]¶
DataListof all (user + system)Triggerobjects in the database. Loads lazily.
- property all_views: DataList[View]¶
DataListof all (user + system)Viewobjects in the database. Loads lazily.
- property backup_history: DataList[BackupHistory]¶
DataListof allBackupHistoryobjects 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]¶
DataListof allCharacterSetobjects defined in the database. Loads lazily.
- property collations: DataList[Collation]¶
DataListof allCollationobjects defined in the database. Loads lazily.
- property constraints: DataList[Constraint]¶
DataListof allConstraintobjects in the database. Loads lazily.
- property default_character_set: CharacterSet¶
Default
CharacterSetfor database.
- property dependencies: DataList[Dependency]¶
DataListof allDependencyobjects in the database. Loads lazily.
- deterministic_flags: ClassVar[dict[int, str]] = {}¶
Mapping from determinism flag codes (RDB$DETERMINISTIC_FLAG) to names.
- property domains: DataList[Domain]¶
DataListof all user-definedDomainobjects in the database. Loads lazily.
- property exceptions: DataList[DatabaseException]¶
DataListof allDatabaseExceptionobjects 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]¶
DataListof allDatabaseFileobjects in the database. Loads lazily.
- property filters: DataList[Filter]¶
DataListof all user-defiendFilterobjects 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]¶
DataListof all user-definedFunctionobjects in the database. Loads lazily.
- property generators: DataList[Sequence]¶
DataListof all user-definedSequenceobjects (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]¶
DataListof all user-definedIndexobjects in the database. Loads lazily.
- legacy_flags: ClassVar[dict[int, str]] = {}¶
Mapping from legacy flag codes (RDB$LEGACY_FLAG) to names.
- mechanism_types: ClassVar[dict[str, str]] = {}¶
Mapping from mechanism codes (RDB$MECHANISM) to names.
- object_types: ClassVar[dict[int, str]] = {}¶
Mapping from object type codes (RDB$OBJECT_TYPE) to descriptive strings.
- 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 packages: DataList[Package]¶
DataListof allPackageobjects in the database. Loads lazily.
- 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]¶
DataListof allPrivilegeobjects 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]¶
DataListof all user-definedProcedureobjects in the database. Loads lazily.
- relation_types: ClassVar[dict[int, str]] = {}¶
Mapping from relation type codes (RDB$RELATION_TYPE) to names.
- property security_class: str¶
Can refer to the security class applied as databasewide access control limits.
- property sys_domains: DataList[Domain]¶
DataListof all systemDomainobjects in the database. Loads lazily.
- property sys_functions: DataList[Function]¶
DataListof all systemFunctionobjects in the database. Loads lazily.
- property sys_generators: DataList[Sequence]¶
DataListof all systemSequenceobjects (generators) in the database. Loads lazily.
- property sys_indices: DataList[Index]¶
DataListof all systemIndexobjects in the database. Loads lazily.
- property sys_procedures: DataList[Procedure]¶
DataListof all systemProcedureobjects in the database. Loads lazily.
- property sys_tables: DataList[Table]¶
DataListof all systemTableobjects in the database. Loads lazily.
- property sys_triggers: DataList[Trigger]¶
DataListof all systemTriggerobjects in the database. Loads lazily.
- property sys_views: DataList[View]¶
DataListof all systemViewobjects 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]¶
DataListof all user-definedTableobjects 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.
- class firebird.lib.schema.SchemaItem(schema: Schema, attributes: dict[str, Any])[source]¶
Bases:
VisitableAbstract 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
Schemainstance (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 parentSchemaobject.- Parameters:
- _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
paramsdictionary are present in theparam_nameslist of allowed parameters for a specific SQL action.- Parameters:
- Raises:
ValueError – If
paramscontains any key not found inparam_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:
- _get_create_sql(**params) str[source]¶
Abstract method for generating ‘CREATE’ SQL. Subclasses must implement.
- Return type:
- _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’).
- _get_quoted_ident(ident: str) str[source]¶
Internal helper: Returns the identifier, quoted if necessary.
- _get_recreate_sql(**params) str[source]¶
Generates ‘RECREATE’ SQL by prefixing the ‘CREATE’ SQL. Subclasses can override if ‘RECREATE’ differs more significantly.
- Return type:
- _needs_quoting(ident: str) bool[source]¶
Internal helper: Determines if an identifier requires double quotes in SQL.
Checks based on
Schema.opt_always_quotesetting, reserved words (Schema.is_keyword), starting characters, and allowed characters (A-Z, 0-9, _, $).
- _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.dependenciesbased on this object’snameand_type_code.- Returns:
A
DataListcontainingDependencyobjects where this item is thedependentobject. Returns an empty list if this object has no dependencies or dependencies haven’t been loaded in the parent schema.- Return type:
- get_dependents() DataList[Dependency][source]¶
Returns list of all database objects that depend on this one.
- Return type:
- get_quoted_name() str[source]¶
Retrieves a list of database objects that depend on this object.
Queries
Schema.dependenciesbased on this object’snameand_type_code.- Returns:
A
DataListcontainingDependencyobjects where this item is thedepended_onobject. Returns an empty list if no dependents are found or dependencies haven’t been loaded in the parent schema.- Return type:
- 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
actionslist.**params (dict) – Keyword arguments specific to the requested
action. These are validated and passed directly to the internal_get_<action>_sqlmethod 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
actionis not supported for this object type, or if invalid/missingparamsare provided for the action.NotImplementedError – If the action is listed but the corresponding
_get_<action>_sqlmethod is not implemented.
- Return type:
- is_sys_object() bool[source]¶
Checks if this schema object is a system-defined object.
Typically determined by checking the
RDB$SYSTEM_FLAGattribute (> 0). Subclasses may provide more specific logic (e.g., based on name prefixes like ‘RDB$’).
- 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, orNoneif it has no description.
- class firebird.lib.schema.Collation(schema: Schema, attributes: dict[str, Any])[source]¶
Bases:
SchemaItemRepresents 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$COLLATIONSsystem table. They are typically accessed viaSchema.collationsorCharacterSet.collations.Supported SQL actions via
get_sql_for():User-defined collations:
create,drop,comment.System collations:
comment.
- Parameters:
- _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 COLLATIONSQL string. Sets comment toNULLifself.descriptionis None, otherwise uses the description text with proper escaping.- Return type:
- _get_create_sql(**params) str[source]¶
Generates the SQL command to CREATE this collation.
Constructs the
CREATE COLLATIONstatement including character set, base collation (internal or external), padding, case/accent sensitivity, and specific attributes.- Parameters:
**params – Accepts no parameters.
- Returns:
The
CREATE COLLATIONSQL string.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _get_drop_sql(**params) str[source]¶
Generates the SQL command to DROP this collation.
- Parameters:
**params – Accepts no parameters.
- Returns:
The
DROP COLLATIONSQL string.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- 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_NAMEexists but does not correspond to another collation defined within the database schema.
- property attributes: CollationFlag¶
A
CollationFlagenum value representing the combined attributes (pad space, case/accent sensitivity) defined byRDB$COLLATION_ATTRIBUTES.
- property base_collation: Collation | None¶
The base
Collationobject this collation derives from, if any.Returns
Noneif this collation is a primary collation for its character set or if it’s based on an external definition (checkis_based_on_external()).
- property character_set: CharacterSet¶
The
CharacterSetobject this collation belongs to.
- property id: int¶
The unique numeric ID (
RDB$COLLATION_ID) assigned to this collation within its character set.
- class firebird.lib.schema.CharacterSet(schema: Schema, attributes: dict[str, Any])[source]¶
Bases:
SchemaItemRepresents 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_SETSsystem table. They are typically accessed viaSchema.character_sets.Supported SQL actions via
get_sql_for():alter(keyword argumentcollation:Collationinstance or collation name): Sets the default collation for this character set.comment: Adds or removes a descriptive comment for the character set.
- Parameters:
- _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): TheCollationobject or the string name of the collation to set as the default for this character set. Required.
- Returns:
The
ALTER CHARACTER SETSQL string.- Raises:
ValueError – If the required
collationparameter is missing or if unexpected parameters are passed.- Return type:
- _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 SETSQL string. Sets comment toNULLifself.descriptionis None, otherwise uses the description text with proper escaping.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- get_collation_by_id(id_: int) Collation | None[source]¶
Retrieves a specific
Collationbelonging to this character set by its ID.Searches the cached
collationsassociated with this character set.
- 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
DataListof allCollationobjects associated with this character set.
- class firebird.lib.schema.DatabaseException(schema: Schema, attributes: dict[str, Any])[source]¶
Bases:
SchemaItemRepresents 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$EXCEPTIONSsystem table. They are typically accessed viaSchema.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 argumentmessage: 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:
- _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 EXCEPTIONSQL string with the new message text, properly escaped.- Raises:
ValueError – If the required
messageparameter is missing, is not a string, or if unexpected parameters are passed.- Return type:
- _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 EXCEPTIONSQL string. Sets comment toNULLifself.descriptionis None, otherwise uses the description text with proper escaping.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _get_create_sql(**params) str[source]¶
Generates the SQL command to CREATE this exception.
- Parameters:
**params – Accepts no parameters.
- Returns:
The
CREATE EXCEPTIONSQL string, including the message text with single quotes properly escaped.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _get_drop_sql(**params) str[source]¶
Generates the SQL command to DROP this exception.
- Parameters:
**params – Accepts no parameters.
- Returns:
The
DROP EXCEPTIONSQL string.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- class firebird.lib.schema.Sequence(schema: Schema, attributes: dict[str, Any])[source]¶
Bases:
SchemaItemRepresents 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$GENERATORSsystem table. They are typically accessed viaSchema.generators,Schema.sys_generators, orSchema.all_generators. The current value is retrieved dynamically using theGEN_ID()function.The SQL keyword used (
SEQUENCEorGENERATOR) in generated DDL depends on theSchema.opt_generator_keywordsetting.Supported SQL actions via
get_sql_for():User-defined sequences:
create(optional keyword args:value: int,increment: int): Creates the sequence, optionally settingSTART WITHandINCREMENT BY.alter(optional keyword args:value: int,increment: int): Alters the sequence, optionally settingRESTART WITHand/orINCREMENT 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:
- _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:
- Returns:
The
ALTER SEQUENCEorALTER GENERATORSQL string.- Raises:
ValueError – If neither
valuenorincrementis provided, or if unexpected parameters are passed.- Return type:
- _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 SEQUENCEorCOMMENT ON GENERATORSQL string. Sets comment toNULLifself.descriptionis None, otherwise uses the description text with proper escaping.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _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:
- Returns:
The
CREATE SEQUENCEorCREATE GENERATORSQL string.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _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 SEQUENCEorDROP GENERATORSQL string.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- is_identity() bool[source]¶
Checks if this sequence is system-generated for an IDENTITY column.
Determined by checking if
RDB$SYSTEM_FLAGhas the specific value 6.
- property increment: int¶
The increment step (
INCREMENT BY) defined for the sequence (RDB$GENERATOR_INCREMENT). ReturnsNoneif 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
Noneeven if an increment was conceptually set.
- property inital_value: int | None¶
The initial value (
START WITH) defined for the sequence (RDB$INITIAL_VALUE). ReturnsNoneif 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
Noneeven if a start value was conceptually set.
- property security_class: str | None¶
The security class name associated with this sequence, if any (
RDB$SECURITY_CLASS). ReturnsNoneif 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$DATABASEagainst 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:
SchemaItemRepresents 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_FIELDSsystem table, linking toRDB$FIELDSviaRDB$FIELD_SOURCEfor domain/type information. They are typically accessed via theTable.columnsproperty.Supported SQL actions via
get_sql_for():User table columns:
drop: GeneratesALTER TABLE ... DROP COLUMN ....comment: GeneratesCOMMENT 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 theCOMPUTED BYexpression. Requires the column to already be computed.restart(int | None): Restarts the sequence associated with an IDENTITY column. Provide an integer forRESTART WITH value, orNoneforRESTART(uses sequence’s next value). Only applicable to identity columns.
System table columns:
comment: Adds or removes a descriptive comment.
- Parameters:
- _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 ifexpressionis also provided.expression(str): The newCOMPUTED BY (...)expression. Cannot be used ifdatatypeis also provided. Only applicable to computed columns.restart(int | None): Restarts the identity sequence. Provide an integer value forWITHorNoneto 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:
- _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 toNULLifself.descriptionis None, otherwise uses the description text with proper escaping.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _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:
- get_computedby() str | None[source]¶
Returns the
COMPUTED BY (...)expression string if this is a computed column.
- 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.dependencieswhere this column’s table and name are thedependentreference.- Returns:
A
DataListcontainingDependencyobjects where this column is part of thedependentreference.- Return type:
- get_dependents() DataList[Dependency][source]¶
Retrieves a list of database objects that depend on this specific column.
Searches
Schema.dependenciesmatching the table name (RDB$RELATION_NAME), object type (0 for table), and this column’s name (RDB$FIELD_NAME).- Returns:
A
DataListcontainingDependencyobjects where this column is part of thedepended_onreference.- Return type:
- has_default() bool[source]¶
Checks if the column has a
DEFAULTvalue defined.Based on the presence of
RDB$DEFAULT_SOURCE. Note thatis_identity()should be checked first, as identity columns may technically have a default source internally but are conceptually different.
- is_identity() bool[source]¶
Checks if this column is an IDENTITY column (
GENERATED ... AS IDENTITY).Determined by checking if
RDB$IDENTITY_TYPEis not NULL.
- is_nullable() bool[source]¶
Checks if the column allows
NULLvalues.Based on the
RDB$NULL_FLAGattribute (0 = nullable, 1 = not nullable).
- is_writable() bool[source]¶
Checks if the column can be directly written to (e.g., not computed).
Based on the
RDB$UPDATE_FLAGattribute (1 = writable, 0 = not writable).
- property collation: Collation | None¶
The specific
Collationobject applied to this column (RDB$COLLATION_ID), if applicable (for character types).Returns
Noneif 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
DEFAULTvalue expression string defined for the column (RDB$DEFAULT_SOURCE).Returns the expression string (e.g., ‘CURRENT_TIMESTAMP’, “‘ACTIVE’”, ‘0’) or
Noneif no default is defined. The leading ‘DEFAULT ‘ keyword is removed.
- property domain: Domain¶
The underlying
Domainobject 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).
- property identity_type: int | None¶
The type of IDENTITY generation (
ALWAYSorBY DEFAULT) specified for the column.- Returns:
An
IdentityTypeenum member if this is an identity column (RDB$IDENTITY_TYPEis not NULL), otherwiseNone.
- 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
DataListof specific privileges (SELECT,UPDATE,REFERENCES) granted directly on this column.
- class firebird.lib.schema.Index(schema: Schema, attributes: dict[str, Any])[source]¶
Bases:
SchemaItemRepresents 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$INDICESandRDB$INDEX_SEGMENTSsystem tables. They are typically accessed viaSchema.indices,Schema.sys_indices,Schema.all_indices, orTable.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:
- _get_activate_sql(**params) str[source]¶
Generates the SQL command to ACTIVATE this index.
- Parameters:
**params – Accepts no parameters.
- Returns:
The
ALTER INDEX ... ACTIVESQL string.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _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 toNULLifself.descriptionis None, otherwise uses the description text with proper escaping.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _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 INDEXSQL string.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _get_deactivate_sql(**params) str[source]¶
Generates the SQL command to DEACTIVATE this index.
- Parameters:
**params – Accepts no parameters.
- Returns:
The
ALTER INDEX ... INACTIVESQL 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:
- _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:
- _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:
- 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.
- is_expression() bool[source]¶
Checks if this is an expression-based index (
COMPUTED BY).Determined by checking if
RDB$EXPRESSION_SOURCEis not NULL.
- is_inactive() bool[source]¶
Checks if the index is currently inactive (
INACTIVE).Based on the
RDB$INDEX_INACTIVEattribute (1 = inactive, 0 = active).
- is_sys_object() bool[source]¶
Checks if this index is a system-defined object.
Considers both the
RDB$SYSTEM_FLAGand whether the index enforces a constraint and has a system-generated name (like ‘RDB$…’).
- is_unique() bool[source]¶
Checks if the index enforces uniqueness (
UNIQUE).Based on the
RDB$UNIQUE_FLAGattribute (1 = unique, 0 = non-unique).
- property condition: str | None¶
The partial index condition string (
RDB$CONDITION_SOURCE), if defined.Returns the condition string (typically enclosed in parentheses), or
Noneif 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
Constraintobject (PK, UK, FK) that this index enforces, if any.Returns
Noneif 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
Noneif this is a segment-based index.
- property index_type: IndexType¶
The index ordering type (
IndexType.ASCENDINGorIndexType.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
Indexit references (RDB$FOREIGN_KEYcontains the partner index name).
- 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
DataListof theTableColumnobjects corresponding to the index segments.Returns an empty list for expression-based indexes. Uses
segment_namesto look up columns in the associatedTable.
- class firebird.lib.schema.ViewColumn(schema: Schema, view: View, attributes: dict[str, Any])[source]¶
Bases:
SchemaItemRepresents 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_FIELDSwhere the relation type is VIEW. Information about the source column/expression is often limited compared to table columns. They are accessed via theView.columnsproperty.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:
- _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 toNULLifself.descriptionis None, otherwise uses the description text with proper escaping.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- get_dependencies() DataList[Dependency][source]¶
Retrieves a list of database objects that this view column depends on.
Searches
Schema.dependencieswhere this view column’s view name and column name are thedependentreference (dependent type is 1 for VIEW).- Returns:
A
DataListcontainingDependencyobjects where this view column is part of thedependentreference.- Return type:
- get_dependents() DataList[Dependency][source]¶
Retrieves a list of database objects that depend on this specific view column.
Searches
Schema.dependenciesmatching the view name (RDB$RELATION_NAME), object type (1 for view), and this column’s name (RDB$FIELD_NAME).- Returns:
A
DataListcontainingDependencyobjects where this view column is part of thedepended_onreference.- Return type:
- is_nullable() bool[source]¶
Checks if the view column allows
NULLvalues.Based on the
RDB$NULL_FLAGattribute derived from the underlying source or view definition.
- 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.
- 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) andBASE_RELATION(source object name). It attempts to find the source in tables, views, or procedures.- Returns:
A
TableColumn,ViewColumn, orProcedureParameterinstance representing the ultimate source, orNoneif 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
Collationobject applied to this view column (RDB$COLLATION_ID), if applicable (for character types) and different from the domain default.Returns
Noneif 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
Domainobject 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
DataListof 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.
- class firebird.lib.schema.Domain(schema: Schema, attributes: dict[str, Any])[source]¶
Bases:
SchemaItemRepresents 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 NULLconstraintDEFAULTvalueCHECKconstraint (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$FIELDSsystem table. They are accessed viaSchema.domains,Schema.sys_domains, orSchema.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, orNone/empty string toDROP DEFAULT.check(str | None): Adds or drops the check constraint. Provide theCHECK (...)expression string (without theCHECKkeyword itself), orNone/empty string toDROP CONSTRAINT.datatype(str): Changes the base data type (ALTER DOMAIN ... TYPE ...).
System domains:
comment: Adds or removes a descriptive comment.
- Parameters:
- _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, orNone/”” to drop the default.check(str | None): The new check constraint expression (inside the parentheses), orNone/”” to drop the check constraint.datatype(str): The new base SQL data type definition.
- Returns:
The
ALTER DOMAINSQL string.- Raises:
ValueError – If multiple alteration types are specified, if required parameters are missing, or if unexpected parameters are passed.
- Return type:
- _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 DOMAINSQL string. Sets comment toNULLifself.descriptionis None, otherwise uses the description text with proper escaping.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _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 DOMAINSQL string.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _get_drop_sql(**params) str[source]¶
Generates the SQL command to DROP this domain.
- Parameters:
**params – Accepts no parameters.
- Returns:
The
DROP DOMAINSQL string.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- has_default() bool[source]¶
Checks if the domain has a
DEFAULTvalue defined.Based on the presence of
RDB$DEFAULT_SOURCE.
- is_array() bool[source]¶
Checks if the domain defines an array data type.
Based on the presence of
RDB$DIMENSIONS.
- is_computed() bool[source]¶
Checks if this domain represents a
COMPUTED BYdefinition.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.
- is_nullable() bool[source]¶
Checks if the domain allows
NULLvalues (i.e., not defined withNOT NULL).Based on the
RDB$NULL_FLAGattribute (0 = nullable, 1 = not nullable).
- is_sys_object() bool[source]¶
Checks if this domain is a system-defined object.
Considers both the
RDB$SYSTEM_FLAGand whether the name starts with ‘RDB$’.
- is_validated() bool[source]¶
Checks if the domain has a
CHECKconstraint defined.Based on the presence of
RDB$VALIDATION_SOURCE.
- property character_length: int¶
Length of character types (
CHAR,VARCHAR) in characters, not bytes (RDB$CHARACTER_LENGTH). ReturnsNonefor non-character types.
- property character_set: CharacterSet | None¶
The
CharacterSetobject associated with the domain (RDB$CHARACTER_SET_ID), if applicable (for character/text types). ReturnsNoneotherwise.
- property collation: Collation | None¶
The specific
Collationobject defined for the domain (RDB$COLLATION_ID), if applicable (for character/text types).Returns
Noneif 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
DEFAULTvalue expression string (RDB$DEFAULT_SOURCE).Returns the expression string (e.g., ‘CURRENT_TIMESTAMP’, “‘ACTIVE’”, ‘0’) or
Noneif 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). ReturnsNoneif the domain is not an array type (RDB$DIMENSIONSis NULL). Fetched lazily by queryingRDB$FIELD_DIMENSIONS.
- property expression: str | None¶
The
COMPUTED BY (...)expression string, if applicable (RDB$COMPUTED_SOURCE). TypicallyNonefor user-defined domains.
- property external_length: int¶
Length of the field if mapped from an external table (
RDB$EXTERNAL_LENGTH). Typically 0 orNonefor regular domains.
- property external_scale: int | None¶
Scale of the field if mapped from an external table (
RDB$EXTERNAL_SCALE). Typically 0 orNone.
- property external_type: FieldType | None¶
Data type code (
FieldType) of the field if mapped from an external table (RDB$EXTERNAL_TYPE). ReturnsNoneotherwise.
- 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 likeCHAR,VARCHAR,BLOB. May beNone.
- property precision: int | None¶
The precision (total number of digits) for exact numeric types (
NUMERIC,DECIMAL) or approximate types (FLOAT,DOUBLE) (RDB$FIELD_PRECISION). ReturnsNoneif not applicable.
- property scale: int¶
The scale (number of digits to the right of the decimal point) for
NUMERICorDECIMALtypes (RDB$FIELD_SCALE). Stored as a negative number. ReturnsNonefor non-exact numeric types.
- property security_class: str | None¶
The security class name associated with this domain, if any (
RDB$SECURITY_CLASS). ReturnsNoneif no specific security class is assigned.
- property segment_length: int | None¶
Suggested segment size for
BLOBtypes (RDB$SEGMENT_LENGTH). ReturnsNonefor non-BLOB types.
- property sub_type: int | None¶
The field sub-type code (
RDB$FIELD_SUB_TYPE).Commonly used for
BLOBsubtypes (0=binary, 1=text) orNUMERIC/DECIMALindication (1=numeric, 2=decimal) for exact numeric types. Returns the raw integer if not a standardFieldSubTypeenum member, orNone.
- class firebird.lib.schema.Dependency(schema: Schema, attributes: dict[str, Any])[source]¶
Bases:
SchemaItemRepresents a dependency relationship between two database schema objects.
This class maps a single row from the
RDB$DEPENDENCIESsystem 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.dependenciesor by callingget_dependents()orget_dependencies()on otherSchemaItemobjects.This class itself does not support any direct SQL actions via
get_sql_for().- Parameters:
- _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
Noneas 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:
- get_dependents() DataList[source]¶
Dependencies do not have further dependents.
- Returns:
An empty
DataList.- Return type:
- 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 thedependentobject is inside the package.
- is_sys_object() bool[source]¶
Indicates that dependency entries themselves are considered system metadata.
- 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 potentiallyRDB$FIELD_NAME. Iffield_nameis set, this property attempts to return the specific column object; otherwise, it returns the container object (table, view, procedure, etc.).- Returns:
The
SchemaItemsubclass instance (e.g.,Table,Procedure,Domain) or aTableColumn/ViewColumninstance representing the object being depended upon, orNoneif it cannot be resolved or the type is unhandled.
- 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_NAMEandRDB$DEPENDENT_TYPE.- Returns:
The
SchemaItemsubclass instance (e.g.,View,Procedure,Trigger) representing the dependent object, orNoneif the object cannot be found or the type is currently unhandled.
- 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
Noneif the dependency is on the object as a whole.
- class firebird.lib.schema.Constraint(schema: Schema, attributes: dict[str, Any])[source]¶
Bases:
SchemaItemRepresents 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 withRDB$REF_CONSTRAINTS(for FK) andRDB$CHECK_CONSTRAINTS(for CHECK). They are typically accessed viaSchema.constraintsorTable.constraints.Supported SQL actions via
get_sql_for():User-defined constraints (excluding NOT NULL):
create: Generates theALTER TABLE ... ADD CONSTRAINT ...statement. Handles PK, UNIQUE, FK (including rules), and CHECK constraints.drop: Generates theALTER 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
createordropactions here. They are managed viaALTER DOMAINorALTER TABLE ... ALTER COLUMN.- Parameters:
- _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:
- _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:
- is_check() bool[source]¶
Checks if this is a
CHECKconstraint.- Returns:
Trueifconstraint_typeisConstraintType.CHECK,Falseotherwise.- Return type:
- is_deferrable() bool[source]¶
Checks if the constraint is defined as
DEFERRABLE.Based on
RDB$DEFERRABLE(‘YES’ or ‘NO’).
- is_deferred() bool[source]¶
Checks if the constraint is defined as
INITIALLY DEFERRED.Based on
RDB$INITIALLY_DEFERRED(‘YES’ or ‘NO’). Relevant only ifis_deferrable()is True.
- is_fkey() bool[source]¶
Checks if this is a
FOREIGN KEYconstraint.- Returns:
Trueifconstraint_typeisConstraintType.FOREIGN_KEY,Falseotherwise.- Return type:
- is_not_null() bool[source]¶
Checks if this is a
NOT NULLconstraint.- Returns:
Trueifconstraint_typeisConstraintType.NOT_NULL,Falseotherwise.- Return type:
- is_pkey() bool[source]¶
Checks if this is a
PRIMARY KEYconstraint.- Returns:
Trueifconstraint_typeisConstraintType.PRIMARY_KEY,Falseotherwise.- Return type:
- is_unique() bool[source]¶
Checks if this is a
UNIQUEconstraint.- Returns:
Trueifconstraint_typeisConstraintType.UNIQUE,Falseotherwise.- Return type:
- property column_name: str | None¶
The name of the column it applies to.
Returns
Nonefor other constraint types.- Type:
For a
NOT NULLconstraint
- property constraint_type: ConstraintType¶
The type of the constraint (
ConstraintTypeenum).Derived from
RDB$CONSTRAINT_TYPE(‘PRIMARY KEY’, ‘UNIQUE’, etc.). ReturnsNoneif 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’). ReturnsNonefor other constraint types.- Type:
For a
FOREIGN KEYconstraint
- property index: Index | None¶
The
Indexobject used to enforce the constraint (RDB$INDEX_NAME).Relevant for PRIMARY KEY, UNIQUE, and FOREIGN KEY constraints. Returns
Nonefor 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). ReturnsNonefor other constraint types.- Type:
For a
FOREIGN KEYconstraint
- property partner_constraint: Constraint | None¶
The referenced
PRIMARY KEYorUNIQUEConstraintobject (RDB$CONST_NAME_UQ).Returns
Nonefor other constraint types or if the partner constraint cannot be found.- Type:
For a
FOREIGN KEYconstraint
- property trigger_names: list[str]¶
A list of trigger names that enforce it. For a
NOT NULLconstraint: The name of the single column it applies to. ReturnsNonefor other constraint types.- Type:
For a
CHECKconstraint
- class firebird.lib.schema.Table(schema: Schema, attributes: dict[str, Any])[source]¶
Bases:
SchemaItemRepresents 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$RELATIONSsystem table whereRDB$VIEW_BLRis 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, orSchema.all_tables.Supported SQL actions via
get_sql_for():User-defined tables:
create(optional keyword args:no_pk: bool=False,no_unique: bool=False): GeneratesCREATE [GLOBAL TEMPORARY] TABLE ...statement. Includes column definitions. Optionally includes inline PRIMARY KEY and UNIQUE constraints unless excluded byno_pk=Trueorno_unique=Truerespectively. CHECK and FOREIGN KEY constraints are not included inline by this method.recreate(optional keyword args:no_pk: bool=False,no_unique: bool=False): GeneratesRECREATE [GLOBAL TEMPORARY] TABLE ...(similar tocreate).drop: GeneratesDROP TABLE ....comment: GeneratesCOMMENT ON TABLE ... IS ....insert(optional keyword args:update: bool=False,returning: list[str]=None,matching: list[str]=None): Generates anINSERTorUPDATE OR INSERTstatement template with placeholders for all columns. Optionally addsMATCHINGandRETURNINGclauses.
System tables:
comment: Adds or removes a descriptive comment.
- Parameters:
- _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 toNULLifself.descriptionis None, otherwise uses the description text with proper escaping.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _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:
- Returns:
The
CREATE [GLOBAL TEMPORARY] TABLESQL string.- Raises:
ValueError – If unexpected parameters are passed.
Error – If essential information (like columns) cannot be loaded.
- Return type:
- _get_drop_sql(**params) str[source]¶
Generates the SQL command to DROP this table.
- Parameters:
**params – Accepts no parameters.
- Returns:
The
DROP TABLESQL string.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _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): IfTrue, generatesUPDATE OR INSERTinstead ofINSERT. Defaults toFalse.returning(list[str]): A list of column names or expressions to include in theRETURNINGclause. Defaults toNone.matching(list[str]): A list of column names to include in theMATCHING (...)clause (used withUPDATE OR INSERT). Defaults toNone.
- Returns:
The generated
INSERTorUPDATE OR INSERTSQL statement string.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- has_fkey() bool[source]¶
Checks if the table has at least one
FOREIGN KEYconstraint defined.Iterates through the table’s constraints.
- has_pkey() bool[source]¶
Checks if the table has a
PRIMARY KEYconstraint defined.Iterates through the table’s constraints.
- is_external() bool[source]¶
Checks if this table is an External Table.
Based on the presence of the
RDB$EXTERNAL_FILEattribute.
- is_gtt() bool[source]¶
Checks if this table is a Global Temporary Table (GTT).
- Returns:
Trueiftable_typeisRelationType.GLOBAL_TEMPORARY_DELETEorRelationType.GLOBAL_TEMPORARY_PRESERVE,Falseotherwise.- Return type:
- is_persistent() bool[source]¶
Checks if this table is a standard persistent table or an external table.
Excludes views and GTTs.
- Returns:
Trueiftable_typeisRelationType.PERSISTENTorRelationType.EXTERNAL,Falseotherwise.- Return type:
- property columns: DataList[TableColumn]¶
A lazily-loaded
DataListof allTableColumnobjects defined for this table.Columns are ordered by their position (
RDB$FIELD_POSITION). Fetched fromRDB$RELATION_FIELDS.
- property constraints: DataList[Constraint]¶
A
DataListof allConstraintobjects (PK, FK, UK, CHECK) defined for this table.Filters the main
Schema.constraintscollection.
- property dbkey_length: int¶
Length of the internal
RDB$DB_KEYpseudo-column in bytes (RDB$DBKEY_LENGTH).
- property external_file: str | None¶
The full path and filename of the external data file (
RDB$EXTERNAL_FILE). ReturnsNoneif this is not an external table.
- property foreign_keys: DataList[Constraint]¶
A
DataListof allFOREIGN KEYConstraintobjects defined for this table.
- property format: int¶
The internal format version number (
RDB$FORMAT) for the table’s record structure.
- property indices: DataList[Index]¶
A
DataListof allIndexobjects defined for this table.Filters the main
Schema.all_indicescollection.
- property primary_key: Constraint | None¶
The
PRIMARY KEYConstraintobject defined for this table.- Returns:
The
Constraintobject representing the primary key, orNoneif no primary key is defined on this table. Finds the first constraint marked as PK.
- property privileges: DataList[Privilege]¶
A
DataListof allPrivilegeobjects granted on this table.Filters the main
Schema.privilegescollection. Includes privileges granted on the table as a whole, not column-specific privileges (seeTableColumn.privileges).
- property security_class: str | None¶
The security class name associated with this table, if any (
RDB$SECURITY_CLASS). Used for access control limits. ReturnsNoneif not set.
- property table_type: RelationType¶
The type of the relation (
RelationTypeenum).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
DataListof allTriggerobjects defined for this table.Filters the main
Schema.triggerscollection (which contains user triggers). UseSchema.all_triggersif system triggers are needed.
- class firebird.lib.schema.View(schema: Schema, attributes: dict[str, Any])[source]¶
Bases:
SchemaItemRepresents 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$RELATIONSsystem table whereRDB$VIEW_BLRis NOT NULL. Associated columns are fetched fromRDB$RELATION_FIELDS.Access typically occurs via
Schema.views,Schema.sys_views, orSchema.all_views.Supported SQL actions via
get_sql_for():User-defined views:
create: GeneratesCREATE VIEW view_name (col1, ...) AS SELECT ....Includes the column list and the view’s query (
AS SELECT ...).
recreate: GeneratesRECREATE VIEW ...(similar structure tocreate).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 newSELECT ...statement defining the view.check(bool, optional): IfTrue, addsWITH CHECK OPTIONto the view definition. Defaults toFalse.
create_or_alter: GeneratesCREATE OR ALTER VIEW ...(combines create/alter logic).drop: GeneratesDROP VIEW ....comment: GeneratesCOMMENT ON VIEW ... IS ....
System views:
comment: Adds or removes a descriptive comment.
- Parameters:
- _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 newSELECT ...statement for the view.check(bool, optional): Set toTrueto addWITH CHECK OPTION. Defaults toFalse.
- Returns:
The
ALTER VIEWSQL string.- Raises:
ValueError – If the required
queryparameter is missing, if parameter types are incorrect, or if unexpected parameters are passed.- Return type:
- _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 toNULLifself.descriptionis None, otherwise uses the description text with proper escaping.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _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 VIEWSQL string.- Raises:
ValueError – If unexpected parameters are passed.
Error – If view columns cannot be loaded.
- Return type:
- _get_drop_sql(**params) str[source]¶
Generates the SQL command to DROP this view.
- Parameters:
**params – Accepts no parameters.
- Returns:
The
DROP VIEWSQL string.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- 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 (
sqlproperty).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.
- property columns: DataList[ViewColumn]¶
A lazily-loaded
DataListof allViewColumnobjects defined for this view.Columns are ordered by their position (
RDB$FIELD_POSITION). Fetched fromRDB$RELATION_FIELDSpotentially joined withRDB$VIEW_RELATIONS.
- property dbkey_length: int¶
Length of the internal
RDB$DB_KEYpseudo-column in bytes (RDB$DBKEY_LENGTH).
- property default_class: str | None¶
Default security class name (
RDB$DEFAULT_CLASS). Usage may vary.
- property privileges: DataList[Privilege]¶
A
DataListof allPrivilegeobjects granted on this view.Filters the main
Schema.privilegescollection. Includes privileges granted on the view as a whole. Column-specific privileges are accessed viaViewColumn.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). ReturnsNoneif no specific security class is assigned.
- property sql: str | None¶
The
SELECTstatement text that defines the view (RDB$VIEW_SOURCE). ReturnsNoneif the source is not available.
- property triggers: DataList[Trigger]¶
A
DataListof all userTriggerobjects defined for this view.Filters the main
Schema.triggerscollection. UseSchema.all_triggersif system triggers are needed.
- class firebird.lib.schema.Trigger(schema: Schema, attributes: dict[str, Any])[source]¶
Bases:
SchemaItemRepresents 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/DROPof various objects).
Triggers have an activation time (
BEFOREorAFTERthe 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$TRIGGERSsystem table. They are accessed viaSchema.triggers,Schema.sys_triggers,Schema.all_triggers, orTable.triggers/View.triggers.Supported SQL actions via
get_sql_for():User-defined triggers:
create(optional keyword arginactive: bool=False): GeneratesCREATE TRIGGER ...statement with full definition (relation/event, time, position, source code). Can create it initially inactive.recreate: GeneratesRECREATE TRIGGER ....create_or_alter: GeneratesCREATE OR ALTER TRIGGER ....drop: GeneratesDROP TRIGGER ....comment: GeneratesCOMMENT ON TRIGGER ... IS ....alter(keyword args): Modifies the trigger definition. Allows changingfire_on(event string),activestatus,sequenceposition,declaresection (variable declarations), andcode(trigger body). At least one parameter must be provided. Trigger type (DML/DB/DDL) cannot be changed viaALTER.
System triggers:
comment: Adds or removes a descriptive comment.
- Parameters:
- _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:
- _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).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 TRIGGERSQL string.- Raises:
ValueError – If no parameters are provided, if
declareis provided withoutcode, if attempting to change trigger type viafire_on, or if unexpected parameters are passed.- Return type:
- _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 toNULLifself.descriptionis None, otherwise uses the description text with proper escaping.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _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:
- Returns:
The
CREATE TRIGGERSQL string.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _get_drop_sql(**params) str[source]¶
Generates the SQL command to DROP this trigger.
- Parameters:
**params – Accepts no parameters.
- Returns:
The
DROP TRIGGERSQL string.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- 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:
- is_db_trigger() bool[source]¶
Checks if this is a database-level trigger (ON CONNECT, etc.).
- Returns:
Trueiftrigger_typeisTriggerType.DB,Falseotherwise.- Return type:
- is_ddl_trigger() bool[source]¶
Checks if this is a DDL trigger (ON CREATE TABLE, etc.).
- Returns:
Trueiftrigger_typeisTriggerType.DDL,Falseotherwise.- Return type:
- property action: DMLTrigger | DBTrigger | DDLTrigger¶
The specific event that fires the trigger.
- Returns:
For DML triggers: A
DMLTriggerflag combination (e.g.,INSERT|UPDATE).For DB triggers: A
DBTriggerenum member (e.g.,CONNECT).For DDL triggers: A
DDLTriggerenum 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).
- property engine_name: str | None¶
The name of the external engine used, if this is an external trigger (
RDB$ENGINE_NAME). ReturnsNonefor 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). ReturnsNonefor PSQL triggers.
- property relation: Table | View | None¶
The
TableorViewobject this trigger is associated with (RDB$RELATION_NAME).Returns
Nonefor 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). ReturnsNoneif 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. ReturnsNoneif the type code is unrecognized.
- class firebird.lib.schema.ProcedureParameter(schema: Schema, proc: Procedure, attributes: dict[str, Any])[source]¶
Bases:
SchemaItemRepresents 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_PARAMETERSsystem table. They are accessed via theProcedure.input_paramsorProcedure.output_paramsproperties.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:
- _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 toNULLifself.descriptionis None, otherwise uses the description text with proper escaping.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- get_sql_definition() str[source]¶
Generates the SQL string representation of the parameter’s definition.
Used when constructing
CREATE PROCEDUREstatements. 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 PROCEDUREparameter lists.- Return type:
- has_default() bool[source]¶
Checks if the parameter has a
DEFAULTvalue defined.Based on the presence of
RDB$DEFAULT_SOURCE. Only applicable to input parameters.
- is_input() bool[source]¶
Checks if this is an INPUT parameter.
- Returns:
Trueifparameter_typeisParameterType.INPUT,Falseotherwise.- Return type:
- is_nullable() bool[source]¶
Checks if the parameter allows
NULLvalues.Based on
RDB$NULL_FLAG(0 = nullable, 1 = not nullable).
- is_packaged() bool[source]¶
Checks if the parameter belongs to a procedure defined within a package.
Based on the presence of
RDB$PACKAGE_NAME.
- property collation: Collation | None¶
The specific
Collationobject applied to this parameter (RDB$COLLATION_ID), if applicable (for character types) and different from the domain default.Returns
Noneif 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 sourceTableColumnobject.Based on
RDB$RELATION_NAMEandRDB$FIELD_NAME. ReturnsNoneotherwise.
- 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
DEFAULTvalue expression string defined for the parameter (RDB$DEFAULT_SOURCE).Applies only to input parameters. Returns the expression string (e.g., ‘0’, “‘PENDING’”) or
Noneif no default is defined. The leading ‘= ‘ or ‘DEFAULT ‘ keyword is removed.
- property domain: Domain¶
The underlying
Domainobject 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 fromRDB$PARAMETER_MECHANISM.Indicates if passed by value or reference, relevant for type determination. Returns
Noneif the mechanism code is unrecognized or missing.
- property package: Package | None¶
The
Packageobject this parameter’s procedure belongs to, if any.Based on
RDB$PACKAGE_NAME. ReturnsNoneif 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).
- class firebird.lib.schema.Procedure(schema: Schema, attributes: dict[str, Any])[source]¶
Bases:
SchemaItemRepresents 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$PROCEDURESsystem table. Associated parameters are fetched fromRDB$PROCEDURE_PARAMETERS. Procedures are accessed viaSchema.procedures,Schema.sys_procedures,Schema.all_procedures, orPackage.procedures.Supported SQL actions via
get_sql_for():User-defined, standalone procedures:
create(optional keyword argno_code: bool=False): GeneratesCREATE PROCEDURE ...statement, including parameter definitions and the PSQL source code (unlessno_code=True, which generates an emptyBEGIN ENDblock).recreate(optional keyword argno_code: bool=False): GeneratesRECREATE PROCEDURE ....create_or_alter(optional keyword argno_code: bool=False): GeneratesCREATE OR ALTER PROCEDURE ....drop: GeneratesDROP PROCEDURE ....comment: GeneratesCOMMENT 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 (forRETURNS (...)).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:
- _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
codeparameter 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 PROCEDURESQL string.- Raises:
ValueError – If the required
codeparameter is missing, if parameter types are invalid, or if unexpected parameters are passed.- Return type:
- _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 toNULLifself.descriptionis None, otherwise uses the description text with proper escaping.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _get_create_sql(**params) str[source]¶
Generates the SQL command to CREATE this procedure.
Includes input parameter list
(...), output parameter listRETURNS (...)if applicable, and theAS BEGIN ... ENDblock with PSQL source code.- Parameters:
**params –
Accepts one optional keyword argument:
- Returns:
The
CREATE PROCEDURESQL string.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _get_drop_sql(**params) str[source]¶
Generates the SQL command to DROP this procedure.
- Parameters:
**params – Accepts no parameters.
- Returns:
The
DROP PROCEDURESQL string.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- 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
ProcedureParameterobject, orNoneif 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.
- has_output() bool[source]¶
Checks if the procedure defines any output parameters (
RETURNS).Based on
RDB$PROCEDURE_OUTPUTS> 0.
- is_packaged() bool[source]¶
Checks if the procedure is defined within a package.
Based on the presence of
RDB$PACKAGE_NAME.
- property engine_name: str | None¶
The name of the external engine used, if this is an external procedure (
RDB$ENGINE_NAME). ReturnsNonefor 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). ReturnsNonefor PSQL procedures.
- property input_params: DataList[ProcedureParameter]¶
A lazily-loaded
DataListof the procedure’s inputProcedureParameterobjects.Ordered by position (
RDB$PARAMETER_NUMBER). Returns an empty list if the procedure has no input parameters. Fetched fromRDB$PROCEDURE_PARAMETERS.
- property output_params: DataList[ProcedureParameter]¶
A lazily-loaded
DataListof the procedure’s outputProcedureParameterobjects.Ordered by position (
RDB$PARAMETER_NUMBER). Returns an empty list if the procedure has no output parameters (i.e., does not have aRETURNSclause). Fetched fromRDB$PROCEDURE_PARAMETERS.
- property package: Package | None¶
The
Packageobject this procedure belongs to, if any (RDB$PACKAGE_NAME).Returns
Noneif the procedure is standalone.
- property privacy: Privacy¶
The privacy flag (PUBLIC or PRIVATE) for packaged procedures.
Derived from
RDB$PRIVATE_FLAG. ReturnsNoneif not a packaged procedure or flag is missing.
- property privileges: DataList[Privilege]¶
A
DataListofEXECUTEPrivilegeobjects granted on this procedure.Filters the main
Schema.privilegescollection 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). ReturnsNoneif not set.
- class firebird.lib.schema.Role(schema: Schema, attributes: dict[str, Any])[source]¶
Bases:
SchemaItemRepresents 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$ADMINis a predefined system role.Instances map data primarily from the
RDB$ROLESsystem table. They are accessed viaSchema.roles.Supported SQL actions via
get_sql_for():User-defined roles:
create: GeneratesCREATE ROLE role_name.drop: GeneratesDROP ROLE role_name.comment: GeneratesCOMMENT ON ROLE role_name IS ....
System roles (like
RDB$ADMIN):comment: Adds or removes a descriptive comment.
- Parameters:
- _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 toNULLifself.descriptionis None, otherwise uses the description text with proper escaping.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _get_create_sql(**params) str[source]¶
Generates the SQL command to CREATE this role.
- Parameters:
**params – Accepts no parameters.
- Returns:
The
CREATE ROLESQL string.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _get_drop_sql(**params) str[source]¶
Generates the SQL command to DROP this role.
- Parameters:
**params – Accepts no parameters.
- Returns:
The
DROP ROLESQL string.- Raises:
ValueError – If unexpected parameters are passed.
Error – If attempting to drop a system role.
- Return type:
- property privileges: DataList[Privilege]¶
A
DataListof allPrivilegeobjects granted to this role.Filters the main
Schema.privilegescollection 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.
- class firebird.lib.schema.FunctionArgument(schema: Schema, function: Function, attributes: dict[str, Any])[source]¶
Bases:
SchemaItemRepresents 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_ARGUMENTSsystem table. They are accessed via theFunction.argumentsorFunction.returnsproperties.This class itself does not support any direct SQL actions via
get_sql_for(). Its definition is part of theDECLARE EXTERNAL FUNCTIONorCREATE FUNCTIONstatement.- Parameters:
- get_sql_definition() str[source]¶
Generates the SQL string representation of the argument’s definition.
Used when constructing
DECLARE EXTERNAL FUNCTIONorCREATE FUNCTIONstatements. 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 DESCRIPTORExternal UDF return:
VARCHAR(100) CHARACTER SET WIN1252 BY DESCRIPTOR FREE_ITPSQL function input:
P_ID INTEGER NOT NULL = 0PSQL function return:
VARCHAR(50) CHARACTER SET UTF8 COLLATE UNICODE_CI
- Returns:
A string suitable for use within function DDL statements.
- Return type:
- has_default() bool[source]¶
Checks if the argument has a
DEFAULTvalue defined (relevant for PSQL function inputs).Based on the presence of
RDB$DEFAULT_SOURCE.
- 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). IfFalse(default), specifically checks only forBY_VMS_DESCRIPTOR(legacy).- Returns:
Trueif the argument uses the specified descriptor mechanism(s),Falseotherwise.- Return type:
- 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.
- is_freeit() bool[source]¶
Checks if the engine should free memory allocated for a
RETURNS BY DESCRIPTORvalue.Indicated by a negative value in
RDB$MECHANISM.
- 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).
- is_packaged() bool[source]¶
Checks if the argument belongs to a function defined within a package.
Based on the presence of
RDB$PACKAGE_NAME.
- is_returning() bool[source]¶
Checks if this argument represents the function’s return value.
Determined by comparing
positionwith the function’sRDB$RETURN_ARGUMENT.
- is_with_null() bool[source]¶
Checks if the argument is passed by reference with explicit NULL indicator support (
RDB$MECHANISM = 5).
- property argument_mechanism: Mechanism | None¶
The mechanism (
Mechanism) used for passing PSQL function parameters (RDB$ARGUMENT_MECHANISM). ReturnsNonefor 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 beNonefor external UDF arguments.
- property character_length: int¶
Length in characters (
RDB$CHARACTER_LENGTH) forCHAR,VARCHAR,CSTRING.
- property character_set: CharacterSet | None¶
The
CharacterSetobject (RDB$CHARACTER_SET_ID) for character/text types. ReturnsNoneotherwise.
- property collation: Collation | None¶
The specific
Collationobject (RDB$COLLATION_ID) for character types. ReturnsNoneif not applicable or using default.
- property column: TableColumn | None¶
The source
TableColumnif a PSQL parameter usesTYPE OF COLUMN. ReturnsNoneotherwise.
- 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
DEFAULTvalue expression string (RDB$DEFAULT_SOURCE) for PSQL input arguments. ReturnsNoneif no default or not applicable.
- property domain: Domain | None¶
The underlying
Domainobject (RDB$FIELD_SOURCE) for PSQL function parameters. ReturnsNonefor 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
Noneif the type code is missing or zero (may occur for PSQL params relying solely on domain/column type).
- property length: int¶
The defined length (
RDB$FIELD_LENGTH) in bytes for types likeCHAR,VARCHAR,BLOB.
- property mechanism: Mechanism | None¶
The mechanism (
Mechanismenum) used for passing the argument.Derived from the absolute value of
RDB$MECHANISM. Seeis_freeit()for sign meaning. ReturnsNoneif the mechanism code is unrecognized or missing.
- property package: Package | None¶
The
Packageif the function is part of one (RDB$PACKAGE_NAME). ReturnsNoneotherwise.
- 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. ReturnsNoneif not applicable.
- property sub_type: FieldSubType | None¶
The field sub-type code (
RDB$FIELD_SUB_TYPE).Returns a
FieldSubTypeenum member (e.g.,BINARY,TEXT,NUMERIC,DECIMAL) if recognized, the raw integer code otherwise, orNoneif missing.
- class firebird.lib.schema.Function(schema: Schema, attributes: dict[str, Any])[source]¶
Bases:
SchemaItemRepresents 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 theRETURNSclause. Can be standalone or part of aPackage.
Instances map data primarily from the
RDB$FUNCTIONSsystem table. Associated arguments/return values are fetched fromRDB$FUNCTION_ARGUMENTS. Functions are accessed viaSchema.functions,Schema.sys_functions,Schema.all_functions, orPackage.functions.Supported SQL actions via
get_sql_for():External UDFs:
declare: GeneratesDECLARE [EXTERNAL] FUNCTION ... ENTRY_POINT ... MODULE_NAME ....drop: GeneratesDROP [EXTERNAL] FUNCTION ....comment: GeneratesCOMMENT ON [EXTERNAL] FUNCTION ... IS ....
User-defined, standalone PSQL Functions:
create(optional keyword argno_code: bool=False): GeneratesCREATE FUNCTION ... RETURNS ... AS BEGIN ... END. Includes parameter and return type definitions. Uses empty body ifno_code=True.recreate(optional keyword argno_code: bool=False): GeneratesRECREATE FUNCTION ....create_or_alter(optional keyword argno_code: bool=False): GeneratesCREATE OR ALTER FUNCTION ....drop: GeneratesDROP FUNCTION ....comment: GeneratesCOMMENT ON FUNCTION ... IS ....alter(keyword args): Modifies the function definition. Requirescode.
System functions or packaged functions:
comment: Adds or removes a descriptive comment.Note: Packaged functions are typically managed via
ALTER PACKAGE.
- Parameters:
- _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
returnsandcodeparameters 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 FUNCTIONSQL 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:
- _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 toNULLifself.descriptionis None, otherwise uses the description text with proper escaping.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _get_create_sql(**params) str[source]¶
Generates the SQL command to CREATE this PSQL function.
Includes input parameter list
(...),RETURNSclause, and theAS BEGIN ... ENDblock with PSQL source code.- Parameters:
**params –
Accepts one optional keyword argument:
- Returns:
The
CREATE FUNCTIONSQL 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:
- _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 FUNCTIONSQL 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:
- _get_drop_sql(**params) str[source]¶
Generates the SQL command to DROP this function.
- Parameters:
**params – Accepts no parameters.
- Returns:
The
DROP EXTERNAL FUNCTIONorDROP FUNCTIONSQL string.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _load_arguments(mock: dict[str, Any] | None = None) None[source]¶
Internal helper: Loads function arguments from RDB$FUNCTION_ARGUMENTS.
- has_arguments() bool[source]¶
Checks if the function defines any input arguments.
Excludes the argument designated as the return value.
- 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.
- 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_ARGUMENTpoints to a non-zero argument position. Modern functions usually return directly (position 0 or implied).
- is_external() bool[source]¶
Checks if this is an external UDF (declared with
MODULE_NAME).- Returns:
Trueifmodule_nameis not None/empty,Falseotherwise (PSQL function).- Return type:
- is_packaged() bool[source]¶
Checks if the function is defined within a package.
Based on the presence of
RDB$PACKAGE_NAME.
- property arguments: DataList[FunctionArgument]¶
A lazily-loaded
DataListof the function’s inputFunctionArgumentobjects.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
Noneif 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 orNonefor external UDFs.
- property entrypoint: str | None¶
The function name within the external library (
RDB$ENTRYPOINT) for external UDFs. ReturnsNonefor PSQL functions.
- property legacy_flag: Legacy¶
Indicates if the function uses legacy syntax/behavior (
Legacyenum).Derived from
RDB$LEGACY_FLAG.
- property module_name: str | None¶
The external library name (
RDB$MODULE_NAME) for external UDFs. ReturnsNonefor PSQL functions.
- property package: Package | None¶
The
Packageobject this function belongs to, if any (RDB$PACKAGE_NAME). ReturnsNoneif the function is standalone.
- property private_flag: Privacy | None¶
PUBLIC or PRIVATE) for packaged functions.
Derived from
RDB$PRIVATE_FLAG. ReturnsNoneif not a packaged function.- Type:
The privacy flag (
Privacy
- property returns: FunctionArgument | None¶
The
FunctionArgumentobject representing the function’s return value.This argument is identified by the
RDB$RETURN_ARGUMENTfield inRDB$FUNCTIONS. ReturnsNoneif 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). ReturnsNoneif not set.
- class firebird.lib.schema.DatabaseFile(schema: Schema, attributes: dict[str, Any])[source]¶
Bases:
SchemaItemRepresents 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$FILESsystem table. They are typically accessed viaSchema.files(for main database files) orShadow.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:
- _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
sequencenumber for identification purposes within the library.
- 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.
- class firebird.lib.schema.Shadow(schema: Schema, attributes: dict[str, Any])[source]¶
Bases:
SchemaItemRepresents 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$FILESwhereRDB$SHADOW_NUMBER> 0. They are accessed viaSchema.shadows.Supported SQL actions via
get_sql_for():create: Generates theCREATE SHADOW shadow_id [AUTO|MANUAL] [CONDITIONAL] FILE '...' [LENGTH N] [FILE '...' STARTING AT P [LENGTH N]] ...statement.drop(optional keyword argpreserve: bool=False): GeneratesDROP SHADOW shadow_id [PRESERVE FILE]. Ifpreserveis True, addsPRESERVE FILEclause.
Note:
Shadows do not have user-assigned names in SQL; they are identified by their numeric ID.
- Parameters:
- _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 SHADOWSQL string.- Raises:
ValueError – If unexpected parameters are passed.
Error – If the associated shadow files cannot be loaded.
- Return type:
- _get_drop_sql(**params) str[source]¶
Generates the SQL command to DROP this shadow.
- Parameters:
**params –
Accepts one optional keyword argument:
- Returns:
The
DROP SHADOWSQL string.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _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:
- 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.CONDITIONALflag.
- is_inactive() bool[source]¶
Checks if the shadow is currently marked as inactive (
INACTIVE).Based on the
ShadowFlag.INACTIVEflag. The engine typically ignores inactive shadows.
- is_manual() bool[source]¶
Checks if the shadow requires manual intervention (
MANUAL).Based on the
ShadowFlag.MANUALflag.
- property files: DataList[DatabaseFile]¶
A lazily-loaded
DataListof theDatabaseFileobjects comprising this shadow.Ordered by sequence number. Fetched from
RDB$FILESmatching this shadow’s ID.
- property flags: ShadowFlag¶
A
ShadowFlagenum value representing the combined flags (INACTIVE, MANUAL, CONDITIONAL) defined byRDB$FILE_FLAGSfor this shadow.
- class firebird.lib.schema.Privilege(schema: Schema, attributes: dict[str, Any])[source]¶
Bases:
SchemaItemRepresents a single privilege granted on a database object to a user or another object.
This class maps a single row from the
RDB$USER_PRIVILEGESsystem 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.privilegesor filtered using methods likeSchema.get_privileges_of()or properties likeTable.privileges.Supported SQL actions via
get_sql_for():grant(optional keyword arggrantors: list[str]=[‘SYSDBA’]): Generates theGRANT ... ON ... TO ... [WITH GRANT/ADMIN OPTION] [GRANTED BY ...]statement. TheGRANTED BYclause is added if the actual grantor is not in thegrantorslist.revoke(optional keyword args:grantors: list[str]=[‘SYSDBA’],grant_option: bool=False): Generates theREVOKE [GRANT/ADMIN OPTION FOR] ... FROM ... [GRANTED BY ...]statement. Ifgrant_optionis True, revokes only the grant/admin option, not the privilege itself. TheGRANTED BYclause is added if the actual grantor is not in thegrantorslist.
- Parameters:
- _get_grant_sql(**params) str[source]¶
Generates the SQL command to GRANT this specific privilege.
Constructs the
GRANTstatement 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 actualgrantor_nameof this privilege is not in this list, aGRANTED BYclause will be appended. Defaults to['SYSDBA'].
- Returns:
The
GRANTSQL string.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _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’
- _get_revoke_sql(**params) str[source]¶
Generates the SQL command to REVOKE this specific privilege.
Constructs the
REVOKEstatement 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 actualgrantor_nameis not in this list, aGRANTED BYclause will be appended. Defaults to['SYSDBA'].grant_option(bool): IfTrue, revokes only the ability to grant the privilege (GRANT OPTION FORorADMIN OPTION FOR), not the privilege itself. Defaults toFalse.
- Returns:
The
REVOKESQL string.- Raises:
ValueError – If
grant_optionis True but the privilege was not granted with the grant/admin option, or if unexpected parameters are passed.- Return type:
- has_grant() bool[source]¶
Checks if this privilege was granted with the
WITH GRANT OPTIONorWITH ADMIN OPTION.
- is_execute() bool[source]¶
Checks if this is an
EXECUTEprivilege (on a procedure or function).- Return type:
- is_reference() bool[source]¶
Checks if this is a
REFERENCESprivilege (for foreign keys).- Return type:
- 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
Noneif 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). ReturnsNoneif the option code is unrecognized or missing.
- property grantor: UserInfo | None¶
the user who granted the privilege (
RDB$GRANTOR).- Returns:
A
UserInfoobject representing the grantor, orNoneif the grantor name is missing.- Type:
The grantor
- property privilege: PrivilegeCode¶
The type of privilege granted (
PrivilegeCodeenum).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_nameandsubject_type. May return specific column objects iffield_nameis set.- Returns:
The specific object (e.g.,
Table,Procedure,Role,TableColumn), orNoneif 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) andRDB$USER_TYPE.
- 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:
SchemaItemRepresents 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$PACKAGESsystem table. Contained procedures and functions are linked viaRDB$PACKAGE_NAMEin their respective system tables (RDB$PROCEDURES,RDB$FUNCTIONS). Packages are accessed viaSchema.packages.Supported SQL actions via
get_sql_for():create(keyword argumentbody: bool=False): GeneratesCREATE PACKAGE [BODY] ... AS ... END. IfbodyisFalse(default), creates the package header usingself.header. IfbodyisTrue, creates the package body usingself.body.recreate(keyword argumentbody: bool=False): GeneratesRECREATE PACKAGE [BODY] .... Same logic ascreateregarding thebodyparameter.create_or_alter(keyword argumentbody: bool=False): GeneratesCREATE OR ALTER PACKAGE [BODY] .... Same logic ascreateregarding thebodyparameter.drop(keyword argumentbody: bool=False): GeneratesDROP PACKAGE [BODY] .... IfbodyisFalse(default), drops the package header (and implicitly the body). IfbodyisTrue, drops only the package body.comment: GeneratesCOMMENT 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 specificALTER PACKAGEcommand to modify parts (which is less common in Firebird PSQL).- Parameters:
- _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, generatesALTER PACKAGEusing the value as source. Otherwise it generatesALTER PACKAGEwith empty source.
- Returns:
The
ALTER PACKAGESQL string.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _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 toNULLifself.descriptionis None, otherwise uses the description text with proper escaping.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _get_create_sql(**params) str[source]¶
Generates the SQL command to CREATE the package header or body.
- Parameters:
**params –
Accepts one optional keyword argument:
- Returns:
The
CREATE PACKAGE [BODY]SQL string.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _get_drop_sql(**params) str[source]¶
Generates the SQL command to DROP the package header or body.
- Parameters:
**params –
Accepts one optional keyword argument:
- Returns:
The
DROP PACKAGE [BODY]SQL string.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- 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.
- property body: str | None¶
The PSQL source code for the package body (
RDB$PACKAGE_BODY_SOURCE). Contains implementations and private declarations. ReturnsNoneif unavailable.
- property functions: DataList[Function]¶
A
DataListof allFunctionobjects defined within this package.Filters the main
Schema.functionscollection based on package name.
- property header: str | None¶
The PSQL source code for the package header (
RDB$PACKAGE_HEADER_SOURCE). Contains public declarations. ReturnsNoneif unavailable.
- property procedures: DataList[Procedure]¶
A
DataListof allProcedureobjects defined within this package.Filters the main
Schema.procedurescollection based on package name.
- class firebird.lib.schema.BackupHistory(schema: Schema, attributes: dict[str, Any])[source]¶
Bases:
SchemaItemRepresents an entry in the database’s NBackup history log.
Each entry records details about a physical backup operation performed using the
nbackuputility, 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_HISTORYsystem table. They are accessed viaSchema.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 bynbackupoperations and potentially explicitDELETE FROM RDB$BACKUP_HISTORYstatements (use with caution).- Parameters:
- _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.
- 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.
- class firebird.lib.schema.Filter(schema: Schema, attributes: dict[str, Any])[source]¶
Bases:
SchemaItemRepresents 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$FILTERSsystem table. They are typically accessed viaSchema.filters.Supported SQL actions via
get_sql_for():User-defined filters:
declare: GeneratesDECLARE FILTER filter_name ... ENTRY_POINT ... MODULE_NAME ....drop: GeneratesDROP FILTER filter_name.comment: GeneratesCOMMENT ON FILTER filter_name IS ....
System filters (if any exist):
comment: Adds or removes a descriptive comment.
- Parameters:
- _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 toNULLifself.descriptionis None, otherwise uses the description text with proper escaping.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _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 FILTERSQL string.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- _get_drop_sql(**params) str[source]¶
Generates the SQL command to DROP this BLOB filter.
- Parameters:
**params – Accepts no parameters.
- Returns:
The
DROP FILTERSQL string.- Raises:
ValueError – If unexpected parameters are passed.
- Return type:
- 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.