Python Objects — Firebird Pack for PowerConsole v0.9.1 documentation

### Navigation

- index
- previous |
- Firebird Pack for PowerConsole v0.9.1 documentation »

# Python Objects

## Using database objects in PowerConsole

Firebird Pack uses library `fbcore` build on top of KInterbasDB database driver, that defines set of higher-level objects to work with Firebird databases instead classic Python Database API, and above all, represents database metadata as Python objects.

Each connected database (represented by `Database` object) is also accessible in PowerConsole’s user space for direct use. You may specify the name under which it would be available using `AS` clause of `CONECT` or `CREATE DATABASE` statements, otherwise it would get the default name “db”.

You may use these objects directly at command propt, in your PowerConsole scripts or pass them as parameters to PowerConsole commands. Here are some examples:

1. List names and owners of all user tables

       >>> connect 'employee' user 'sysdba' password 'masterkey'
       Database employee as db, user sysdba
       >>> list name,owner_name in db.tables
       name             owner_name
       ================ ==========
       COUNTRY          SYSDBA
       JOB              SYSDBA
       DEPARTMENT       SYSDBA
       EMPLOYEE         SYSDBA
       PROJECT          SYSDBA
       CUSTOMER         SYSDBA
       EMPLOYEE_PROJECT SYSDBA
       PROJ_DEPT_BUDGET SYSDBA
       SALARY_HISTORY   SYSDBA
       SALES            SYSDBA

2. List all indices on JOB table

       >>> connect 'employee' user 'sysdba' password 'masterkey'
       Database employee as db, user sysdba
       >>> t = db.getTable('JOB')
       >>> list t.indices
       RDB$PRIMARY2 unique system index on JOB(JOB_CODE,JOB_GRADE,JOB_COUNTRY)
       RDB$FOREIGN3 system(FK) index on JOB(JOB_COUNTRY)
       MINSALX index on JOB(JOB_COUNTRY,MIN_SALARY)
       MAXSALX index on JOB(JOB_COUNTRY,MAX_SALARY)

3. Because Firebird Pack installs object renderers to your PowerConsole environment, you may see enhanced output for these objects when they’re evaluated on command prompt:

       >>> t = db.getTable('JOB')
       >>> t
       Table JOB (129) owned by SYSDBA
       JOB_CODE                          (JOBCODE) VARCHAR(5) Not Null
                                         CHECK (VALUE > '99999')
       JOB_GRADE                         (JOBGRADE) SMALLINT Not Null
                                         CHECK (VALUE BETWEEN 0 AND 6)
       JOB_COUNTRY                       (COUNTRYNAME) VARCHAR(15) Not Null
       JOB_TITLE                         VARCHAR(25) Not Null
       MIN_SALARY                        (SALARY) NUMERIC(10, 2) Not Null DEFAULT 0
                                         CHECK (VALUE > 0)
       MAX_SALARY                        (SALARY) NUMERIC(10, 2) Not Null DEFAULT 0
                                         CHECK (VALUE > 0)
       JOB_REQUIREMENT                   BLOB segment 400, subtype TEXT Nullable
       LANGUAGE_REQ                      ARRAY OF [5] VARCHAR(15) Nullable

       Constraints:
       PRIMARY KEY INTEG_10:
       Index RDB$PRIMARY2(JOB_CODE,JOB_GRADE,JOB_COUNTRY)
       FOREIGN KEY INTEG_11:
       Index RDB$FOREIGN3(JOB_COUNTRY)
       References COUNTRY RDB$PRIMARY1(COUNTRY)
       CHECK INTEG_12:
       CHECK (min_salary < max_salary)

       Indices:
       RDB$PRIMARY2 unique system index on (JOB_CODE,JOB_GRADE,JOB_COUNTRY)
       RDB$FOREIGN3 system(FK) index on (JOB_COUNTRY)
       MINSALX index on (JOB_COUNTRY,MIN_SALARY)
       MAXSALX index on (JOB_COUNTRY,MAX_SALARY)

