pg_proboscis is a pg_pqueue based driver for PostgreSQL. It provides a GreenTrunk and a DB-API 2.0 interface to PostgreSQL databases.
contents
- postgresql.interface.proboscis.tracenull
- postgresql.interface.proboscis.greentrunk
- postgresql.interface.proboscis.dbapi2
- postgresql.interface.proboscis.python
- pb_python (console script for postgresql.interface.proboscis.python)
examples
Run a console with a connection:
$ pb_python -h localhost -U pgsql -d postgres Python 2.5.1 (r251:54863, Dec 8 2007, 09:22:18) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. (SavingConsole) >>> gtx <postgresql.interface.proboscis.tracenull.GreenTrunk_Connection[pq://pgsql@localhost:5432/postgres] T.0> >>>
Make a GreenTrunk connection manually:
>>> import postgresql.interface.proboscis.greentrunk as gt >>> con = gt.connector(user = 'pgsql', host = 'localhost', port = 5432, database = 'postgres') >>> c=con()
Make a DB-API 2.0 connection manually:
>>> import postgresql.interface.proboscis.dbapi2 as db >>> c=db.connect(user = 'pgsql', host = 'localhost', port = 5432, database = 'postgres')
Notably, DSN strings are not directly supported. However, if you want connection strings, the postgresql.utility.client.iri module has means for parsing PQ IRIs and the postgresql.utility.client.dsn module has means for parsing DSNs.
chapter connecting.txt
Connecting to PostgreSQL with pg_proboscis
Making a greentrunk connection
pg_proboscis conforms to postgresql.protocol.greentrunk.api, but the specification does not discuss how connections are made. Connecting to the database is a matter for the implementation to handle as how communication should occur is not for the specification to define.
The postgresql.interface.proboscis.greentrunk module provides connect, connector, and connection attributes. They provide the following capabilities:
- connector
The connector is a usual mechanism to create a new connection. A connector is actually a "bookmark" object that creates the connection:
import postgresql.interface.proboscis.greentrunk as gt con = gt.connector(host = 'localhost', user = 'postgres', port = 5432) gtx = con()Calling the created connector objects creates the connection to the database. The connector provides a channel for pg_proboscis to share information across connections.
- connect
A simple function that returns a new connection. It provides a more convenient mechanism for simple systems. It implies the creation of the connector and just returns a new connection:
import postgresql.interface.proboscis.greentrunk as gt gtx = gt.connect(host = 'localhost', user = 'postgres', port = 5432)- connection
The class that will be instantiated when a connection is made. connect will return an instance of this class. Normally, if this object is to be subclassed, the connector would also be subclassed and its connection_class would be set to the newly created connector class:
import postgresql.interface.proboscis.greentrunk as gt class my_connection(gt.connection): def aNewHandyMethod(self): raise NotImplementedError class my_connector(gt.connector): connection_class = my_connection
Making a connection using PQ IRIs
pg_proboscis doesn't support iri or dsn keyword arguments. So, in order to use these, a parser must be used to transform an IRI or DSN string into a dictionary with the necessary mappings to make the desired connection.
The pg_foundation projects provides an IRI parser. It can be used to construct the necessary dictionary for a connection:
import postgresql.interface.proboscis.greentrunk as gt
import postgresql.utility.client.iri as pg_iri
gtx = gt.connect(**pg_iri.parse('pq://postgres@localhost:5432/dbname'))
Notably, IRI parsing will not fill in defaults. The port and user fields are not filled in if they are not specified within the string.
Keyword Parameters
Connection interfaces only use keyword parameters. DSN or IRI strings are not directly supported--that is a matter for a parser or another interface to handle.
- user
- The user to connect and authenticate as.
- password
- The password for the user.
- host
- The IP host to connect to.
- port
- The port on the host to connect to. This is required iff host is the method.
- database
- The name of the database to connect to.
- sslmode
Under what condition should the connection be secured using SSL. Can be one of:
- "prefer"
- If SSL is available, use it, otherwise fall back to an unsecured connection.
- "allow"
- By default, use an unsecured connection, but if only a secure connection is available, allow it.
- "require"
- SSL connection must be used.
- "disallow"
- SSL connection cannot be used.
- unix
- Connect to the database via a file system socket. The file system path to the socket file.
- process
A tuple stating the subprocess to facilitate the connection using the process's standard input and output. This can be used make a connection via ssh. For example:
import postgresql.interface.proboscis.greentrunk as gt gt.connect(user='postgres', process=( 'ssh', 'remotehost.tld', 'nc localhost 5432' ) )- options
- Extra command line options for the server.
- tracer
This option provides a means to log PQ transmission. The representation of every message that was sent and received is sent to the function given as the tracer keyword's value. For example:
import postgresql.interface.proboscis.greentrunk as gt gtx = gt.connect( user='postgres', host='localhost', port=5432, tracer=sys.stderr.write )- other
- Any other parameter passed in is used as a setting and value to initiate the connection with. This can be used to set the search_path, or other GUC parameter.
chapter pb_python.txt
The pb_python Console Script
The pb_python script provides a simple way to write scripts against a single target database. Usually these would tend to be scripts that do condition processing that is difficult to do in pure SQL, or simple report construction.
Usage
Usage: pb_python [connection options] [script] [-- script options] [args]
- Options:
-d DATABASE, --database=DATABASE database's name -h SOCKET_PROVIDER, --host=SOCKET_PROVIDER database server host -p PORT, --port=PORT database server port -U USER, --username=USER user name to connect as -W, --password prompt for password --unix-socket=SOCKET_PROVIDER path to filesystem socket --process=SOCKET_PROVIDER the subprocess to execute to facilitate the connection --server-options=OPTIONS command line options for the remote Postgres backend --ssl-mode=SSLMODE SSL rules for connectivity --require-ssl require an SSL connection --role=ROLE run operation as the role --fragment=FRAGMENT Additional user data for the connection -s SETTINGS, --setting=SETTINGS run-time parameters to set upon connecting --path=PATH Path to prefix search_path with --pg-service-file=PG_SERVICE_FILE Postgres service file use to for lookups --pg-service=PG_SERVICE Postgres service name to connect to -I IRI, --iri=IRI complete resource identifier, pq IRI -1, --with-transaction run operation with a transaction block --python-context=PYTHON_CONTEXT Python context code to run[file://,module:,<code>(__context__)] -m PYTHON_MAIN Python module to run as script(__main__) -c PYTHON_MAIN Python expression to run(__main__) --python-postmortem=PYTHON_POSTMORTEM Execute the specified function after a fatal exception --pdb-pm Postmortem using pdb.pm --pq-trace=PQ_TRACE trace PQ protocol transmissions --version show program's version number and exit --help show this help message and exit
Environment
pb_python creates a Python environment with an already established connection based on the given arguments. It uses the pkg:jwp_python_command package to aid in harnessing the basic Python command features and then pkg:pg_foundation to fill in the connectivity options. In order to provide global access to these additional object, it assigns them in __builtins__ to the following names:
- gtx (the connection object)
- gtc (the connector that created the connection)
- xact (gtx.xact)
- settings (gtx.settings)
- query (gtx.query)
- cquery (gtx.cquery)
- proc (gtx.proc)
- cursor (gtx.cursor)
- statement (gtx.statement)
All of these are provided for convenience. With a single target being the primary use-case, ambiguity is not an issue. Surely, saving four characters for accessing each of these is not substantial, but it helps keep code concise and tends to be very useful when using pb_python interactively.
Interactive Console Backslash Commands
Inspired by psql:
>>> \? Backslash Commands: \? Show this help message. \E Edit a file or a temporary script. \e Edit and Execute the file directly in the context. \i Execute a Python script within the interpreter's context. \s Wrap each execution code of in a new SAVEPOINT; Rollback on exception \set Configure environment variables. \set without arguments to show all \x Execute the Python command within this process.
package postgresql.interface.proboscis
Proboscis interface space
module postgresql.interface.proboscis.python
<Option at 0x13d4120: --pq-trace>
module postgresql.interface.proboscis.tracenull
GreenTrunk interface for PostgreSQL servers that support the PQ version 3.0 protocol.
GreenTrunk_Connector(**config) -> Connector All arguments to Connector are keywords. At the very least, user, and socket, may be provided. If socket, unix, or process is not provided, host and port must be.
create and connect a socket using the configured _socket_data
postgresql.interface.proboscis.tracenull.GreenTrunk_Connection
'prefer'
Object used to provide interfaces for copy and simple commands. Ties to a given transaction. These objects provide a way for transactions to be marked as defunct, so that no more time is wasted completing them.
reduce the buffer's size
helper method to step until the result handle's type message is received. This is a copy begin message or a complete message.
internal helper function to put more copy data onto the buffer for reading. This function will only append to the buffer and never set the offset.
The completion message's command identifier
The completion message's count number
get the next copy line
Read the specified number of COPY lines from the connection.
Write a sequence of COPY lines to the connection.
whether the result handle is the current transaction
GreenTrunk_Connection(connector) -> GreenTrunk_Connection GreenTrunk API <-> PQ Protocol <-> PostgreSQL
Create a connection based on the given connector.
Create a Portal using the given client prepared statement
Execute a query with the given arguments that does not return rows
[internal] Send notification to any listeners; NOTIFY messages
[internal] print a notice message using the notifier attribute
[internal] Receive ShowOption message
Connect on entrance.
Close the connection on exit.
connection can issue a query without an existing impediment
close portals and statements slated for closure. NOTE: Assumes no running transaction.
Clear container objects of data.
[internal] complete the current transaction
Initialize the connection between the client and the server. This requires that a socket interface has been set on the 'socket' attribute.
[internal] remove the transaction and raise the exception if any
[internal] lookup a PostgreSQL error and instantiate it
[internal] setup the given transaction to be processed
[internal] protocol message reader. internal use only
[internal] read more messages into self._read when self._read is empty
Reset state and connection information attributes.
[internal] send unsent data initialized for delivery
[internal] read more messages into self._read when self._read is empty
[internal] protocol message writer
[internal] make a single transition on the transaction
[internal] _message_reader used when tracing
[internal] _message_writer used when tracing
lookup a type's IO routines from a given typoid
create a sequence of I/O routines from a pq descriptor
[internal] protocol message writer
Close the connection and reinitialize the state and information
Establish the connection to the server
Create a query and store it in a dictionary that associates the created query with the string that defines the query. Passing the string back into the method will yield the same query object that was returned by prior calls. (Not consistent across disconnects)
Create a Portal object that references an already existing cursor
Execute an arbitrary block of SQL
Send a CancelQuery message to the backend
Create a StoredProcedure object using the given procedure identity
Create a query object using the given query string
close() and connect()
restore original settings, reset the transaction, drop temporary objects
Create a query object using the statement identifier
Explicitly send a Synchronize message to the backend. Useful for forcing the completion of lazily processed transactions. [Avoids garbage collection not pushing; _complete, then set _xact.]
[internal] subscription method to client_encoding on settings
[internal] subscription method to TimeZone on settings
Whether the connection is closed or not
Callable object to pass protocol trace strings to. (Normally a write method.)
Class for controlling a Postgres protocol cursor. Provides buffering, seeking, and iterator interfaces
reduce the number of tuples in the buffer by removing past tuples
internal helper function to put more tuples onto the buffer for reading. This function will only append to the buffer and never set the offset.
given a PQ tuple, return a map tuple
{0: 'ABSOLUTE', 1: 'RELATIVE', 2: 'LAST'}Client statement created cursors
self,
query,
params,
output,
output_io,
rformats
):
Server declared cursor interfaces
Interface to functions kept in the backend
complete initialization that the prime() method started.
Push initialization messages to the server, but don't wait for the return as there may be things that can be done while waiting for the return. Use the finish() to complete.
A prepared statement generated by the connection user
Push out initialization messages for query preparation
structured search_path interface
Name addressable items tuple; mapping and sequence
postgresql.exceptions.AbortTransaction
take a would be connection socket and secure it with SSL
generate an id for a client statement or cursor
Transform object data into an object using the associated IO routines
Transform objects into object data using the associated IO routines
generator for yielding None if x is None or unpack(x)
unpack the array, normalize the lower bounds and return a pg_types.array
connection,
typoid,
typio,
hasbin_input,
hasbin_output
):
create an array's typio pair
create the typio pair for a given composite type
Used to process tuples for bulk loads
create a dictionary from a pq desc that maps attribute names to their index
helper function to get the last set of digits in a command completion as an integer.
<postgresql.interface.proboscis.tracenull.ClosedConnection object at 0x131ed50>
'%s(py:%s)'
postgresql.protocol.typical.pstruct.array_pack
postgresql.protocol.typical.pstruct.array_unpack
_hashlib.openssl_md5
<type 'cbuffer.pq_message_stream'>
postgresql.protocol.typical.pstruct.record_pack
postgresql.protocol.typical.pstruct.record_unpack
module postgresql.interface.proboscis.dbapi2
DB-API 2.0 conforming interface on proboscis.greentrunk
DB-API 2.0 connection implementation for GreenTrunk connection objects.
postgresql.exceptions.DataError
postgresql.interface.proboscis.dbapi2.NotSupportedError
postgresql.exceptions.IntegrityError
postgresql.exceptions.Error
postgresql.interface.proboscis.dbapi2.InterfaceError
postgresql.exceptions.Warning
postgresql.exceptions.IRError
postgresql.exceptions.SEARVError
postgresql.exceptions.InternalError
postgresql.exceptions.Error
Given a sequence of keywords, `nseq`, yield each mapping object in `seq` as a tuple whose objects are the values of the keys specified in `nseq` in an order consistent with that in `nseq`
str
str
datetime.datetime
postgresql.exceptions.DataError
postgresql.exceptions.Error
datetime.date
postgresql.exceptions.Error
postgresql.exceptions.IntegrityError
postgresql.exceptions.InternalError
int
postgresql.exceptions.IRError
postgresql.exceptions.SEARVError
int
unicode
datetime.time
datetime.datetime
postgresql.exceptions.Warning
{}'2.0'
'pyformat'
1
module postgresql.interface.proboscis.greentrunk
GreenTrunk module--only requires the Connector and Connection