Reference

postgresql

py-postgresql is a Python package for using PostgreSQL. This includes low-level protocol tools, a driver(PG-API and DB-API), and cluster management tools.

If it’s not documented in the narratives, postgresql.documentation.index, then the stability of the APIs should not be trusted.

See <http://postgresql.org> for more information about PostgreSQL.

postgresql.version = '1.1.0'

The version string of py-postgresql.

postgresql.version_info = (1, 1, 0)

The version triple of py-postgresql: (major, minor, patch).

postgresql.open(iri=None, prompt_title=None, **kw)[source]

Create a postgresql.api.Connection to the server referenced by the given iri:

>>> import postgresql
# General Format:
>>> db = postgresql.open('pq://user:password@host:port/database')

# Connect to 'postgres' at localhost.
>>> db = postgresql.open('localhost/postgres')

Connection keywords can also be used with open. See the narratives for more information.

The prompt_title keyword is ignored. open will never prompt for the password unless it is explicitly instructed to do so.

(Note: “pq” is the name of the protocol used to communicate with PostgreSQL)

postgresql.api

Application Programmer Interfaces for PostgreSQL.

postgresql.api is a collection of Python APIs for the PostgreSQL DBMS. It is designed to take full advantage of PostgreSQL’s features to provide the Python programmer with substantial convenience.

This module is used to define “PG-API”. It creates a set of ABCs that makes up the basic interfaces used to work with a PostgreSQL server.

class postgresql.api.Message[source]

Bases: postgresql.python.element.Element

A message emitted by PostgreSQL. A message being a NOTICE, WARNING, INFO, etc.

code[source]

The SQL state code of the message.

details[source]

The additional details given with the message. Common keys should be the following:

  • ‘severity’
  • ‘context’
  • ‘detail’
  • ‘hint’
  • ‘file’
  • ‘line’
  • ‘function’
  • ‘position’
  • ‘internal_position’
  • ‘internal_query’
isconsistent(other)[source]

Whether the fields of the other Message object is consistent with the fields of self.

This must return the result of the comparison of code, source, message, and details.

This method is provided as the alternative to overriding equality; often, pointer equality is the desirable means for comparison, but equality of the fields is also necessary.

message[source]

The primary message string.

source[source]

Where the message originated from. Normally, ‘SERVER’, but sometimes ‘CLIENT’.

class postgresql.api.Statement[source]

Bases: postgresql.python.element.Element, collections.abc.Callable, collections.abc.Iterable

Instances of Statement are returned by the prepare method of Database instances.

A Statement is an Iterable as well as Callable.

The Iterable interface is supported for queries that take no arguments at all. It allows the syntax:

>>> for x in db.prepare('select * FROM table'):
...  pass
clone()[source]

Create a new statement object using the same factors as self.

When used for refreshing plans, the new clone should replace references to the original.

close()[source]

Close the prepared statement releasing resources associated with it.

column_names[source]

The attribute names of the columns produced by the statement.

A sequence of str objects stating the column name:

['column1', 'column2', 'emp_name']
column_types[source]

The Python types of the columns produced by the statement.

A sequence of type objects:

[<class 'int'>, <class 'str'>]
parameter_types[source]

The Python types expected of parameters given to the statement.

A sequence of type objects:

[<class 'int'>, <class 'str'>]
pg_column_types[source]

The type Oids of the columns produced by the statement.

A sequence of int objects stating the SQL type name:

[27, 28]
pg_parameter_types[source]

The type Oids of the parameters required by the statement.

A sequence of int objects stating the PostgreSQL type Oid:

[27, 28]
sql_column_types[source]

The type of the columns produced by the statement.

A sequence of str objects stating the SQL type name:

['INTEGER', 'VARCHAR', 'INTERVAL']
sql_parameter_types[source]

The type of the parameters required by the statement.

A sequence of str objects stating the SQL type name:

['INTEGER', 'VARCHAR', 'INTERVAL']
statement_id[source]

The statment’s identifier.

string[source]

The SQL string of the prepared statement.

None if not available. This can happen in cases where a statement is prepared on the server and a reference to the statement is sent to the client which subsequently uses the statement via the Database‘s statement constructor.

class postgresql.api.Cursor[source]

Bases: postgresql.api.Result, collections.abc.Iterator, collections.abc.Iterable

A Cursor object is an interface to a sequence of tuples(rows). A result set. Cursors publish a file-like interface for reading tuples from a cursor declared on the database.

Cursor objects are created by invoking the Statement.declare method or by opening a cursor using an identifier via the Database.cursor_from_id method.

clone()[source]

Create a new cursor using the same factors as self.

direction[source]

The default direction argument for read().

When True reads are FORWARD. When False reads are BACKWARD.

Cursor operation option.

read(quantity=None, direction=None)[source]

Read, fetch, the specified number of rows and return them in a list. If quantity is None, all records will be fetched.

direction can be used to override the default configured direction.

This alters the cursor’s position.

Read does not directly correlate to FETCH. If zero is given as the quantity, an empty sequence must be returned.

seek(offset, whence='ABSOLUTE')[source]

Set the cursor’s position to the given offset with respect to the whence parameter and the configured direction.

Whence values:

0 or "ABSOLUTE"
Absolute.
1 or "RELATIVE"
Relative.
2 or "FROM_END"
Absolute from end.
3 or "FORWARD"
Relative forward.
4 or "BACKWARD"
Relative backward.

Direction effects whence. If direction is BACKWARD, ABSOLUTE positioning will effectively be FROM_END, RELATIVE’s position will be negated, and FROM_END will effectively be ABSOLUTE.

class postgresql.api.Connector(user=None, password=None, database=None, settings=None, category=None)[source]

Bases: postgresql.python.element.Element

A connector is an object providing the necessary information to establish a connection. This includes credentials, database settings, and many times addressing information.

class postgresql.api.Category[source]

Bases: postgresql.python.element.Element

A category is an object that initializes the subject connection for a specific purpose.

Arguably, a runtime class for use with connections.

class postgresql.api.Database[source]

Bases: postgresql.python.element.Element

The interface to an individual database. Connection objects inherit from this

backend_id[source]

The backend’s process identifier.

client_address[source]

The client address that the server sees. This is obtainable by querying the pg_catalog.pg_stat_activity relation.

