Documentation cleanup

Added several links to the Python documentation using the 'intersphinx'
extension.
This commit is contained in:
Daniele Varrazzo 2011-02-19 16:16:28 +00:00
parent 75c61c2e80
commit 556b4d461e
16 changed files with 164 additions and 135 deletions

View File

@ -103,14 +103,15 @@ There are two basic ways to have a Python object adapted to SQL:
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
example you can take a look to the source code for the
example you can take a look at the source code for the
`psycopg2.extras.Inet` object.
- If implementing the `!ISQLQuote` interface directly in the object is not an
option, you can use an adaptation function, taking the object to be adapted
as argument and returning a conforming object. The adapter must be
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
registered via the `~psycopg2.extensions.register_adapter()` function. A
simple example wrapper is the `!psycopg2.extras.UUID_adapter` used by the
simple example wrapper is `!psycopg2.extras.UUID_adapter` used by the
`~psycopg2.extras.register_uuid()` function.
A convenient object to write adapters is the `~psycopg2.extensions.AsIs`
@ -254,7 +255,7 @@ 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
function such as |select()|_ to sleep until awaken from the kernel when there is
function such as :py:func:`~select.select` to sleep until awaken from the kernel when there is
some data to read on the connection, thereby using no CPU unless there is
something to read::
@ -288,9 +289,9 @@ in a separate :program:`psql` shell, the output may look similar to::
Timeout
...
Notice that the payload is only available from PostgreSQL 9.0: notifications
received from a previous version server will have the `!payload` attribute set
to the empty string.
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.
.. versionchanged:: 2.3
Added `~psycopg2.extensions.Notify` object and handling notification
@ -321,7 +322,7 @@ descriptor and `~connection.poll()` to make communication proceed according to
the current connection state.
The following is an example loop using methods `!fileno()` and `!poll()`
together with the Python |select()|_ function in order to carry on
together with the Python :py:func:`~select.select` function in order to carry on
asynchronous operations with Psycopg::
def wait(conn):
@ -336,9 +337,6 @@ asynchronous operations with Psycopg::
else:
raise psycopg2.OperationalError("poll() returned %s" % state)
.. |select()| replace:: `!select()`
.. _select(): http://docs.python.org/library/select.html#select.select
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
@ -371,7 +369,7 @@ client and available using the regular cursor methods:
42
When an asynchronous query is being executed, `connection.isexecuting()` returns
`True`. Two cursors can't execute concurrent queries on the same asynchronous
`!True`. Two cursors can't execute concurrent queries on the same asynchronous
connection.
There are several limitations in using asynchronous connections: the

View File

@ -23,7 +23,7 @@ sys.path.append(os.path.abspath('tools/lib'))
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.ifconfig',
'sphinx.ext.doctest']
'sphinx.ext.doctest', 'sphinx.ext.intersphinx' ]
# Specific extensions for Psycopg documentation.
extensions += [ 'dbapi_extension', 'sql_role' ]
@ -42,7 +42,7 @@ master_doc = 'index'
# General information about the project.
project = u'Psycopg'
copyright = u'2001-2010, Federico Di Gregorio. Documentation by Daniele Varrazzo'
copyright = u'2001-2011, Federico Di Gregorio. Documentation by Daniele Varrazzo'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
@ -50,14 +50,21 @@ copyright = u'2001-2010, Federico Di Gregorio. Documentation by Daniele Varrazzo
#
# The short X.Y version.
version = '2.0'
# The full version, including alpha/beta/rc tags.
try:
import psycopg2
release = psycopg2.__version__.split()[0]
version = '.'.join(release.split('.')[:2])
except ImportError:
print "WARNING: couldn't import psycopg to read version."
release = version
intersphinx_mapping = {
'py': ('http://docs.python.org/', None),
'py3': ('http://docs.python.org/3.2', None),
}
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None

View File

