Use the default role for cross referencing Python objects.

This commit is contained in:
Daniele Varrazzo 2010-02-26 00:17:52 +00:00
parent 4412826556
commit 97ced0d4f1
16 changed files with 261 additions and 261 deletions

View File

@ -21,10 +21,10 @@ Connection and cursor factories
------------------------------- -------------------------------
Psycopg exposes two new-style classes that can be sub-classed and expanded to Psycopg exposes two new-style classes that can be sub-classed and expanded to
adapt them to the needs of the programmer: :class:`psycopg2.extensions.cursor` adapt them to the needs of the programmer: `psycopg2.extensions.cursor`
and :class:`psycopg2.extensions.connection`. The :class:`connection` class is and `psycopg2.extensions.connection`. The `connection` class is
usually sub-classed only to provide an easy way to create customized cursors usually sub-classed only to provide an easy way to create customized cursors
but other uses are possible. :class:`cursor` is much more interesting, because but other uses are possible. `cursor` is much more interesting, because
it is the class where query building, execution and result type-casting into it is the class where query building, execution and result type-casting into
Python variables happens. Python variables happens.
@ -67,24 +67,24 @@ Adapting new Python types to SQL syntax
Any Python class or type can be adapted to an SQL string. Adaptation mechanism 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 is similar to the Object Adaptation proposed in the :pep:`246` and is exposed
by the :func:`psycopg2.extensions.adapt` function. by the `psycopg2.extensions.adapt()` function.
The :meth:`~cursor.execute` method adapts its arguments to the The `~cursor.execute()` method adapts its arguments to the
:class:`~psycopg2.extensions.ISQLQuote` protocol. Objects that conform to this `~psycopg2.extensions.ISQLQuote` protocol. Objects that conform to this
protocol expose a :meth:`!getquoted` method returning the SQL representation protocol expose a `!getquoted()` method returning the SQL representation
of the object as a string. of the object as a string.
The easiest way to adapt an object to an SQL string is to register an adapter The easiest way to adapt an object to an SQL string is to register an adapter
function via the :func:`~psycopg2.extensions.register_adapter` function. The function via the `~psycopg2.extensions.register_adapter()` function. The
adapter function must take the value to be adapted as argument and return a adapter function must take the value to be adapted as argument and return a
conform object. A convenient object is the :class:`~psycopg2.extensions.AsIs` conform object. A convenient object is the `~psycopg2.extensions.AsIs`
wrapper, whose :meth:`!getquoted` result is simply the :meth:`!str`\ ing wrapper, whose `!getquoted()` result is simply the `!str()`\ ing
conversion of the wrapped object. conversion of the wrapped object.
.. index:: .. index::
single: Example; Types adaptation single: Example; Types adaptation
Example: mapping of a :class:`!Point` class into the |point|_ PostgreSQL Example: mapping of a `!Point` class into the |point|_ PostgreSQL
geometric type: geometric type:
.. doctest:: .. doctest::
@ -126,7 +126,7 @@ through an user-defined adapting function. An adapter function takes two
arguments: the object string representation as returned by PostgreSQL and the arguments: the object string representation as returned by PostgreSQL and the
cursor currently being read, and should return a new Python object. For cursor currently being read, and should return a new Python object. For
example, the following function parses the PostgreSQL :sql:`point` example, the following function parses the PostgreSQL :sql:`point`
representation into the previously defined :class:`!Point` class: representation into the previously defined `!Point` class:
>>> def cast_point(value, cur): >>> def cast_point(value, cur):
... if value is None: ... if value is None:
@ -142,7 +142,7 @@ representation into the previously defined :class:`!Point` class:
In order to create a mapping from a PostgreSQL type (either standard or 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 user-defined), its OID must be known. It can be retrieved either by the second
column of the :attr:`cursor.description`: column of the `cursor.description`:
>>> cur.execute("SELECT NULL::point") >>> cur.execute("SELECT NULL::point")
>>> point_oid = cur.description[0][1] >>> point_oid = cur.description[0][1]
@ -168,9 +168,9 @@ After you know the object OID, you must can and register the new type:
>>> POINT = psycopg2.extensions.new_type((point_oid,), "POINT", cast_point) >>> POINT = psycopg2.extensions.new_type((point_oid,), "POINT", cast_point)
>>> psycopg2.extensions.register_type(POINT) >>> psycopg2.extensions.register_type(POINT)
The :func:`~psycopg2.extensions.new_type` function binds the object OIDs The `~psycopg2.extensions.new_type()` function binds the object OIDs
(more than one can be specified) to the adapter function. (more than one can be specified) to the adapter function.
:func:`~psycopg2.extensions.register_type` completes the spell. Conversion `~psycopg2.extensions.register_type()` completes the spell. Conversion
is automatically performed when a column whose type is a registered OID is is automatically performed when a column whose type is a registered OID is
read: read:
@ -196,9 +196,9 @@ facilities offered by PostgreSQL commands |LISTEN|_ and |NOTIFY|_. Please
refer to the PostgreSQL documentation for examples of how to use this form of refer to the PostgreSQL documentation for examples of how to use this form of
communications. communications.
Notifications received are made available in the :attr:`connection.notifies` Notifications received are made available in the `connection.notifies`
list. Notifications can be sent from Python code simply using a :sql:`NOTIFY` list. Notifications can be sent from Python code simply using a :sql:`NOTIFY`
command in an :meth:`~cursor.execute` call. command in an `~cursor.execute()` call.
Because of the way sessions interact with notifications (see |NOTIFY|_ Because of the way sessions interact with notifications (see |NOTIFY|_
documentation), you should keep the connection in :ref:`autocommit documentation), you should keep the connection in :ref:`autocommit
@ -261,7 +261,7 @@ Asynchronous queries
Discussion, testing and suggestions are welcome. Discussion, testing and suggestions are welcome.
Program code can initiate an asynchronous query by passing an ``async=1`` flag Program code can initiate an asynchronous query by passing an ``async=1`` flag
to the :meth:`~cursor.execute` or :meth:`~cursor.callproc` cursor methods. A to the `~cursor.execute()` or `~cursor.callproc()` cursor methods. A
very simple example, from the connection to the query:: very simple example, from the connection to the query::
conn = psycopg2.connect(database='test') conn = psycopg2.connect(database='test')
@ -273,39 +273,39 @@ doomed to fail (and raise an exception) until the original cursor (the one
executing the query) complete the asynchronous operation. This can happen in executing the query) complete the asynchronous operation. This can happen in
a number of different ways: a number of different ways:
1) one of the :meth:`!fetch*` methods is called, effectively blocking until 1) one of the `!fetch*()` methods is called, effectively blocking until
data has been sent from the backend to the client, terminating the query. data has been sent from the backend to the client, terminating the query.
2) :meth:`connection.cancel` is called. This method tries to abort the 2) `connection.cancel()` is called. This method tries to abort the
current query and will block until the query is aborted or fully executed. current query and will block until the query is aborted or fully executed.
The return value is ``True`` if the query was successfully aborted or The return value is ``True`` if the query was successfully aborted or
``False`` if it was executed. Query result are discarded in both cases. ``False`` if it was executed. Query result are discarded in both cases.
3) :meth:`~cursor.execute` is called again on the same cursor 3) `~cursor.execute()` is called again on the same cursor
(:meth:`!execute` on a different cursor will simply raise an exception). (`!execute()` on a different cursor will simply raise an exception).
This waits for the complete execution of the current query, discard any This waits for the complete execution of the current query, discard any
data and execute the new one. data and execute the new one.
Note that calling :meth:`!execute` two times in a row will not abort the Note that calling `!execute()` two times in a row will not abort the
former query and will temporarily go to synchronous mode until the first of former query and will temporarily go to synchronous mode until the first of
the two queries is executed. the two queries is executed.
Cursors now have some extra methods that make them useful during Cursors now have some extra methods that make them useful during
asynchronous queries: asynchronous queries:
:meth:`~cursor.fileno` `~cursor.fileno()`
Returns the file descriptor associated with the current connection and Returns the file descriptor associated with the current connection and
make possible to use a cursor in a context where a file object would be make possible to use a cursor in a context where a file object would be
expected (like in a :func:`select` call). expected (like in a `select()` call).
:meth:`~cursor.isready` `~cursor.isready()`
Returns ``False`` if the backend is still processing the query or ``True`` Returns ``False`` if the backend is still processing the query or ``True``
if data is ready to be fetched (by one of the :meth:`!fetch*` methods). if data is ready to be fetched (by one of the `!fetch*()` methods).
.. index:: .. index::
single: Example; Asynchronous query single: Example; Asynchronous query
A code snippet that shows how to use the cursor object in a :func:`!select` A code snippet that shows how to use the cursor object in a `!select()`
call:: call::
import psycopg2 import psycopg2

View File

@ -76,7 +76,7 @@ except ImportError:
exclude_trees = ['_build', 'html'] exclude_trees = ['_build', 'html']
# The reST default role (used for this markup: `text`) to use for all documents. # The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None default_role = 'obj'
# If true, '()' will be appended to :func: etc. cross-reference text. # If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True #add_function_parentheses = True

View File