4. List all triggers that post events

       >>> connect 'employee' user 'sysdba' password 'masterkey'
       Database employee as db, user sysdba
       >>> list name in (t for t in db.triggers if 'POST_EVENT' in t.source)
       name
       ==============
       POST_NEW_ORDER

5. Show procedures that are not in another database

       >>> connect 'employee' user 'sysdba' password 'masterkey'
       Database employee as db, user sysdba
       >>> connect '/data/db/employee-copy.fdb' user 'sysdba' password 'masterkey' as db2
       Database /data/db/employee-copy.fdb as db2, user sysdba
       >>> ready db
       Main database set to db
       >>> list name in (p for p in db.procedures if db2.getProcedure(p.name) is None)
       name
       ==========
       MAIL_LABEL
       >>> list name in (p for p in db.procedures if not db2.getProcedure(p.name))
       name
       ==========
       MAIL_LABEL

6. Find out what procedures differ in source code and then show the differences:

       >>> connect 'employee' user 'sysdba' password 'masterkey'
       Database employee as db, user sysdba
       >>> connect '/data/db/employee-copy.fdb' user 'sysdba' password 'masterkey' as db2
       Database /data/db/employee-copy.fdb as db2, user sysdba
       >>> ready db
       Main database set to db
       >>> common_proc = [p for p in db.procedures if db2.getProcedure(p.name)]
       >>> list name in common_proc
       name
       ===============
       GET_EMP_PROJ
       ADD_EMP_PROJ
       SUB_TOT_BUDGET
       DELETE_EMPLOYEE
       DEPT_BUDGET
       ORG_CHART
       SHIP_ORDER
       SHOW_LANGS
       ALL_LANGS
       >>> different = [p for p in common_proc if p.source != db2.getProcedure(p.name).source]
       >>> list name in different
       name
       ===========
       DEPT_BUDGET
       >>> params = zip(different,map(db2.getProcedure,(p.name for p in different)))
       >>> import difflib
       >>> list difflib.ndiff(params[0][0].source.split('\n'),params[0][1].source.split('\n'))
       -       DECLARE VARIABLE sumb DECIMAL(12, 2);
       ? -

       + DECLARE VARIABLE sumb DECIMAL(12, 2);
               DECLARE VARIABLE rdno CHAR(3);
               DECLARE VARIABLE cnt INTEGER;
       BEGIN
       -       tot = 0;
       +       total = 0;
       ?          ++

       -       SELECT budget FROM department WHERE dept_no = :dno INTO :tot;
       +       SELECT budget FROM department WHERE dept_no = :dno INTO :total;
       ?                                                                   ++

               SELECT count(budget) FROM department WHERE head_dept = :dno INTO :cnt;

               IF (cnt = 0) THEN
                       SUSPEND;

               FOR SELECT dept_no
                       FROM department
                       WHERE head_dept = :dno
                       INTO :rdno
               DO
                       BEGIN
                               EXECUTE PROCEDURE dept_budget :rdno RETURNING_VALUES :sumb;
       -                       tot = tot + sumb;
       +                       total = total + sumb;
       ?                          ++      ++

                       END

               SUSPEND;
       END

   If you want to use it more often, you can save a lot of typing with handy function:

       >>> def source_diff(a,b):
       ...   result = ['Procedure %s' % a.name]
       ...   result.extend(difflib.ndiff(a.source.split('\n'),b.source.split('\n')))
       ...   return '\n'.join(result)
       ...
       >>> list map(source_diff,different,map(db2.getProcedure,(p.name for p in different)))
       Procedure DEPT_BUDGET
       -       DECLARE VARIABLE sumb DECIMAL(12, 2);
       ? -

       + DECLARE VARIABLE sumb DECIMAL(12, 2);
               DECLARE VARIABLE rdno CHAR(3);
               DECLARE VARIABLE cnt INTEGER;
       BEGIN
       -       tot = 0;
       +       total = 0;
       ?          ++

       -       SELECT budget FROM department WHERE dept_no = :dno INTO :tot;
       +       SELECT budget FROM department WHERE dept_no = :dno INTO :total;
       ?                                                                   ++

               SELECT count(budget) FROM department WHERE head_dept = :dno INTO :cnt;

               IF (cnt = 0) THEN
                       SUSPEND;

               FOR SELECT dept_no
                       FROM department
                       WHERE head_dept = :dno
                       INTO :rdno
               DO
                       BEGIN
                               EXECUTE PROCEDURE dept_budget :rdno RETURNING_VALUES :sumb;
       -                       tot = tot + sumb;
       +                       total = total + sumb;
       ?                          ++      ++

                       END

               SUSPEND;
       END

   If you know that both databases have the same procedures that just differ in source, you may write:

       >>> list map(source_diff,db.procedures,db2.procedures)

   to list all procedures that differ in source including the diff report.

   Tip

   You can create your own library from these functions and import them any time to the PowerConsole. You can even use PowerConsole commands in these libraries, but in that case you have to install them to your interactive session via PowerConsole’s `RUN` command.