None if unavailable.

client_port[source]

The client port that the server sees. This is obtainable by querying the pg_catalog.pg_stat_activity relation.

None if unavailable.

cursor_from_id(cursor_id)[source]

Create a Cursor object from the given cursor_id that was already declared on the server.

Cursor objects created this way must not be closed when the object is garbage collected. Rather, the user must explicitly close it for the server resources to be released. This is in contrast to Cursor objects that are created by invoking a Statement or a SRF StoredProcedure.

do(language, source)[source]

Execute a DO statement using the given language and source. Always returns None.

Likely to be a function of Connection.execute.

execute(sql)[source]

Execute an arbitrary block of SQL. Always returns None and raise an exception on error.

iternotifies(timeout=None)[source]

Return an iterator to the notifications received by the connection. The iterator must produce triples in the form (channel, payload, pid).

If timeout is not None, None must be emitted at the specified timeout interval. If the timeout is zero, all the pending notifications must be yielded by the iterator and then StopIteration must be raised.

If the connection is closed for any reason, the iterator must silently stop by raising StopIteration. Further error control is then the responsibility of the user.

listen(*channels)[source]

Start listening to the given channels.

Equivalent to issuing “LISTEN <x>” for x in channels.

listening_channels()[source]

Return an iterator to all the channels currently being listened to.

notify(*channels, **channel_and_payload)[source]

NOTIFY the channels with the given payload.

Equivalent to issuing “NOTIFY <channel>” or “NOTIFY <channel>, <payload>” for each item in channels and channel_and_payload. All NOTIFYs issued must occur in the same transaction.

The items in channels can either be a string or a tuple. If a string, no payload is given, but if an item is a builtins.tuple, the second item will be given as the payload. channels offers a means to issue NOTIFYs in guaranteed order.

The items in channel_and_payload are all payloaded NOTIFYs where the keys are the channels and the values are the payloads. Order is undefined.

prepare(sql)[source]

Create a new Statement instance bound to the connection using the given SQL.

>>> s = db.prepare("SELECT 1")
>>> c = s()
>>> c.next()
(1,)
proc(procedure_id)[source]

Create a StoredProcedure instance using the given identifier.

The proc_id given can be either an Oid, or a regprocedure that identifies the stored procedure to create the interface for.

>>> p = db.proc('version()')
>>> p()
'PostgreSQL 8.3.0'
>>> qstr = "select oid from pg_proc where proname = 'generate_series'"
>>> db.prepare(qstr).first()
1069
>>> generate_series = db.proc(1069)
>>> list(generate_series(1,5))
[1, 2, 3, 4, 5]
reset()[source]

Reset the connection into it’s original state.

Issues a RESET ALL to the database. If the database supports removing temporary tables created in the session, then remove them. Reapply initial configuration settings such as path.

The purpose behind this method is to provide a soft-reconnect method that re-initializes the connection into its original state. One obvious use of this would be in a connection pool where the connection is being recycled.

settings[source]

A Settings instance bound to the Database.

statement_from_id(statement_id)[source]

Create a Statement object that was already prepared on the server. The distinction between this and a regular query is that it must be explicitly closed if it is no longer desired, and it is instantiated using the statement identifier as opposed to the SQL statement itself.

unlisten(*channels)[source]

Stop listening to the given channels.

Equivalent to issuing “UNLISTEN <x>” for x in channels.

version_info[source]

A version tuple of the database software similar Python’s sys.version_info.

>>> db.version_info
(8, 1, 3, '', 0)
xact[source]

Create a Transaction object using the given keyword arguments as its configuration.

class postgresql.api.Connection[source]

Bases: postgresql.api.Database

The interface to a connection to a PostgreSQL database. This is a Database interface with the additional connection management tools that are particular to using a remote database.

clone()[source]

Create another connection using the same factors as self. The returned object should be open and ready for use.

close()[source]

Close the connection.

Does nothing if the connection is already closed.

closed[source]

True if the Connection is closed, False if the Connection is open.

>>> db.closed
True
connect()[source]

Establish the connection to the server and initialize the category.

Does nothing if the connection is already established.

connector[source]

The Connector instance facilitating the Connection object’s communication and initialization.

query[source]

The Execution instance providing a one-shot query interface:

connection.query.<method>(sql, *parameters) == connection.prepare(sql).<method>(*parameters)
class postgresql.api.Transaction[source]

Bases: postgresql.python.element.Element

A Tranaction is an element that represents a transaction in the session. Once created, it’s ready to be started, and subsequently committed or rolled back.

Read-only transaction:

>>> with db.xact(mode = 'read only'):
...  ...

Read committed isolation:

>>> with db.xact(isolation = 'READ COMMITTED'):
...  ...

Savepoints are created if inside a transaction block:

>>> with db.xact():
...  with db.xact():
...   ...
abort()

Abort the transaction.

If the transaction is a savepoint, ROLLBACK TO the savepoint identifier.

If the transaction is a transaction block, issue an ABORT.

If the transaction has already been aborted, do nothing.

begin()

Start the transaction.

If the database is in a transaction block, the transaction should be configured as a savepoint. If any transaction block configuration was applied to the transaction, raise a postgresql.exceptions.OperationError.

If the database is not in a transaction block, start one using the configuration where:

self.isolation specifies the ISOLATION LEVEL. Normally, READ COMMITTED, SERIALIZABLE, or READ UNCOMMITTED.

self.mode specifies the mode of the transaction. Normally, READ ONLY or READ WRITE.

If the transaction is already open, do nothing.

If the transaction has been committed or aborted, raise an postgresql.exceptions.OperationError.

commit()[source]

Commit the transaction.

If the transaction is a block, issue a COMMIT statement.

If the transaction was started inside a transaction block, it should be identified as a savepoint, and the savepoint should be released.

If the transaction has already been committed, do nothing.

isolation[source]

The isolation level of the transaction block:

START TRANSACTION <isolation> [MODE];

The isolation property is a string and will be directly interpolated into the START TRANSACTION statement.

mode[source]

The mode of the transaction block:

START TRANSACTION [ISOLATION] <mode>;

The mode property is a string and will be directly interpolated into the START TRANSACTION statement.

rollback()[source]

Abort the transaction.

If the transaction is a savepoint, ROLLBACK TO the savepoint identifier.

