### Navigation

- index
- modules |
- next |
- previous |
- py-postgresql 1.0.4 documentation »

# Modules

Modules intended for general use.

## `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.0.4'

  The version string of py-postgresql.

`postgresql.``version_info` = (1, 0, 4)

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

`postgresql.``open`(iri=None, prompt_title=None, **kw)

  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.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)

  Built-in error formatter. DON’T TOUCH!

`postgresql.sys.``default_msghook`(msg, format_message=<function format_element at 0x102bd4380>)

  Built-in message hook. DON’T TOUCH!

`postgresql.sys.``errformat`(*args, **kw)

  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)

  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 0x102bab2f8>)

  restore the original excformat function

`postgresql.sys.``reset_msghook`(with_func=<function msghook at 0x102bab408>)

  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)

  Replace every instance of ” with “”

`postgresql.string.``escape_literal`(text)

  Replace every instance of ‘ with ‘’

`postgresql.string.``qname`(*args)

  Quote the identifiers and join them using ‘.’

`postgresql.string.``quote_ident`(text)

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

`postgresql.string.``quote_ident_if_needed`(text)

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

`postgresql.string.``quote_literal`(text)

  Escape the literal and wrap it in [single] quotations

`postgresql.string.``split`(text)

  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)

  Split a series of identifiers using the specified separator.

`postgresql.string.``split_qname`(text, maxsplit=-1)

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

`postgresql.string.``split_sql`(sql, sep=';')

  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=';')

  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)

  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)

  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)

  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)

  Bases: `postgresql.exceptions.Error`

  Configuration File Error

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

  Bases: `postgresql.exceptions.Error`

  Wrong number of rows returned

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

  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)

  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)

  Bases: `postgresql.exceptions.ConnectionError`

  The connection is closed or was never connected.

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

  Bases: `postgresql.exceptions.ConnectionError`

  Raised when a connection is dropped

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

  Bases: `postgresql.exceptions.Error`

  Dependent Privilege Descriptors Still Exist

exception `postgresql.exceptions.``Disconnection`

  Bases: `postgresql.exceptions.Exception`

  Exception identifying errors that result in disconnection

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

  Bases: `postgresql.exceptions.Error`

  Errors originating in the driver’s implementation.

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

  Bases: `postgresql.exceptions.Error`

  External Routine Exception

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

  Bases: `postgresql.exceptions.Error`

  External Routine Invocation Exception

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

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

  A PostgreSQL Error

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

  Bases: `postgresql.exceptions.DataError`

  Invalid escape character

exception `postgresql.exceptions.``Exception`

  Bases: `builtins.Exception`

  Base PostgreSQL exception class

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

  Bases: `postgresql.exceptions.Error`

  Unsupported feature

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

  Bases: `postgresql.exceptions.Error`

  Integrity Contraint Violation

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

  Bases: `postgresql.exceptions.Error`

  Insufficient Resource Error

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

  Bases: `postgresql.exceptions.TransactionError`

  Invalid Transaction State

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

  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)

  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)

  Bases: `postgresql.exceptions.ITSError`

  The held cursor requires the same isolation.

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

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

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

exception `postgresql.exceptions.``LoadError`

  Bases: `postgresql.exceptions.Exception`

  Failed to load a library

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

  Bases: `postgresql.exceptions.Error`

  Operator Intervention

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

  Bases: `postgresql.exceptions.Error`

  Object Not In Prerequisite State

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

  Bases: `postgresql.exceptions.DriverError`

  An invalid operation on an interface element.