## Available objects

### Database

class `fbcore.` `Database`(**args)

  This class represents a database.

  It contains methods to attach, create or drop database, properties and methods to access metadata or create new metadata objects.

  `close`()
    Close connection to the database.
  `commit`()
    Commits transaction.
  `drop`()
    Drop attached database.
  `getDomain`(name)
    Return `Domain` object with specified name.
  `rollback`()
    Rollback transaction.
  `character_sets`
    List of all character sets in database. Items are CharacterSet objects.
  `collations`
    List of all collations in database. Items are `Collation` objects.
  `constraints`
    List of all constraints in database. Items are `Constraint` objects.
  `default_character_set`
    Default character set name, NULL if it’s character set NONE.
  `dependencies`
    List of all dependencies in database. Items are `Dependency` objects.
  `description`
    Database description or None if it doesn’t have a description.
  `domains`
    List of all user domains in database. Items are `Domain` objects.
  `exceptions`
    List of all exceptions in database. Items are `Exception` objects.
  `files`
    List of all extension and shadow files defined for database. Items are `DbFile` objects.
  `functions`
    List of all user functions defined in database. Items are `Function` objects.
  `generators`
    List of all user generators in database. Items are `Generator` objects.
  `indices`
    List of all user indices in database. Items are `Index` objects.
  `owner_name`
    Database owner name.
  `procedures`
    List of all user procedures in database. Items are `Procedure` objects.
  `roles`
    List of all roles in database. Items are `Role` objects.
  `security_class`
    Can refer to the security class applied as databasewide access control limits.
  `sysdomains`
    List of all system domains in database. Items are `Domain` objects.
  `sysgenerators`
    List of all system generators in database. Items are `Generator` objects.
  `sysindices`
    List of all system indices in database. Items are `Index` objects.
  `sysprocedures`
    List of all system procedures in database. Items are `Procedure` objects.
  `systables`
    List of all system tables in database. Items are `Table` objects.
  `systriggers`
    List of all system triggers in database. Items are `Trigger` objects.
  `sysviews`
    List of all system views in database. Items are `View` objects.
  `tables`
    List of all user tables in database. Items are `Table` objects.
  `triggers`
    List of all user triggers in database. Items are `Trigger` objects.
  `views`
    List of all user views in database. Items are `View` objects.

### Database File

class `fbcore.` `DbFile`(db, attributes)

  Represents database extension or shadow file.

  `getDependencies`()
    Return list of database objects that this objects depend on.
  `getDependents`()
    Return list of all database objects that depend on this one.
  `isConditional`()
    Return True if it’s CONDITIONAL shadow file.
  `isInactive`()
    Return True if it’s INACTIVE shadow file.
  `isManual`()
    Return True if it’s MANUAL shadow file.
  `isShadow`()
    Return True if this file represents SHADOW.
  `isSystemObject`()
    Return True if this database object is system object.
  `description`
    Database object description or None if object doesn’t have a description.
  `file_name`
    File name.
  `flags`
    File flags.
  `length`
    File length in pages.
  `name`
    Database object name or None if object doesn’t have a name.
  `sequence`
    File sequence number.
  `shadow_number`
    Shadow file number.
  `start`
    File start page number.