@ -62,8 +62,8 @@ The ``connection`` class
.. method:: close()
Close the connection now (rather than whenever `__del__()` is
called). The connection will be unusable from this point forward; an
Close the connection now (rather than whenever `del` is executed).
The connection will be unusable from this point forward; an
`~psycopg2.InterfaceError` will be raised if any operation is
attempted with the connection. The same applies to all cursor objects
trying to use the connection. Note that closing a connection without
@ -124,9 +124,10 @@ The ``connection`` class
constraints are explained in :ref:`tpc`.
The values passed to the method will be available on the returned
object as the members `!format_id`, `!gtrid`, `!bqual`. The object
also allows accessing to these members and unpacking as a 3-items
tuple.
object as the members `~psycopg2.extensions.Xid.format_id`,
`~psycopg2.extensions.Xid.gtrid`, `~psycopg2.extensions.Xid.bqual`.
The object also allows accessing to these members and unpacking as a
3-items tuple.
.. method:: tpc_begin(xid)
@ -230,7 +231,7 @@ The ``connection`` class
If a transaction was not initiated by Psycopg, the returned Xids will
have attributes `~psycopg2.extensions.Xid.format_id` and
`~psycopg2.extensions.Xid.bqual` set to `None` and the
`~psycopg2.extensions.Xid.bqual` set to `!None` and the
`~psycopg2.extensions.Xid.gtrid` set to the PostgreSQL transaction ID: such Xids are still
usable for recovery. Psycopg uses the same algorithm of the
`PostgreSQL JDBC driver`__ to encode a XA triple in a string, so
@ -418,7 +419,7 @@ The ``connection`` class
``session_authorization``, ``DateStyle``, ``TimeZone``,
``integer_datetimes``, and ``standard_conforming_strings``.
If server did not report requested parameter, return ``None``.
If server did not report requested parameter, return `!None`.
.. seealso:: libpq docs for `PQparameterStatus()`__ for details.
@ -499,8 +500,8 @@ The ``connection`` class
a new large object and and have its OID assigned automatically.
:param mode: Access mode to the object, see below.
:param new_oid: Create a new object using the specified OID. The
function raises `OperationalError` if the OID is already in
use. Default is 0, meaning assign a new one automatically.
function raises `~psycopg2.OperationalError` if the OID is already
in use. Default is 0, meaning assign a new one automatically.
:param new_file: The name of a file to be imported in the the database
(using the |lo_import|_ function)
:param lobject_factory: Subclass of
@ -518,8 +519,8 @@ The ``connection`` class
``w`` Open for write only
``rw`` Open for read/write
``n`` Don't open the file
``b`` Don't decode read data (return data as `str` in Python 2 or `bytes` in Python 3)
``t`` Decode read data according to `connection.encoding` (return data as `unicode` in Python 2 or `str` in Python 3)
``b`` Don't decode read data (return data as `!str` in Python 2 or `!bytes` in Python 3)
``t`` Decode read data according to `connection.encoding` (return data as `!unicode` in Python 2 or `!str` in Python 3)
======= =========
``b`` and ``t`` can be specified together with a read/write mode. If
@ -571,7 +572,7 @@ The ``connection`` class
.. method:: isexecuting()
Return `True` if the connection is executing an asynchronous operation.
Return `!True` if the connection is executing an asynchronous operation.
.. testcode::

View File