If the transaction is a transaction block, issue an ABORT.

If the transaction has already been aborted, do nothing.

start()[source]

Start the transaction.

If the database is in a transaction block, the transaction should be configured as a savepoint. If any transaction block configuration was applied to the transaction, raise a postgresql.exceptions.OperationError.

If the database is not in a transaction block, start one using the configuration where:

self.isolation specifies the ISOLATION LEVEL. Normally, READ COMMITTED, SERIALIZABLE, or READ UNCOMMITTED.

self.mode specifies the mode of the transaction. Normally, READ ONLY or READ WRITE.

If the transaction is already open, do nothing.

If the transaction has been committed or aborted, raise an postgresql.exceptions.OperationError.

class postgresql.api.Settings[source]

Bases: postgresql.python.element.Element, collections.abc.MutableMapping

A mapping interface to the session’s settings. This provides a direct interface to SHOW or SET commands. Identifiers and values need not be quoted specially as the implementation must do that work for the user.

get(key, default=None)[source]

Get the setting with the corresponding key. If the setting does not exist, return the default.

getset(keys)[source]

Return a dictionary containing the key-value pairs of the requested settings. If any of the keys do not exist, a KeyError must be raised with the set of keys that did not exist.

items()[source]

Return an iterator to all of the setting value pairs.

keys()[source]

Return an iterator to all of the settings’ keys.

update(mapping)[source]

For each key-value pair, incur the effect of the __setitem__ method.

values()[source]

Return an iterator to all of the settings’ values.

class postgresql.api.StoredProcedure[source]

Bases: postgresql.python.element.Element, collections.abc.Callable

A function stored on the database.

class postgresql.api.Driver[source]

Bases: postgresql.python.element.Element

The Driver element provides the Connector and other information pertaining to the implementation of the driver. Information about what the driver supports is available in instances.

connect(**kw)[source]

Create a connection using the given parameters for the Connector.

class postgresql.api.Installation[source]

Bases: postgresql.python.element.Element

Interface to a PostgreSQL installation. Instances would provide various information about an installation of PostgreSQL accessible by the Python

ssl[source]

Whether the installation supports SSL.

type[source]

The “type” of PostgreSQL. Normally, the first component of the string returned by pg_config.

version[source]

A version string consistent with what SELECT version() would output.

version_info[source]

A tuple specifying the version in a form similar to Python’s sys.version_info. (8, 3, 3, ‘final’, 0)

See postgresql.versionstring.

class postgresql.api.Cluster[source]

Bases: postgresql.python.element.Element

Interface to a PostgreSQL cluster–a data directory. An implementation of this provides a means to control a server.

data_directory[source]

The path to the data directory of the cluster.

drop()[source]

Kill the server and completely remove the data directory.

init(initdb=None, user=None, password=None, encoding=None, locale=None, collate=None, ctype=None, monetary=None, numeric=None, time=None, text_search_config=None, xlogdir=None)[source]

Create the cluster at the data_directory associated with the Cluster instance.

installation[source]

The installation used by the cluster.

kill()[source]

Kill the server.

restart()[source]

Restart the cluster.

settings[source]

A Settings interface to the postgresql.conf file associated with the cluster.

start()[source]

Start the cluster.

stop()[source]

Signal the server to shutdown.

wait_until_started(timeout=10)[source]

After the start() method is ran, the database may not be ready for use. This method provides a mechanism to block until the cluster is ready for use.

If the timeout is reached, the method must throw a postgresql.exceptions.ClusterTimeoutError.

wait_until_stopped(timeout=10)[source]

After the stop() method is ran, the database may still be running. This method provides a mechanism to block until the cluster is completely shutdown.

If the timeout is reached, the method must throw a postgresql.exceptions.ClusterTimeoutError.

postgresql.sys

py-postgresql system functions and data.

Data

libpath
The local file system paths that contain query libraries.

Overridable Functions

excformat
Information that makes up an exception’s displayed “body”. Effectively, the implementation of postgresql.exception.Error.__str__
msghook
Display a message.
postgresql.sys.default_errformat(val)[source]

Built-in error formatter. DON’T TOUCH!

postgresql.sys.default_msghook(msg, format_message=<function format_element at 0x105d11f80>)[source]

Built-in message hook. DON’T TOUCH!

postgresql.sys.errformat(*args, **kw)[source]

Raised Database Error formatter pointing to default_excformat.

Override if you like. All postgresql.exceptions.Error’s are formatted using this function.

postgresql.sys.msghook(*args, **kw)[source]

Message hook pointing to default_msghook.

Override if you like. All untrapped messages raised by driver connections come here to be printed to stderr.

postgresql.sys.reset_errformat(with_func=<function errformat at 0x105957ef0>)[source]

restore the original excformat function

postgresql.sys.reset_msghook(with_func=<function msghook at 0x105957830>)[source]

restore the original msghook function

postgresql.string

String split and join operations for dealing with literals and identifiers.

Notably, the functions in this module are intended to be used for simple use-cases. It attempts to stay away from “real” parsing and simply provides functions for common needs, like the ability to identify unquoted portions of a query string so that logic or transformations can be applied to only unquoted portions. Scanning for statement terminators, or safely interpolating identifiers.

All functions deal with strict quoting rules.

postgresql.string.escape_ident(text)[source]

Replace every instance of ” with “”

postgresql.string.escape_literal(text)[source]

Replace every instance of ‘ with ‘’

postgresql.string.qname(*args)[source]

Quote the identifiers and join them using ‘.’

postgresql.string.quote_ident(text)[source]

Replace every instance of ‘ with and place ‘ on each end

postgresql.string.quote_ident_if_needed(text)[source]

If needed, replace every instance of ‘”’ with ‘”“’ and place ‘”’ on each end. Otherwise, just return the text.

postgresql.string.quote_literal(text)[source]

Escape the literal and wrap it in [single] quotations

postgresql.string.split(text)[source]

split the string up by into non-quoted and quoted portions. Zero and even numbered indexes are unquoted portions, while odd indexes are quoted portions.

Unquoted portions are regular strings, whereas quoted portions are pair-tuples specifying the quotation mechanism and the content thereof.

>>> list(split("select $$foobar$$"))
['select ', ('$$', 'foobar'), '']