### Character Set

class `fbcore.` `CharacterSet`(db, attributes)

  Represents character set.

  `getCollation`(name)
    Return `Collation` object with specifid name that belongs to this character set.
  `getCollationById`(id)
    Return `Collation` object with specifid id that belongs to this character set.
  `getDependencies`()
    Return list of database objects that this objects depend on.
  `getDependents`()
    Return list of all database objects that depend on this one.
  `isSystemObject`()
    Return True if this database object is system object.
  `bytes_per_character`
    Size of characters in bytes.
  `collations`
    List of Collations associated with character set.
  `default_collate_name`
    Name of default collate.
  `description`
    Database object description or None if object doesn’t have a description.
  `id`
    Character set ID.
  `name`
    Database object name or None if object doesn’t have a name.

### Collation

class `fbcore.` `Collation`(db, attributes)

  Represents collation.

  `getCharacterSet`()
    Return `CharacterSet` object to which this collation belongs.
  `character_set_id`
    Character set ID associated with collation.
  `id`
    Collation ID.

### Domain

class `fbcore.` `Domain`(db, attributes)
  `getCharacterSet`()
    Return `CharacterSet` object that belongs to this domain.
  `getCollation`()
    Return `Collation` object that belongs to this domain.
  `isSystemObject`()
    Return True if this database object is system object.
  `character_length`
    Length of CHAR and VARCHAR column, in characters (not bytes).
  `character_set_id`
    Number ID of the character set for a character or text BLOB column.
  `collation_id`
    Number ID of the collation sequence (if defined) for a character column.
  `computed_source`
    Expression that defines the COMPUTED BY column or None.
  `datatype`
    Comlete SQL datatype definition.
  `default_source`
    Expression that defines the default value or None.
  `dimensions`
    Number of dimensions defined, if column is an array type. Always zero for non-array columns.
  `external_length`
    Length of field as it is in an external table. Always 0 for regular tables.
  `external_scale`
    Scale factor of an integer field as it is in an external table.
  `external_type`
    Data type of the field as it is in an external table.
  `field_type`
    Number code of the data type defined for the column.
  `length`
    Length of the column in bytes.
  `nullable`
    True if domain is not defined with NOT NULL.
  `precision`
    Indicates the number of digits of precision available to the data type of the column.
  `scale`
    Negative number representing the scale of NUMBER and DECIMAL column.
  `segment_length`
    For BLOB columns, a suggested length for BLOB buffers.
  `sub_type`
    BLOB subtype.
  `validation_source`
    Expression that defines the CHECK constarint for the column or None.

### Table

class `fbcore.` `Table`(db, attributes)

  Represents Table in database.

  `getColumn`(name)
    Return `TableColumn` object with specified name.
  `columns`
    Returns list of columns defined for table. Items are `TableColumn` objects.
  `constraints`
    Returns list of constraints defined for table. Items are `Constraint` objects.
  `dbkey_length`
    Length of the RDB$DB_KEY column in bytes.
  `default_class`
    Default security class.
  `external_file`
    Full path to the external data file, if any.
  `flags`
    Internal flags.
  `format`
    Internal format ID for the table.
  `indices`
    Returns list of indices defined for table. Items are `Index` objects.
  `owner_name`
    User name of table’s creator.
  `relation_id`
    Internam number ID for the table.
  `security_class`
    Security class that define access limits to the table.
  `table_name`
    Name of the table.
  `triggers`
    Returns list of triggers defined for table. Items are `Trigger` objects.

### Table Column

class `fbcore.` `TableColumn`(db, table, attributes)

  Represents table column.

  `getCollation`()
    Return `Collation` object that belongs to this character column.
  `getDependencies`()
    Return list of database objects that this objects depend on.
  `getDependents`()
    Return list of all database objects that depend on this one.
  `getDomain`()
    Return `Domain` object for this column.
  `collation_id`
    Collation ID or None.
  `datatype`
    Comlete SQL datatype definition.
  `default_value`
    Default value for column or None.
  `domain_name`
    Name of the domain this column is based on.
  `field_name`
    Name of the column.
  `nullable`
    True if column can accept NULL values.
  `position`
    Column’s sequence number in row.
  `security_class`
    Security class name or None.
  `table_name`
    Name of the table this column belongs to.