@ -40,7 +40,7 @@ The ``cursor`` class
This read-only attribute is a sequence of 7-item sequences.
Each of these sequences is a named tuple (a regular tuple if
`!collections.namedtuple()` is not available) containing information
:func:`collections.namedtuple` is not available) containing information
describing one result column:
0. `!name`: the name of the column returned.
@ -62,7 +62,7 @@ The ``cursor`` class
columns of type |NUMERIC|. `!None` for other types.
6. `!null_ok`: always `!None` as not easy to retrieve from the libpq.
This attribute will be ``None`` for operations that do not return rows
This attribute will be `!None` for operations that do not return rows
or if the cursor has not had an operation invoked via the
|execute*|_ methods yet.
@ -79,15 +79,15 @@ The ``cursor`` class
.. method:: close()
Close the cursor now (rather than whenever `!__del__()` is
called). The cursor will be unusable from this point forward; an
Close the cursor now (rather than whenever `del` is executed).
The cursor will be unusable from this point forward; an
`~psycopg2.InterfaceError` will be raised if any operation is
attempted with the cursor.
.. attribute:: closed
Read-only boolean attribute: specifies if the cursor is closed
(``True``) or not (``False``).
(`!True`) or not (`!False`).
.. extension::
@ -106,7 +106,7 @@ The ``cursor`` class
.. attribute:: name
Read-only attribute containing the name of the cursor if it was
creates as named cursor by `connection.cursor()`, or ``None`` if
creates as named cursor by `connection.cursor()`, or `!None` if
it is a client side cursor. See :ref:`server-side-cursors`.
.. extension::
@ -131,7 +131,7 @@ The ``cursor`` class
positional (``%s``) or named (:samp:`%({name})s`) placeholders. See
:ref:`query-parameters`.
The method returns `None`. If a query was executed, the returned
The method returns `!None`. If a query was executed, the returned
values can be retrieved using |fetch*|_ methods.
@ -215,7 +215,7 @@ The ``cursor`` class
.. method:: fetchone()
Fetch the next row of a query result set, returning a single tuple,
or ``None`` when no more data is available:
or `!None` when no more data is available:
>>> cur.execute("SELECT * FROM test WHERE id = %s", (3,))
>>> cur.fetchone()
@ -333,14 +333,14 @@ The ``cursor`` class
.. note::
The |DBAPI|_ interface reserves to redefine the latter case to
have the object return ``None`` instead of -1 in future versions
have the object return `!None` instead of -1 in future versions
of the specification.
.. attribute:: rownumber
This read-only attribute provides the current 0-based index of the
cursor in the result set or ``None`` if the index cannot be
cursor in the result set or `!None` if the index cannot be
determined.
The index can be seen as index of the cursor in a sequence (the result
@ -355,7 +355,7 @@ The ``cursor`` class
This read-only attribute provides the OID of the last row inserted
by the cursor. If the table wasn't created with OID support or the
last operation is not a single record insert, the attribute is set to
``None``.
`!None`.
.. note::
@ -374,7 +374,7 @@ The ``cursor`` class
.. attribute:: query
Read-only attribute containing the body of the last query sent to the
backend (including bound arguments). ``None`` if no query has been
backend (including bound arguments). `!None` if no query has been
executed yet:
>>> cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)", (42, 'bar'))
@ -419,11 +419,9 @@ The ``cursor`` class
.. attribute:: tzinfo_factory
The time zone factory used to handle data types such as
:sql:`TIMESTAMP WITH TIME ZONE`. It should be a |tzinfo|_ object.
See also the `psycopg2.tz` module.
.. |tzinfo| replace:: `!tzinfo`
.. _tzinfo: http://docs.python.org/library/datetime.html#tzinfo-objects
:sql:`TIMESTAMP WITH TIME ZONE`. It should be a `~datetime.tzinfo`
object. A few implementations are available in the `psycopg2.tz`
module.
.. method:: nextset()
@ -448,15 +446,15 @@ The ``cursor`` class
.. method:: copy_from(file, table, sep='\\t', null='\\N', columns=None)
Read data *from* the file-like object `file` appending them to
the table named `table`. `file` must have both
Read data *from* the file-like object *file* appending them to
the table named *table*. *file* must have both
`!read()` and `!readline()` method. See :ref:`copy` for an
overview.
The optional argument `sep` is the columns separator and
`null` represents :sql:`NULL` values in the file.
The optional argument *sep* is the columns separator and
*null* represents :sql:`NULL` values in the file.
The `columns` argument is a sequence containing the name of the
The *columns* argument is a sequence containing the name of the
fields where the read data will be entered. Its length and column
type should match the content of the read file. If not specifies, it
is assumed that the entire table matches the file structure.
@ -468,20 +466,24 @@ The ``cursor`` class
[(6, 42, 'foo'), (7, 74, 'bar')]
.. versionchanged:: 2.0.6
added the `columns` parameter.
added the *columns* parameter.
.. versionchanged:: 2.4
data read from files implementing the `io.TextIOBase` interface
are encoded in the connection `~connection.encoding` when sent to
the backend.
.. method:: copy_to(file, table, sep='\\t', null='\\N', columns=None)
Write the content of the table named `table` *to* the file-like
object `file`. `file` must have a `!write()` method.
Write the content of the table named *table* *to* the file-like
object *file*. *file* must have a `!write()` method.
See :ref:`copy` for an overview.
The optional argument `sep` is the columns separator and
`null` represents :sql:`NULL` values in the file.
The optional argument *sep* is the columns separator and
*null* represents :sql:`NULL` values in the file.
The `columns` argument is a sequence of field names: if not
``None`` only the specified fields will be included in the dump.
The *columns* argument is a sequence of field names: if not
`!None` only the specified fields will be included in the dump.
>>> cur.copy_to(sys.stdout, 'test', sep="|")
1|100|abc'def
@ -489,7 +491,12 @@ The ``cursor`` class
...
.. versionchanged:: 2.0.6
added the `columns` parameter.
added the *columns* parameter.
.. versionchanged:: 2.4
data sent to files implementing the `io.TextIOBase` interface
are decoded in the connection `~connection.encoding` when read
from the backend.
.. method:: copy_expert(sql, file [, size])
@ -498,10 +505,10 @@ The ``cursor`` class
handle all the parameters that PostgreSQL makes available (see
|COPY|__ command documentation).
`file` must be an open, readable file for :sql:`COPY FROM` or an
open, writeable file for :sql:`COPY TO`. The optional `size`
*file* must be an open, readable file for :sql:`COPY FROM` or an
open, writeable file for :sql:`COPY TO`. The optional *size*
argument, when specified for a :sql:`COPY FROM` statement, will be
passed to `file`\ 's read method to control the read buffer
passed to *file*\ 's read method to control the read buffer
size.
>>> cur.copy_expert("COPY test TO STDOUT WITH CSV HEADER", sys.stdout)
@ -515,6 +522,10 @@ The ``cursor`` class
.. versionadded:: 2.0.6
.. versionchanged:: 2.4
files implementing the `io.TextIOBase` interface are dealt with
using Unicode data instead of bytes.
.. testcode::
:hide:

