diff --git a/doc/src/advanced.rst b/doc/src/advanced.rst index 64aa7044..40360648 100644 --- a/doc/src/advanced.rst +++ b/doc/src/advanced.rst @@ -21,10 +21,10 @@ Connection and cursor factories ------------------------------- 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` -and :class:`psycopg2.extensions.connection`. The :class:`connection` class is +adapt them to the needs of the programmer: `psycopg2.extensions.cursor` +and `psycopg2.extensions.connection`. The `connection` class is 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 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 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 -:class:`~psycopg2.extensions.ISQLQuote` protocol. Objects that conform to this -protocol expose a :meth:`!getquoted` method returning the SQL representation +The `~cursor.execute()` method adapts its arguments to the +`~psycopg2.extensions.ISQLQuote` protocol. Objects that conform to this +protocol expose a `!getquoted()` method returning the SQL representation of the object as a string. 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 -conform object. A convenient object is the :class:`~psycopg2.extensions.AsIs` -wrapper, whose :meth:`!getquoted` result is simply the :meth:`!str`\ ing +conform object. A convenient object is the `~psycopg2.extensions.AsIs` +wrapper, whose `!getquoted()` result is simply the `!str()`\ ing conversion of the wrapped object. .. index:: 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: .. 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 cursor currently being read, and should return a new Python object. For 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): ... 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 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") >>> 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) >>> 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. -: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 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 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` -command in an :meth:`~cursor.execute` call. +command in an `~cursor.execute()` call. Because of the way sessions interact with notifications (see |NOTIFY|_ documentation), you should keep the connection in :ref:`autocommit @@ -261,7 +261,7 @@ Asynchronous queries Discussion, testing and suggestions are welcome. 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:: 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 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. -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. The return value is ``True`` if the query was successfully aborted or ``False`` if it was executed. Query result are discarded in both cases. -3) :meth:`~cursor.execute` is called again on the same cursor - (:meth:`!execute` on a different cursor will simply raise an exception). +3) `~cursor.execute()` is called again on the same cursor + (`!execute()` on a different cursor will simply raise an exception). This waits for the complete execution of the current query, discard any 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 the two queries is executed. Cursors now have some extra methods that make them useful during asynchronous queries: -:meth:`~cursor.fileno` +`~cursor.fileno()` 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 - 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`` - 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:: 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:: import psycopg2 diff --git a/doc/src/conf.py b/doc/src/conf.py index f7f370b6..4036b5bf 100644 --- a/doc/src/conf.py +++ b/doc/src/conf.py @@ -76,7 +76,7 @@ except ImportError: exclude_trees = ['_build', 'html'] # 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. #add_function_parentheses = True diff --git a/doc/src/connection.rst b/doc/src/connection.rst index 6addc033..1e65b299 100644 --- a/doc/src/connection.rst +++ b/doc/src/connection.rst @@ -16,14 +16,14 @@ The ``connection`` class a database session. Connections are created using the factory function - :func:`~psycopg2.connect`. + `~psycopg2.connect()`. Connections are thread safe and can be shared among many thread. See :ref:`thread-safety` for details. .. 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 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 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. .. extension:: @@ -47,7 +47,7 @@ The ``connection`` class Commit any pending transaction to the database. Psycopg can be set to perform automatic commits at each operation, see - :meth:`~connection.set_isolation_level`. + `~connection.set_isolation_level()`. .. index:: @@ -62,14 +62,14 @@ The ``connection`` class .. 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 - :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 trying to use the connection. Note that closing a connection without committing the changes first will cause an implicit rollback to be performed (unless a different isolation level has been selected: see - :meth:`~connection.set_isolation_level`). + `~connection.set_isolation_level()`). .. index:: @@ -77,8 +77,8 @@ The ``connection`` class .. rubric:: Excetptions as connection class attributes - The :class:`!connection` also exposes as attributes the same exceptions - available in the :mod:`psycopg2` module. See :ref:`dbapi-exceptions`. + The `!connection` also exposes as attributes the same exceptions + available in the `psycopg2` module. See :ref:`dbapi-exceptions`. .. extension:: @@ -131,13 +131,13 @@ The ``connection`` class database between concurrent transactions. 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. The default level is :sql:`READ COMMITTED`: at this level a transaction is automatically started the first time a database command 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:: >>> 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 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. .. seealso:: libpq docs for `PQtransactionStatus()`__ for details. @@ -288,7 +288,7 @@ The ``connection`` class A read-only integer representing the status of the connection. 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. @@ -302,15 +302,15 @@ The ``connection`` class :param mode: Access mode to the object: can be ``r``, ``w``, ``rw`` or ``n`` (meaning don't open it). :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. :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 - :class:`~psycopg2.extensions.lobject` to be instantiated. - :rtype: :class:`~psycopg2.extensions.lobject` + `~psycopg2.extensions.lobject` to be instantiated. + :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 .. versionadded:: 2.0.8 diff --git a/doc/src/cursor.rst b/doc/src/cursor.rst index dcb6c22b..ffdce6f2 100644 --- a/doc/src/cursor.rst +++ b/doc/src/cursor.rst @@ -19,7 +19,7 @@ The ``cursor`` class .. class:: cursor 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 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 other cursors. Cursors created from different connections can or can not be isolated, depending on the connections' :ref:`isolation level - `. See also :meth:`~connection.rollback` and - :meth:`~connection.commit` methods. + `. See also `~connection.rollback()` and + `~connection.commit()` methods. Cursors are *not* thread safe: a multithread application can create many cursors from the same connection and should use each cursor from @@ -66,9 +66,9 @@ The ``cursor`` class .. 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 - :exc:`~psycopg2.InterfaceError` will be raised if any operation is + `~psycopg2.InterfaceError` will be raised if any operation is attempted with the cursor. .. attribute:: closed @@ -78,7 +78,7 @@ The ``cursor`` class .. extension:: - The :attr:`closed` attribute is a Psycopg extension to the + The `closed` attribute is a Psycopg extension to the |DBAPI|. .. versionadded:: 2.0.7 @@ -86,23 +86,23 @@ The ``cursor`` class .. 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. .. attribute:: name 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`. .. 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*: @@ -123,7 +123,7 @@ The ``cursor`` class If `async` is ``True``, query execution will be asynchronous: 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 :ref:`asynchronous-queries`. @@ -136,14 +136,14 @@ The ``cursor`` class Return a query string after arguments binding. The string returned is 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')) "INSERT INTO test (num, data) VALUES (42, E'bar')" .. 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) @@ -156,7 +156,7 @@ The ``cursor`` class any result set returned by the query is discarded. 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]) @@ -172,7 +172,7 @@ The ``cursor`` class If `async` is ``True``, procedure execution will be asynchronous: 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 :ref:`asynchronous-queries`. @@ -188,7 +188,7 @@ The ``cursor`` class - .. |fetch*| replace:: :meth:`!fetch*` + .. |fetch*| replace:: `!fetch*()` .. _fetch*: @@ -196,12 +196,12 @@ The ``cursor`` class The following methods are used to read data from the database after an - :meth:`~cursor.execute` call. + `~cursor.execute()` call. .. note:: - :class:`cursor` objects are iterable, so, instead of calling - explicitly :meth:`~cursor.fetchone` in a loop, the object itself can + `cursor` objects are iterable, so, instead of calling + explicitly `~cursor.fetchone()` in a loop, the object itself can be used: >>> cur.execute("SELECT * FROM test;") @@ -222,7 +222,7 @@ The ``cursor`` class >>> cur.fetchone() (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 yet. @@ -233,7 +233,7 @@ The ``cursor`` class 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. - 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 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 @@ -247,14 +247,14 @@ The ``cursor`` class >>> 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. Note there are performance considerations involved with the size 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 - :meth:`fetchmany` call to the next. + `fetchmany()` call to the next. .. method:: fetchall() @@ -267,7 +267,7 @@ The ``cursor`` class >>> cur.fetchall() [(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. @@ -281,7 +281,7 @@ The ``cursor`` class value states an absolute target position. 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. The method can be used both for client-side cursors and @@ -290,7 +290,7 @@ The ``cursor`` class .. note:: 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:: try: @@ -302,7 +302,7 @@ The ``cursor`` class .. attribute:: arraysize 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. @@ -332,7 +332,7 @@ The ``cursor`` class 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 - :attr:`rownumber` in that sequence. + `rownumber` in that sequence. .. index:: oid @@ -359,7 +359,7 @@ The ``cursor`` class .. method:: nextset() 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]) @@ -380,7 +380,7 @@ The ``cursor`` class .. extension:: - The :attr:`query` attribute is a Psycopg extension to the |DBAPI|. + The `query` attribute is a Psycopg extension to the |DBAPI|. .. attribute:: statusmessage @@ -394,7 +394,7 @@ The ``cursor`` class .. extension:: - The :attr:`statusmessage` attribute is a Psycopg extension to the + The `statusmessage` attribute is a Psycopg extension to the |DBAPI|. @@ -406,28 +406,28 @@ The ``cursor`` class .. extension:: - The :meth:`isready` method is a Psycopg extension to the |DBAPI|. + The `isready()` method is a Psycopg extension to the |DBAPI|. .. method:: fileno() Return the file descriptor associated with the current connection and 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`. .. 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 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 :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 @@ -443,7 +443,7 @@ The ``cursor`` class Read data *from* the file-like object `file` appending them to 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. 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) 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. The optional argument `sep` is the columns separator and diff --git a/doc/src/errorcodes.rst b/doc/src/errorcodes.rst index a0c10337..463bf7d5 100644 --- a/doc/src/errorcodes.rst +++ b/doc/src/errorcodes.rst @@ -1,4 +1,4 @@ -:mod:`psycopg2.errorcodes` -- Error codes defined by PostgreSQL +`psycopg2.errorcodes` -- Error codes defined by PostgreSQL =============================================================== .. sectionauthor:: Daniele Varrazzo @@ -15,8 +15,8 @@ .. versionadded:: 2.0.6 This module contains symbolic names for all PostgreSQL error codes and error -classes codes. Subclasses of :exc:`~psycopg2.Error` make the PostgreSQL error -code available in the :attr:`~psycopg2.Error.pgcode` attribute. +classes codes. Subclasses of `~psycopg2.Error` make the PostgreSQL error +code available in the `~psycopg2.Error.pgcode` attribute. From PostgreSQL documentation: diff --git a/doc/src/extensions.rst b/doc/src/extensions.rst index ed34f614..3f4959ea 100644 --- a/doc/src/extensions.rst +++ b/doc/src/extensions.rst @@ -1,4 +1,4 @@ -:mod:`psycopg2.extensions` -- Extensions to the DB API +`psycopg2.extensions` -- Extensions to the DB API ====================================================== .. sectionauthor:: Daniele Varrazzo @@ -15,31 +15,31 @@ functionalities defined by the |DBAPI|_. .. class:: connection - Is the class usually returned by the :func:`~psycopg2.connect` function. - It is exposed by the :mod:`extensions` module in order to allow + Is the class usually returned by the `~psycopg2.connect()` function. + It is exposed by the `extensions` module in order to allow 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`. - For a complete description of the class, see :class:`connection`. + For a complete description of the class, see `connection`. .. class:: cursor - It is the class usually returnded by the :meth:`connection.cursor` - method. It is exposed by the :mod:`extensions` module in order to allow + It is the class usually returnded by the `connection.cursor()` + method. It is exposed by the `extensions` module in order to allow 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`. - 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 ]]]]) Wrapper for a PostgreSQL large object. See :ref:`large-objects` for an overview. - The class can be subclassed: see the :meth:`connection.lobject` to know - how to specify a :class:`!lobject` subclass. + The class can be subclassed: see the `connection.lobject()` to know + how to specify a `!lobject` subclass. .. versionadded:: 2.0.8 @@ -67,7 +67,7 @@ functionalities defined by the |DBAPI|_. 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 .. method:: seek(offset, whence=0) @@ -105,33 +105,33 @@ deal with Python objects adaptation: .. function:: adapt(obj) 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 - using the :func:`register_adapter` function. + using the `register_adapter()` function. The function is the entry point of the adaptation mechanism: it can be used to write adapters for complex objects by recursively calling - :func:`!adapt` on its components. + `!adapt()` on its components. .. function:: register_adapter(class, adapter) Register a new adapter for the objects of class `class`. `adapter` should be a function taking a single argument (the object - to adapt) and returning an object conforming the :class:`ISQLQuote` - protocol (e.g. exposing a :meth:`!getquoted` method). The :class:`AsIs` is + to adapt) and returning an object conforming the `ISQLQuote` + protocol (e.g. exposing a `!getquoted()` method). The `AsIs` is often useful for this task. 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) 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 - enough to expose a :meth:`!getquoted` method to be conforming. + Adapters may subclass `!ISQLQuote`, but is not necessary: it is + enough to expose a `!getquoted()` method to be conforming. .. attribute:: _wrapped @@ -140,24 +140,24 @@ deal with Python objects adaptation: .. method:: getquoted() 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. .. 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. .. method:: getquoted() - Return the :meth:`str` conversion of the wrapped object. + Return the `str()` conversion of the wrapped object. >>> AsIs(42).getquoted() '42' .. class:: QuotedString - Adapter conform to the :class:`ISQLQuote` protocol for string-like + Adapter conform to the `ISQLQuote` protocol for string-like objects. .. method:: getquoted() @@ -171,21 +171,21 @@ deal with Python objects adaptation: .. class:: Binary - Adapter conform to the :class:`ISQLQuote` protocol for binary objects. + Adapter conform to the `ISQLQuote` protocol for binary objects. .. method:: getquoted() 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. >>> Binary("\x00\x08\x0F").getquoted() "'\\\\000\\\\010\\\\017'" .. 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 :mod:`!psycopg2._psycopg`. + module `!psycopg2._psycopg`. @@ -212,7 +212,7 @@ deal with Python objects adaptation: .. data:: adapters 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 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 name: the name of the new type adapter. :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. `adapter` should have signature :samp:`fun({value}, {cur})` where @@ -246,10 +246,10 @@ details. .. 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 - :class:`cursor`: the type caster will be effective only limited to the + If `scope` is specified, it should be a `connection` or a + `cursor`: the type caster will be effective only limited to the 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 - (subclasses :exc:`~psycopg2.OperationalError`) + (subclasses `~psycopg2.OperationalError`) Error related to SQL query cancelation. It can be trapped specifically to detect a timeout. @@ -293,7 +293,7 @@ The module exports a few exceptions in addition to the :ref:`standard ones .. exception:: TransactionRollbackError - (subclasses :exc:`~psycopg2.OperationalError`) + (subclasses `~psycopg2.OperationalError`) Error causing transaction rollback (deadlocks, serialisation failures, 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 ------------------------- -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 -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 -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: .. data:: ISOLATION_LEVEL_AUTOCOMMIT 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` 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 This is the default value. A new transaction is started at the first - :meth:`~cursor.execute` command on a cursor and at each new - :meth:`!execute` after a :meth:`~connection.commit` or a - :meth:`~connection.rollback`. The transaction runs in the PostgreSQL + `~cursor.execute()` command on a cursor and at each new + `!execute()` after a `~connection.commit()` or a + `~connection.rollback()`. The transaction runs in the PostgreSQL :sql:`READ COMMITTED` isolation level. .. data:: ISOLATION_LEVEL_REPEATABLE_READ @@ -368,7 +368,7 @@ Transaction status constants ---------------------------- 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 @@ -401,7 +401,7 @@ Connection status constants --------------------------- 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 @@ -417,7 +417,7 @@ can be read from the :attr:`~connection.status` attribute. .. data:: STATUS_IN_TRANSACTION - An alias for :const:`STATUS_BEGIN` + An alias for `STATUS_BEGIN` .. data:: STATUS_SYNC @@ -432,11 +432,11 @@ can be read from the :attr:`~connection.status` attribute. 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 Python objects. All the typecasters are automatically registered, except -:data:`UNICODE` and :data:`UNICODEARRAY`: you can register them using -:func:`register_type` in order to receive Unicode objects instead of strings +`UNICODE` and `UNICODEARRAY`: you can register them using +`register_type()` in order to receive Unicode objects instead of strings from the database. See :ref:`unicode-handling` for details. .. data:: BINARYARRAY diff --git a/doc/src/extras.rst b/doc/src/extras.rst index 3184669f..9eeddccf 100644 --- a/doc/src/extras.rst +++ b/doc/src/extras.rst @@ -1,4 +1,4 @@ -:mod:`psycopg2.extras` -- Miscellaneous goodies for Psycopg 2 +`psycopg2.extras` -- Miscellaneous goodies for Psycopg 2 ============================================================= .. sectionauthor:: Daniele Varrazzo @@ -26,10 +26,10 @@ Dictionary-like cursor 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 -either passing :class:`DictConnection` as `connection_factory` argument -to the :func:`~psycopg2.connect` function or passing :class:`DictCursor` as -the :class:`!cursor_factory` argument to the :meth:`~connection.cursor` method -of a regular :class:`connection`. +either passing `DictConnection` as `connection_factory` argument +to the `~psycopg2.connect()` function or passing `DictCursor` as +the `!cursor_factory` argument to the `~connection.cursor()` method +of a regular `connection`. >>> dict_cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) >>> dict_cur.execute("INSERT INTO test (num, data) VALUES(%s, %s)", diff --git a/doc/src/faq.rst b/doc/src/faq.rst index 9041eadc..b45d1032 100644 --- a/doc/src/faq.rst +++ b/doc/src/faq.rst @@ -3,17 +3,17 @@ Frequently Asked Questions .. sectionauthor:: Daniele Varrazzo -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! .. 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 - 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 - :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 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 ` mode to avoid a new 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 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 @@ -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! There was a problem *in the previous* command to the database, which 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 PostgreSQL supports nested transactions using the |SAVEPOINT|_ command). .. |SAVEPOINT| replace:: :sql:`SAVEPOINT` .. _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 safe). If you are forking the Python process ensure to create a new 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:: 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. -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 ``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 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 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 - 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 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 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 - left "idle in transaction". See also :mod:`psycopg2.pool` for lightweight + left "idle in transaction". See also `psycopg2.pool` for lightweight connection pooling. 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 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: - 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. diff --git a/doc/src/module.rst b/doc/src/module.rst index f4ef27b2..76a8f58c 100644 --- a/doc/src/module.rst +++ b/doc/src/module.rst @@ -1,4 +1,4 @@ -The :mod:`psycopg2` module content +The `psycopg2` module content ================================== .. sectionauthor:: Daniele Varrazzo @@ -18,7 +18,7 @@ The module interface respects the standard defined in the |DBAPI|_. .. 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:: @@ -53,19 +53,19 @@ The module interface respects the standard defined in the |DBAPI|_. .. 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``. .. data:: threadsafety 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. .. data:: paramstyle 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`. @@ -101,12 +101,12 @@ available through the following exceptions: .. attribute:: pgcode 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. .. extension:: - The :attr:`~Error.pgerror` and :attr:`~Error.pgcode` attributes are + The `~Error.pgerror` and `~Error.pgcode` attributes are Psycopg extensions. .. doctest:: @@ -124,26 +124,26 @@ available through the following exceptions: LINE 1: SELECT * FROM barf ^ - .. versionchanged:: 2.0.7 added :attr:`Error.pgerror` and - :attr:`Error.pgcode` attributes. + .. versionchanged:: 2.0.7 added `Error.pgerror` and + `Error.pgcode` attributes. .. exception:: InterfaceError 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 raised for errors that are related to the database. It is a - subclass of :exc:`Error`. + subclass of `Error`. .. exception:: DataError 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 - subclass of :exc:`DatabaseError`. + subclass of `DatabaseError`. .. exception:: OperationalError @@ -151,41 +151,41 @@ available through the following exceptions: and not necessarily under the control of the programmer, e.g. an unexpected disconnect occurs, the data source name is not found, a 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 raised when the relational integrity of the database is affected, e.g. a foreign key check fails. It is a subclass of - :exc:`DatabaseError`. + `DatabaseError`. .. exception:: InternalError 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 - subclass of :exc:`DatabaseError`. + subclass of `DatabaseError`. .. exception:: ProgrammingError Exception raised for programming errors, e.g. table not found or already 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 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 - off. It is a subclass of :exc:`DatabaseError`. + off. It is a subclass of `DatabaseError`. .. extension:: Psycopg may raise a few other, more specialized, exceptions: currently - :exc:`~psycopg2.extensions.QueryCanceledError` and - :exc:`~psycopg2.extensions.TransactionRollbackError` are defined. These - exceptions are not exposed by the main :mod:`!psycopg2` module but are - made available by the :mod:`~psycopg2.extensions` module. All the + `~psycopg2.extensions.QueryCanceledError` and + `~psycopg2.extensions.TransactionRollbackError` are defined. These + exceptions are not exposed by the main `!psycopg2` module but are + made available by the `~psycopg2.extensions` module. All the additional exceptions are subclasses of standard |DBAPI| exceptions, so trapping them specifically is not required. @@ -195,21 +195,21 @@ This is the exception inheritance layout: .. parsed-literal:: |StandardError| - \|__ :exc:`Warning` - \|__ :exc:`Error` - \|__ :exc:`InterfaceError` - \|__ :exc:`DatabaseError` - \|__ :exc:`DataError` - \|__ :exc:`OperationalError` - \| \|__ :exc:`psycopg2.extensions.QueryCanceledError` - \| \|__ :exc:`psycopg2.extensions.TransactionRollbackError` - \|__ :exc:`IntegrityError` - \|__ :exc:`InternalError` - \|__ :exc:`ProgrammingError` - \|__ :exc:`NotSupportedError` + \|__ `Warning` + \|__ `Error` + \|__ `InterfaceError` + \|__ `DatabaseError` + \|__ `DataError` + \|__ `OperationalError` + \| \|__ `psycopg2.extensions.QueryCanceledError` + \| \|__ `psycopg2.extensions.TransactionRollbackError` + \|__ `IntegrityError` + \|__ `InternalError` + \|__ `ProgrammingError` + \|__ `NotSupportedError` -.. |StandardError| replace:: :exc:`!StandardError` +.. |StandardError| replace:: `!StandardError` .. _StandardError: http://docs.python.org/library/exceptions.html#exceptions.StandardError diff --git a/doc/src/pool.rst b/doc/src/pool.rst index 1be2c6a3..952565c7 100644 --- a/doc/src/pool.rst +++ b/doc/src/pool.rst @@ -18,7 +18,7 @@ directly into the client application. New *minconn* connections are created automatically. The pool will support 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: @@ -38,7 +38,7 @@ directly into the client 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. .. autoclass:: SimpleConnectionPool diff --git a/doc/src/tz.rst b/doc/src/tz.rst index 86d26996..9f5168cb 100644 --- a/doc/src/tz.rst +++ b/doc/src/tz.rst @@ -1,4 +1,4 @@ -:mod:`psycopg2.tz` -- ``tzinfo`` implementations for Psycopg 2 +`psycopg2.tz` -- ``tzinfo`` implementations for Psycopg 2 =============================================================== .. sectionauthor:: Daniele Varrazzo @@ -7,7 +7,7 @@ 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 :attr:`cursor.tzinfo_factory` attribute in +functions or used to set the `cursor.tzinfo_factory` attribute in cursors. .. todo:: should say something more about tz handling diff --git a/doc/src/usage.rst b/doc/src/usage.rst index 74f538e1..c57b3da2 100644 --- a/doc/src/usage.rst +++ b/doc/src/usage.rst @@ -41,25 +41,25 @@ basic commands:: The main entry point of Psycopg are: -- The function :func:`~psycopg2.connect` creates a new database session and - returns a new :class:`connection` instance. +- The function `~psycopg2.connect()` creates a new database session and + 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, - - terminate the session using the methods :meth:`~connection.commit` or - :meth:`~connection.rollback`. + - terminate the session using the methods `~connection.commit()` or + `~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` - and :meth:`~cursor.executemany`, + - send commands to the database using methods such as `~cursor.execute()` + and `~cursor.executemany()`, - retrieve data from the database using methods such as - :meth:`~cursor.fetchone`, :meth:`~cursor.fetchmany`, - :meth:`~cursor.fetchall`. + `~cursor.fetchone()`, `~cursor.fetchmany()`, + `~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 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. |sql-warn|__. @@ -127,7 +127,7 @@ query: - 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 - 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. 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 >>> 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, 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. -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. .. index:: @@ -221,8 +221,8 @@ the SQL string that would be sent to the database. single: Float; Adaptation single: Decimal; Adaptation -- Numeric objects: :class:`!int`, :class:`!long`, :class:`!float`, - :class:`!Decimal` are converted in the PostgreSQL numerical representation:: +- Numeric objects: `!int`, `!long`, `!float`, + `!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;' @@ -234,10 +234,10 @@ the SQL string that would be sent to the database. single: bytea; Adaptation single: Binary string -- String types: :class:`!str`, :class:`!unicode` are converted in SQL string - syntax. :class:`!buffer` is converted in PostgreSQL binary string syntax, +- String types: `!str`, `!unicode` are converted in SQL string + syntax. `!buffer` is converted in PostgreSQL binary string syntax, 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`. .. index:: @@ -246,8 +246,8 @@ the SQL string that would be sent to the database. single: Interval objects; Adaptation single: mx.DateTime; Adaptation -- Date and time objects: builtin :class:`!datetime`, :class:`!date`, - :class:`!time`. :class:`!timedelta` are converted into PostgreSQL's +- Date and time objects: builtin `!datetime`, `!date`, + `!time`. `!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:: @@ -289,7 +289,7 @@ the SQL string that would be sent to the database. .. note:: 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. .. versionadded:: 2.0.6 @@ -305,10 +305,10 @@ Unicode handling ^^^^^^^^^^^^^^^^ 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 -:attr:`connection.encoding`, is translated into a `Python codec`__ using an -:data:`~psycopg2.extensions.encodings` mapping):: +`connection.encoding`, is translated into a `Python codec`__ using an +`~psycopg2.extensions.encodings` mapping):: >>> print u, type(u) àèìòù€ @@ -319,7 +319,7 @@ defined on the database connection (the `PostgreSQL encoding`__, available in .. __: http://docs.python.org/library/codecs.html#standard-encodings 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 UTF8 @@ -336,7 +336,7 @@ When reading data from the database, the strings returned are usually 8 bit >>> print type(x), repr(x) '\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 *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) àèìòù€ 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 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. .. note:: @@ -375,28 +375,28 @@ the connection or globally: see the function 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 -: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 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 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 -: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 -connection using the :meth:`~connection.close` method or destroying the -connection object (calling :meth:`!__del__` or letting it fall out of scope) -will result in an implicit :meth:`!rollback` call. +connection using the `~connection.close()` method or destroying the +connection object (calling `!__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 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 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 -: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 ------------------- -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 process. If the query returned an huge amount of data, a proportionally large 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. 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, -allowing the user to move in the dataset using the :meth:`~cursor.scroll` -methog and to read the data using :meth:`~cursor.fetchone` and -:meth:`~cursor.fetchmany` methods. +allowing the user to move in the dataset using the `~cursor.scroll()` +methog and to read the data using `~cursor.fetchone()` and +`~cursor.fetchmany()` methods. .. |DECLARE| replace:: :sql:`DECLARE` .. _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 -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 -: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 --------------------------- -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. The methods exposed are: -:meth:`~cursor.copy_from` +`~cursor.copy_from()` 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 - :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 - 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` features available in PostgreSQL. @@ -500,13 +500,13 @@ whole. .. __: http://www.postgresql.org/docs/8.4/static/largeobjects.html Psycopg allows access to the large object using the -:class:`~psycopg2.extensions.lobject` class. Objects are generated using the -:meth:`connection.lobject` factory method. +`~psycopg2.extensions.lobject` class. Objects are generated using the +`connection.lobject()` factory method. Psycopg large object support efficient import/export with file system files 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_export| replace:: :func:`!lo_export` +.. |lo_export| replace:: `!lo_export()` .. _lo_export: http://www.postgresql.org/docs/8.4/static/lo-interfaces.html#AEN36330 diff --git a/lib/errorcodes.py b/lib/errorcodes.py index 95672011..e305de5d 100644 --- a/lib/errorcodes.py +++ b/lib/errorcodes.py @@ -32,7 +32,7 @@ This module contains symbolic names for all PostgreSQL error codes. def lookup(code, _cache={}): """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: return _cache[code] diff --git a/lib/extras.py b/lib/extras.py index 26b6208e..87c9f7ce 100644 --- a/lib/extras.py +++ b/lib/extras.py @@ -97,7 +97,7 @@ class DictCursorBase(_cursor): return res class DictConnection(_connection): - """A connection that uses :class:`DictCursor` automatically.""" + """A connection that uses `DictCursor` automatically.""" def cursor(self, name=None): if name is None: return _connection.cursor(self, cursor_factory=DictCursor) @@ -180,7 +180,7 @@ class DictRow(list): return self._index.__contains__(x) class RealDictConnection(_connection): - """A connection that uses :class:`RealDictCursor` automatically.""" + """A connection that uses `RealDictCursor` automatically.""" def cursor(self, name=None): if name is None: 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 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 - the generic :class:`DictCursor` instead of :class:`!RealDictCursor`. + the generic `DictCursor` instead of `!RealDictCursor`. """ def __init__(self, *args, **kwargs): @@ -298,13 +298,13 @@ class LoggingCursor(_cursor): class MinTimeLoggingConnection(LoggingConnection): """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 - :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. Note that this connection uses the specialized cursor - :class:`MinTimeLoggingCursor`. + `MinTimeLoggingCursor`. """ def initialize(self, logobj, mintime=0): LoggingConnection.initialize(self, logobj) @@ -323,7 +323,7 @@ class MinTimeLoggingConnection(LoggingConnection): return _connection.cursor(self, name, cursor_factory=MinTimeLoggingCursor) 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): self.timestamp = time.time() diff --git a/lib/pool.py b/lib/pool.py index 030cb686..f9cdab68 100644 --- a/lib/pool.py +++ b/lib/pool.py @@ -199,7 +199,7 @@ class PersistentConnectionPool(AbstractConnectionPool): Note that this connection pool generates by itself the required keys 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 - :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. """ diff --git a/lib/tz.py b/lib/tz.py index 9f078c77..f3e9544f 100644 --- a/lib/tz.py +++ b/lib/tz.py @@ -35,7 +35,7 @@ class FixedOffsetTimezone(datetime.tzinfo): """Fixed offset in minutes east from UTC. 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.). .. __: http://docs.python.org/library/datetime.html#datetime-tzinfo