If the split ends on a quoted section, it means the string’s quote was not terminated. Subsequently, there will be an even number of objects in the list.

Quotation errors are detected, but never raised. Rather it’s up to the user to identify the best course of action for the given split.

postgresql.string.split_ident(text, sep=', ', quote='"', maxsplit=-1)[source]

Split a series of identifiers using the specified separator.

postgresql.string.split_qname(text, maxsplit=-1)[source]

Call to .split_ident() with a ‘.’ sep parameter.

postgresql.string.split_sql(sql, sep=';')[source]

Given SQL, safely split using the given separator. Notably, this yields fully split text. This should be used instead of split_sql_str() when quoted sections need be still be isolated.

>>> list(split_sql('select $$1$$ AS "foo;"; select 2;'))
[['select ', ('$$', '1'), ' AS ', ('"', 'foo;'), ''], (' select 2',), ['']]
postgresql.string.split_sql_str(sql, sep=';')[source]

Identical to split_sql but yields unsplit text.

>>> list(split_sql_str('select $$1$$ AS "foo;"; select 2;'))
['select $$1$$ AS "foo;"', ' select 2', '']
postgresql.string.split_using(text, quote, sep='.', maxsplit=-1)[source]

split the string on the seperator ignoring the separator in quoted areas.

This is only useful for simple quoted strings. Dollar quotes, and backslash escapes are not supported.

postgresql.string.unsplit(splitted_iter)[source]

catenate a split string. This is needed to handle the special cases created by pg.string.split(). (Run-away quotations, primarily)

postgresql.exceptions

PostgreSQL exceptions and warnings with associated state codes.

The primary entry points of this module is the ErrorLookup function and the WarningLookup function. Given an SQL state code, they give back the most appropriate Error or Warning subclass.

For more information on error codes see:
http://www.postgresql.org/docs/current/static/errcodes-appendix.html

This module is executable via -m: python -m postgresql.exceptions. It provides a convenient way to look up the exception object mapped to by the given error code:

$ python -m postgresql.exceptions XX000
postgresql.exceptions.InternalError [XX000]

If the exact error code is not found, it will try to find the error class’s exception(The first two characters of the error code make up the class identity):

$ python -m postgresql.exceptions XX400
postgresql.exceptions.InternalError [XX000]

If that fails, it will return postgresql.exceptions.Error

exception postgresql.exceptions.AuthenticationMethodError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.DriverError, postgresql.exceptions.Disconnection

Server requested an authentication method that is not supported by the driver.

exception postgresql.exceptions.CFError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.Error

Configuration File Error

exception postgresql.exceptions.CardinalityError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.Error

Wrong number of rows returned

exception postgresql.exceptions.ClientCannotConnectError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.ConnectionError

Client was unable to establish a connection to the server.

exception postgresql.exceptions.ConnectTimeoutError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.DriverError, postgresql.exceptions.Disconnection

Client was unable to esablish a connection in the given time

exception postgresql.exceptions.ConnectionDoesNotExistError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.ConnectionError

The connection is closed or was never connected.

exception postgresql.exceptions.ConnectionFailureError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.ConnectionError

Raised when a connection is dropped

exception postgresql.exceptions.DPDSEError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.Error

Dependent Privilege Descriptors Still Exist

exception postgresql.exceptions.Disconnection[source]

Bases: postgresql.exceptions.Exception

Exception identifying errors that result in disconnection

exception postgresql.exceptions.DriverError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.Error

Errors originating in the driver’s implementation.

exception postgresql.exceptions.EREError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.Error

External Routine Exception

exception postgresql.exceptions.ERIEError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.Error

External Routine Invocation Exception