View File

@ -201,10 +201,10 @@ deal with Python objects adaptation:
A conform object can implement this method if the SQL
representation depends on any server parameter, such as the server
version or the ``standard_conforming_string`` setting. Container
version or the :envvar:`standard_conforming_string` setting. Container
objects may store the connection and use it to recursively prepare
contained objects: see the implementation for
``psycopg2.extensions.SQL_IN`` for a simple example.
`psycopg2.extensions.SQL_IN` for a simple example.
.. class:: AsIs(object)
@ -303,7 +303,7 @@ details.
*adapter* should have signature :samp:`fun({value}, {cur})` where
*value* is the string representation returned by PostgreSQL and
*cur* is the cursor from which data are read. In case of
:sql:`NULL`, *value* will be ``None``. The adapter should return the
:sql:`NULL`, *value* will be `!None`. The adapter should return the
converted object.
See :ref:`type-casting-from-sql-to-python` for an usage example.

View File

@ -83,7 +83,7 @@ Real dictionary cursor
.. versionadded:: 2.3
These objects require `!collection.namedtuple()` to be found, so it is
These objects require :py:func:`collections.namedtuple` to be found, so it is
available out-of-the-box only from Python 2.6. Anyway, the namedtuple
implementation is compatible with previous Python versions, so all you
have to do is to `download it`__ and make it available where we
@ -143,8 +143,8 @@ been greatly improved in capacity and usefulness with the addiction of many
functions. It supports GiST or GIN indexes allowing search by keys or
key/value pairs as well as regular BTree indexes for equality, uniqueness etc.
Psycopg can convert Python `dict` objects to and from |hstore| structures.
Only dictionaries with string/unicode keys and values are supported. `None`
Psycopg can convert Python `!dict` objects to and from |hstore| structures.
Only dictionaries with string/unicode keys and values are supported. `!None`
is also allowed as value. Psycopg uses a more efficient |hstore|
representation when dealing with PostgreSQL 9.0 but previous server versions
are supportes as well. By default the adapter/typecaster are disabled: they
@ -169,7 +169,7 @@ Composite types casting
Using `register_composite()` it is possible to cast a PostgreSQL composite
type (e.g. created with |CREATE TYPE|_ command) into a Python named tuple, or
into a regular tuple if `!collections.namedtuple()` is not found.
into a regular tuple if :py:func:`collections.namedtuple` is not found.
.. |CREATE TYPE| replace:: :sql:`CREATE TYPE`
.. _CREATE TYPE: http://www.postgresql.org/docs/9.0/static/sql-createtype.html

View File

@ -73,7 +73,7 @@ I try to execute a query but it fails with the error *not all arguments converte
>>> cur.execute("INSERT INTO foo VALUES (%s)", ("bar",)) # correct
>>> cur.execute("INSERT INTO foo VALUES (%s)", ["bar"]) # correct
My database is Unicode, but I receive all the strings as UTF-8 `str`. Can I receive `unicode` objects instead?
My database is Unicode, but I receive all the strings as UTF-8 `!str`. Can I receive `!unicode` objects instead?
The following magic formula will do the trick::
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
@ -100,8 +100,8 @@ Transferring binary data from PostgreSQL 9.0 doesn't work.
earlier. Three options to solve the problem are:
- set the bytea_output__ parameter to ``escape`` in the server;
- use ``SET bytea_output TO escape`` in the client before reading binary
data;
- execute the database command ``SET bytea_output TO escape;`` in the
session before reading binary data;
- upgrade the libpq library on the client to at least 9.0.
.. __: http://www.postgresql.org/docs/9.0/static/datatype-binary.html

View File