@ -16,14 +16,14 @@ The ``connection`` class
a database session. a database session.
Connections are created using the factory function Connections are created using the factory function
:func:`~psycopg2.connect`. `~psycopg2.connect()`.
Connections are thread safe and can be shared among many thread. See Connections are thread safe and can be shared among many thread. See
:ref:`thread-safety` for details. :ref:`thread-safety` for details.
.. method:: cursor([name] [, cursor_factory]) .. method:: cursor([name] [, cursor_factory])
Return a new :class:`cursor` object using the connection. Return a new `cursor` object using the connection.
If `name` is specified, the returned cursor will be a *server If `name` is specified, the returned cursor will be a *server
side* (or *named*) cursor. Otherwise the cursor will be *client side*. side* (or *named*) cursor. Otherwise the cursor will be *client side*.
@ -31,7 +31,7 @@ The ``connection`` class
The `cursor_factory` argument can be used to create non-standard The `cursor_factory` argument can be used to create non-standard
cursors. The class returned should be a subclass of cursors. The class returned should be a subclass of
:class:`psycopg2.extensions.cursor`. See :ref:`subclassing-cursor` for `psycopg2.extensions.cursor`. See :ref:`subclassing-cursor` for
details. details.
.. extension:: .. extension::
@ -47,7 +47,7 @@ The ``connection`` class
Commit any pending transaction to the database. Psycopg can be set to Commit any pending transaction to the database. Psycopg can be set to
perform automatic commits at each operation, see perform automatic commits at each operation, see
:meth:`~connection.set_isolation_level`. `~connection.set_isolation_level()`.
.. index:: .. index::
@ -62,14 +62,14 @@ The ``connection`` class
.. method:: close() .. method:: close()
Close the connection now (rather than whenever :meth:`__del__` is Close the connection now (rather than whenever `__del__()` is
called). The connection will be unusable from this point forward; an called). The connection will be unusable from this point forward; an
:exc:`~psycopg2.InterfaceError` will be raised if any operation is `~psycopg2.InterfaceError` will be raised if any operation is
attempted with the connection. The same applies to all cursor objects attempted with the connection. The same applies to all cursor objects
trying to use the connection. Note that closing a connection without trying to use the connection. Note that closing a connection without
committing the changes first will cause an implicit rollback to be committing the changes first will cause an implicit rollback to be
performed (unless a different isolation level has been selected: see performed (unless a different isolation level has been selected: see
:meth:`~connection.set_isolation_level`). `~connection.set_isolation_level()`).
.. index:: .. index::
@ -77,8 +77,8 @@ The ``connection`` class
.. rubric:: Excetptions as connection class attributes .. rubric:: Excetptions as connection class attributes
The :class:`!connection` also exposes as attributes the same exceptions The `!connection` also exposes as attributes the same exceptions
available in the :mod:`psycopg2` module. See :ref:`dbapi-exceptions`. available in the `psycopg2` module. See :ref:`dbapi-exceptions`.
.. extension:: .. extension::
@ -131,13 +131,13 @@ The ``connection`` class
database between concurrent transactions. database between concurrent transactions.
The value set or read is an integer: symbolic constants are defined in The value set or read is an integer: symbolic constants are defined in
the module :mod:`psycopg2.extensions`: see the module `psycopg2.extensions`: see
:ref:`isolation-level-constants` for the available values. :ref:`isolation-level-constants` for the available values.
The default level is :sql:`READ COMMITTED`: at this level a The default level is :sql:`READ COMMITTED`: at this level a
transaction is automatically started the first time a database command transaction is automatically started the first time a database command
is executed. If you want an *autocommit* mode, switch to is executed. If you want an *autocommit* mode, switch to
:const:`~psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT` before `~psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT` before
executing any command:: executing any command::
>>> conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) >>> conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
@ -240,7 +240,7 @@ The ``connection`` class
Return the current session transaction status as an integer. Symbolic Return the current session transaction status as an integer. Symbolic
constants for the values are defined in the module constants for the values are defined in the module
:mod:`psycopg2.extensions`: see :ref:`transaction-status-constants` `psycopg2.extensions`: see :ref:`transaction-status-constants`
for the available values. for the available values.
.. seealso:: libpq docs for `PQtransactionStatus()`__ for details. .. seealso:: libpq docs for `PQtransactionStatus()`__ for details.
@ -288,7 +288,7 @@ The ``connection`` class
A read-only integer representing the status of the connection. A read-only integer representing the status of the connection.
Symbolic constants for the values are defined in the module Symbolic constants for the values are defined in the module
:mod:`psycopg2.extensions`: see :ref:`connection-status-constants` `psycopg2.extensions`: see :ref:`connection-status-constants`
for the available values. for the available values.
@ -302,15 +302,15 @@ The ``connection`` class
:param mode: Access mode to the object: can be ``r``, ``w``, :param mode: Access mode to the object: can be ``r``, ``w``,
``rw`` or ``n`` (meaning don't open it). ``rw`` or ``n`` (meaning don't open it).
:param new_oid: Create a new object using the specified OID. The :param new_oid: Create a new object using the specified OID. The
function raises :exc:`OperationalError` if the OID is already in function raises `OperationalError` if the OID is already in
use. Default is 0, meaning assign a new one automatically. 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 :param new_file: The name of a file to be imported in the the database
(using the |lo_import|_ function) (using the |lo_import|_ function)
:param lobject_factory: Subclass of :param lobject_factory: Subclass of
:class:`~psycopg2.extensions.lobject` to be instantiated. `~psycopg2.extensions.lobject` to be instantiated.
:rtype: :class:`~psycopg2.extensions.lobject` :rtype: `~psycopg2.extensions.lobject`
.. |lo_import| replace:: :func:`!lo_import` .. |lo_import| replace:: `!lo_import()`
.. _lo_import: http://www.postgresql.org/docs/8.4/static/lo-interfaces.html#AEN36307 .. _lo_import: http://www.postgresql.org/docs/8.4/static/lo-interfaces.html#AEN36307
.. versionadded:: 2.0.8 .. versionadded:: 2.0.8

View File

