2010-02-09 07:58:28 +03:00
|
|
|
More advanced topics
|
|
|
|
====================
|
|
|
|
|
|
|
|
.. sectionauthor:: Daniele Varrazzo <daniele.varrazzo@gmail.com>
|
|
|
|
|
2010-02-13 19:06:39 +03:00
|
|
|
.. testsetup:: *
|
|
|
|
|
|
|
|
import re
|
2010-04-20 02:49:14 +04:00
|
|
|
import select
|
2010-02-13 19:06:39 +03:00
|
|
|
|
|
|
|
cur.execute("CREATE TABLE atable (apoint point)")
|
|
|
|
conn.commit()
|
|
|
|
|
2010-04-20 02:49:14 +04:00
|
|
|
def wait(conn):
|
|
|
|
while 1:
|
|
|
|
state = conn.poll()
|
|
|
|
if state == psycopg2.extensions.POLL_OK:
|
|
|
|
break
|
|
|
|
elif state == psycopg2.extensions.POLL_WRITE:
|
|
|
|
select.select([], [conn.fileno()], [])
|
|
|
|
elif state == psycopg2.extensions.POLL_READ:
|
|
|
|
select.select([conn.fileno()], [], [])
|
|
|
|
else:
|
|
|
|
raise psycopg2.OperationalError("poll() returned %s" % state)
|
|
|
|
|
|
|
|
aconn = psycopg2.connect(database='test', async=1)
|
|
|
|
wait(aconn)
|
|
|
|
acurs = aconn.cursor()
|
|
|
|
|
2013-04-07 05:30:12 +04:00
|
|
|
|
2010-02-14 07:59:40 +03:00
|
|
|
.. index::
|
|
|
|
double: Subclassing; Cursor
|
|
|
|
double: Subclassing; Connection
|
|
|
|
|
|
|
|
.. _subclassing-connection:
|
|
|
|
.. _subclassing-cursor:
|
|
|
|
|
2010-02-09 07:58:28 +03:00
|
|
|
Connection and cursor factories
|
|
|
|
-------------------------------
|
|
|
|
|
|
|
|
Psycopg exposes two new-style classes that can be sub-classed and expanded to
|
2010-02-26 03:17:52 +03:00
|
|
|
adapt them to the needs of the programmer: `psycopg2.extensions.cursor`
|
|
|
|
and `psycopg2.extensions.connection`. The `connection` class is
|
2010-02-09 07:58:28 +03:00
|
|
|
usually sub-classed only to provide an easy way to create customized cursors
|
2010-02-26 03:17:52 +03:00
|
|
|
but other uses are possible. `cursor` is much more interesting, because
|
2010-02-09 07:58:28 +03:00
|
|
|
it is the class where query building, execution and result type-casting into
|
|
|
|
Python variables happens.
|
|
|
|
|
2013-04-07 05:30:12 +04:00
|
|
|
The `~psycopg2.extras` module contains several examples of :ref:`connection
|
2016-03-09 23:51:02 +03:00
|
|
|
and cursor subclasses <cursor-subclasses>`.
|
2013-04-07 05:30:12 +04:00
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
|
|
|
If you only need a customized cursor class, since Psycopg 2.5 you can use
|
|
|
|
the `~connection.cursor_factory` parameter of a regular connection instead
|
|
|
|
of creating a new `!connection` subclass.
|
|
|
|
|
|
|
|
|
2010-02-11 06:15:14 +03:00
|
|
|
.. index::
|
|
|
|
single: Example; Cursor subclass
|
|
|
|
|
2010-02-09 07:58:28 +03:00
|
|
|
An example of cursor subclass performing logging is::
|
|
|
|
|
|
|
|
import psycopg2
|
|
|
|
import psycopg2.extensions
|
|
|
|
import logging
|
|
|
|
|
|
|
|
class LoggingCursor(psycopg2.extensions.cursor):
|
|
|
|
def execute(self, sql, args=None):
|
|
|
|
logger = logging.getLogger('sql_debug')
|
|
|
|
logger.info(self.mogrify(sql, args))
|
|
|
|
|
|
|
|
try:
|
|
|
|
psycopg2.extensions.cursor.execute(self, sql, args)
|
|
|
|
except Exception, exc:
|
|
|
|
logger.error("%s: %s" % (exc.__class__.__name__, exc))
|
|
|
|
raise
|
|
|
|
|
|
|
|
conn = psycopg2.connect(DSN)
|
2010-02-13 19:06:39 +03:00
|
|
|
cur = conn.cursor(cursor_factory=LoggingCursor)
|
|
|
|
cur.execute("INSERT INTO mytable VALUES (%s, %s, %s);",
|
2010-02-09 07:58:28 +03:00
|
|
|
(10, 20, 30))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
.. index::
|
|
|
|
single: Objects; Creating new adapters
|
|
|
|
single: Adaptation; Creating new adapters
|
|
|
|
single: Data types; Creating new adapters
|
2010-02-10 07:03:30 +03:00
|
|
|
|
2010-02-09 07:58:28 +03:00
|
|
|
.. _adapting-new-types:
|
|
|
|
|
|
|
|
Adapting new Python types to SQL syntax
|
|
|
|
---------------------------------------
|
|
|
|
|
|
|
|
Any Python class or type can be adapted to an SQL string. Adaptation mechanism
|
|
|
|
is similar to the Object Adaptation proposed in the :pep:`246` and is exposed
|
2010-02-26 03:17:52 +03:00
|
|
|
by the `psycopg2.extensions.adapt()` function.
|
2010-02-09 07:58:28 +03:00
|
|
|
|
2010-02-26 03:17:52 +03:00
|
|
|
The `~cursor.execute()` method adapts its arguments to the
|
|
|
|
`~psycopg2.extensions.ISQLQuote` protocol. Objects that conform to this
|
|
|
|
protocol expose a `!getquoted()` method returning the SQL representation
|
2011-02-10 04:44:37 +03:00
|
|
|
of the object as a string (the method must return `!bytes` in Python 3).
|
|
|
|
Optionally the conform object may expose a
|
|
|
|
`~psycopg2.extensions.ISQLQuote.prepare()` method.
|
|
|
|
|
|
|
|
There are two basic ways to have a Python object adapted to SQL:
|
|
|
|
|
|
|
|
- the object itself is conform, or knows how to make itself conform. Such
|
|
|
|
object must expose a `__conform__()` method that will be called with the
|
|
|
|
protocol object as argument. The object can check that the protocol is
|
|
|
|
`!ISQLQuote`, in which case it can return `!self` (if the object also
|
|
|
|
implements `!getquoted()`) or a suitable wrapper object. This option is
|
|
|
|
viable if you are the author of the object and if the object is specifically
|
|
|
|
designed for the database (i.e. having Psycopg as a dependency and polluting
|
|
|
|
its interface with the required methods doesn't bother you). For a simple
|
2011-02-19 19:16:28 +03:00
|
|
|
example you can take a look at the source code for the
|
2011-02-10 04:44:37 +03:00
|
|
|
`psycopg2.extras.Inet` object.
|
|
|
|
|
|
|
|
- If implementing the `!ISQLQuote` interface directly in the object is not an
|
2011-02-19 19:16:28 +03:00
|
|
|
option (maybe because the object to adapt comes from a third party library),
|
|
|
|
you can use an *adaptation function*, taking the object to be adapted as
|
|
|
|
argument and returning a conforming object. The adapter must be
|
2011-02-10 04:44:37 +03:00
|
|
|
registered via the `~psycopg2.extensions.register_adapter()` function. A
|
2011-02-19 19:16:28 +03:00
|
|
|
simple example wrapper is `!psycopg2.extras.UUID_adapter` used by the
|
2011-02-10 04:44:37 +03:00
|
|
|
`~psycopg2.extras.register_uuid()` function.
|
|
|
|
|
|
|
|
A convenient object to write adapters is the `~psycopg2.extensions.AsIs`
|
|
|
|
wrapper, whose `!getquoted()` result is simply the `!str()`\ ing conversion of
|
|
|
|
the wrapped object.
|
2010-02-09 07:58:28 +03:00
|
|
|
|
2010-02-11 06:15:14 +03:00
|
|
|
.. index::
|
|
|
|
single: Example; Types adaptation
|
|
|
|
|
2010-02-26 03:17:52 +03:00
|
|
|
Example: mapping of a `!Point` class into the |point|_ PostgreSQL
|
2010-02-13 19:06:39 +03:00
|
|
|
geometric type:
|
2010-02-09 07:58:28 +03:00
|
|
|
|
2010-02-13 19:06:39 +03:00
|
|
|
.. doctest::
|
2010-02-10 07:03:30 +03:00
|
|
|
|
2010-02-13 19:06:39 +03:00
|
|
|
>>> from psycopg2.extensions import adapt, register_adapter, AsIs
|
2010-02-10 07:03:30 +03:00
|
|
|
|
2010-02-13 19:06:39 +03:00
|
|
|
>>> class Point(object):
|
|
|
|
... def __init__(self, x, y):
|
|
|
|
... self.x = x
|
|
|
|
... self.y = y
|
2010-02-10 07:03:30 +03:00
|
|
|
|
2010-02-13 19:06:39 +03:00
|
|
|
>>> def adapt_point(point):
|
2014-11-02 16:15:51 +03:00
|
|
|
... x = adapt(point.x).getquoted()
|
|
|
|
... y = adapt(point.y).getquoted()
|
|
|
|
... return AsIs("'(%s, %s)'" % (x, y))
|
2010-02-10 07:03:30 +03:00
|
|
|
|
2010-02-13 19:06:39 +03:00
|
|
|
>>> register_adapter(Point, adapt_point)
|
|
|
|
|
|
|
|
>>> cur.execute("INSERT INTO atable (apoint) VALUES (%s)",
|
|
|
|
... (Point(1.23, 4.56),))
|
2010-02-09 07:58:28 +03:00
|
|
|
|
2010-02-10 07:03:30 +03:00
|
|
|
|
2010-02-11 06:15:14 +03:00
|
|
|
.. |point| replace:: :sql:`point`
|
2012-02-28 20:28:07 +04:00
|
|
|
.. _point: http://www.postgresql.org/docs/current/static/datatype-geometric.html#DATATYPE-GEOMETRIC
|
2010-02-10 07:03:30 +03:00
|
|
|
|
2010-02-09 07:58:28 +03:00
|
|
|
The above function call results in the SQL command::
|
|
|
|
|
2011-07-24 23:42:23 +04:00
|
|
|
INSERT INTO atable (apoint) VALUES ('(1.23, 4.56)');
|
2010-02-09 07:58:28 +03:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
.. index:: Type casting
|
|
|
|
|
|
|
|
.. _type-casting-from-sql-to-python:
|
|
|
|
|
2010-02-10 07:03:30 +03:00
|
|
|
Type casting of SQL types into Python objects
|
|
|
|
---------------------------------------------
|
2010-02-09 07:58:28 +03:00
|
|
|
|
|
|
|
PostgreSQL objects read from the database can be adapted to Python objects
|
|
|
|
through an user-defined adapting function. An adapter function takes two
|
2010-02-09 16:33:31 +03:00
|
|
|
arguments: the object string representation as returned by PostgreSQL and the
|
2010-02-09 07:58:28 +03:00
|
|
|
cursor currently being read, and should return a new Python object. For
|
2010-02-11 06:15:14 +03:00
|
|
|
example, the following function parses the PostgreSQL :sql:`point`
|
2010-02-26 03:17:52 +03:00
|
|
|
representation into the previously defined `!Point` class:
|
2010-02-11 06:15:14 +03:00
|
|
|
|
2010-02-13 19:06:39 +03:00
|
|
|
>>> def cast_point(value, cur):
|
|
|
|
... if value is None:
|
|
|
|
... return None
|
|
|
|
...
|
|
|
|
... # Convert from (f1, f2) syntax using a regular expression.
|
|
|
|
... m = re.match(r"\(([^)]+),([^)]+)\)", value)
|
|
|
|
... if m:
|
|
|
|
... return Point(float(m.group(1)), float(m.group(2)))
|
|
|
|
... else:
|
|
|
|
... raise InterfaceError("bad point representation: %r" % value)
|
2010-02-11 06:15:14 +03:00
|
|
|
|
2010-02-10 07:03:30 +03:00
|
|
|
|
2010-02-11 06:15:14 +03:00
|
|
|
In order to create a mapping from a PostgreSQL type (either standard or
|
|
|
|
user-defined), its OID must be known. It can be retrieved either by the second
|
2010-02-26 03:17:52 +03:00
|
|
|
column of the `cursor.description`:
|
2010-02-09 07:58:28 +03:00
|
|
|
|
2010-02-13 19:06:39 +03:00
|
|
|
>>> cur.execute("SELECT NULL::point")
|
2010-02-14 07:59:40 +03:00
|
|
|
>>> point_oid = cur.description[0][1]
|
|
|
|
>>> point_oid
|
|
|
|
600
|
2010-02-09 07:58:28 +03:00
|
|
|
|
2010-03-03 20:43:24 +03:00
|
|
|
or by querying the system catalog for the type name and namespace (the
|
2010-02-13 19:06:39 +03:00
|
|
|
namespace for system objects is :sql:`pg_catalog`):
|
2010-02-09 07:58:28 +03:00
|
|
|
|
2010-02-13 19:06:39 +03:00
|
|
|
>>> cur.execute("""
|
|
|
|
... SELECT pg_type.oid
|
|
|
|
... FROM pg_type JOIN pg_namespace
|
|
|
|
... ON typnamespace = pg_namespace.oid
|
|
|
|
... WHERE typname = %(typename)s
|
|
|
|
... AND nspname = %(namespace)s""",
|
|
|
|
... {'typename': 'point', 'namespace': 'pg_catalog'})
|
|
|
|
>>> point_oid = cur.fetchone()[0]
|
2010-02-14 07:59:40 +03:00
|
|
|
>>> point_oid
|
|
|
|
600
|
2010-02-10 07:03:30 +03:00
|
|
|
|
2010-03-03 20:43:24 +03:00
|
|
|
After you know the object OID, you can create and register the new type:
|
2010-02-09 07:58:28 +03:00
|
|
|
|
2010-02-13 19:06:39 +03:00
|
|
|
>>> POINT = psycopg2.extensions.new_type((point_oid,), "POINT", cast_point)
|
|
|
|
>>> psycopg2.extensions.register_type(POINT)
|
2010-02-09 07:58:28 +03:00
|
|
|
|
2010-02-26 03:17:52 +03:00
|
|
|
The `~psycopg2.extensions.new_type()` function binds the object OIDs
|
2010-02-09 07:58:28 +03:00
|
|
|
(more than one can be specified) to the adapter function.
|
2010-02-26 03:17:52 +03:00
|
|
|
`~psycopg2.extensions.register_type()` completes the spell. Conversion
|
2010-02-10 07:03:30 +03:00
|
|
|
is automatically performed when a column whose type is a registered OID is
|
2010-02-13 19:06:39 +03:00
|
|
|
read:
|
2010-02-09 07:58:28 +03:00
|
|
|
|
2010-02-13 19:06:39 +03:00
|
|
|
>>> cur.execute("SELECT '(10.2,20.3)'::point")
|
|
|
|
>>> point = cur.fetchone()[0]
|
2010-02-09 07:58:28 +03:00
|
|
|
>>> print type(point), point.x, point.y
|
2010-02-13 19:06:39 +03:00
|
|
|
<class 'Point'> 10.2 20.3
|
2010-02-09 07:58:28 +03:00
|
|
|
|
2011-09-22 18:08:53 +04:00
|
|
|
A typecaster created by `!new_type()` can be also used with
|
|
|
|
`~psycopg2.extensions.new_array_type()` to create a typecaster converting a
|
|
|
|
PostgreSQL array into a Python list.
|
2010-02-09 07:58:28 +03:00
|
|
|
|
|
|
|
|
2010-02-09 20:52:41 +03:00
|
|
|
.. index::
|
|
|
|
pair: Asynchronous; Notifications
|
|
|
|
pair: LISTEN; SQL command
|
|
|
|
pair: NOTIFY; SQL command
|
|
|
|
|
|
|
|
.. _async-notify:
|
|
|
|
|
|
|
|
Asynchronous notifications
|
|
|
|
--------------------------
|
|
|
|
|
|
|
|
Psycopg allows asynchronous interaction with other database sessions using the
|
|
|
|
facilities offered by PostgreSQL commands |LISTEN|_ and |NOTIFY|_. Please
|
2010-10-16 03:21:03 +04:00
|
|
|
refer to the PostgreSQL documentation for examples about how to use this form of
|
2010-10-08 13:16:59 +04:00
|
|
|
communication.
|
2010-02-09 20:52:41 +03:00
|
|
|
|
2010-10-16 03:21:03 +04:00
|
|
|
Notifications are instances of the `~psycopg2.extensions.Notify` object made
|
|
|
|
available upon reception in the `connection.notifies` list. Notifications can
|
2010-11-06 23:59:10 +03:00
|
|
|
be sent from Python code simply executing a :sql:`NOTIFY` command in an
|
2010-10-16 03:21:03 +04:00
|
|
|
`~cursor.execute()` call.
|
2010-02-09 20:52:41 +03:00
|
|
|
|
|
|
|
Because of the way sessions interact with notifications (see |NOTIFY|_
|
2011-05-31 03:05:50 +04:00
|
|
|
documentation), you should keep the connection in `~connection.autocommit`
|
|
|
|
mode if you wish to receive or send notifications in a timely manner.
|
2010-02-09 20:52:41 +03:00
|
|
|
|
2010-02-11 06:15:14 +03:00
|
|
|
.. |LISTEN| replace:: :sql:`LISTEN`
|
2012-02-28 20:28:07 +04:00
|
|
|
.. _LISTEN: http://www.postgresql.org/docs/current/static/sql-listen.html
|
2010-02-11 06:15:14 +03:00
|
|
|
.. |NOTIFY| replace:: :sql:`NOTIFY`
|
2012-02-28 20:28:07 +04:00
|
|
|
.. _NOTIFY: http://www.postgresql.org/docs/current/static/sql-notify.html
|
2010-02-09 20:52:41 +03:00
|
|
|
|
2010-10-08 13:16:59 +04:00
|
|
|
Notifications are received after every query execution. If the user is
|
|
|
|
interested in receiving notifications but not in performing any query, the
|
|
|
|
`~connection.poll()` method can be used to check for new messages without
|
2010-04-20 21:17:27 +04:00
|
|
|
wasting resources.
|
|
|
|
|
|
|
|
A simple application could poll the connection from time to time to check if
|
|
|
|
something new has arrived. A better strategy is to use some I/O completion
|
2016-02-02 21:48:16 +03:00
|
|
|
function such as :py:func:`~select.select` to sleep until awakened by the kernel when there is
|
2010-04-20 21:17:27 +04:00
|
|
|
some data to read on the connection, thereby using no CPU unless there is
|
|
|
|
something to read::
|
2010-02-09 20:52:41 +03:00
|
|
|
|
|
|
|
import select
|
|
|
|
import psycopg2
|
|
|
|
import psycopg2.extensions
|
|
|
|
|
|
|
|
conn = psycopg2.connect(DSN)
|
|
|
|
conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
|
|
|
|
|
|
|
|
curs = conn.cursor()
|
|
|
|
curs.execute("LISTEN test;")
|
|
|
|
|
2010-11-06 23:59:10 +03:00
|
|
|
print "Waiting for notifications on channel 'test'"
|
2010-02-09 20:52:41 +03:00
|
|
|
while 1:
|
2010-04-20 15:30:41 +04:00
|
|
|
if select.select([conn],[],[],5) == ([],[],[]):
|
2010-02-09 20:52:41 +03:00
|
|
|
print "Timeout"
|
|
|
|
else:
|
2010-04-20 15:30:41 +04:00
|
|
|
conn.poll()
|
|
|
|
while conn.notifies:
|
2015-05-21 10:24:00 +03:00
|
|
|
notify = conn.notifies.pop(0)
|
2010-11-06 23:59:10 +03:00
|
|
|
print "Got NOTIFY:", notify.pid, notify.channel, notify.payload
|
2010-02-09 20:52:41 +03:00
|
|
|
|
2010-11-06 23:59:10 +03:00
|
|
|
Running the script and executing a command such as :sql:`NOTIFY test, 'hello'`
|
|
|
|
in a separate :program:`psql` shell, the output may look similar to::
|
2010-02-09 20:52:41 +03:00
|
|
|
|
2010-11-06 23:59:10 +03:00
|
|
|
Waiting for notifications on channel 'test'
|
2010-02-09 20:52:41 +03:00
|
|
|
Timeout
|
|
|
|
Timeout
|
2010-11-06 23:59:10 +03:00
|
|
|
Got NOTIFY: 6535 test hello
|
2010-02-09 20:52:41 +03:00
|
|
|
Timeout
|
|
|
|
...
|
|
|
|
|
2011-02-19 19:16:28 +03:00
|
|
|
Note that the payload is only available from PostgreSQL 9.0: notifications
|
|
|
|
received from a previous version server will have the
|
|
|
|
`~psycopg2.extensions.Notify.payload` attribute set to the empty string.
|
2010-11-06 23:59:10 +03:00
|
|
|
|
|
|
|
.. versionchanged:: 2.3
|
|
|
|
Added `~psycopg2.extensions.Notify` object and handling notification
|
|
|
|
payload.
|
|
|
|
|
2015-06-02 19:02:04 +03:00
|
|
|
.. versionchanged:: 2.7
|
|
|
|
The `~connection.notifies` attribute is writable: it is possible to
|
|
|
|
replace it with any object exposing an `!append()` method. An useful
|
|
|
|
example would be to use a `~collections.deque` object.
|
2010-02-09 20:52:41 +03:00
|
|
|
|
|
|
|
|
2010-02-09 07:58:28 +03:00
|
|
|
.. index::
|
2010-04-08 16:22:55 +04:00
|
|
|
double: Asynchronous; Connection
|
2010-02-10 07:03:30 +03:00
|
|
|
|
2010-04-08 16:22:55 +04:00
|
|
|
.. _async-support:
|
2010-02-09 07:58:28 +03:00
|
|
|
|
2010-04-08 16:22:55 +04:00
|
|
|
Asynchronous support
|
2010-02-09 07:58:28 +03:00
|
|
|
--------------------
|
|
|
|
|
2010-04-08 16:22:55 +04:00
|
|
|
.. versionadded:: 2.2.0
|
|
|
|
|
2010-04-20 02:49:14 +04:00
|
|
|
Psycopg can issue asynchronous queries to a PostgreSQL database. An asynchronous
|
2010-04-20 15:30:41 +04:00
|
|
|
communication style is established passing the parameter *async*\=1 to the
|
2010-04-08 16:22:55 +04:00
|
|
|
`~psycopg2.connect()` function: the returned connection will work in
|
2010-04-20 02:49:14 +04:00
|
|
|
*asynchronous mode*.
|
2010-04-08 16:22:55 +04:00
|
|
|
|
2010-04-20 02:49:14 +04:00
|
|
|
In asynchronous mode, a Psycopg connection will rely on the caller to poll the
|
|
|
|
socket file descriptor, checking if it is ready to accept data or if a query
|
|
|
|
result has been transferred and is ready to be read on the client. The caller
|
|
|
|
can use the method `~connection.fileno()` to get the connection file
|
|
|
|
descriptor and `~connection.poll()` to make communication proceed according to
|
|
|
|
the current connection state.
|
2010-04-08 16:22:55 +04:00
|
|
|
|
2010-04-20 02:49:14 +04:00
|
|
|
The following is an example loop using methods `!fileno()` and `!poll()`
|
2011-02-19 19:16:28 +03:00
|
|
|
together with the Python :py:func:`~select.select` function in order to carry on
|
2010-04-20 02:49:14 +04:00
|
|
|
asynchronous operations with Psycopg::
|
|
|
|
|
|
|
|
def wait(conn):
|
2010-04-08 16:22:55 +04:00
|
|
|
while 1:
|
2010-04-20 02:49:14 +04:00
|
|
|
state = conn.poll()
|
2010-04-08 16:22:55 +04:00
|
|
|
if state == psycopg2.extensions.POLL_OK:
|
|
|
|
break
|
|
|
|
elif state == psycopg2.extensions.POLL_WRITE:
|
2010-04-20 02:49:14 +04:00
|
|
|
select.select([], [conn.fileno()], [])
|
2010-04-08 16:22:55 +04:00
|
|
|
elif state == psycopg2.extensions.POLL_READ:
|
2010-04-20 02:49:14 +04:00
|
|
|
select.select([conn.fileno()], [], [])
|
2010-04-08 16:22:55 +04:00
|
|
|
else:
|
|
|
|
raise psycopg2.OperationalError("poll() returned %s" % state)
|
|
|
|
|
2010-04-20 02:49:14 +04:00
|
|
|
The above loop of course would block an entire application: in a real
|
|
|
|
asynchronous framework, `!select()` would be called on many file descriptors
|
|
|
|
waiting for any of them to be ready. Nonetheless the function can be used to
|
|
|
|
connect to a PostgreSQL server only using nonblocking commands and the
|
|
|
|
connection obtained can be used to perform further nonblocking queries. After
|
|
|
|
`!poll()` has returned `~psycopg2.extensions.POLL_OK`, and thus `!wait()` has
|
|
|
|
returned, the connection can be safely used:
|
2010-04-08 16:22:55 +04:00
|
|
|
|
2010-04-20 02:49:14 +04:00
|
|
|
>>> aconn = psycopg2.connect(database='test', async=1)
|
|
|
|
>>> wait(aconn)
|
|
|
|
>>> acurs = aconn.cursor()
|
2010-02-09 07:58:28 +03:00
|
|
|
|
2011-10-15 02:59:49 +04:00
|
|
|
Note that there are a few other requirements to be met in order to have a
|
2010-04-08 16:22:55 +04:00
|
|
|
completely non-blocking connection attempt: see the libpq documentation for
|
|
|
|
|PQconnectStart|_.
|
2010-02-09 07:58:28 +03:00
|
|
|
|
2010-04-08 16:22:55 +04:00
|
|
|
.. |PQconnectStart| replace:: `!PQconnectStart()`
|
2012-02-28 20:28:07 +04:00
|
|
|
.. _PQconnectStart: http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-PQCONNECTSTARTPARAMS
|
2010-02-09 07:58:28 +03:00
|
|
|
|
2010-04-20 02:49:14 +04:00
|
|
|
The same loop should be also used to perform nonblocking queries: after
|
|
|
|
sending a query via `~cursor.execute()` or `~cursor.callproc()`, call
|
|
|
|
`!poll()` on the connection available from `cursor.connection` until it
|
2010-10-08 13:16:59 +04:00
|
|
|
returns `!POLL_OK`, at which point the query has been completely sent to the
|
2010-04-20 02:49:14 +04:00
|
|
|
server and, if it produced data, the results have been transferred to the
|
|
|
|
client and available using the regular cursor methods:
|
|
|
|
|
|
|
|
>>> acurs.execute("SELECT pg_sleep(5); SELECT 42;")
|
|
|
|
>>> wait(acurs.connection)
|
|
|
|
>>> acurs.fetchone()[0]
|
|
|
|
42
|
|
|
|
|
2010-04-20 03:50:34 +04:00
|
|
|
When an asynchronous query is being executed, `connection.isexecuting()` returns
|
2011-02-19 19:16:28 +03:00
|
|
|
`!True`. Two cursors can't execute concurrent queries on the same asynchronous
|
2010-04-08 16:22:55 +04:00
|
|
|
connection.
|
2010-02-09 07:58:28 +03:00
|
|
|
|
2010-04-20 02:49:14 +04:00
|
|
|
There are several limitations in using asynchronous connections: the
|
2011-05-31 03:05:50 +04:00
|
|
|
connection is always in `~connection.autocommit` mode and it is not
|
|
|
|
possible to change it. So a
|
2010-04-20 02:49:14 +04:00
|
|
|
transaction is not implicitly started at the first query and is not possible
|
|
|
|
to use methods `~connection.commit()` and `~connection.rollback()`: you can
|
|
|
|
manually control transactions using `~cursor.execute()` to send database
|
2011-05-31 03:05:50 +04:00
|
|
|
commands such as :sql:`BEGIN`, :sql:`COMMIT` and :sql:`ROLLBACK`. Similarly
|
2011-06-08 17:22:11 +04:00
|
|
|
`~connection.set_session()` can't be used but it is still possible to invoke the
|
2011-05-31 03:05:50 +04:00
|
|
|
:sql:`SET` command with the proper :sql:`default_transaction_...` parameter.
|
2010-02-09 07:58:28 +03:00
|
|
|
|
2010-04-08 16:22:55 +04:00
|
|
|
With asynchronous connections it is also not possible to use
|
|
|
|
`~connection.set_client_encoding()`, `~cursor.executemany()`, :ref:`large
|
|
|
|
objects <large-objects>`, :ref:`named cursors <server-side-cursors>`.
|
2010-02-09 07:58:28 +03:00
|
|
|
|
2010-04-08 16:22:55 +04:00
|
|
|
:ref:`COPY commands <copy>` are not supported either in asynchronous mode, but
|
|
|
|
this will be probably implemented in a future release.
|
2010-02-09 07:58:28 +03:00
|
|
|
|
|
|
|
|
|
|
|
|
2010-04-04 06:10:18 +04:00
|
|
|
|
|
|
|
.. index::
|
2010-12-02 18:15:31 +03:00
|
|
|
single: Greenlet
|
|
|
|
single: Coroutine
|
|
|
|
single: Eventlet
|
|
|
|
single: gevent
|
|
|
|
single: Wait callback
|
2010-04-04 06:10:18 +04:00
|
|
|
|
|
|
|
.. _green-support:
|
|
|
|
|
2012-07-27 13:48:28 +04:00
|
|
|
Support for coroutine libraries
|
|
|
|
-------------------------------
|
2010-04-04 06:10:18 +04:00
|
|
|
|
2016-08-07 04:07:16 +03:00
|
|
|
.. versionadded:: 2.2
|
2010-04-04 06:10:18 +04:00
|
|
|
|
2012-07-27 13:48:28 +04:00
|
|
|
Psycopg can be used together with coroutine_\-based libraries and participate
|
|
|
|
in cooperative multithreading.
|
2010-04-04 06:10:18 +04:00
|
|
|
|
|
|
|
Coroutine-based libraries (such as Eventlet_ or gevent_) can usually patch the
|
2010-04-23 16:19:43 +04:00
|
|
|
Python standard library in order to enable a coroutine switch in the presence of
|
2010-04-04 06:10:18 +04:00
|
|
|
blocking I/O: the process is usually referred as making the system *green*, in
|
2010-04-23 16:19:43 +04:00
|
|
|
reference to the `green threads`_.
|
2010-04-04 06:10:18 +04:00
|
|
|
|
|
|
|
Because Psycopg is a C extension module, it is not possible for coroutine
|
|
|
|
libraries to patch it: Psycopg instead enables cooperative multithreading by
|
|
|
|
allowing the registration of a *wait callback* using the
|
|
|
|
`psycopg2.extensions.set_wait_callback()` function. When a wait callback is
|
|
|
|
registered, Psycopg will use `libpq non-blocking calls`__ instead of the regular
|
|
|
|
blocking ones, and will delegate to the callback the responsibility to wait
|
2010-04-23 16:19:43 +04:00
|
|
|
for the socket to become readable or writable.
|
2010-04-04 06:10:18 +04:00
|
|
|
|
2010-04-23 16:19:43 +04:00
|
|
|
Working this way, the caller does not have the complete freedom to schedule the
|
|
|
|
socket check whenever they want as with an :ref:`asynchronous connection
|
|
|
|
<async-support>`, but has the advantage of maintaining a complete |DBAPI|
|
|
|
|
semantics: from the point of view of the end user, all Psycopg functions and
|
|
|
|
objects will work transparently in the coroutine environment (blocking the
|
|
|
|
calling green thread and giving other green threads the possibility to be
|
|
|
|
scheduled), allowing non modified code and third party libraries (such as
|
|
|
|
SQLAlchemy_) to be used in coroutine-based programs.
|
2010-04-04 06:10:18 +04:00
|
|
|
|
2010-11-06 02:58:10 +03:00
|
|
|
.. warning::
|
|
|
|
Psycopg connections are not *green thread safe* and can't be used
|
2011-06-05 19:22:54 +04:00
|
|
|
concurrently by different green threads. Trying to execute more than one
|
|
|
|
command at time using one cursor per thread will result in an error (or a
|
|
|
|
deadlock on versions before 2.4.2).
|
2010-11-06 02:58:10 +03:00
|
|
|
|
|
|
|
Therefore, programmers are advised to either avoid sharing connections
|
|
|
|
between coroutines or to use a library-friendly lock to synchronize shared
|
|
|
|
connections, e.g. for pooling.
|
2010-04-04 06:10:18 +04:00
|
|
|
|
|
|
|
Coroutine libraries authors should provide a callback implementation (and
|
2010-11-06 02:58:10 +03:00
|
|
|
possibly a method to register it) to make Psycopg as green as they want. An
|
|
|
|
example callback (using `!select()` to block) is provided as
|
2010-04-04 06:10:18 +04:00
|
|
|
`psycopg2.extras.wait_select()`: it boils down to something similar to::
|
|
|
|
|
|
|
|
def wait_select(conn):
|
|
|
|
while 1:
|
|
|
|
state = conn.poll()
|
|
|
|
if state == extensions.POLL_OK:
|
|
|
|
break
|
|
|
|
elif state == extensions.POLL_READ:
|
|
|
|
select.select([conn.fileno()], [], [])
|
|
|
|
elif state == extensions.POLL_WRITE:
|
|
|
|
select.select([], [conn.fileno()], [])
|
|
|
|
else:
|
|
|
|
raise OperationalError("bad state from poll: %s" % state)
|
|
|
|
|
2010-12-02 20:13:13 +03:00
|
|
|
Providing callback functions for the single coroutine libraries is out of
|
|
|
|
psycopg2 scope, as the callback can be tied to the libraries' implementation
|
|
|
|
details. You can check the `psycogreen`_ project for further informations and
|
|
|
|
resources about the topic.
|
|
|
|
|
2010-04-04 06:10:18 +04:00
|
|
|
.. _coroutine: http://en.wikipedia.org/wiki/Coroutine
|
|
|
|
.. _greenlet: http://pypi.python.org/pypi/greenlet
|
2010-04-23 16:19:43 +04:00
|
|
|
.. _green threads: http://en.wikipedia.org/wiki/Green_threads
|
2010-04-04 06:10:18 +04:00
|
|
|
.. _Eventlet: http://eventlet.net/
|
|
|
|
.. _gevent: http://www.gevent.org/
|
|
|
|
.. _SQLAlchemy: http://www.sqlalchemy.org/
|
2010-12-02 20:13:13 +03:00
|
|
|
.. _psycogreen: http://bitbucket.org/dvarrazzo/psycogreen/
|
2012-02-28 20:28:07 +04:00
|
|
|
.. __: http://www.postgresql.org/docs/current/static/libpq-async.html
|
2010-04-04 06:10:18 +04:00
|
|
|
|
2010-04-21 15:42:25 +04:00
|
|
|
.. warning::
|
2011-09-22 18:50:50 +04:00
|
|
|
|
2010-04-21 15:42:25 +04:00
|
|
|
:ref:`COPY commands <copy>` are currently not supported when a wait callback
|
|
|
|
is registered, but they will be probably implemented in a future release.
|
2010-04-04 06:10:18 +04:00
|
|
|
|
2010-05-09 23:34:02 +04:00
|
|
|
:ref:`Large objects <large-objects>` are not supported either: they are
|
|
|
|
not compatible with asynchronous connections.
|
|
|
|
|
2010-04-04 06:10:18 +04:00
|
|
|
|
2010-02-13 19:06:39 +03:00
|
|
|
.. testcode::
|
|
|
|
:hide:
|
|
|
|
|
2010-04-20 02:49:14 +04:00
|
|
|
aconn.close()
|
2010-02-13 19:06:39 +03:00
|
|
|
conn.rollback()
|
|
|
|
cur.execute("DROP TABLE atable")
|
|
|
|
conn.commit()
|
|
|
|
cur.close()
|
|
|
|
conn.close()
|
2016-08-07 04:07:16 +03:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
.. index::
|
|
|
|
single: Replication
|
|
|
|
|
|
|
|
Replication protocol support
|
|
|
|
----------------------------
|
|
|
|
|
|
|
|
.. versionadded:: 2.7
|
|
|
|
|
|
|
|
Modern PostgreSQL servers (version 9.0 and above) support replication. The
|
|
|
|
replication protocol is built on top of the client-server protocol and can be
|
|
|
|
operated using ``libpq``, as such it can be also operated by ``psycopg2``.
|
|
|
|
The replication protocol can be operated on both synchronous and
|
|
|
|
:ref:`asynchronous <async-support>` connections.
|
|
|
|
|
|
|
|
Server version 9.4 adds a new feature called *Logical Replication*.
|
|
|
|
|
|
|
|
.. seealso::
|
|
|
|
|
|
|
|
- PostgreSQL `Streaming Replication Protocol`__
|
|
|
|
|
|
|
|
.. __: http://www.postgresql.org/docs/current/static/protocol-replication.html
|
|
|
|
|
|
|
|
|
|
|
|
Logical replication Quick-Start
|
|
|
|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
|
|
|
|
|
|
You must be using PostgreSQL server version 9.4 or above to run this quick
|
|
|
|
start.
|
|
|
|
|
|
|
|
Make sure that replication connections are permitted for user ``postgres`` in
|
|
|
|
``pg_hba.conf`` and reload the server configuration. You also need to set
|
|
|
|
``wal_level=logical`` and ``max_wal_senders``, ``max_replication_slots`` to
|
|
|
|
value greater than zero in ``postgresql.conf`` (these changes require a server
|
|
|
|
restart). Create a database ``psycopg2test``.
|
|
|
|
|
|
|
|
Then run the following code to quickly try the replication support out. This
|
|
|
|
is not production code -- it has no error handling, it sends feedback too
|
|
|
|
often, etc. -- and it's only intended as a simple demo of logical
|
|
|
|
replication::
|
|
|
|
|
|
|
|
from __future__ import print_function
|
|
|
|
import sys
|
|
|
|
import psycopg2
|
|
|
|
import psycopg2.extras
|
|
|
|
|
|
|
|
conn = psycopg2.connect('dbname=psycopg2test user=postgres',
|
|
|
|
connection_factory=psycopg2.extras.LogicalReplicationConnection)
|
|
|
|
cur = conn.cursor()
|
|
|
|
try:
|
|
|
|
# test_decoding produces textual output
|
|
|
|
cur.start_replication(slot_name='pytest', decode=True)
|
|
|
|
except psycopg2.ProgrammingError:
|
|
|
|
cur.create_replication_slot('pytest', output_plugin='test_decoding')
|
|
|
|
cur.start_replication(slot_name='pytest', decode=True)
|
|
|
|
|
|
|
|
class DemoConsumer(object):
|
|
|
|
def __call__(self, msg):
|
|
|
|
print(msg.payload)
|
|
|
|
msg.cursor.send_feedback(flush_lsn=msg.data_start)
|
|
|
|
|
|
|
|
democonsumer = DemoConsumer()
|
|
|
|
|
|
|
|
print("Starting streaming, press Control-C to end...", file=sys.stderr)
|
|
|
|
try:
|
|
|
|
cur.consume_stream(democonsumer)
|
|
|
|
except KeyboardInterrupt:
|
|
|
|
cur.close()
|
|
|
|
conn.close()
|
|
|
|
print("The slot 'pytest' still exists. Drop it with "
|
|
|
|
"SELECT pg_drop_replication_slot('pytest'); if no longer needed.",
|
|
|
|
file=sys.stderr)
|
|
|
|
print("WARNING: Transaction logs will accumulate in pg_xlog "
|
|
|
|
"until the slot is dropped.", file=sys.stderr)
|
|
|
|
|
|
|
|
|
|
|
|
You can now make changes to the ``psycopg2test`` database using a normal
|
|
|
|
psycopg2 session, ``psql``, etc. and see the logical decoding stream printed
|
|
|
|
by this demo client.
|
|
|
|
|
|
|
|
This will continue running until terminated with ``Control-C``.
|
|
|
|
|
|
|
|
For the details see :ref:`replication-objects`.
|