@ -30,13 +30,13 @@ The module interface respects the standard defined in the |DBAPI|_.
The full list of available parameters is:
- `dbname` -- the database name (only in dsn string)
- `database` -- the database name (only as keyword argument)
- `user` -- user name used to authenticate
- `password` -- password used to authenticate
- `host` -- database host address (defaults to UNIX socket if not provided)
- `port` -- connection port number (defaults to 5432 if not provided)
- `sslmode` -- `SSL TCP/IP negotiation`__ mode
- `!dbname` -- the database name (only in dsn string)
- `!database` -- the database name (only as keyword argument)
- `!user` -- user name used to authenticate
- `!password` -- password used to authenticate
- `!host` -- database host address (defaults to UNIX socket if not provided)
- `!port` -- connection port number (defaults to 5432 if not provided)
- `!sslmode` -- `SSL TCP/IP negotiation`__ mode
.. __: http://www.postgresql.org/docs/9.0/static/libpq-ssl.html#LIBPQ-SSL-SSLMODE-STATEMENTS
@ -87,23 +87,23 @@ available through the following exceptions:
.. exception:: Warning
Exception raised for important warnings like data truncations while
inserting, etc. It is a subclass of the Python |StandardError|_.
inserting, etc. It is a subclass of the Python `~exceptions.StandardError`.
.. exception:: Error
Exception that is the base class of all other error exceptions. You can
use this to catch all errors with one single ``except`` statement. Warnings
use this to catch all errors with one single `!except` statement. Warnings
are not considered errors and thus not use this class as base. It
is a subclass of the Python |StandardError|_.
is a subclass of the Python `!StandardError`.
.. attribute:: pgerror
String representing the error message returned by the backend,
``None`` if not available.
`!None` if not available.
.. attribute:: pgcode
String representing the error code returned by the backend, ``None``
String representing the error code returned by the backend, `!None`
if not available. The `~psycopg2.errorcodes` module contains
symbolic constants representing PostgreSQL error codes.
@ -197,7 +197,7 @@ This is the exception inheritance layout:
.. parsed-literal::
|StandardError|
`!StandardError`
\|__ `Warning`
\|__ `Error`
\|__ `InterfaceError`
@ -212,9 +212,6 @@ This is the exception inheritance layout:
\|__ `NotSupportedError`
.. |StandardError| replace:: `!StandardError`
.. _StandardError: http://docs.python.org/library/exceptions.html#exceptions.StandardError
.. _type-objects-and-constructors:

View File

@ -24,7 +24,7 @@ directly into the client application.
.. method:: getconn(key=None)
Get a free connection and assign it to *key* if not ``None``.
Get a free connection and assign it to *key* if not `!None`.
.. method:: putconn(conn, key=None)

View File

@ -6,8 +6,8 @@
.. module:: psycopg2.tz
This module holds two different tzinfo implementations that can be used as the
`tzinfo` argument to datetime constructors, directly passed to Psycopg
functions or used to set the `cursor.tzinfo_factory` attribute in
`tzinfo` argument to `~datetime.datetime` constructors, directly passed to
Psycopg functions or used to set the `cursor.tzinfo_factory` attribute in
cursors.
.. autoclass:: psycopg2.tz.FixedOffsetTimezone

View File