exception `postgresql.exceptions.``PLEError`

  Bases: `builtins.OverflowError`

  Program Limit Exceeded

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

  Bases: `postgresql.exceptions.Error`

  Error raised by a PL/PgSQL procedural function

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

  Bases: `postgresql.exceptions.PLPGSQLError`

  Error raised by a PL/PgSQL RAISE statement.

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

  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)

  Bases: `postgresql.exceptions.Error`

  Syntax Error or Access Rule Violation

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

  Bases: `postgresql.exceptions.Error`

  System I/O

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

  Bases: `postgresql.exceptions.Error`

  SQL Routine Exception

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

  Bases: `postgresql.exceptions.TransactionError`

  Classification error designating errors that relate to savepoints.

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

  Bases: `postgresql.exceptions.ITSError`

  Mixed schema and data statements not allowed.

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

  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)

  Bases: `postgresql.exceptions.TransactionError`

  Transaction Rollback

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

  Bases: `postgresql.exceptions.DriverWarning`

  Report a potential issue with a conversion.

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

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

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

## `postgresql.temporal`

Temporary PostgreSQL cluster for the process.

class `postgresql.temporal.``Temporal`

  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`()

    S.format(*args, **kwargs) -> str

    Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{‘ and ‘}’).

`postgresql.temporal.``pg_tmp` = <postgresql.temporal.Temporal object at 0x1024c7c10>

  The process’ temporary cluster.

## `postgresql.installation`

Collect and access PostgreSQL installation information.

class `postgresql.installation.``Installation`(info)

  Bases: `postgresql.api.Installation`

  Class providing a Python interface to PostgreSQL installation information.

  `ssl`

    Whether the installation was compiled with SSL support.

`postgresql.installation.``default`(typ=<class 'postgresql.installation.Installation'>)

  Get the default Installation.

  Uses default_pg_config() to identify the executable.

`postgresql.installation.``default_pg_config`(execname='pg_config', envkey='PGINSTALLATION')

  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)

  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)

  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`()

    Get the host-port pair from the configuration.

  `connect`(**kw)

    Create an established connection from the connector.

    Cluster must be running.

  `connection`(**kw)

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

  `connector`(**kw)

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

  `daemon_path`

    Path to the executable to use to startup the cluster.

  `drop`()

    Stop the cluster and remove it from the filesystem

  `get_pid_from_file`()

    The current pid from the postmaster.pid file.

  `hba_file`

    The path to the HBA file of the cluster.

  `init`(password=None, **kw)

    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`()

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

  `kill`()

    Stop the cluster immediately(SIGKILL).

    Does not wait for shutdown.

  `pid`

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

  `ready_for_connections`()

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

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

  `reload`()

    Signal the cluster to reload its configuration file.

  `restart`(logfile=None, settings=None, timeout=10)

    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`()

    Whether or not the postmaster is running.

    This does not mean the cluster is accepting connections.

  `shutdown`()

    Shutdown the cluster as soon as possible, disconnecting clients.

  `start`(logfile=None, settings=None)

    Start the cluster.

  `stop`()

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

  `wait_until_started`(timeout=10, delay=0.05)

    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)

    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)

  Bases: `postgresql.exceptions.Error`

  General cluster error.

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

  Bases: `postgresql.cluster.ClusterError`

  General cluster initialization failure

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

  Bases: `postgresql.cluster.ClusterError`

  Cluster is not running

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

  Bases: `postgresql.cluster.ClusterError`

  Cluster startup failed

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

  Bases: `postgresql.cluster.ClusterError`

  Cluster operation timed out

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

  Bases: `postgresql.exceptions.Warning`

  Warning issued by cluster operations

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

  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)

  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)

  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)

  Bases: `postgresql.python.element.Element`, `_abcoll.Iterator`

  A class for managing COPY operations.

  Connects the producer to the receivers.

  `reconcile`(r)

    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`

  Bases: `postgresql.copyman.Producer`

  Produces no copy data.

exception `postgresql.copyman.``ProducerFault`(manager)

  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)

  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)

    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)

  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 bytes object at 0x102778260>)

  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 unpack at 0x102611490>, len=<built-in function len>)

    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)

  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)

  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>)

    Acquire the locks using the configured identifiers.

  `locked`()

    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`

    The mode of the lock class.

  `release`()

    Release the locks using the configured identifiers.