exception postgresql.exceptions.Error(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.message.Message, postgresql.exceptions.Exception

A PostgreSQL Error

exception postgresql.exceptions.EscapeCharacterError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.DataError

Invalid escape character

exception postgresql.exceptions.Exception[source]

Bases: builtins.Exception

Base PostgreSQL exception class

exception postgresql.exceptions.FeatureError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.Error

Unsupported feature

exception postgresql.exceptions.ICVError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.Error

Integrity Contraint Violation

exception postgresql.exceptions.IRError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.Error

Insufficient Resource Error

exception postgresql.exceptions.ITSError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.TransactionError

Invalid Transaction State

class postgresql.exceptions.IgnoredClientParameterWarning(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.DriverWarning

Warn the user of a valid, but ignored parameter.

exception postgresql.exceptions.InFailedTransactionError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.ITSError

Occurs when an action occurs in a failed transaction.

exception postgresql.exceptions.InconsistentCursorIsolationError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.ITSError

The held cursor requires the same isolation.

exception postgresql.exceptions.InsecurityError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.DriverError, postgresql.exceptions.Disconnection

Error signifying a secure channel to a server cannot be established.

exception postgresql.exceptions.LoadError[source]

Bases: postgresql.exceptions.Exception

Failed to load a library

exception postgresql.exceptions.OIError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.Error

Operator Intervention

exception postgresql.exceptions.ONIPSError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.Error

Object Not In Prerequisite State

exception postgresql.exceptions.OperationError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.DriverError

An invalid operation on an interface element.

exception postgresql.exceptions.PLEError[source]

Bases: builtins.OverflowError

Program Limit Exceeded

exception postgresql.exceptions.PLPGSQLError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.Error

Error raised by a PL/PgSQL procedural function

exception postgresql.exceptions.PLPGSQLRaiseError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.PLPGSQLError

Error raised by a PL/PgSQL RAISE statement.

exception postgresql.exceptions.ReadOnlyTransactionError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.ITSError

Occurs when an alteration occurs in a read-only transaction.

exception postgresql.exceptions.SEARVError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.Error

Syntax Error or Access Rule Violation

exception postgresql.exceptions.SIOError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.Error

System I/O

exception postgresql.exceptions.SREError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.Error

SQL Routine Exception

exception postgresql.exceptions.SavepointError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.TransactionError

Classification error designating errors that relate to savepoints.

exception postgresql.exceptions.SchemaAndDataStatementsError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.ITSError

Mixed schema and data statements not allowed.

exception postgresql.exceptions.ServerNotReadyError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.OIError, postgresql.exceptions.Disconnection

Thrown when a connection is established to a server that is still starting up.

exception postgresql.exceptions.TRError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.TransactionError

Transaction Rollback

class postgresql.exceptions.TypeConversionWarning(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.DriverWarning

Report a potential issue with a conversion.

exception postgresql.exceptions.TypeIOError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.DriverError

Driver failed to pack or unpack a tuple.

postgresql.exceptions.map_errors_and_warnings(objs, error_container={'': <class 'postgresql.exceptions.Error'>, '44000': <class 'postgresql.exceptions.WithCheckOptionError'>, '42611': <class 'postgresql.exceptions.ColumnDefinitionError'>, '42622': <class 'postgresql.exceptions.NameTooLongError'>, '42830': <class 'postgresql.exceptions.ForeignKeyCreationError'>, '40P01': <class 'postgresql.exceptions.DeadlockError'>, '0P000': <class 'postgresql.exceptions.RoleSpecificationError'>, '53000': <class 'postgresql.exceptions.IRError'>, 'XX001': <class 'postgresql.exceptions.DataCorruptedError'>, 'XX000': <class 'postgresql.exceptions.InternalError'>, 'XX002': <class 'postgresql.exceptions.IndexCorruptedError'>, '2BP01': <class 'postgresql.exceptions.DPDSEObjectError'>, '42701': <class 'postgresql.exceptions.DuplicateColumnError'>, '--TOE': <class 'postgresql.exceptions.ConnectTimeoutError'>, '42702': <class 'postgresql.exceptions.AmbiguousColumnError'>, '57000': <class 'postgresql.exceptions.OIError'>, '22020': <class 'postgresql.exceptions.LimitValueError'>, '23000': <class 'postgresql.exceptions.ICVError'>, '42704': <class 'postgresql.exceptions.UndefinedObjectError'>, '42P20': <class 'postgresql.exceptions.WindowError'>, 'F0001': <class 'postgresql.exceptions.LockFileExistsError'>, 'F0000': <class 'postgresql.exceptions.CFError'>, '2201F': <class 'postgresql.exceptions.PowerFunctionArgumentError'>, '27000': <class 'postgresql.exceptions.TriggeredDataChangeViolation'>, '42846': <class 'postgresql.exceptions.CoercionError'>, '53200': <class 'postgresql.exceptions.MemoryError'>, '26000': <class 'postgresql.exceptions.StatementNameError'>, '34000': <class 'postgresql.exceptions.CursorNameError'>, '39P01': <class 'postgresql.exceptions.TriggerProtocolError'>, '0L000': <class 'postgresql.exceptions.GrantorError'>, '--000': <class 'postgresql.exceptions.DriverError'>, '0F001': <class 'postgresql.exceptions.LocatorSpecificationError'>, '0F000': <class 'postgresql.exceptions.LocatorError'>, '42601': <class 'postgresql.exceptions.SyntaxError'>, '42602': <class 'postgresql.exceptions.SEARVNameError'>, '42P13': <class 'postgresql.exceptions.FunctionDefinitionError'>, '--cIO': <class 'postgresql.exceptions.CompositeError'>, '53100': <class 'postgresql.exceptions.DiskFullError'>, '25004': <class 'postgresql.exceptions.BadIsolationForBranchError'>, '25005': <class 'postgresql.exceptions.NoActiveTransactionForBranchError'>, '25006': <class 'postgresql.exceptions.ReadOnlyTransactionError'>, '25007': <class 'postgresql.exceptions.SchemaAndDataStatementsError'>, '25000': <class 'postgresql.exceptions.ITSError'>, '25001': <class 'postgresql.exceptions.ActiveTransactionError'>, '25002': <class 'postgresql.exceptions.BranchAlreadyActiveError'>, '25003': <class 'postgresql.exceptions.BadAccessModeForBranchError'>, '--TIO': <class 'postgresql.exceptions.TypeIOError'>, '22015': <class 'postgresql.exceptions.IntervalFieldOverflowError'>, '--PIO': <class 'postgresql.exceptions.ParameterError'>, '55P03': <class 'postgresql.exceptions.UnavailableLockError'>, '55P02': <class 'postgresql.exceptions.ImmutableRuntimeParameterError'>, '22011': <class 'postgresql.exceptions.SubstringError'>, '40001': <class 'postgresql.exceptions.SerializationError'>, '40000': <class 'postgresql.exceptions.TRError'>, '40003': <class 'postgresql.exceptions.StatementCompletionUnknownError'>, '40002': <class 'postgresql.exceptions.IntegrityConstraintViolationError'>, '2F005': <class 'postgresql.exceptions.FunctionExecutedNoReturnStatementError'>, '2F004': <class 'postgresql.exceptions.ReadingDataProhibitedError'>, '2F000': <class 'postgresql.exceptions.SREError'>, '2F003': <class 'postgresql.exceptions.StatementProhibitedError'>, '2F002': <class 'postgresql.exceptions.DataModificationProhibitedError'>, '21000': <class 'postgresql.exceptions.CardinalityError'>, '42P04': <class 'postgresql.exceptions.DuplicateDatabaseError'>, '42501': <class 'postgresql.exceptions.InsufficientPrivilegeError'>, '42P02': <class 'postgresql.exceptions.UndefinedParameterError'>, '08001': <class 'postgresql.exceptions.ClientCannotConnectError'>, '08000': <class 'postgresql.exceptions.ConnectionError'>, '08003': <class 'postgresql.exceptions.ConnectionDoesNotExistError'>, '08004': <class 'postgresql.exceptions.ConnectionRejectionError'>, '08007': <class 'postgresql.exceptions.TransactionResolutionUnknownError'>, '08006': <class 'postgresql.exceptions.ConnectionFailureError'>, '22023': <class 'postgresql.exceptions.ParameterValueError'>, '22022': <class 'postgresql.exceptions.IndicatorOverflowError'>, '22021': <class 'postgresql.exceptions.EncodingError'>, '42703': <class 'postgresql.exceptions.UndefinedColumnError'>, '22027': <class 'postgresql.exceptions.TrimError'>, '22026': <class 'postgresql.exceptions.StringDataLengthError'>, '22025': <class 'postgresql.exceptions.EscapeSequenceError'>, '22024': <class 'postgresql.exceptions.UnterminatedCStringError'>, '42P14': <class 'postgresql.exceptions.PreparedStatementDefinitionError'>, '42P15': <class 'postgresql.exceptions.SchemaDefinitionError'>, '42P16': <class 'postgresql.exceptions.TableDefinitionError'>, '42P17': <class 'postgresql.exceptions.ObjectDefinitionError'>, '42P10': <class 'postgresql.exceptions.ColumnReferenceError'>, '42P11': <class 'postgresql.exceptions.CursorDefinitionError'>, '42P12': <class 'postgresql.exceptions.DatabaseDefinitionError'>, '--OPE': <class 'postgresql.exceptions.OperationError'>, '58000': <class 'postgresql.exceptions.SIOError'>, '42939': <class 'postgresql.exceptions.ReservedNameError'>, '42P18': <class 'postgresql.exceptions.IndeterminateTypeError'>, '42P19': <class 'postgresql.exceptions.RecursionError'>, '08P01': <class 'postgresql.exceptions.ProtocolError'>, '09000': <class 'postgresql.exceptions.TriggeredActionError'>, '--SEC': <class 'postgresql.exceptions.InsecurityError'>, '24000': <class 'postgresql.exceptions.CursorStateError'>, '23503': <class 'postgresql.exceptions.ForeignKeyError'>, '23502': <class 'postgresql.exceptions.NotNullError'>, '55000': <class 'postgresql.exceptions.ONIPSError'>, '55006': <class 'postgresql.exceptions.ObjectInUseError'>, '23505': <class 'postgresql.exceptions.UniqueError'>, '42809': <class 'postgresql.exceptions.WrongObjectTypeError'>, '2D000': <class 'postgresql.exceptions.TransactionTerminationError'>, '42804': <class 'postgresql.exceptions.TypeMismatchError'>, '42803': <class 'postgresql.exceptions.GroupingError'>, '2200S': <class 'postgresql.exceptions.XMLCommentError'>, 'P0001': <class 'postgresql.exceptions.PLPGSQLRaiseError'>, 'P0000': <class 'postgresql.exceptions.PLPGSQLError'>, 'P0003': <class 'postgresql.exceptions.PLPGSQLTooManyRowsError'>, 'P0002': <class 'postgresql.exceptions.PLPGSQLNoDataFoundError'>, '2200T': <class 'postgresql.exceptions.XMLProcessingInstructionError'>, '42883': <class 'postgresql.exceptions.UndefinedFunctionError'>, '2B000': <class 'postgresql.exceptions.DPDSEError'>, '03000': <class 'postgresql.exceptions.SQLNotYetCompleteError'>, '28000': <class 'postgresql.exceptions.AuthenticationSpecificationError'>, '53300': <class 'postgresql.exceptions.TooManyConnectionsError'>, '20000': <class 'postgresql.exceptions.CaseNotFoundError'>, '23514': <class 'postgresql.exceptions.CheckError'>, '2202E': <class 'postgresql.exceptions.ArrayElementError'>, '22001': <class 'postgresql.exceptions.StringRightTruncationError'>, '22000': <class 'postgresql.exceptions.DataError'>, '22003': <class 'postgresql.exceptions.NumericRangeError'>, '22002': <class 'postgresql.exceptions.NullValueNoIndicatorParameter'>, '22005': <class 'postgresql.exceptions.AssignmentError'>, '22004': <class 'postgresql.exceptions.NullValueNotAllowedError'>, '22007': <class 'postgresql.exceptions.DateTimeFormatError'>, '22009': <class 'postgresql.exceptions.TimeZoneDisplacementValueError'>, '22008': <class 'postgresql.exceptions.DateTimeFieldOverflowError'>, '57014': <class 'postgresql.exceptions.QueryCanceledError'>, '42725': <class 'postgresql.exceptions.AmbiguousFunctionError'>, '0LP01': <class 'postgresql.exceptions.GrantorOperationError'>, '42723': <class 'postgresql.exceptions.DuplicateFunctionError'>, '38002': <class 'postgresql.exceptions.ModifyingSQLDataNotPermittedError'>, '38003': <class 'postgresql.exceptions.ProhibitedSQLStatementError'>, '38000': <class 'postgresql.exceptions.EREError'>, '38001': <class 'postgresql.exceptions.ContainingSQLNotPermittedError'>, '3B000': <class 'postgresql.exceptions.SavepointError'>, '3B001': <class 'postgresql.exceptions.InvalidSavepointSpecificationError'>, '38004': <class 'postgresql.exceptions.ReadingSQLDataNotPermittedError'>, '39004': <class 'postgresql.exceptions.NullValueNotAllowed'>, '39001': <class 'postgresql.exceptions.InvalidSQLState'>, '39000': <class 'postgresql.exceptions.ERIEError'>, '22P01': <class 'postgresql.exceptions.FloatingPointError'>, '22P03': <class 'postgresql.exceptions.BinaryRepresentationError'>, '22P02': <class 'postgresql.exceptions.TextRepresentationError'>, '22P05': <class 'postgresql.exceptions.UntranslatableCharacterError'>, '22P04': <class 'postgresql.exceptions.BadCopyError'>, '2201X': <class 'postgresql.exceptions.OffsetValueError'>, '23001': <class 'postgresql.exceptions.RestrictError'>, '2201W': <class 'postgresql.exceptions.LimitValueError'>, '0A000': <class 'postgresql.exceptions.FeatureError'>, '42000': <class 'postgresql.exceptions.SEARVError'>, '3F000': <class 'postgresql.exceptions.SchemaNameError'>, '2201G': <class 'postgresql.exceptions.WidthBucketFunctionArgumentError'>, '2201E': <class 'postgresql.exceptions.LogArgumentError'>, '2201B': <class 'postgresql.exceptions.RegularExpressionError'>, '39P02': <class 'postgresql.exceptions.SRFProtocolError'>, '3D000': <class 'postgresql.exceptions.CatalogNameError'>, '22018': <class 'postgresql.exceptions.CastCharacterValueError'>, '42712': <class 'postgresql.exceptions.DuplicateAliasError'>, '42710': <class 'postgresql.exceptions.DuplicateObjectError'>, '22012': <class 'postgresql.exceptions.ZeroDivisionError'>, '22010': <class 'postgresql.exceptions.IndicatorParameterValueError'>, '25P01': <class 'postgresql.exceptions.NoActiveTransactionError'>, '42P07': <class 'postgresql.exceptions.DuplicateTableError'>, '42P06': <class 'postgresql.exceptions.DuplicateSchemaError'>, '42P05': <class 'postgresql.exceptions.DuplicatePreparedStatementError'>, '0B000': <class 'postgresql.exceptions.TransactionInitiationError'>, '42P03': <class 'postgresql.exceptions.DuplicateCursorError'>, '25P02': <class 'postgresql.exceptions.InFailedTransactionError'>, '42P01': <class 'postgresql.exceptions.UndefinedTableError'>, '25008': <class 'postgresql.exceptions.InconsistentCursorIsolationError'>, '42P09': <class 'postgresql.exceptions.AmbiguousAliasError'>, '42P08': <class 'postgresql.exceptions.AmbiguousParameterError'>, '57P01': <class 'postgresql.exceptions.AdminShutdownError'>, '57P03': <class 'postgresql.exceptions.ServerNotReadyError'>, '57P02': <class 'postgresql.exceptions.CrashShutdownError'>, '58P01': <class 'postgresql.exceptions.UndefinedFileError'>, '58P02': <class 'postgresql.exceptions.DuplicateFileError'>, '22P06': <class 'postgresql.exceptions.NonstandardUseOfEscapeCharacterError'>, '2200L': <class 'postgresql.exceptions.NotXMLError'>, '2200C': <class 'postgresql.exceptions.EscapeCharacterError'>, '2200B': <class 'postgresql.exceptions.EscapeCharacterConflictError'>, '--CIO': <class 'postgresql.exceptions.ColumnError'>, '2200D': <class 'postgresql.exceptions.EscapeOctetError'>, '2200G': <class 'postgresql.exceptions.SpecificTypeMismatch'>, '2200F': <class 'postgresql.exceptions.ZeroLengthString'>, '2200M': <class 'postgresql.exceptions.XMLDocumentError'>, '--AUT': <class 'postgresql.exceptions.AuthenticationMethodError'>, '2200N': <class 'postgresql.exceptions.XMLContentError'>}, warning_container={'0100C': <class 'postgresql.exceptions.DynamicResultSetsReturnedWarning'>, '01-CP': <class 'postgresql.exceptions.IgnoredClientParameterWarning'>, '02001': <class 'postgresql.exceptions.NoMoreSetsReturned'>, '02000': <class 'postgresql.exceptions.NoDataWarning'>, '01008': <class 'postgresql.exceptions.ImplicitZeroBitPaddingWarning'>, '01-TP': <class 'postgresql.exceptions.TypeConversionWarning'>, '01006': <class 'postgresql.exceptions.PrivilegeNotRevokedWarning'>, '01007': <class 'postgresql.exceptions.PrivilegeNotGrantedWarning'>, '01004': <class 'postgresql.exceptions.StringDataRightTruncationWarning'>, '01-00': <class 'postgresql.exceptions.DriverWarning'>, '01003': <class 'postgresql.exceptions.NullValueEliminatedInSetFunctionWarning'>, '01000': <class 'postgresql.exceptions.Warning'>, '01P01': <class 'postgresql.exceptions.DeprecationWarning'>})[source]

Construct the code-to-error and code-to-warning associations.

postgresql.temporal

Temporary PostgreSQL cluster for the process.

class postgresql.temporal.Temporal[source]

Bases: builtins.object

Manages a temporary cluster for the duration of the process.

Instances of this class reference a distinct cluster. These clusters are transient; they will only exist until the process exits.

Usage:

>>> from postgresql.temporal import pg_tmp
>>> with pg_tmp:
...  ps = db.prepare('SELECT 1')
...  assert ps.first() == 1

Or pg_tmp can decorate a method or function.

cluster_dirname()

Format the cluster directory name.

postgresql.temporal.pg_tmp = <postgresql.temporal.Temporal object at 0x105fcef50>

The process’ temporary cluster.

postgresql.installation

Collect and access PostgreSQL installation information.

class postgresql.installation.Installation(info)[source]

Bases: postgresql.api.Installation

Class providing a Python interface to PostgreSQL installation information.

ssl[source]

Whether the installation was compiled with SSL support.

postgresql.installation.default(typ=<class 'postgresql.installation.Installation'>)[source]

Get the default Installation.

Uses default_pg_config() to identify the executable.

postgresql.installation.default_pg_config(execname='pg_config', envkey='PGINSTALLATION')[source]

Get the default pg_config executable on the system.

If ‘PGINSTALLATION’ is in the environment, use it. Otherwise, look through the system’s PATH environment.

postgresql.installation.pg_config_dictionary(*pg_config_path)[source]

Create a dictionary of the information available in the given pg_config_path. This provides a one-shot solution to fetching information from the pg_config binary. Returns a dictionary object.

postgresql.cluster

Create, control, and destroy PostgreSQL clusters.

postgresql.cluster provides a programmer’s interface to controlling a PostgreSQL cluster. It provides direct access to proper signalling interfaces.

class postgresql.cluster.Cluster(installation, data_directory)[source]

Bases: postgresql.api.Cluster

Interface to a PostgreSQL cluster.

Provides mechanisms to start, stop, restart, kill, drop, and initalize a cluster(data directory).

Cluster does not strive to be consistent with pg_ctl. This is considered to be a base class for managing a cluster, and is intended to be extended to accommodate for a particular purpose.

address()[source]

Get the host-port pair from the configuration.

connect(**kw)[source]

Create an established connection from the connector.

Cluster must be running.

connection(**kw)[source]

Create a connection object to the cluster, but do not connect.

connector(**kw)[source]

Create a postgresql.driver connector based on the given keywords and listen_addresses and port configuration in settings.

daemon_path[source]

Path to the executable to use to startup the cluster.

drop()[source]

Stop the cluster and remove it from the filesystem

get_pid_from_file()[source]

The current pid from the postmaster.pid file.

hba_file[source]

The path to the HBA file of the cluster.

init(password=None, **kw)[source]

Create the cluster at the given data_directory using the provided keyword parameters as options to the command.

command_option_map provides the mapping of keyword arguments to command options.

initialized()[source]

Whether or not the data directory appears to be a valid cluster.

kill()[source]

Stop the cluster immediately(SIGKILL).

Does not wait for shutdown.

pid[source]

If we have the subprocess, use the pid on the object.

ready_for_connections()[source]

If the daemon is running, and is not in startup mode.

This only works for clusters configured for TCP/IP connections.

reload()[source]

Signal the cluster to reload its configuration file.

restart(logfile=None, settings=None, timeout=10)[source]

Restart the cluster gracefully.

This provides a higher level interface to stopping then starting the cluster. It will perform the wait operations and block until the restart is complete.

If waiting is not desired, .start() and .stop() should be used directly.

running()[source]

Whether or not the postmaster is running.

This does not mean the cluster is accepting connections.

shutdown()[source]

Shutdown the cluster as soon as possible, disconnecting clients.

start(logfile=None, settings=None)[source]

Start the cluster.

stop()[source]

Stop the cluster gracefully waiting for clients to disconnect(SIGTERM).

wait_until_started(timeout=10, delay=0.05)[source]

After the start method is used, this can be ran in order to block until the cluster is ready for use.

This method loops until ready_for_connections returns True in order to make sure that the cluster is actually up.

wait_until_stopped(timeout=10, delay=0.05)[source]

After the stop method is used, this can be ran in order to block until the cluster is shutdown.

Additionally, catching ClusterTimeoutError exceptions would be a starting point for making decisions about whether or not to issue a kill to the daemon.

exception postgresql.cluster.ClusterError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.Error

General cluster error.

exception postgresql.cluster.ClusterInitializationError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.cluster.ClusterError

General cluster initialization failure

exception postgresql.cluster.ClusterNotRunningError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.cluster.ClusterError

Cluster is not running

exception postgresql.cluster.ClusterStartupError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.cluster.ClusterError

Cluster startup failed

exception postgresql.cluster.ClusterTimeoutError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.cluster.ClusterError

Cluster operation timed out

class postgresql.cluster.ClusterWarning(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.exceptions.Warning

Warning issued by cluster operations

exception postgresql.cluster.InitDBError(message, code=None, details={}, source=None, creator=None)[source]

Bases: postgresql.cluster.ClusterInitializationError

A non-zero result was returned by the initdb command

postgresql.copyman

Manage complex COPY operations; one-to-many COPY streaming.

Primarily this module houses the CopyManager class, and the transfer function for a high-level interface to using the CopyManager.

class postgresql.copyman.CallReceiver(callable)[source]

Bases: postgresql.copyman.Receiver

Call the given object with a list of COPY lines.

exception postgresql.copyman.CopyFail(manager, reason=None, receiver_faults=None, producer_fault=None)[source]

Bases: builtins.Exception

Exception thrown by the CopyManager when the COPY operation failed.

The ‘manager’ attribute the CopyManager that raised the CopyFail.

The ‘reason’ attribute is a string indicating why it failed.

The ‘receiver_faults’ attribute is a mapping of receivers to exceptions that were raised on exit.

The ‘producer_fault’ attribute specifies if the producer raise an exception on exit.

class postgresql.copyman.CopyManager(producer, *receivers)[source]

Bases: postgresql.python.element.Element, collections.abc.Iterator

A class for managing COPY operations.

Connects the producer to the receivers.

reconcile(r)[source]

Reconcile a receiver that faulted.

This method should be used to add back a receiver that failed to complete its write operation, but is capable of completing the operation at this time.

class postgresql.copyman.NullProducer[source]

Bases: postgresql.copyman.Producer

Produces no copy data.

exception postgresql.copyman.ProducerFault(manager)[source]

Bases: postgresql.copyman.Fault

Exception raised when the Producer caused an exception.

Normally, Producer faults are fatal.

class postgresql.copyman.ProtocolProducer(recv_into, buffer_size=10240)[source]

Bases: postgresql.copyman.Producer

Producer using a PQv3 data stream.

Normally, this class needs to be subclassed as it assumes that the given recv_into function will write COPY messages.

recover(view)[source]

Given a view containing data read from the wire, recover the controller’s state.

This needs to be implemented by subclasses in order for the ProtocolReceiver to pass control back to the original state machine.

exception postgresql.copyman.ReceiverFault(manager, faults)[source]

Bases: postgresql.copyman.Fault

Exception raised when Receivers cause an exception.

Faults should be trapped if recovery from an exception is possible, or if the failed receiver is optional to the succes of the operation.

The ‘manager’ attribute is the CopyManager that raised the fault.

The ‘faults’ attribute is a dictionary mapping the receiver to the exception instance raised.

class postgresql.copyman.WireState(condition=<method-wrapper '__ne__' of int object at 0x103d38990>)[source]

Bases: builtins.object

Manages the state of the wire.

This class manages three possible positions:

  1. Between wire messages
  2. Inside message header
  3. Inside message (with complete header)

The wire state will become unusable when the configured condition is True.

update(view, getlen=<function mk_pack.<locals>.unpack at 0x106053200>, len=<built-in function len>)[source]

Given the state of the COPY and new data, advance the position on the COPY stream.

postgresql.copyman.default_buffer_size = 10240

10KB buffer for COPY messages by default.

postgresql.copyman.transfer(producer, *receivers)[source]

Perform a COPY operation using the given statements:

>>> import copyman
>>> copyman.transfer(src.prepare("COPY table TO STDOUT"), dst.prepare("COPY table FROM STDIN"))
postgresql.copyman.ulong_pack()

S.pack(v1, v2, ...) -> bytes

Return a bytes object containing values v1, v2, ... packed according to the format string S.format. See help(struct) for more on format strings.

postgresql.alock

Tools for Advisory Locks

class postgresql.alock.ALock(database, *identifiers)[source]

Bases: postgresql.python.element.Element

Advisory Lock class for managing the acquisition and release of a sequence of PostgreSQL advisory locks.

ALock()’s are fairly consistent with threading.RLock()’s. They can be acquired multiple times, and they must be released the same number of times for the lock to actually be released.

A notably difference is that ALock’s manage a sequence of lock identifiers. This means that a given ALock() may represent multiple advisory locks.

acquire(blocking=True, len=<built-in function len>)[source]

Acquire the locks using the configured identifiers.

locked()[source]

Whether the locks have been acquired. This method is sensitive to the connection’s state. If the connection is closed, it will return False.

mode[source]

The mode of the lock class.

release()[source]

Release the locks using the configured identifiers.