### Table Constraint

class `fbcore.` `Constraint`(db, attributes)

  Represents table or column constraint.

  `isCheck`()
    Return True if it’s CHECK constraint.
  `isDeferrable`()
    Return True if it’s DEFERRABLE constraint.
  `isForeignKey`()
    Return True if it’s FOREIGN KEY constraint.
  `isInitiallyDeferred`()
    Return True if it’s INITIALLY DEFERRED constraint.
  `isNotNull`()
    Return True if it’s NOT NULL constraint.
  `isPrimaryKey`()
    Return True if it’s PRIMARY KEY constraint.
  `isSystemObject`()
    Return True if this database object is system object.
  `isUnique`()
    Return True if it’s UNIQUE constraint.
  `column_name`
    For a NOT NULL constraint, this is the name of the column to which the constraint applies.
  `constraint_name`
    Name of a table-level constraint.
  `constraint_type`
    primary key/unique/foreign key/check/not null.
  `deferrable`
    Currently NO in all cases; reserved for future use.
  `delete_rule`
    For a FOREIGN KEY constraint, this is the action applicable to when primary key is deleted.
  `index_name`
    Name of the index that enforces the constraint. Applicable if constraint is primary key/unique or foreign key.
  `initially_deferred`
    Currently NO in all cases; reserved for future use.
  `match_option`
    For a FOREIGN KEY constraint only. Current value is FULL in all cases.
  `relation_name`
    Name of the table this constraint applies to.
  `trigger_names`
    For a CHECK constraint, this is list trigger names that enforces the constraint.
  `update_rule`
    For a FOREIGN KEY constraint, this is the action applicable to when primary key is updated.
  `uq_constraint_name`
    For a FOREIGN KEY constraint, this is the name of the unique or primary key constraint referred by this constraint.

### Index

class `fbcore.` `Index`(db, attributes)

  Represents database index.

  `expression`
    Source of an expression or None.
  `foreign_key`
    name of the associated foreign key constraint, or None.
  `id`
    Internal number ID of the index.
  `inactive`
    True if the index is currently inactive.
  `segments`
    List of index segment names.
  `statistics`
    Latest selectivity of the index.
  `table_name`
    The name of the table the index applies to.
  `unique`
    True if the index is unique.

### View

class `fbcore.` `View`(db, attributes)

  Represents database View.

  `getColumn`(name)
    Return `TableColumn` object with specified name.
  `getTrigger`(name)
    Return `Trigger` object with specified name.
  `columns`
    Returns list of columns defined for view. Items are `ViewColumn` objects.
  `dbkey_length`
    Length of the RDB$DB_KEY column in bytes.
  `default_class`
    Default security class.
  `flags`
    Internal flags.
  `format`
    Internal format ID for the view.
  `owner_name`
    User name of view’s creator.
  `relation_id`
    Internal number ID for the view.
  `security_class`
    Security class that define access limits to the view.
  `source_sql`
    The query specification.
  `triggers`
    Returns list of triggers defined for view. Items are `Trigger` objects.
  `view_name`
    Name of the view.

### View Column

class `fbcore.` `ViewColumn`(db, view, attributes)

  Represents view column.

  `getCollation`()
    Return `Collation` object that belongs to this column.
  `getDependencies`()
    Return list of database objects that this objects depend on.
  `getDependents`()
    Return list of all database objects that depend on this one.
  `getDomain`()
    Return `Domain` object for this column.
  `base_field`
    The column name from the base table.
  `collation_id`
    Collation ID or None.
  `datatype`
    Comlete SQL datatype definition.
  `domain_name`
    Name of the domain this column is based on.
  `field_name`
    Name of the column.
  `nullable`
    True if column can accept NULL values.
  `position`
    Column’s sequence number in row.
  `security_class`
    Security class name or None.
  `view_context`
    Internal number ID for the base table where the field come from.
  `view_name`
    Name of the view this column belongs to.