## `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`

  Bases: `postgresql.python.element.Element`

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

  `code`

    The SQL state code of the message.

  `details`

    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)

    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`

    The primary message string.

  `source`

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

class `postgresql.api.``Statement`

  Bases: `postgresql.python.element.Element`, `_abcoll.Callable`, `_abcoll.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

  `chunks`(*parameters)

    Return an iterator producing sequences of rows produced by the cursor created from the statement bound with the given parameters.

    Chunking iterators are never scrollable.

    Supporting cursors will be WITH HOLD when outside of a transaction.

    chunks is designed for moving large data sets efficiently.

    Each iteration returns sequences of rows normally of length(seq) == chunksize. If chunksize is unspecified, a default, positive integer will be filled in. The rows contained in the sequences are only required to support the basic collections.Sequence interfaces; simple and quick sequence types should be used.

  `clone`()

    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`()

    Close the prepared statement releasing resources associated with it.

  `column`(*parameters)

    Return an iterator producing the values of the first column in the cursor created from the statement bound with the given parameters.

    Column iterators are never scrollable.

    Supporting cursors will be WITH HOLD when outside of a transaction to allow cross-transaction access.

    column is designed for the situations involving large data sets.

    Each iteration returns a single value. column is equivalent to:

        return map(operator.itemgetter(0), self.rows(*parameters))

  `column_names`

    Abstract Property -> [<class ‘str’>]

    GET::

      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`

    Abstract Property -> [<class ‘type’>]

    GET::

      The Python types of the columns produced by the statement.

      A sequence of type objects:

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

  `declare`(*parameters)

    Return a scrollable cursor with hold using the statement bound with the given parameters.

  `first`(*parameters)

    Execute the prepared statement with the given arguments as parameters. If the statement returns rows with multiple columns, return the first row. If the statement returns rows with a single column, return the first column in the first row. If the query does not return rows at all, return the count or None if no count exists in the completion message.

    Usage:

        >>> db.prepare("SELECT * FROM ttable WHERE key = $1").first("somekey")
        ('somekey', 'somevalue')
        >>> db.prepare("SELECT 'foo'").first()
        'foo'
        >>> db.prepare("INSERT INTO atable (col) VALUES (1)").first()
        1

  `load_chunks`(iterable)

    Given an iterable, iterable, feed the produced parameters of the chunks produced by the iterable to the query. This is a bulk-loading interface for parameterized queries.

    Effectively, it is equivalent to:

        >>> ps = db.prepare(...)
        >>> for c in iterable:
        ...  for i in c:
        ...   q(*i)

    Its purpose is to allow the implementation to take advantage of the knowledge that a series of chunks of parameters are to be loaded so that the operation can be optimized.

  `load_rows`(iterable)

    Given an iterable, iterable, feed the produced parameters to the query. This is a bulk-loading interface for parameterized queries.

    Effectively, it is equivalent to:

        >>> q = db.prepare(sql)
        >>> for i in iterable:
        ...  q(*i)

    Its purpose is to allow the implementation to take advantage of the knowledge that a series of parameters are to be loaded so that the operation can be optimized.

  `parameter_types`

    Abstract Property -> [<class ‘type’>]

    GET::

      The Python types expected of parameters given to the statement.

      A sequence of type objects:

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

  `pg_column_types`

    Abstract Property -> [<class ‘int’>]

    GET::

      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`

    Abstract Property -> [<class ‘int’>]

    GET::

      The type Oids of the parameters required by the statement.

      A sequence of int objects stating the PostgreSQL type Oid:

          [27, 28]

  `rows`(*parameters)

    Return an iterator producing rows produced by the cursor created from the statement bound with the given parameters.

    Row iterators are never scrollable.

    Supporting cursors will be WITH HOLD when outside of a transaction to allow cross-transaction access.

    rows is designed for the situations involving large data sets.

    Each iteration returns a single row. Arguably, best implemented:

        return itertools.chain.from_iterable(self.chunks(*parameters))

  `sql_column_types`

    Abstract Property -> [<class ‘str’>]

    GET::

      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`

    Abstract Property -> [<class ‘str’>]

    GET::

      The type of the parameters required by the statement.

      A sequence of str objects stating the SQL type name:

          ['INTEGER', 'VARCHAR', 'INTERVAL']

  `statement_id`

    Abstract Property -> <class ‘str’>

    GET::
      The statment’s identifier.
  `string`

    Abstract Property -> <class ‘object’>

    GET::

      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`

  Bases: `postgresql.api.Result`, `_abcoll.Iterator`, `_abcoll.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`()

    Create a new cursor using the same factors as self.

  `direction`

    Abstract Property -> <class ‘bool’>

    GET::

      The default direction argument for read().

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

      Cursor operation option.

  `read`(quantity=None, direction=None)

    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')

    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)

  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`

  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`

  Bases: `postgresql.python.element.Element`

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

  `backend_id`

    Abstract Property -> (<class ‘int’>, None)

    GET::
      The backend’s process identifier.
  `client_address`

    Abstract Property -> (<class ‘str’>, None)

    GET::

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

      None if unavailable.

  `client_port`

    Abstract Property -> (<class ‘int’>, None)

    GET::

      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)

    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)

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

    Likely to be a function of Connection.execute.

  `execute`(sql)

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

  `iternotifies`(timeout=None)

    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)

    Start listening to the given channels.

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

  `listening_channels`()

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

  `notify`(*channels, **channel_and_payload)

    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)

    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)

    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`()

    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`

    Abstract Property -> <class ‘postgresql.api.Settings’>

    GET::
      A Settings instance bound to the Database.
  `statement_from_id`(statement_id)

    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)

    Stop listening to the given channels.

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

  `version_info`

    Abstract Property -> <class ‘tuple’>

    GET::

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

          >>> db.version_info
          (8, 1, 3, '', 0)

  `xact`

    Abstract Property -> <class ‘postgresql.api.Transaction’>

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

class `postgresql.api.``Connection`

  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`()

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

  `close`()

    Close the connection.

    Does nothing if the connection is already closed.

  `closed`

    Abstract Property -> <class ‘bool’>

    GET::

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

          >>> db.closed
          True

  `connect`()

    Establish the connection to the server and initialize the category.

    Does nothing if the connection is already established.

  `connector`

    Abstract Property -> <class ‘postgresql.api.Connector’>

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