@ -19,7 +19,7 @@ The ``cursor`` class
.. class:: cursor .. class:: cursor
Allows Python code to execute PostgreSQL command in a database session. Allows Python code to execute PostgreSQL command in a database session.
Cursors are created by the :meth:`connection.cursor` method: they are Cursors are created by the `connection.cursor()` method: they are
bound to the connection for the entire lifetime and all the commands are bound to the connection for the entire lifetime and all the commands are
executed in the context of the database session wrapped by the connection. executed in the context of the database session wrapped by the connection.
@ -27,8 +27,8 @@ The ``cursor`` class
changes done to the database by a cursor are immediately visible by the changes done to the database by a cursor are immediately visible by the
other cursors. Cursors created from different connections can or can not other cursors. Cursors created from different connections can or can not
be isolated, depending on the connections' :ref:`isolation level be isolated, depending on the connections' :ref:`isolation level
<transactions-control>`. See also :meth:`~connection.rollback` and <transactions-control>`. See also `~connection.rollback()` and
:meth:`~connection.commit` methods. `~connection.commit()` methods.
Cursors are *not* thread safe: a multithread application can create Cursors are *not* thread safe: a multithread application can create
many cursors from the same connection and should use each cursor from many cursors from the same connection and should use each cursor from
@ -66,9 +66,9 @@ The ``cursor`` class
.. method:: close() .. method:: close()
Close the cursor now (rather than whenever :meth:`!__del__` is Close the cursor now (rather than whenever `!__del__()` is
called). The cursor will be unusable from this point forward; an called). The cursor will be unusable from this point forward; an
:exc:`~psycopg2.InterfaceError` will be raised if any operation is `~psycopg2.InterfaceError` will be raised if any operation is
attempted with the cursor. attempted with the cursor.
.. attribute:: closed .. attribute:: closed
@ -78,7 +78,7 @@ The ``cursor`` class
.. extension:: .. extension::
The :attr:`closed` attribute is a Psycopg extension to the The `closed` attribute is a Psycopg extension to the
|DBAPI|. |DBAPI|.
.. versionadded:: 2.0.7 .. versionadded:: 2.0.7
@ -86,23 +86,23 @@ The ``cursor`` class
.. attribute:: connection .. attribute:: connection
Read-only attribute returning a reference to the :class:`connection` Read-only attribute returning a reference to the `connection`
object on which the cursor was created. object on which the cursor was created.
.. attribute:: name .. attribute:: name
Read-only attribute containing the name of the cursor if it was Read-only attribute containing the name of the cursor if it was
creates as named cursor by :meth:`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`. it is a client side cursor. See :ref:`server-side-cursors`.
.. extension:: .. extension::
The :attr:`name` attribute is a Psycopg extension to the |DBAPI|. The `name` attribute is a Psycopg extension to the |DBAPI|.
.. |execute*| replace:: :meth:`execute*` .. |execute*| replace:: `execute*()`
.. _execute*: .. _execute*:
@ -123,7 +123,7 @@ The ``cursor`` class
If `async` is ``True``, query execution will be asynchronous: If `async` is ``True``, query execution will be asynchronous:
the function returns immediately while the query is executed by the the function returns immediately while the query is executed by the
backend. Use the :meth:`~cursor.isready` method to see if the data is backend. Use the `~cursor.isready()` method to see if the data is
ready for return via |fetch*|_ methods. See ready for return via |fetch*|_ methods. See
:ref:`asynchronous-queries`. :ref:`asynchronous-queries`.
@ -136,14 +136,14 @@ The ``cursor`` class
Return a query string after arguments binding. The string returned is Return a query string after arguments binding. The string returned is
exactly the one that would be sent to the database running the exactly the one that would be sent to the database running the
:meth:`~cursor.execute` method or similar. `~cursor.execute()` method or similar.
>>> cur.mogrify("INSERT INTO test (num, data) VALUES (%s, %s)", (42, 'bar')) >>> cur.mogrify("INSERT INTO test (num, data) VALUES (%s, %s)", (42, 'bar'))
"INSERT INTO test (num, data) VALUES (42, E'bar')" "INSERT INTO test (num, data) VALUES (42, E'bar')"
.. extension:: .. extension::
The :meth:`mogrify` method is a Psycopg extension to the |DBAPI|. The `mogrify()` method is a Psycopg extension to the |DBAPI|.
.. method:: executemany(operation, seq_of_parameters) .. method:: executemany(operation, seq_of_parameters)
@ -156,7 +156,7 @@ The ``cursor`` class
any result set returned by the query is discarded. any result set returned by the query is discarded.
Parameters are bounded to the query using the same rules described in Parameters are bounded to the query using the same rules described in
the :meth:`~cursor.execute` method. the `~cursor.execute()` method.
.. method:: callproc(procname [, parameters] [, async]) .. method:: callproc(procname [, parameters] [, async])
@ -172,7 +172,7 @@ The ``cursor`` class
If `async` is ``True``, procedure execution will be asynchronous: If `async` is ``True``, procedure execution will be asynchronous:
the function returns immediately while the procedure is executed by the function returns immediately while the procedure is executed by
the backend. Use the :meth:`~cursor.isready` method to see if the the backend. Use the `~cursor.isready()` method to see if the
data is ready for return via |fetch*|_ methods. See data is ready for return via |fetch*|_ methods. See
:ref:`asynchronous-queries`. :ref:`asynchronous-queries`.
@ -188,7 +188,7 @@ The ``cursor`` class
.. |fetch*| replace:: :meth:`!fetch*` .. |fetch*| replace:: `!fetch*()`
.. _fetch*: .. _fetch*:
@ -196,12 +196,12 @@ The ``cursor`` class
The following methods are used to read data from the database after an The following methods are used to read data from the database after an
:meth:`~cursor.execute` call. `~cursor.execute()` call.
.. note:: .. note::
:class:`cursor` objects are iterable, so, instead of calling `cursor` objects are iterable, so, instead of calling
explicitly :meth:`~cursor.fetchone` in a loop, the object itself can explicitly `~cursor.fetchone()` in a loop, the object itself can
be used: be used:
>>> cur.execute("SELECT * FROM test;") >>> cur.execute("SELECT * FROM test;")
@ -222,7 +222,7 @@ The ``cursor`` class
>>> cur.fetchone() >>> cur.fetchone()
(3, 42, 'bar') (3, 42, 'bar')
A :exc:`~psycopg2.ProgrammingError` is raised if the previous call A `~psycopg2.ProgrammingError` is raised if the previous call
to |execute*|_ did not produce any result set or no call was issued to |execute*|_ did not produce any result set or no call was issued
yet. yet.
@ -233,7 +233,7 @@ The ``cursor`` class
tuples. An empty list is returned when no more rows are available. tuples. An empty list is returned when no more rows are available.
The number of rows to fetch per call is specified by the parameter. The number of rows to fetch per call is specified by the parameter.
If it is not given, the cursor's :attr:`~cursor.arraysize` determines If it is not given, the cursor's `~cursor.arraysize` determines
the number of rows to be fetched. The method should try to fetch as the number of rows to be fetched. The method should try to fetch as
many rows as indicated by the size parameter. If this is not possible many rows as indicated by the size parameter. If this is not possible
due to the specified number of rows not being available, fewer rows due to the specified number of rows not being available, fewer rows
@ -247,14 +247,14 @@ The ``cursor`` class
>>> cur.fetchmany(2) >>> cur.fetchmany(2)
[] []
A :exc:`~psycopg2.ProgrammingError` is raised if the previous call to A `~psycopg2.ProgrammingError` is raised if the previous call to
|execute*|_ did not produce any result set or no call was issued yet. |execute*|_ did not produce any result set or no call was issued yet.
Note there are performance considerations involved with the size Note there are performance considerations involved with the size
parameter. For optimal performance, it is usually best to use the parameter. For optimal performance, it is usually best to use the
:attr:`~cursor.arraysize` attribute. If the size parameter is used, `~cursor.arraysize` attribute. If the size parameter is used,
then it is best for it to retain the same value from one then it is best for it to retain the same value from one
:meth:`fetchmany` call to the next. `fetchmany()` call to the next.
.. method:: fetchall() .. method:: fetchall()
@ -267,7 +267,7 @@ The ``cursor`` class
>>> cur.fetchall() >>> cur.fetchall()
[(1, 100, "abc'def"), (2, None, 'dada'), (3, 42, 'bar')] [(1, 100, "abc'def"), (2, None, 'dada'), (3, 42, 'bar')]
A :exc:`~psycopg2.ProgrammingError` is raised if the previous call to A `~psycopg2.ProgrammingError` is raised if the previous call to
|execute*|_ did not produce any result set or no call was issued yet. |execute*|_ did not produce any result set or no call was issued yet.
@ -281,7 +281,7 @@ The ``cursor`` class
value states an absolute target position. value states an absolute target position.
If the scroll operation would leave the result set, a If the scroll operation would leave the result set, a
:exc:`~psycopg2.ProgrammingError` is raised and the cursor position is `~psycopg2.ProgrammingError` is raised and the cursor position is
not changed. not changed.
The method can be used both for client-side cursors and The method can be used both for client-side cursors and
@ -290,7 +290,7 @@ The ``cursor`` class
.. note:: .. note::
According to the |DBAPI|_, the exception raised for a cursor out According to the |DBAPI|_, the exception raised for a cursor out
of bound should have been :exc:`!IndexError`. The best option is of bound should have been `!IndexError`. The best option is
probably to catch both exceptions in your code:: probably to catch both exceptions in your code::
try: try:
@ -302,7 +302,7 @@ The ``cursor`` class
.. attribute:: arraysize .. attribute:: arraysize
This read/write attribute specifies the number of rows to fetch at a This read/write attribute specifies the number of rows to fetch at a
time with :meth:`~cursor.fetchmany`. It defaults to 1 meaning to fetch time with `~cursor.fetchmany()`. It defaults to 1 meaning to fetch
a single row at a time. a single row at a time.
@ -332,7 +332,7 @@ The ``cursor`` class
The index can be seen as index of the cursor in a sequence (the result The index can be seen as index of the cursor in a sequence (the result
set). The next fetch operation will fetch the row indexed by set). The next fetch operation will fetch the row indexed by
:attr:`rownumber` in that sequence. `rownumber` in that sequence.
.. index:: oid .. index:: oid
@ -359,7 +359,7 @@ The ``cursor`` class
.. method:: nextset() .. method:: nextset()
This method is not supported (PostgreSQL does not have multiple data This method is not supported (PostgreSQL does not have multiple data
sets) and will raise a :exc:`~psycopg2.NotSupportedError` exception. sets) and will raise a `~psycopg2.NotSupportedError` exception.
.. method:: setoutputsize(size [, column]) .. method:: setoutputsize(size [, column])
@ -380,7 +380,7 @@ The ``cursor`` class
.. extension:: .. extension::
The :attr:`query` attribute is a Psycopg extension to the |DBAPI|. The `query` attribute is a Psycopg extension to the |DBAPI|.
.. attribute:: statusmessage .. attribute:: statusmessage
@ -394,7 +394,7 @@ The ``cursor`` class
.. extension:: .. extension::
The :attr:`statusmessage` attribute is a Psycopg extension to the The `statusmessage` attribute is a Psycopg extension to the
|DBAPI|. |DBAPI|.
@ -406,28 +406,28 @@ The ``cursor`` class
.. extension:: .. extension::
The :meth:`isready` method is a Psycopg extension to the |DBAPI|. The `isready()` method is a Psycopg extension to the |DBAPI|.
.. method:: fileno() .. method:: fileno()
Return the file descriptor associated with the current connection and Return the file descriptor associated with the current connection and
make possible to use a cursor in a context where a file object would make possible to use a cursor in a context where a file object would
be expected (like in a :func:`select` call). See be expected (like in a `select()` call). See
:ref:`asynchronous-queries`. :ref:`asynchronous-queries`.
.. extension:: .. extension::
The :meth:`fileno` method is a Psycopg extension to the |DBAPI|. The `fileno()` method is a Psycopg extension to the |DBAPI|.
.. attribute:: tzinfo_factory .. attribute:: tzinfo_factory
The time zone factory used to handle data types such as The time zone factory used to handle data types such as
:sql:`TIMESTAMP WITH TIME ZONE`. It should be a |tzinfo|_ object. :sql:`TIMESTAMP WITH TIME ZONE`. It should be a |tzinfo|_ object.
See also the :mod:`psycopg2.tz` module. See also the `psycopg2.tz` module.
.. |tzinfo| replace:: :class:`!tzinfo` .. |tzinfo| replace:: `!tzinfo`
.. _tzinfo: http://docs.python.org/library/datetime.html#tzinfo-objects .. _tzinfo: http://docs.python.org/library/datetime.html#tzinfo-objects
@ -443,7 +443,7 @@ The ``cursor`` class
Read data *from* the file-like object `file` appending them to Read data *from* the file-like object `file` appending them to
the table named `table`. `file` must have both the table named `table`. `file` must have both
:meth:`!read` and :meth:`!readline` method. See :ref:`copy` for an `!read()` and `!readline()` method. See :ref:`copy` for an
overview. overview.
The optional argument `sep` is the columns separator and The optional argument `sep` is the columns separator and
@ -467,7 +467,7 @@ The ``cursor`` class
.. method:: copy_to(file, table, sep='\\t', null='\\N', columns=None) .. method:: copy_to(file, table, sep='\\t', null='\\N', columns=None)
Write the content of the table named `table` *to* the file-like Write the content of the table named `table` *to* the file-like
object `file`. `file` must have a :meth:`!write` method. object `file`. `file` must have a `!write()` method.
See :ref:`copy` for an overview. See :ref:`copy` for an overview.
The optional argument `sep` is the columns separator and The optional argument `sep` is the columns separator and

View File

@ -1,4 +1,4 @@
:mod:`psycopg2.errorcodes` -- Error codes defined by PostgreSQL `psycopg2.errorcodes` -- Error codes defined by PostgreSQL
=============================================================== ===============================================================
.. sectionauthor:: Daniele Varrazzo <daniele.varrazzo@gmail.com> .. sectionauthor:: Daniele Varrazzo <daniele.varrazzo@gmail.com>
@ -15,8 +15,8 @@
.. versionadded:: 2.0.6 .. versionadded:: 2.0.6
This module contains symbolic names for all PostgreSQL error codes and error This module contains symbolic names for all PostgreSQL error codes and error
classes codes. Subclasses of :exc:`~psycopg2.Error` make the PostgreSQL error classes codes. Subclasses of `~psycopg2.Error` make the PostgreSQL error
code available in the :attr:`~psycopg2.Error.pgcode` attribute. code available in the `~psycopg2.Error.pgcode` attribute.
From PostgreSQL documentation: From PostgreSQL documentation:

View File

@ -1,4 +1,4 @@
:mod:`psycopg2.extensions` -- Extensions to the DB API `psycopg2.extensions` -- Extensions to the DB API
====================================================== ======================================================
.. sectionauthor:: Daniele Varrazzo <daniele.varrazzo@gmail.com> .. sectionauthor:: Daniele Varrazzo <daniele.varrazzo@gmail.com>
@ -15,31 +15,31 @@ functionalities defined by the |DBAPI|_.
.. class:: connection .. class:: connection
Is the class usually returned by the :func:`~psycopg2.connect` function. Is the class usually returned by the `~psycopg2.connect()` function.
It is exposed by the :mod:`extensions` module in order to allow It is exposed by the `extensions` module in order to allow
subclassing to extend its behaviour: the subclass should be passed to the subclassing to extend its behaviour: the subclass should be passed to the
:func:`!connect` function using the `connection_factory` parameter. `!connect()` function using the `connection_factory` parameter.
See also :ref:`subclassing-connection`. See also :ref:`subclassing-connection`.
For a complete description of the class, see :class:`connection`. For a complete description of the class, see `connection`.
.. class:: cursor .. class:: cursor
It is the class usually returnded by the :meth:`connection.cursor` It is the class usually returnded by the `connection.cursor()`
method. It is exposed by the :mod:`extensions` module in order to allow method. It is exposed by the `extensions` module in order to allow
subclassing to extend its behaviour: the subclass should be passed to the subclassing to extend its behaviour: the subclass should be passed to the
:meth:`!cursor` method using the `cursor_factory` parameter. See `!cursor()` method using the `cursor_factory` parameter. See
also :ref:`subclassing-cursor`. also :ref:`subclassing-cursor`.
For a complete description of the class, see :class:`cursor`. For a complete description of the class, see `cursor`.
.. class:: lobject(conn [, oid [, mode [, new_oid [, new_file ]]]]) .. class:: lobject(conn [, oid [, mode [, new_oid [, new_file ]]]])
Wrapper for a PostgreSQL large object. See :ref:`large-objects` for an Wrapper for a PostgreSQL large object. See :ref:`large-objects` for an
overview. overview.
The class can be subclassed: see the :meth:`connection.lobject` to know The class can be subclassed: see the `connection.lobject()` to know
how to specify a :class:`!lobject` subclass. how to specify a `!lobject` subclass.
.. versionadded:: 2.0.8 .. versionadded:: 2.0.8
@ -67,7 +67,7 @@ functionalities defined by the |DBAPI|_.
The method uses the efficient |lo_export|_ libpq function. The method uses the efficient |lo_export|_ libpq function.
.. |lo_export| replace:: :func:`!lo_export` .. |lo_export| replace:: `!lo_export()`
.. _lo_export: http://www.postgresql.org/docs/8.4/static/lo-interfaces.html#AEN36330 .. _lo_export: http://www.postgresql.org/docs/8.4/static/lo-interfaces.html#AEN36330
.. method:: seek(offset, whence=0) .. method:: seek(offset, whence=0)
@ -105,33 +105,33 @@ deal with Python objects adaptation:
.. function:: adapt(obj) .. function:: adapt(obj)
Return the SQL representation of `obj` as a string. Raise a Return the SQL representation of `obj` as a string. Raise a
:exc:`~psycopg2.ProgrammingError` if how to adapt the object is unknown. `~psycopg2.ProgrammingError` if how to adapt the object is unknown.
In order to allow new objects to be adapted, register a new adapter for it In order to allow new objects to be adapted, register a new adapter for it
using the :func:`register_adapter` function. using the `register_adapter()` function.
The function is the entry point of the adaptation mechanism: it can be The function is the entry point of the adaptation mechanism: it can be
used to write adapters for complex objects by recursively calling used to write adapters for complex objects by recursively calling
:func:`!adapt` on its components. `!adapt()` on its components.
.. function:: register_adapter(class, adapter) .. function:: register_adapter(class, adapter)
Register a new adapter for the objects of class `class`. Register a new adapter for the objects of class `class`.
`adapter` should be a function taking a single argument (the object `adapter` should be a function taking a single argument (the object
to adapt) and returning an object conforming the :class:`ISQLQuote` to adapt) and returning an object conforming the `ISQLQuote`
protocol (e.g. exposing a :meth:`!getquoted` method). The :class:`AsIs` is protocol (e.g. exposing a `!getquoted()` method). The `AsIs` is
often useful for this task. often useful for this task.
Once an object is registered, it can be safely used in SQL queries and by Once an object is registered, it can be safely used in SQL queries and by
the :func:`adapt` function. the `adapt()` function.
.. class:: ISQLQuote(wrapped_object) .. class:: ISQLQuote(wrapped_object)
Represents the SQL adaptation protocol. Objects conforming this protocol Represents the SQL adaptation protocol. Objects conforming this protocol
should implement a :meth:`!getquoted` method. should implement a `!getquoted()` method.
Adapters may subclass :class:`!ISQLQuote`, but is not necessary: it is Adapters may subclass `!ISQLQuote`, but is not necessary: it is
enough to expose a :meth:`!getquoted` method to be conforming. enough to expose a `!getquoted()` method to be conforming.
.. attribute:: _wrapped .. attribute:: _wrapped
@ -140,24 +140,24 @@ deal with Python objects adaptation:
.. method:: getquoted() .. method:: getquoted()
Subclasses or other conforming objects should return a valid SQL Subclasses or other conforming objects should return a valid SQL
string representing the wrapped object. The :class:`!ISQLQuote` string representing the wrapped object. The `!ISQLQuote`
implementation does nothing. implementation does nothing.
.. class:: AsIs .. class:: AsIs
Adapter conform to the :class:`ISQLQuote` protocol useful for objects Adapter conform to the `ISQLQuote` protocol useful for objects
whose string representation is already valid as SQL representation. whose string representation is already valid as SQL representation.
.. method:: getquoted() .. method:: getquoted()
Return the :meth:`str` conversion of the wrapped object. Return the `str()` conversion of the wrapped object.
>>> AsIs(42).getquoted() >>> AsIs(42).getquoted()
'42' '42'
.. class:: QuotedString .. class:: QuotedString
Adapter conform to the :class:`ISQLQuote` protocol for string-like Adapter conform to the `ISQLQuote` protocol for string-like
objects. objects.
.. method:: getquoted() .. method:: getquoted()
@ -171,21 +171,21 @@ deal with Python objects adaptation:
.. class:: Binary .. class:: Binary
Adapter conform to the :class:`ISQLQuote` protocol for binary objects. Adapter conform to the `ISQLQuote` protocol for binary objects.
.. method:: getquoted() .. method:: getquoted()
Return the string enclosed in single quotes. It performs the same Return the string enclosed in single quotes. It performs the same
escaping of the :class:`QuotedString` adapter, plus it knows how to escaping of the `QuotedString` adapter, plus it knows how to
escape non-printable chars. escape non-printable chars.
>>> Binary("\x00\x08\x0F").getquoted() >>> Binary("\x00\x08\x0F").getquoted()
"'\\\\000\\\\010\\\\017'" "'\\\\000\\\\010\\\\017'"
.. versionchanged:: 2.0.14(ish) .. versionchanged:: 2.0.14(ish)
previously the adapter was not exposed by the :mod:`extensions` previously the adapter was not exposed by the `extensions`
module. In older version it can be imported from the implementation module. In older version it can be imported from the implementation
module :mod:`!psycopg2._psycopg`. module `!psycopg2._psycopg`.
@ -212,7 +212,7 @@ deal with Python objects adaptation:
.. data:: adapters .. data:: adapters
Dictionary of the currently registered object adapters. Use Dictionary of the currently registered object adapters. Use
:func:`register_adapter` to add an adapter for a new type. `register_adapter()` to add an adapter for a new type.
@ -227,13 +227,13 @@ details.
Create a new type caster to convert from a PostgreSQL type to a Python Create a new type caster to convert from a PostgreSQL type to a Python
object. The created object must be registered using object. The created object must be registered using
:func:`register_type` to be used. `register_type()` to be used.
:param oids: tuple of OIDs of the PostgreSQL type to convert. :param oids: tuple of OIDs of the PostgreSQL type to convert.
:param name: the name of the new type adapter. :param name: the name of the new type adapter.
:param adapter: the adaptation function. :param adapter: the adaptation function.
The object OID can be read from the :attr:`cursor.description` attribute The object OID can be read from the `cursor.description` attribute
or by querying from the PostgreSQL catalog. or by querying from the PostgreSQL catalog.
`adapter` should have signature :samp:`fun({value}, {cur})` where `adapter` should have signature :samp:`fun({value}, {cur})` where
@ -246,10 +246,10 @@ details.
.. function:: register_type(obj [, scope]) .. function:: register_type(obj [, scope])
Register a type caster created using :func:`new_type`. Register a type caster created using `new_type()`.
If `scope` is specified, it should be a :class:`connection` or a If `scope` is specified, it should be a `connection` or a
:class:`cursor`: the type caster will be effective only limited to the `cursor`: the type caster will be effective only limited to the
specified object. Otherwise it will be globally registered. specified object. Otherwise it will be globally registered.
@ -283,7 +283,7 @@ The module exports a few exceptions in addition to the :ref:`standard ones
.. exception:: QueryCanceledError .. exception:: QueryCanceledError
(subclasses :exc:`~psycopg2.OperationalError`) (subclasses `~psycopg2.OperationalError`)
Error related to SQL query cancelation. It can be trapped specifically to Error related to SQL query cancelation. It can be trapped specifically to
detect a timeout. detect a timeout.
@ -293,7 +293,7 @@ The module exports a few exceptions in addition to the :ref:`standard ones
.. exception:: TransactionRollbackError .. exception:: TransactionRollbackError
(subclasses :exc:`~psycopg2.OperationalError`) (subclasses `~psycopg2.OperationalError`)
Error causing transaction rollback (deadlocks, serialisation failures, Error causing transaction rollback (deadlocks, serialisation failures,
etc). It can be trapped specifically to detect a deadlock. etc). It can be trapped specifically to detect a deadlock.
@ -310,17 +310,17 @@ The module exports a few exceptions in addition to the :ref:`standard ones
Isolation level constants Isolation level constants
------------------------- -------------------------
Psycopg2 :class:`connection` objects hold informations about the PostgreSQL Psycopg2 `connection` objects hold informations about the PostgreSQL
`transaction isolation level`_. The current transaction level can be read `transaction isolation level`_. The current transaction level can be read
from the :attr:`~connection.isolation_level` attribute. The default isolation from the `~connection.isolation_level` attribute. The default isolation
level is :sql:`READ COMMITTED`. A different isolation level con be set level is :sql:`READ COMMITTED`. A different isolation level con be set
through the :meth:`~connection.set_isolation_level` method. The level can be through the `~connection.set_isolation_level()` method. The level can be
set to one of the following constants: set to one of the following constants:
.. data:: ISOLATION_LEVEL_AUTOCOMMIT .. data:: ISOLATION_LEVEL_AUTOCOMMIT
No transaction is started when command are issued and no No transaction is started when command are issued and no
:meth:`~connection.commit` or :meth:`~connection.rollback` is required. `~connection.commit()` or `~connection.rollback()` is required.
Some PostgreSQL command such as :sql:`CREATE DATABASE` or :sql:`VACUUM` Some PostgreSQL command such as :sql:`CREATE DATABASE` or :sql:`VACUUM`
can't run into a transaction: to run such command use:: can't run into a transaction: to run such command use::
@ -337,9 +337,9 @@ set to one of the following constants:
.. data:: ISOLATION_LEVEL_READ_COMMITTED .. data:: ISOLATION_LEVEL_READ_COMMITTED
This is the default value. A new transaction is started at the first This is the default value. A new transaction is started at the first
:meth:`~cursor.execute` command on a cursor and at each new `~cursor.execute()` command on a cursor and at each new
:meth:`!execute` after a :meth:`~connection.commit` or a `!execute()` after a `~connection.commit()` or a
:meth:`~connection.rollback`. The transaction runs in the PostgreSQL `~connection.rollback()`. The transaction runs in the PostgreSQL
:sql:`READ COMMITTED` isolation level. :sql:`READ COMMITTED` isolation level.
.. data:: ISOLATION_LEVEL_REPEATABLE_READ .. data:: ISOLATION_LEVEL_REPEATABLE_READ
@ -368,7 +368,7 @@ Transaction status constants
---------------------------- ----------------------------
These values represent the possible status of a transaction: the current value These values represent the possible status of a transaction: the current value
can be read using the :meth:`connection.get_transaction_status` method. can be read using the `connection.get_transaction_status()` method.
.. data:: TRANSACTION_STATUS_IDLE .. data:: TRANSACTION_STATUS_IDLE
@ -401,7 +401,7 @@ Connection status constants
--------------------------- ---------------------------
These values represent the possible status of a connection: the current value These values represent the possible status of a connection: the current value
can be read from the :attr:`~connection.status` attribute. can be read from the `~connection.status` attribute.
.. data:: STATUS_SETUP .. data:: STATUS_SETUP
@ -417,7 +417,7 @@ can be read from the :attr:`~connection.status` attribute.
.. data:: STATUS_IN_TRANSACTION .. data:: STATUS_IN_TRANSACTION
An alias for :const:`STATUS_BEGIN` An alias for `STATUS_BEGIN`
.. data:: STATUS_SYNC .. data:: STATUS_SYNC
@ -432,11 +432,11 @@ can be read from the :attr:`~connection.status` attribute.
Additional database types Additional database types
------------------------- -------------------------
The :mod:`!extensions` module includes typecasters for many standard The `!extensions` module includes typecasters for many standard
PostgreSQL types. These objects allow the conversion of returned data into PostgreSQL types. These objects allow the conversion of returned data into
Python objects. All the typecasters are automatically registered, except Python objects. All the typecasters are automatically registered, except
:data:`UNICODE` and :data:`UNICODEARRAY`: you can register them using `UNICODE` and `UNICODEARRAY`: you can register them using
:func:`register_type` in order to receive Unicode objects instead of strings `register_type()` in order to receive Unicode objects instead of strings
from the database. See :ref:`unicode-handling` for details. from the database. See :ref:`unicode-handling` for details.
.. data:: BINARYARRAY .. data:: BINARYARRAY