### Trigger

class `fbcore.` `Trigger`(db, attributes)

  Represents trigger.

  `getTypeAsString`()
    Return string with action and operation specification.
  `isActive`()
    Return True if this trigger is active.
  `isAfterAction`()
    Return True if this trigger is set for AFTER action.
  `isBeforeAction`()
    Return True if this trigger is set for BEFORE action.
  `isDbTrigger`()
    Return True if this trigger is database trigger.
  `isDeleteAction`()
    Return True if this trigger is set for DELETE operation.
  `isInsertAction`()
    Return True if this trigger is set for INSERT operation.
  `isUpdateAction`()
    Return True if this trigger is set for UPDATE operation.
  `flags`
    Internal flags.
  `relation_name`
    Name of the table or view that the trigger is for.
  `sequence`
    Sequence (position) of trigger. Zero usually means no sequence defined.
  `source`
    PSQL source code.
  `trigger_name`
    Name of the trigger.
  `trigger_type`
    Numeric code for trigger type that define what event and when are covered by trigger.

### Stored Procedure

class `fbcore.` `Procedure`(db, attributes)

  Represents stored procedure.

  `id`
    Internal unique ID number.
  `input_params`
    List of procedure input parameters. Instances are ProcParameter instances.
  `output_params`
    List of procedure output parameters. Instances are ProcParameter instances.
  `owner_name`
    User name of procedure’s creator.
  `procedure_name`
    Name of the stored procedure.
  `security_class`
    Security class that define access limits to the procedure.
  `source`
    PSQL source code.

### Procedure Parameter

class `fbcore.` `ProcParameter`(db, proc, attributes)

  Represents procedure parameter.

  `getDomain`()
    Return `Domain` object for this parameter.
  `datatype`
    Comlete SQL datatype definition.
  `field`
    System-generated unique column name.
  `parameter_name`
    Name of the parameter.
  `parameter_type`
    Indicetas whether parameter is input(0) or output(1).
  `procedure_name`
    Name of the stored procedure.
  `sequence`
    Sequence (position) of parameter.

### Exception

class `fbcore.` `Exception`(db, attributes)

  Represents database exception.

  `id`
    System-assigned unique exception number.
  `message`
    Custom message text.

### Generator

class `fbcore.` `Generator`(db, attributes)

  Represents database generator.

  `id`
    Internal number ID of the generator.
  `value`
    Current generator value.

### Role

class `fbcore.` `Role`(db, attributes)

  Represents user role.

  `isSystemObject`()
    Return True if this database object is system object.
  `owner_name`
    User name of role owner.
  `role_name`
    Role name.

### External Function

class `fbcore.` `Function`(db, attributes)

  Represents user defined function.

  `arguments`
    List of function arguments.
  `entrypoint`
    Entrypoint in module.
  `function_name`
    Function name.
  `module_name`
    Module name.
  `return_argument`
    Ordinal position of return argument in parameter list.

### Function argument

class `fbcore.` `FunctionArgument`(db, function, attributes)

  Represets UDF argument.

  `character_length`
    Length of CHAR and VARCHAR column, in characters (not bytes).
  `character_set_id`
    Number ID of the character set for a character or text BLOB column.
  `datatype`
    Comlete SQL datatype definition.
  `field_type`
    Number code of the data type defined for the argument.
  `function_name`
    Function name.
  `length`
    Length of the column in bytes.
  `mechanism`
    How argument is passed.
  `position`
    Argument position.
  `precision`
    Indicates the number of digits of precision available to the data type of the column.
  `scale`
    Negative number representing the scale of NUMBER and DECIMAL argument.
  `sub_type`
    BLOB subtype.

### Dependencies between objects

class `fbcore.` `Dependency`(db, attributes)

  Maps dependency between database objects.

  `getDependency`()
    Return database object on which the other one depends.
  `getDependent`()
    Return dependent database object.

### Navigation

- index
- previous |
- Firebird Pack for PowerConsole v0.9.1 documentation »