@ -207,39 +207,46 @@ module.
In the following examples the method `~cursor.mogrify()` is used to show
the SQL string that would be sent to the database.
.. _adapt-consts:
.. index::
pair: None; Adaptation
single: NULL; Adaptation
pair: Boolean; Adaptation
- Python ``None`` and boolean values are converted into the proper SQL
literals::
- Python `None` and boolean values `True` and `False` are converted into the
proper SQL literals::
>>> cur.mogrify("SELECT %s, %s, %s;", (None, True, False))
>>> 'SELECT NULL, true, false;'
.. _adapt-numbers:
.. index::
single: Adaptation; numbers
single: Integer; Adaptation
single: Float; Adaptation
single: Decimal; Adaptation
- Numeric objects: `!int`, `!long`, `!float`,
`!Decimal` are converted in the PostgreSQL numerical representation::
- Numeric objects: `int`, `long`, `float`, `~decimal.Decimal` are converted in
the PostgreSQL numerical representation::
>>> cur.mogrify("SELECT %s, %s, %s, %s;", (10, 10L, 10.0, Decimal("10.00")))
>>> 'SELECT 10, 10, 10.0, 10.00;'
.. _adapt-string:
.. index::
pair: Strings; Adaptation
single: Unicode; Adaptation
- String types: `!str`, `!unicode` are converted in SQL string syntax.
- String types: `str`, `unicode` are converted in SQL string syntax.
`!unicode` objects (`!str` in Python 3) are encoded in the connection
`~connection.encoding` to be sent to the backend: trying to send a character
not supported by the encoding will result in an error. Received data can be
converted either as `!str` or `!unicode`: see :ref:`unicode-handling` for
received, either `!str` or `!unicode`
converted either as `!str` or `!unicode`: see :ref:`unicode-handling`.
.. _adapt-binary:
.. index::
single: Buffer; Adaptation
@ -251,8 +258,8 @@ the SQL string that would be sent to the database.
- Binary types: Python types representing binary objects are converted in
PostgreSQL binary string syntax, suitable for :sql:`bytea` fields. Such
types are `!buffer` (only available in Python 2), `!memoryview` (available
from Python 2.7), `!bytearray` (available from Python 2.6) and `!bytes`
types are `buffer` (only available in Python 2), `memoryview` (available
from Python 2.7), `bytearray` (available from Python 2.6) and `bytes`
(only form Python 3: the name is available from Python 2.6 but it's only an
alias for the type `!str`). Any object implementing the `Revised Buffer
Protocol`__ should be usable as binary type where the protocol is supported
@ -287,6 +294,8 @@ the SQL string that would be sent to the database.
.. __: http://www.postgresql.org/docs/9.0/static/datatype-binary.html
.. __: http://www.postgresql.org/docs/9.0/static/runtime-config-client.html#GUC-BYTEA-OUTPUT
.. _adapt-date:
.. index::
single: Adaptation; Date/Time objects
single: Date objects; Adaptation
@ -294,8 +303,8 @@ the SQL string that would be sent to the database.
single: Interval objects; Adaptation
single: mx.DateTime; Adaptation
- Date and time objects: builtin `!datetime`, `!date`,
`!time`. `!timedelta` are converted into PostgreSQL's
- Date and time objects: builtin `~datetime.datetime`, `~datetime.date`,
`~datetime.time`, `~datetime.timedelta` are converted into PostgreSQL's
:sql:`timestamp`, :sql:`date`, :sql:`time`, :sql:`interval` data types.
Time zones are supported too. The Egenix `mx.DateTime`_ objects are adapted
the same way::
@ -310,6 +319,8 @@ the SQL string that would be sent to the database.
>>> cur.mogrify("SELECT %s;", (dt - datetime.datetime(2010,1,1),))
"SELECT '38 days 6027.425337 seconds';"
.. _adapt-list:
.. index::
single: Array; Adaptation
double: Lists; Adaptation
@ -319,6 +330,8 @@ the SQL string that would be sent to the database.
>>> cur.mogrify("SELECT %s;", ([10, 20, 30], ))
'SELECT ARRAY[10, 20, 30];'
.. _adapt-tuple:
.. index::
double: Tuple; Adaptation
single: IN operator
@ -347,11 +360,18 @@ the SQL string that would be sent to the database.
registered.
.. versionchanged:: 2.3
named tuples are adapted like regular tuples and can thus be used to
represent composite types.
`~collections.namedtuple` instances are adapted like regular tuples and
can thus be used to represent composite types.
- Python dictionaries are converted into the |hstore|_ data type. See
`~psycopg2.extras.register_hstore()` for further details.
.. _adapt-dict:
.. index::
single: dict; Adaptation
single: hstore; Adaptation
- Python dictionaries are converted into the |hstore|_ data type. By default
the adapter is not enabled: see `~psycopg2.extras.register_hstore()` for
further details.
.. |hstore| replace:: :sql:`hstore`
.. _hstore: http://www.postgresql.org/docs/9.0/static/hstore.html
@ -441,8 +461,8 @@ Time zones handling
^^^^^^^^^^^^^^^^^^^
The PostgreSQL type :sql:`timestamp with time zone` is converted into Python
`!datetime` objects with a `!tzinfo` attribute set to a
`~psycopg2.tz.FixedOffsetTimezone` instance.
`~datetime.datetime` objects with a `~datetime.datetime.tzinfo` attribute set
to a `~psycopg2.tz.FixedOffsetTimezone` instance.
>>> cur.execute("SET TIME ZONE 'Europe/Rome';") # UTC + 1 hour
>>> cur.execute("SELECT '2010-01-01 10:30:45'::timestamptz;")
@ -450,7 +470,7 @@ The PostgreSQL type :sql:`timestamp with time zone` is converted into Python
psycopg2.tz.FixedOffsetTimezone(offset=60, name=None)
Notice that only time zones with an integer number of minutes are supported:
this is a limitation of the Python `!datetime` module. A few historical time
this is a limitation of the Python `datetime` module. A few historical time
zones had seconds in the UTC offset: these time zones will have the offset
rounded to the nearest minute, with an error of up to 30 seconds.
@ -462,7 +482,7 @@ rounded to the nearest minute, with an error of up to 30 seconds.
.. versionchanged:: 2.2.2
timezones with seconds are supported (with rounding). Previously such
timezones raised an error. In order to deal with them in previous
versions use `psycopg2.extras.register_tstz_w_secs`.
versions use `psycopg2.extras.register_tstz_w_secs()`.
.. index:: Transaction, Begin, Commit, Rollback, Autocommit
@ -485,7 +505,7 @@ The connection is responsible to terminate its transaction, calling either the
`~connection.commit()` or `~connection.rollback()` method. Committed
changes are immediately made persistent into the database. Closing the
connection using the `~connection.close()` method or destroying the
connection object (calling `!__del__()` or letting it fall out of scope)
connection object (using `!del` or letting it fall out of scope)
will result in an implicit `!rollback()` call.
It is possible to set the connection in *autocommit* mode: this way all the
@ -564,13 +584,11 @@ the same connection, all the commands will be executed in the same session
The above observations are only valid for regular threads: they don't apply to
forked processes nor to green threads. `libpq` connections `shouldn't be used by a
forked processes`__, so when using a module such as |multiprocessing|__ or a
forked processes`__, so when using a module such as `multiprocessing` or a
forking web deploy method such as FastCGI ensure to create the connections
*after* the fork.
.. __: http://www.postgresql.org/docs/9.0/static/libpq-connect.html#LIBPQ-CONNECT
.. |multiprocessing| replace:: `!multiprocessing`
.. __: http://docs.python.org/library/multiprocessing.html
Connections shouldn't be shared either by different green threads: doing so
may result in a deadlock. See :ref:`green-support` for further details.

View File

@ -232,7 +232,7 @@ class RealDictCursor(DictCursorBase):
self._query_executed = 0
class RealDictRow(dict):
"""A ``dict`` subclass representing a data record."""
"""A `!dict` subclass representing a data record."""
__slots__ = ('_column_mapping')
@ -253,7 +253,7 @@ class NamedTupleConnection(_connection):
return _connection.cursor(self, *args, **kwargs)
class NamedTupleCursor(_cursor):
"""A cursor that generates results as |namedtuple|__.
"""A cursor that generates results as `~collections.namedtuple`.
`!fetch*()` methods will return named tuples instead of regular tuples, so
their elements can be accessed both as regular numeric items as well as
@ -267,9 +267,6 @@ class NamedTupleCursor(_cursor):
100
>>> rec.data
"abc'def"
.. |namedtuple| replace:: `!namedtuple`
.. __: http://docs.python.org/release/2.6/library/collections.html#collections.namedtuple
"""
Record = None
@ -327,9 +324,9 @@ class LoggingConnection(_connection):
"""
def initialize(self, logobj):
"""Initialize the connection to log to ``logobj``.
"""Initialize the connection to log to `!logobj`.
The ``logobj`` parameter can be an open file object or a Logger
The `!logobj` parameter can be an open file object or a Logger
instance from the standard logging module.
"""
self._logobj = logobj
@ -700,7 +697,7 @@ WHERE typname = 'hstore' and nspname = 'public';
return oids
def register_hstore(conn_or_curs, globally=False, unicode=False):
"""Register adapter and typecaster for `dict`\-\ |hstore| conversions.
"""Register adapter and typecaster for `!dict`\-\ |hstore| conversions.
The function must receive a connection or cursor as the |hstore| oid is
different in each database. The typecaster will normally be registered
@ -708,9 +705,9 @@ def register_hstore(conn_or_curs, globally=False, unicode=False):
uses a single database you can pass *globally*\=True to have the typecaster
registered on all the connections.
On Python 2, by default the returned dicts will have `str` objects as keys and values:
use *unicode*\=True to return `unicode` objects instead. When adapting a
dictionary both `str` and `unicode` keys and values are handled (the
On Python 2, by default the returned dicts will have `!str` objects as keys and values:
use *unicode*\=True to return `!unicode` objects instead. When adapting a
dictionary both `!str` and `!unicode` keys and values are handled (the
`unicode` values will be converted according to the current
`~connection.encoding`). The option is not available on Python 3.
@ -750,9 +747,9 @@ class CompositeCaster(object):
.. attribute:: type
The type of the Python objects returned. If `!collections.namedtuple()`
The type of the Python objects returned. If :py:func:`collections.namedtuple()`
is available, it is a named tuple with attributes equal to the type
components. Otherwise it is just the `tuple` object.
components. Otherwise it is just the `!tuple` object.
.. attribute:: attnames
@ -875,8 +872,8 @@ def register_composite(name, conn_or_curs, globally=False):
the |CREATE TYPE|_ command
:param conn_or_curs: a connection or cursor used to find the type oid and
components; the typecaster is registered in a scope limited to this
object, unless *globally* is set to `True`
:param globally: if `False` (default) register the typecaster only on
object, unless *globally* is set to `!True`
:param globally: if `!False` (default) register the typecaster only on
*conn_or_curs*, otherwise register it globally
:return: the registered `CompositeCaster` instance responsible for the
conversion

View File

@ -638,7 +638,7 @@ psyco_curs_cast(cursorObject *self, PyObject *args)
"fetchone() -> tuple or None\n\n" \
"Return the next row of a query result set in the form of a tuple (by\n" \
"default) or using the sequence factory previously set in the\n" \
"`row_factory` attribute. Return `None` when no more data is available.\n"
"`row_factory` attribute. Return `!None` when no more data is available.\n"
static int
_psyco_curs_prefetch(cursorObject *self)
@ -837,7 +837,7 @@ psyco_curs_next_named(cursorObject *self)
"fetchmany(size=self.arraysize) -> list of tuple\n\n" \
"Return the next `size` rows of a query result set in the form of a list\n" \
"of tuples (by default) or using the sequence factory previously set in\n" \
"the `row_factory` attribute. Return `None` when no more data is available.\n"
"the `row_factory` attribute. Return `!None` when no more data is available.\n"
static PyObject *
psyco_curs_fetchmany(cursorObject *self, PyObject *args, PyObject *kwords)
@ -915,7 +915,7 @@ psyco_curs_fetchmany(cursorObject *self, PyObject *args, PyObject *kwords)
"Return all the remaining rows of a query result set.\n\n" \
"Rows are returned in the form of a list of tuples (by default) or using\n" \
"the sequence factory previously set in the `row_factory` attribute.\n" \
"Return `None` when no more data is available.\n"
"Return `!None` when no more data is available.\n"
static PyObject *
psyco_curs_fetchall(cursorObject *self, PyObject *args)

View File

@ -55,7 +55,7 @@ HIDDEN PyObject *psyco_set_wait_callback(PyObject *self, PyObject *obj);
#define psyco_get_wait_callback_doc \
"Return the currently registered wait callback.\n" \
"\n" \
"Return `None` if no callback is currently registered.\n"
"Return `!None` if no callback is currently registered.\n"
HIDDEN PyObject *psyco_get_wait_callback(PyObject *self, PyObject *obj);
HIDDEN int psyco_green(void);

View File

@ -264,7 +264,7 @@ psyco_connect(PyObject *self, PyObject *args, PyObject *keywds)
" * `name`: Name for the new type\n" \
" * `adapter`: Callable to perform type conversion.\n" \
" It must have the signature ``fun(value, cur)`` where ``value`` is\n" \
" the string representation returned by PostgreSQL (`None` if ``NULL``)\n" \
" the string representation returned by PostgreSQL (`!None` if ``NULL``)\n" \
" and ``cur`` is the cursor from which data are read."
static void

View File

@ -43,7 +43,7 @@ static const char xid_doc[] =
static const char format_id_doc[] =
"Format ID in a XA transaction.\n\n"
"A non-negative 32 bit integer.\n"
"`None` if the transaction doesn't follow the XA standard.";
"`!None` if the transaction doesn't follow the XA standard.";
static const char gtrid_doc[] =
"Global transaction ID in a XA transaction.\n\n"
@ -54,7 +54,7 @@ static const char bqual_doc[] =
"Branch qualifier of the transaction.\n\n"
"In a XA transaction every resource participating to a transaction\n"
"receives a distinct branch qualifier.\n"
"`None` if the transaction doesn't follow the XA standard.";
"`!None` if the transaction doesn't follow the XA standard.";
static const char prepared_doc[] =
"Timestamp (with timezone) in which a recovered transaction was prepared.";
@ -269,7 +269,7 @@ static const char xid_from_string_doc[] =
"the returned object will have `format_id`, `gtrid`, `bqual` set to\n"
"the values of the preparing XA id.\n"
"Otherwise only the `!gtrid` is populated with the unparsed string.\n"
"The operation is the inverse of the one performed by ``str(xid)``.";
"The operation is the inverse of the one performed by `!str(xid)`.";
static PyObject *
xid_from_string_method(PyObject *cls, PyObject *args)