View File

@ -1,4 +1,4 @@
:mod:`psycopg2.extras` -- Miscellaneous goodies for Psycopg 2 `psycopg2.extras` -- Miscellaneous goodies for Psycopg 2
============================================================= =============================================================
.. sectionauthor:: Daniele Varrazzo <daniele.varrazzo@gmail.com> .. sectionauthor:: Daniele Varrazzo <daniele.varrazzo@gmail.com>
@ -26,10 +26,10 @@ Dictionary-like cursor
The dict cursors allow to access to the retrieved records using an iterface The dict cursors allow to access to the retrieved records using an iterface
similar to the Python dictionaries instead of the tuples. You can use it similar to the Python dictionaries instead of the tuples. You can use it
either passing :class:`DictConnection` as `connection_factory` argument either passing `DictConnection` as `connection_factory` argument
to the :func:`~psycopg2.connect` function or passing :class:`DictCursor` as to the `~psycopg2.connect()` function or passing `DictCursor` as
the :class:`!cursor_factory` argument to the :meth:`~connection.cursor` method the `!cursor_factory` argument to the `~connection.cursor()` method
of a regular :class:`connection`. of a regular `connection`.
>>> dict_cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) >>> dict_cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
>>> dict_cur.execute("INSERT INTO test (num, data) VALUES(%s, %s)", >>> dict_cur.execute("INSERT INTO test (num, data) VALUES(%s, %s)",

View File

@ -3,17 +3,17 @@ Frequently Asked Questions
.. sectionauthor:: Daniele Varrazzo <daniele.varrazzo@gmail.com> .. sectionauthor:: Daniele Varrazzo <daniele.varrazzo@gmail.com>
Here are a few gotchas you may encounter using :mod:`psycopg2`. Feel free to Here are a few gotchas you may encounter using `psycopg2`. Feel free to
suggest new entries! suggest new entries!
.. cssclass:: faq .. cssclass:: faq
Why does :mod:`!psycopg2` leave database sessions "idle in transaction"? Why does `!psycopg2` leave database sessions "idle in transaction"?
Psycopg normally starts a new transaction the first time a query is Psycopg normally starts a new transaction the first time a query is
executed, e.g. calling :meth:`cursor.execute`, even if the command is a executed, e.g. calling `cursor.execute()`, even if the command is a
:sql:`SELECT`. The transaction is not closed until an explicit :sql:`SELECT`. The transaction is not closed until an explicit
:meth:`~connection.commit` or :meth:`~connection.rollback`. `~connection.commit()` or `~connection.rollback()`.
If you are writing a long-living program, you should probably ensure to If you are writing a long-living program, you should probably ensure to
call one of the transaction closing methods before leaving the connection call one of the transaction closing methods before leaving the connection
@ -22,7 +22,7 @@ Why does :mod:`!psycopg2` leave database sessions "idle in transaction"?
connection in :ref:`autocommit <autocommit>` mode to avoid a new connection in :ref:`autocommit <autocommit>` mode to avoid a new
transaction to be started at the first command. transaction to be started at the first command.
Why does :meth:`!cursor.execute` raise the exception *can't adapt*? Why does `!cursor.execute()` raise the exception *can't adapt*?
Psycopg converts Python objects in a SQL string representation by looking Psycopg converts Python objects in a SQL string representation by looking
at the object class. The exception is raised when you are trying to pass at the object class. The exception is raised when you are trying to pass
as query parameter an object for which there is no adapter registered for as query parameter an object for which there is no adapter registered for
@ -50,19 +50,19 @@ I try to execute a query but it fails with the error *not all arguments converte
I receive the error *current transaction is aborted, commands ignored until end of transaction block* and can't do anything else! I receive the error *current transaction is aborted, commands ignored until end of transaction block* and can't do anything else!
There was a problem *in the previous* command to the database, which There was a problem *in the previous* command to the database, which
resulted in an error. The database will not recover automatically from resulted in an error. The database will not recover automatically from
this condition: you must run a :meth:`~connection.rollback` before sending this condition: you must run a `~connection.rollback()` before sending
new commands to the session (if this seems too harsh, remember that new commands to the session (if this seems too harsh, remember that
PostgreSQL supports nested transactions using the |SAVEPOINT|_ command). PostgreSQL supports nested transactions using the |SAVEPOINT|_ command).
.. |SAVEPOINT| replace:: :sql:`SAVEPOINT` .. |SAVEPOINT| replace:: :sql:`SAVEPOINT`
.. _SAVEPOINT: http://www.postgresql.org/docs/8.4/static/sql-savepoint.html .. _SAVEPOINT: http://www.postgresql.org/docs/8.4/static/sql-savepoint.html
Why do i get the error *current transaction is aborted, commands ignored until end of transaction block* when I use :mod:`!multiprocessing` (or any other forking system) and not when use :mod:`!threading`? Why do i get the error *current transaction is aborted, commands ignored until end of transaction block* when I use `!multiprocessing` (or any other forking system) and not when use `!threading`?
Psycopg's connections can't be shared across processes (but are thread Psycopg's connections can't be shared across processes (but are thread
safe). If you are forking the Python process ensure to create a new safe). If you are forking the Python process ensure to create a new
connection in each forked child. connection in each forked child.
My database is Unicode, but I receive all the strings as UTF-8 :class:`str`. Can I receive :class:`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:: The following magic formula will do the trick::
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE) psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
@ -70,11 +70,11 @@ My database is Unicode, but I receive all the strings as UTF-8 :class:`str`. Can
See :ref:`unicode-handling` for the gory details. See :ref:`unicode-handling` for the gory details.
I can't compile :mod:`!psycopg2`: the compiler says *error: Python.h: No such file or directory*. What am I missing? I can't compile `!psycopg2`: the compiler says *error: Python.h: No such file or directory*. What am I missing?
You need to install a Python development package: it is usually called You need to install a Python development package: it is usually called
``python-dev``. ``python-dev``.
I can't compile :mod:`!psycopg2`: the compiler says *error: libpq-fe.h: No such file or directory*. What am I missing? I can't compile `!psycopg2`: the compiler says *error: libpq-fe.h: No such file or directory*. What am I missing?
You need to install the development version of the libpq: the package is You need to install the development version of the libpq: the package is
usually called ``libpq-dev``. usually called ``libpq-dev``.
@ -83,7 +83,7 @@ When should I save and re-use a cursor as opposed to creating a new one as neede
any kind of problem. But note that cursors used to fetch result sets will any kind of problem. But note that cursors used to fetch result sets will
cache the data and use memory in proportion to the result set size. Our cache the data and use memory in proportion to the result set size. Our
suggestion is to almost always create a new cursor and dispose old ones as suggestion is to almost always create a new cursor and dispose old ones as
soon as the data is not required anymore (call :meth:`~cursor.close` on soon as the data is not required anymore (call `~cursor.close()` on
them.) The only exception are tight loops where one usually use the same them.) The only exception are tight loops where one usually use the same
cursor for a whole bunch of :sql:`INSERT`\s or :sql:`UPDATE`\s. cursor for a whole bunch of :sql:`INSERT`\s or :sql:`UPDATE`\s.
@ -92,7 +92,7 @@ When should I save and re-use a connection as opposed to creating a new one as n
practice is to create a single connection and keep it open as long as practice is to create a single connection and keep it open as long as
required. It is also good practice to rollback or commit frequently (even required. It is also good practice to rollback or commit frequently (even
after a single :sql:`SELECT` statement) to make sure the backend is never after a single :sql:`SELECT` statement) to make sure the backend is never
left "idle in transaction". See also :mod:`psycopg2.pool` for lightweight left "idle in transaction". See also `psycopg2.pool` for lightweight
connection pooling. connection pooling.
What are the advantages or disadvantages of using named cursors? What are the advantages or disadvantages of using named cursors?
@ -100,5 +100,5 @@ What are the advantages or disadvantages of using named cursors?
that there is a little overhead because a at least two queries (one to that there is a little overhead because a at least two queries (one to
create the cursor and one to fetch the initial result set) are issued to create the cursor and one to fetch the initial result set) are issued to
the backend. The advantage is that data is fetched one chunk at a time: the backend. The advantage is that data is fetched one chunk at a time:
using small :meth:`~cursor.fetchmany` values it is possible to use very using small `~cursor.fetchmany()` values it is possible to use very
little memory on the client and to skip or discard parts of the result set. little memory on the client and to skip or discard parts of the result set.

View File

@ -1,4 +1,4 @@
The :mod:`psycopg2` module content The `psycopg2` module content
================================== ==================================
.. sectionauthor:: Daniele Varrazzo <daniele.varrazzo@gmail.com> .. sectionauthor:: Daniele Varrazzo <daniele.varrazzo@gmail.com>
@ -18,7 +18,7 @@ The module interface respects the standard defined in the |DBAPI|_.
.. function:: connect(dsn or params[, connection_factory]) .. function:: connect(dsn or params[, connection_factory])
Create a new database session and return a new :class:`connection` object. Create a new database session and return a new `connection` object.
You can specify the connection parameters either as a string:: You can specify the connection parameters either as a string::
@ -53,19 +53,19 @@ The module interface respects the standard defined in the |DBAPI|_.
.. data:: apilevel .. data:: apilevel
String constant stating the supported DB API level. For :mod:`psycopg2` is String constant stating the supported DB API level. For `psycopg2` is
``2.0``. ``2.0``.
.. data:: threadsafety .. data:: threadsafety
Integer constant stating the level of thread safety the interface Integer constant stating the level of thread safety the interface
supports. For :mod:`psycopg2` is ``2``, i.e. threads can share the module supports. For `psycopg2` is ``2``, i.e. threads can share the module
and the connection. See :ref:`thread-safety` for details. and the connection. See :ref:`thread-safety` for details.
.. data:: paramstyle .. data:: paramstyle
String constant stating the type of parameter marker formatting expected String constant stating the type of parameter marker formatting expected
by the interface. For :mod:`psycopg2` is ``pyformat``. See also by the interface. For `psycopg2` is ``pyformat``. See also
:ref:`query-parameters`. :ref:`query-parameters`.
@ -101,12 +101,12 @@ available through the following exceptions:
.. attribute:: pgcode .. 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 :mod:`~psycopg2.errorcodes` module contains if not available. The `~psycopg2.errorcodes` module contains
symbolic constants representing PostgreSQL error codes. symbolic constants representing PostgreSQL error codes.
.. extension:: .. extension::
The :attr:`~Error.pgerror` and :attr:`~Error.pgcode` attributes are The `~Error.pgerror` and `~Error.pgcode` attributes are
Psycopg extensions. Psycopg extensions.
.. doctest:: .. doctest::
@ -124,26 +124,26 @@ available through the following exceptions:
LINE 1: SELECT * FROM barf LINE 1: SELECT * FROM barf
^ ^
.. versionchanged:: 2.0.7 added :attr:`Error.pgerror` and .. versionchanged:: 2.0.7 added `Error.pgerror` and
:attr:`Error.pgcode` attributes. `Error.pgcode` attributes.
.. exception:: InterfaceError .. exception:: InterfaceError
Exception raised for errors that are related to the database interface Exception raised for errors that are related to the database interface
rather than the database itself. It is a subclass of :exc:`Error`. rather than the database itself. It is a subclass of `Error`.
.. exception:: DatabaseError .. exception:: DatabaseError
Exception raised for errors that are related to the database. It is a Exception raised for errors that are related to the database. It is a
subclass of :exc:`Error`. subclass of `Error`.
.. exception:: DataError .. exception:: DataError
Exception raised for errors that are due to problems with the processed Exception raised for errors that are due to problems with the processed
data like division by zero, numeric value out of range, etc. It is a data like division by zero, numeric value out of range, etc. It is a
subclass of :exc:`DatabaseError`. subclass of `DatabaseError`.
.. exception:: OperationalError .. exception:: OperationalError
@ -151,41 +151,41 @@ available through the following exceptions:
and not necessarily under the control of the programmer, e.g. an and not necessarily under the control of the programmer, e.g. an
unexpected disconnect occurs, the data source name is not found, a unexpected disconnect occurs, the data source name is not found, a
transaction could not be processed, a memory allocation error occurred transaction could not be processed, a memory allocation error occurred
during processing, etc. It is a subclass of :exc:`DatabaseError`. during processing, etc. It is a subclass of `DatabaseError`.
.. exception:: IntegrityError .. exception:: IntegrityError
Exception raised when the relational integrity of the database is Exception raised when the relational integrity of the database is
affected, e.g. a foreign key check fails. It is a subclass of affected, e.g. a foreign key check fails. It is a subclass of
:exc:`DatabaseError`. `DatabaseError`.
.. exception:: InternalError .. exception:: InternalError
Exception raised when the database encounters an internal error, e.g. the Exception raised when the database encounters an internal error, e.g. the
cursor is not valid anymore, the transaction is out of sync, etc. It is a cursor is not valid anymore, the transaction is out of sync, etc. It is a
subclass of :exc:`DatabaseError`. subclass of `DatabaseError`.
.. exception:: ProgrammingError .. exception:: ProgrammingError
Exception raised for programming errors, e.g. table not found or already Exception raised for programming errors, e.g. table not found or already
exists, syntax error in the SQL statement, wrong number of parameters exists, syntax error in the SQL statement, wrong number of parameters
specified, etc. It is a subclass of :exc:`DatabaseError`. specified, etc. It is a subclass of `DatabaseError`.
.. exception:: NotSupportedError .. exception:: NotSupportedError
Exception raised in case a method or database API was used which is not Exception raised in case a method or database API was used which is not
supported by the database, e.g. requesting a :meth:`!rollback` on a supported by the database, e.g. requesting a `!rollback()` on a
connection that does not support transaction or has transactions turned connection that does not support transaction or has transactions turned
off. It is a subclass of :exc:`DatabaseError`. off. It is a subclass of `DatabaseError`.
.. extension:: .. extension::
Psycopg may raise a few other, more specialized, exceptions: currently Psycopg may raise a few other, more specialized, exceptions: currently
:exc:`~psycopg2.extensions.QueryCanceledError` and `~psycopg2.extensions.QueryCanceledError` and
:exc:`~psycopg2.extensions.TransactionRollbackError` are defined. These `~psycopg2.extensions.TransactionRollbackError` are defined. These
exceptions are not exposed by the main :mod:`!psycopg2` module but are exceptions are not exposed by the main `!psycopg2` module but are
made available by the :mod:`~psycopg2.extensions` module. All the made available by the `~psycopg2.extensions` module. All the
additional exceptions are subclasses of standard |DBAPI| exceptions, so additional exceptions are subclasses of standard |DBAPI| exceptions, so
trapping them specifically is not required. trapping them specifically is not required.
@ -195,21 +195,21 @@ This is the exception inheritance layout:
.. parsed-literal:: .. parsed-literal::
|StandardError| |StandardError|
\|__ :exc:`Warning` \|__ `Warning`
\|__ :exc:`Error` \|__ `Error`
\|__ :exc:`InterfaceError` \|__ `InterfaceError`
\|__ :exc:`DatabaseError` \|__ `DatabaseError`
\|__ :exc:`DataError` \|__ `DataError`
\|__ :exc:`OperationalError` \|__ `OperationalError`
\| \|__ :exc:`psycopg2.extensions.QueryCanceledError` \| \|__ `psycopg2.extensions.QueryCanceledError`
\| \|__ :exc:`psycopg2.extensions.TransactionRollbackError` \| \|__ `psycopg2.extensions.TransactionRollbackError`
\|__ :exc:`IntegrityError` \|__ `IntegrityError`
\|__ :exc:`InternalError` \|__ `InternalError`
\|__ :exc:`ProgrammingError` \|__ `ProgrammingError`
\|__ :exc:`NotSupportedError` \|__ `NotSupportedError`
.. |StandardError| replace:: :exc:`!StandardError` .. |StandardError| replace:: `!StandardError`
.. _StandardError: http://docs.python.org/library/exceptions.html#exceptions.StandardError .. _StandardError: http://docs.python.org/library/exceptions.html#exceptions.StandardError

View File

@ -18,7 +18,7 @@ directly into the client application.
New *minconn* connections are created automatically. The pool will support New *minconn* connections are created automatically. The pool will support
a maximum of about *maxconn* connections. *\*args* and *\*\*kwargs* are a maximum of about *maxconn* connections. *\*args* and *\*\*kwargs* are
passed to the :func:`~psycopg2.connect` function. passed to the `~psycopg2.connect()` function.
The following methods are expected to be implemented by subclasses: The following methods are expected to be implemented by subclasses:
@ -38,7 +38,7 @@ directly into the client application.
eventually in use by the application. eventually in use by the application.
The following classes are :class:`AbstractConnectionPool` subclasses ready to The following classes are `AbstractConnectionPool` subclasses ready to
be used. be used.
.. autoclass:: SimpleConnectionPool .. autoclass:: SimpleConnectionPool

View File

@ -1,4 +1,4 @@
:mod:`psycopg2.tz` -- ``tzinfo`` implementations for Psycopg 2 `psycopg2.tz` -- ``tzinfo`` implementations for Psycopg 2
=============================================================== ===============================================================
.. sectionauthor:: Daniele Varrazzo <daniele.varrazzo@gmail.com> .. sectionauthor:: Daniele Varrazzo <daniele.varrazzo@gmail.com>
@ -7,7 +7,7 @@
This module holds two different tzinfo implementations that can be used as the This module holds two different tzinfo implementations that can be used as the
`tzinfo` argument to datetime constructors, directly passed to Psycopg `tzinfo` argument to datetime constructors, directly passed to Psycopg
functions or used to set the :attr:`cursor.tzinfo_factory` attribute in functions or used to set the `cursor.tzinfo_factory` attribute in
cursors. cursors.
.. todo:: should say something more about tz handling .. todo:: should say something more about tz handling

View File

@ -41,25 +41,25 @@ basic commands::
The main entry point of Psycopg are: The main entry point of Psycopg are:
- The function :func:`~psycopg2.connect` creates a new database session and - The function `~psycopg2.connect()` creates a new database session and
returns a new :class:`connection` instance. returns a new `connection` instance.
- The class :class:`connection` encapsulates a database session. It allows to: - The class `connection` encapsulates a database session. It allows to:
- create new :class:`cursor`\s using the :meth:`~connection.cursor` method to - create new `cursor`\s using the `~connection.cursor()` method to
execute database commands and queries, execute database commands and queries,
- terminate the session using the methods :meth:`~connection.commit` or - terminate the session using the methods `~connection.commit()` or
:meth:`~connection.rollback`. `~connection.rollback()`.
- The class :class:`cursor` allows interaction with the database: - The class `cursor` allows interaction with the database:
- send commands to the database using methods such as :meth:`~cursor.execute` - send commands to the database using methods such as `~cursor.execute()`
and :meth:`~cursor.executemany`, and `~cursor.executemany()`,
- retrieve data from the database using methods such as - retrieve data from the database using methods such as
:meth:`~cursor.fetchone`, :meth:`~cursor.fetchmany`, `~cursor.fetchone()`, `~cursor.fetchmany()`,
:meth:`~cursor.fetchall`. `~cursor.fetchall()`.
@ -101,7 +101,7 @@ While the mechanism resembles regular Python strings manipulation, there are a
few subtle differences you should care about when passing parameters to a few subtle differences you should care about when passing parameters to a
query: query:
- The Python string operator ``%`` is not used: the :meth:`~cursor.execute` - The Python string operator ``%`` is not used: the `~cursor.execute()`
method accepts a tuple or dictionary of values as second parameter. method accepts a tuple or dictionary of values as second parameter.
|sql-warn|__. |sql-warn|__.
@ -127,7 +127,7 @@ query:
- Only variable values should be bound via this method: it shouldn't be used - Only variable values should be bound via this method: it shouldn't be used
to set table or field names. For these elements, ordinary string formatting to set table or field names. For these elements, ordinary string formatting
should be used before running :meth:`~cursor.execute`. should be used before running `~cursor.execute()`.
@ -177,7 +177,7 @@ reliable. It is really the case to stress this point:
string. Not even at gunpoint. string. Not even at gunpoint.
The correct way to pass variables in a SQL command is using the second The correct way to pass variables in a SQL command is using the second
argument of the :meth:`~cursor.execute` method:: argument of the `~cursor.execute()` method::
>>> SQL = "INSERT INTO authors (name) VALUES (%s);" # Notice: no quotes >>> SQL = "INSERT INTO authors (name) VALUES (%s);" # Notice: no quotes
>>> data = ("O'Reilly", ) >>> data = ("O'Reilly", )
@ -199,10 +199,10 @@ objects when a query is executed.
If you need to convert other Python types to and from PostgreSQL data types, If you need to convert other Python types to and from PostgreSQL data types,
see :ref:`adapting-new-types` and :ref:`type-casting-from-sql-to-python`. You see :ref:`adapting-new-types` and :ref:`type-casting-from-sql-to-python`. You
can also find a few other specialized adapters in the :mod:`psycopg2.extras` can also find a few other specialized adapters in the `psycopg2.extras`
module. module.
In the following examples the method :meth:`~cursor.mogrify` is used to show In the following examples the method `~cursor.mogrify()` is used to show
the SQL string that would be sent to the database. the SQL string that would be sent to the database.
.. index:: .. index::
@ -221,8 +221,8 @@ the SQL string that would be sent to the database.
single: Float; Adaptation single: Float; Adaptation
single: Decimal; Adaptation single: Decimal; Adaptation
- Numeric objects: :class:`!int`, :class:`!long`, :class:`!float`, - Numeric objects: `!int`, `!long`, `!float`,
:class:`!Decimal` are converted in the PostgreSQL numerical representation:: `!Decimal` are converted in the PostgreSQL numerical representation::
>>> cur.mogrify("SELECT %s, %s, %s, %s;", (10, 10L, 10.0, Decimal("10.00"))) >>> cur.mogrify("SELECT %s, %s, %s, %s;", (10, 10L, 10.0, Decimal("10.00")))
>>> 'SELECT 10, 10, 10.0, 10.00;' >>> 'SELECT 10, 10, 10.0, 10.00;'
@ -234,10 +234,10 @@ the SQL string that would be sent to the database.
single: bytea; Adaptation single: bytea; Adaptation
single: Binary string single: Binary string
- String types: :class:`!str`, :class:`!unicode` are converted in SQL string - String types: `!str`, `!unicode` are converted in SQL string
syntax. :class:`!buffer` is converted in PostgreSQL binary string syntax, syntax. `!buffer` is converted in PostgreSQL binary string syntax,
suitable for :sql:`bytea` fields. When reading textual fields, either suitable for :sql:`bytea` fields. When reading textual fields, either
:class:`!str` or :class:`!unicode` can be received: see `!str` or `!unicode` can be received: see
:ref:`unicode-handling`. :ref:`unicode-handling`.
.. index:: .. index::
@ -246,8 +246,8 @@ the SQL string that would be sent to the database.
single: Interval objects; Adaptation single: Interval objects; Adaptation
single: mx.DateTime; Adaptation single: mx.DateTime; Adaptation
- Date and time objects: builtin :class:`!datetime`, :class:`!date`, - Date and time objects: builtin `!datetime`, `!date`,
:class:`!time`. :class:`!timedelta` are converted into PostgreSQL's `!time`. `!timedelta` are converted into PostgreSQL's
:sql:`timestamp`, :sql:`date`, :sql:`time`, :sql:`interval` data types. :sql:`timestamp`, :sql:`date`, :sql:`time`, :sql:`interval` data types.
Time zones are supported too. The Egenix `mx.DateTime`_ objects are adapted Time zones are supported too. The Egenix `mx.DateTime`_ objects are adapted
the same way:: the same way::
@ -289,7 +289,7 @@ the SQL string that would be sent to the database.
.. note:: .. note::
The IN adapter is automatically registered when the The IN adapter is automatically registered when the
:mod:`~psycopg2.extensions` module is imported. This behaviour may change `~psycopg2.extensions` module is imported. This behaviour may change
in the future and the adapter will probably be always active. in the future and the adapter will probably be always active.
.. versionadded:: 2.0.6 .. versionadded:: 2.0.6
@ -305,10 +305,10 @@ Unicode handling
^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^
Psycopg can exchange Unicode data with a PostgreSQL database. Python Psycopg can exchange Unicode data with a PostgreSQL database. Python
:class:`!unicode` objects are automatically *encoded* in the client encoding `!unicode` objects are automatically *encoded* in the client encoding
defined on the database connection (the `PostgreSQL encoding`__, available in defined on the database connection (the `PostgreSQL encoding`__, available in
:attr:`connection.encoding`, is translated into a `Python codec`__ using an `connection.encoding`, is translated into a `Python codec`__ using an
:data:`~psycopg2.extensions.encodings` mapping):: `~psycopg2.extensions.encodings` mapping)::
>>> print u, type(u) >>> print u, type(u)
àèìòù€ <type 'unicode'> àèìòù€ <type 'unicode'>
@ -319,7 +319,7 @@ defined on the database connection (the `PostgreSQL encoding`__, available in
.. __: http://docs.python.org/library/codecs.html#standard-encodings .. __: http://docs.python.org/library/codecs.html#standard-encodings
When reading data from the database, the strings returned are usually 8 bit When reading data from the database, the strings returned are usually 8 bit
:class:`!str` objects encoded in the database client encoding:: `!str` objects encoded in the database client encoding::
>>> print conn.encoding >>> print conn.encoding
UTF8 UTF8
@ -336,7 +336,7 @@ When reading data from the database, the strings returned are usually 8 bit
>>> print type(x), repr(x) >>> print type(x), repr(x)
<type 'str'> '\xe0\xe8\xec\xf2\xf9\xa4' <type 'str'> '\xe0\xe8\xec\xf2\xf9\xa4'
In order to obtain :class:`!unicode` objects instead, it is possible to In order to obtain `!unicode` objects instead, it is possible to
register a typecaster so that PostgreSQL textual types are automatically register a typecaster so that PostgreSQL textual types are automatically
*decoded* using the current client encoding:: *decoded* using the current client encoding::
@ -347,10 +347,10 @@ register a typecaster so that PostgreSQL textual types are automatically
>>> print x, type(x), repr(x) >>> print x, type(x), repr(x)
àèìòù€ <type 'unicode'> u'\xe0\xe8\xec\xf2\xf9\u20ac' àèìòù€ <type 'unicode'> u'\xe0\xe8\xec\xf2\xf9\u20ac'
In the above example, the :data:`~psycopg2.extensions.UNICODE` typecaster is In the above example, the `~psycopg2.extensions.UNICODE` typecaster is
registered only on the cursor. It is also possible to register typecasters on registered only on the cursor. It is also possible to register typecasters on
the connection or globally: see the function the connection or globally: see the function
:func:`~psycopg2.extensions.register_type` and `~psycopg2.extensions.register_type()` and
:ref:`type-casting-from-sql-to-python` for details. :ref:`type-casting-from-sql-to-python` for details.
.. note:: .. note::
@ -375,28 +375,28 @@ the connection or globally: see the function
Transactions control Transactions control
-------------------- --------------------
In Psycopg transactions are handled by the :class:`connection` class. By In Psycopg transactions are handled by the `connection` class. By
default, the first time a command is sent to the database (using one of the default, the first time a command is sent to the database (using one of the
:class:`cursor`\ s created by the connection), a new transaction is created. `cursor`\ s created by the connection), a new transaction is created.
The following database commands will be executed in the context of the same The following database commands will be executed in the context of the same
transaction -- not only the commands issued by the first cursor, but the ones transaction -- not only the commands issued by the first cursor, but the ones
issued by all the cursors created by the same connection. Should any command issued by all the cursors created by the same connection. Should any command
fail, the transaction will be aborted and no further command will be executed fail, the transaction will be aborted and no further command will be executed
until a call to the :meth:`connection.rollback` method. until a call to the `connection.rollback()` method.
The connection is responsible to terminate its transaction, calling either the The connection is responsible to terminate its transaction, calling either the
:meth:`~connection.commit` or :meth:`~connection.rollback` method. Committed `~connection.commit()` or `~connection.rollback()` method. Committed
changes are immediately made persistent into the database. Closing the changes are immediately made persistent into the database. Closing the
connection using the :meth:`~connection.close` method or destroying the connection using the `~connection.close()` method or destroying the
connection object (calling :meth:`!__del__` or letting it fall out of scope) connection object (calling `!__del__()` or letting it fall out of scope)
will result in an implicit :meth:`!rollback` call. will result in an implicit `!rollback()` call.
It is possible to set the connection in *autocommit* mode: this way all the It is possible to set the connection in *autocommit* mode: this way all the
commands executed will be immediately committed and no rollback is possible. A commands executed will be immediately committed and no rollback is possible. A
few commands (e.g. :sql:`CREATE DATABASE`, :sql:`VACUUM`...) require to be run few commands (e.g. :sql:`CREATE DATABASE`, :sql:`VACUUM`...) require to be run
outside any transaction: in order to be able to run these commands from outside any transaction: in order to be able to run these commands from
Psycopg, the session must be in autocommit mode. Read the documentation for Psycopg, the session must be in autocommit mode. Read the documentation for
:meth:`connection.set_isolation_level` to know how to change the commit mode. `connection.set_isolation_level()` to know how to change the commit mode.
@ -412,7 +412,7 @@ Psycopg, the session must be in autocommit mode. Read the documentation for
Server side cursors Server side cursors
------------------- -------------------
When a database query is executed, the Psycopg :class:`cursor` usually fetches When a database query is executed, the Psycopg `cursor` usually fetches
all the records returned by the backend, transferring them to the client all the records returned by the backend, transferring them to the client
process. If the query returned an huge amount of data, a proportionally large process. If the query returned an huge amount of data, a proportionally large
amount of memory will be allocated by the client. amount of memory will be allocated by the client.
@ -426,11 +426,11 @@ Server side cursor are created in PostgreSQL using the |DECLARE|_ command and
subsequently handled using :sql:`MOVE`, :sql:`FETCH` and :sql:`CLOSE` commands. subsequently handled using :sql:`MOVE`, :sql:`FETCH` and :sql:`CLOSE` commands.
Psycopg wraps the database server side cursor in *named cursors*. A named Psycopg wraps the database server side cursor in *named cursors*. A named
cursor is created using the :meth:`~connection.cursor` method specifying the cursor is created using the `~connection.cursor()` method specifying the
`name` parameter. Such cursor will behave mostly like a regular cursor, `name` parameter. Such cursor will behave mostly like a regular cursor,
allowing the user to move in the dataset using the :meth:`~cursor.scroll` allowing the user to move in the dataset using the `~cursor.scroll()`
methog and to read the data using :meth:`~cursor.fetchone` and methog and to read the data using `~cursor.fetchone()` and
:meth:`~cursor.fetchmany` methods. `~cursor.fetchmany()` methods.
.. |DECLARE| replace:: :sql:`DECLARE` .. |DECLARE| replace:: :sql:`DECLARE`
.. _DECLARE: http://www.postgresql.org/docs/8.4/static/sql-declare.html .. _DECLARE: http://www.postgresql.org/docs/8.4/static/sql-declare.html
@ -445,9 +445,9 @@ Thread safety
------------- -------------
The Psycopg module is *thread-safe*: threads can access the same database The Psycopg module is *thread-safe*: threads can access the same database
using separate session (by creating a :class:`connection` per thread) or using using separate session (by creating a `connection` per thread) or using
the same session (accessing to the same connection and creating separate the same session (accessing to the same connection and creating separate
:class:`cursor`\ s). In |DBAPI|_ parlance, Psycopg is *level 2 thread safe*. `cursor`\ s). In |DBAPI|_ parlance, Psycopg is *level 2 thread safe*.
@ -459,20 +459,20 @@ the same session (accessing to the same connection and creating separate
Using COPY TO and COPY FROM Using COPY TO and COPY FROM
--------------------------- ---------------------------
Psycopg :class:`cursor` objects provide an interface to the efficient Psycopg `cursor` objects provide an interface to the efficient
PostgreSQL |COPY|__ command to move data from files to tables and back. PostgreSQL |COPY|__ command to move data from files to tables and back.
The methods exposed are: The methods exposed are:
:meth:`~cursor.copy_from` `~cursor.copy_from()`
Reads data *from* a file-like object appending them to a database table Reads data *from* a file-like object appending them to a database table
(:sql:`COPY table FROM file` syntax). The source file must have both (:sql:`COPY table FROM file` syntax). The source file must have both
:meth:`!read` and :meth:`!readline` method. `!read()` and `!readline()` method.
:meth:`~cursor.copy_to` `~cursor.copy_to()`
Writes the content of a table *to* a file-like object (:sql:`COPY table TO Writes the content of a table *to* a file-like object (:sql:`COPY table TO
file` syntax). The target file must have a :meth:`write` method. file` syntax). The target file must have a `write()` method.
:meth:`~cursor.copy_expert` `~cursor.copy_expert()`
Allows to handle more specific cases and to use all the :sql:`COPY` Allows to handle more specific cases and to use all the :sql:`COPY`
features available in PostgreSQL. features available in PostgreSQL.
@ -500,13 +500,13 @@ whole.
.. __: http://www.postgresql.org/docs/8.4/static/largeobjects.html .. __: http://www.postgresql.org/docs/8.4/static/largeobjects.html
Psycopg allows access to the large object using the Psycopg allows access to the large object using the
:class:`~psycopg2.extensions.lobject` class. Objects are generated using the `~psycopg2.extensions.lobject` class. Objects are generated using the
:meth:`connection.lobject` factory method. `connection.lobject()` factory method.
Psycopg large object support efficient import/export with file system files Psycopg large object support efficient import/export with file system files
using the |lo_import|_ and |lo_export|_ libpq functions. using the |lo_import|_ and |lo_export|_ libpq functions.
.. |lo_import| replace:: :func:`!lo_import` .. |lo_import| replace:: `!lo_import()`
.. _lo_import: http://www.postgresql.org/docs/8.4/static/lo-interfaces.html#AEN36307 .. _lo_import: http://www.postgresql.org/docs/8.4/static/lo-interfaces.html#AEN36307
.. |lo_export| replace:: :func:`!lo_export` .. |lo_export| replace:: `!lo_export()`
.. _lo_export: http://www.postgresql.org/docs/8.4/static/lo-interfaces.html#AEN36330 .. _lo_export: http://www.postgresql.org/docs/8.4/static/lo-interfaces.html#AEN36330

View File

@ -32,7 +32,7 @@ This module contains symbolic names for all PostgreSQL error codes.
def lookup(code, _cache={}): def lookup(code, _cache={}):
"""Lookup an error code or class code and return its symbolic name. """Lookup an error code or class code and return its symbolic name.
Raise :exc:`KeyError` if the code is not found. Raise `KeyError` if the code is not found.
""" """
if _cache: if _cache:
return _cache[code] return _cache[code]

View File

@ -97,7 +97,7 @@ class DictCursorBase(_cursor):
return res return res
class DictConnection(_connection): class DictConnection(_connection):
"""A connection that uses :class:`DictCursor` automatically.""" """A connection that uses `DictCursor` automatically."""
def cursor(self, name=None): def cursor(self, name=None):
if name is None: if name is None:
return _connection.cursor(self, cursor_factory=DictCursor) return _connection.cursor(self, cursor_factory=DictCursor)
@ -180,7 +180,7 @@ class DictRow(list):
return self._index.__contains__(x) return self._index.__contains__(x)
class RealDictConnection(_connection): class RealDictConnection(_connection):
"""A connection that uses :class:`RealDictCursor` automatically.""" """A connection that uses `RealDictCursor` automatically."""
def cursor(self, name=None): def cursor(self, name=None):
if name is None: if name is None:
return _connection.cursor(self, cursor_factory=RealDictCursor) return _connection.cursor(self, cursor_factory=RealDictCursor)
@ -193,7 +193,7 @@ class RealDictCursor(DictCursorBase):
Note that this cursor is extremely specialized and does not allow Note that this cursor is extremely specialized and does not allow
the normal access (using integer indices) to fetched data. If you need the normal access (using integer indices) to fetched data. If you need
to access database rows both as a dictionary and a list, then use to access database rows both as a dictionary and a list, then use
the generic :class:`DictCursor` instead of :class:`!RealDictCursor`. the generic `DictCursor` instead of `!RealDictCursor`.
""" """
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
@ -298,13 +298,13 @@ class LoggingCursor(_cursor):
class MinTimeLoggingConnection(LoggingConnection): class MinTimeLoggingConnection(LoggingConnection):
"""A connection that logs queries based on execution time. """A connection that logs queries based on execution time.
This is just an example of how to sub-class :class:`LoggingConnection` to This is just an example of how to sub-class `LoggingConnection` to
provide some extra filtering for the logged queries. Both the provide some extra filtering for the logged queries. Both the
:meth:`inizialize` and :meth:`filter` methods are overwritten to make sure `inizialize()` and `filter()` methods are overwritten to make sure
that only queries executing for more than ``mintime`` ms are logged. that only queries executing for more than ``mintime`` ms are logged.
Note that this connection uses the specialized cursor Note that this connection uses the specialized cursor
:class:`MinTimeLoggingCursor`. `MinTimeLoggingCursor`.
""" """
def initialize(self, logobj, mintime=0): def initialize(self, logobj, mintime=0):
LoggingConnection.initialize(self, logobj) LoggingConnection.initialize(self, logobj)
@ -323,7 +323,7 @@ class MinTimeLoggingConnection(LoggingConnection):
return _connection.cursor(self, name, cursor_factory=MinTimeLoggingCursor) return _connection.cursor(self, name, cursor_factory=MinTimeLoggingCursor)
class MinTimeLoggingCursor(LoggingCursor): class MinTimeLoggingCursor(LoggingCursor):
"""The cursor sub-class companion to :class:`MinTimeLoggingConnection`.""" """The cursor sub-class companion to `MinTimeLoggingConnection`."""
def execute(self, query, vars=None, async=0): def execute(self, query, vars=None, async=0):
self.timestamp = time.time() self.timestamp = time.time()

View File

@ -199,7 +199,7 @@ class PersistentConnectionPool(AbstractConnectionPool):
Note that this connection pool generates by itself the required keys Note that this connection pool generates by itself the required keys
using the current thread id. This means that until a thread puts away using the current thread id. This means that until a thread puts away
a connection it will always get the same connection object by successive a connection it will always get the same connection object by successive
:meth:`!getconn` calls. This also means that a thread can't use more than one `!getconn()` calls. This also means that a thread can't use more than one
single connection from the pool. single connection from the pool.
""" """

View File

@ -35,7 +35,7 @@ class FixedOffsetTimezone(datetime.tzinfo):
"""Fixed offset in minutes east from UTC. """Fixed offset in minutes east from UTC.
This is exactly the implementation__ found in Python 2.3.x documentation, This is exactly the implementation__ found in Python 2.3.x documentation,
with a small change to the :meth:`!__init__` method to allow for pickling with a small change to the `!__init__()` method to allow for pickling
and a default name in the form ``sHH:MM`` (``s`` is the sign.). and a default name in the form ``sHH:MM`` (``s`` is the sign.).
.. __: http://docs.python.org/library/datetime.html#datetime-tzinfo .. __: http://docs.python.org/library/datetime.html#datetime-tzinfo