class `postgresql.api.``Transaction`

  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`()

    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`

    Abstract Property -> (None, <class ‘str’>)

    GET::

      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`

    Abstract Property -> (None, <class ‘str’>)

    GET::

      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`()

    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`()

    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`

  Bases: `postgresql.python.element.Element`, `_abcoll.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)

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

  `getset`(keys)

    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`()

    Return an iterator to all of the setting value pairs.

  `keys`()

    Return an iterator to all of the settings’ keys.

  `update`(mapping)

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

  `values`()

    Return an iterator to all of the settings’ values.

class `postgresql.api.``StoredProcedure`

  Bases: `postgresql.python.element.Element`, `_abcoll.Callable`

  A function stored on the database.

class `postgresql.api.``Driver`

  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)

    Create a connection using the given parameters for the Connector.

class `postgresql.api.``Installation`

  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`

    Abstract Property -> <class ‘bool’>

    GET::
      Whether the installation supports SSL.
  `type`

    Abstract Property

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

    Abstract Property

    GET::
      A version string consistent with what SELECT version() would output.
  `version_info`

    Abstract Property

    GET::

      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`

  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`

    Abstract Property -> <class ‘str’>

    GET::
      The path to the data directory of the cluster.
  `drop`()

    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)

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

  `installation`

    Abstract Property -> <class ‘postgresql.api.Installation’>

    GET::
      The installation used by the cluster.
  `kill`()

    Kill the server.

  `restart`()

    Restart the cluster.

  `settings`

    Abstract Property

    GET::
      A Settings interface to the `postgresql.conf` file associated with the cluster.
  `start`()

    Start the cluster.

  `stop`()

    Signal the server to shutdown.

  `wait_until_started`(timeout=10)

    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)

    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.

### Navigation

- index
- modules |
- next |
- previous |
- py-postgresql 1.0.4 documentation »