psycodict.base

The shared plumbing underneath every psycodict object.

PostgresBase is the common base of the database, table and statistics classes; it owns statement execution through _execute (logging, slow-query warnings, commit/rollback bookkeeping and reconnection) together with helpers for inspecting tables, indexes and constraints. The module also defines the layout of the meta_* tables – the column lists, types and creation statements shared by everything that reads or writes them – and the metadata format version (META_FORMAT) stamped into meta_format.

exception psycodict.base.InvalidColumnTypeError[source]

Bases: ValueError, RuntimeError

Raised for a column type psycodict will not put into a statement.

A ValueError, since an unusable type is a bad argument, and also a RuntimeError, which is what psycodict raised for an invalid type before 1.0.0 and what existing callers may catch.

psycodict.base.validate_column_type(typ)[source]

Check that typ is a PostgreSQL column type psycodict is willing to create, and return the spelling that callers must put into DDL.

Validation is centralized here because a column type is interpolated into CREATE TABLE and ALTER TABLE statements as SQL text rather than bound as a value: PostgreSQL has no placeholder for a type. Callers must emit the returned spelling and never the string they passed in, since the two are equal only for input that needed no normalization.

INPUT:

  • typ – a string, e.g. 'bigint', 'numeric(10, 2)' or 'text COLLATE "C"'. Surrounding whitespace is ignored.

OUTPUT:

A pair (sql_spelling, storage_cost). storage_cost is the width of the type in bytes, or -1 if it is variable, and is used to order columns when creating a table.

Raises InvalidColumnTypeError (a ValueError) on anything else, including a type that merely starts with a valid type.

psycodict.base.column_type_sql(typ)[source]

The SQL fragment for a column type, validated by validate_column_type().

INPUT:

  • typ – a string giving a PostgreSQL column type

OUTPUT:

A psycopg.sql.SQL fragment naming the type, ready to be interpolated into a CREATE TABLE or ALTER TABLE statement.

psycodict.base.jsonb_idx(cols, cols_type)[source]

The positions in cols whose type is jsonb, as a tuple of indexes. Used to decide which values need json decoding when reading rows of the meta_* tables.

INPUT:

  • cols – a list of column names

  • cols_type – a dictionary mapping column names to their types

class psycodict.base.PostgresBase(loggername, db)[source]

Bases: object

A base class for various objects that interact with Postgres.

Any class inheriting from this one must provide a connection to the postgres database, as well as a name used when creating a logger.