From: Daniele Varrazzo Date: Wed, 11 Nov 2020 22:54:59 +0000 (+0000) Subject: More docs X-Git-Tag: 3.0.dev0~380 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=d497a572e181ab8069272d0c8e37475626ca4456;p=thirdparty%2Fpsycopg.git More docs --- diff --git a/.gitignore b/.gitignore index 54ca4839a..1abeb25fe 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ *.pstats /.mypy_cache __pycache__/ +/docs/_build/ diff --git a/docs/connection.rst b/docs/connection.rst index 1f0e869c3..16067494f 100644 --- a/docs/connection.rst +++ b/docs/connection.rst @@ -1,6 +1,8 @@ The ``Connection`` classes ========================== +.. currentmodule:: psycopg3 + The `Connection` and `AsyncConnection` classes are the main wrappers for a PostgreSQL database session. You can imagine them similar to a :program:`psql` session. @@ -10,7 +12,7 @@ usually handles a transaction automatically: other sessions will not be able to see the changes until you have committed them, more or less explicitly. Take a look to :ref:`transactions` for the details. -.. autoclass:: psycopg3.Connection +.. autoclass:: Connection This class implements a DBAPI-compliant interface. It is what you want to use if you write a "classic", blocking program (eventually using threads or @@ -21,33 +23,41 @@ Take a look to :ref:`transactions` for the details. transaction will be committed (or rolled back, in case of exception) and the connection will be closed. + .. rubric:: Methods you will need every day + .. automethod:: connect - Connection parameters can be passed either as a `conninfo string`__ (a - ``postgresql://`` url or a list of ``key=value pairs``) or as keywords. - Keyword parameters override the ones specified in the connection string. + Connection parameters can be passed either as a `conninfo string`__ (a + ``postgresql://`` url or a list of ``key=value pairs``) or as keywords. + Keyword parameters override the ones specified in the connection string. - .. __: https://www.postgresql.org/docs/current/libpq-connect.html - #LIBPQ-CONNSTRING + .. __: https://www.postgresql.org/docs/current/libpq-connect.html + #LIBPQ-CONNSTRING - This method is also aliased as `psycopg3.connect()`. + This method is also aliased as `psycopg3.connect()`. - .. seealso:: + .. seealso:: - - the list of `the accepted connection parameters`__ - - the `environment varialbes`__ affecting connection + - the list of `the accepted connection parameters`__ + - the `environment varialbes`__ affecting connection - .. __: https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS - .. __: https://www.postgresql.org/docs/current/libpq-envars.html - - .. rubric:: Methods you will need every day + .. __: https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS + .. __: https://www.postgresql.org/docs/current/libpq-envars.html .. automethod:: cursor .. automethod:: commit .. automethod:: rollback + + .. autoattribute:: autocommit + + The property is writable for sync connections, read-only for async + ones: you can call `~AsyncConnection.set_autocommit()` on those. + + For details see :ref:`transactions`. + .. automethod:: close - .. rubric:: Checking the connection state + .. rubric:: Checking and configuring the connection state .. autoproperty:: closed .. autoproperty:: client_encoding @@ -55,6 +65,10 @@ Take a look to :ref:`transactions` for the details. The property is writable for sync connections, read-only for async ones: you can call `~AsyncConnection.set_client_encoding()` on those. + .. attribute:: info + + TODO + .. rubric:: Methods you will need if you do something cool .. automethod:: notifies @@ -68,7 +82,8 @@ Take a look to :ref:`transactions` for the details. See :ref:`async-notify` for details. -.. autoclass:: psycopg3.AsyncConnection + +.. autoclass:: AsyncConnection This class implements a DBAPI-inspired interface, with all the blocking methods implemented as coroutines. Unless specified otherwise, @@ -84,6 +99,7 @@ Take a look to :ref:`transactions` for the details. .. automethod:: rollback .. automethod:: notifies .. automethod:: set_client_encoding + .. automethod:: set_autocommit -.. autoclass:: psycopg3.Notify +.. autoclass:: Notify diff --git a/docs/usage.rst b/docs/usage.rst index efc0034fc..1ee333160 100644 --- a/docs/usage.rst +++ b/docs/usage.rst @@ -1,3 +1,6 @@ +.. currentmodule:: psycopg3 + + .. index:: pair: Example; Usage @@ -65,6 +68,36 @@ Note that the `cursor.execute()` method returns the cursor itself, so the print(record) +The main entry points of `!psycopg3` are: + +- The function `connect()` creates a new database session and + returns a new `connection` instance. `AsyncConnection.connect()` + creates an `asyncio` connection instead. + +- The `~Connection` class encapsulates a database session. It allows to: + + - create new `~Cursor` instances using the `~Connection.cursor()` method to + execute database commands and queries, + + - terminate transactions using the methods `~Connection.commit()` or + `~Connection.rollback()`. + +- The class `~Cursor` allows interaction with the database: + + - send commands to the database using methods such as `~Cursor.execute()` + and `~Cursor.executemany()`, + + - retrieve data from the database :ref:`by iteration ` or + using methods such as `~Cursor.fetchone()`, `~Cursor.fetchmany()`, + `~Cursor.fetchall()`. + + + +.. index:: with + +``with`` connections and cursors +-------------------------------- + The connections and cursors act as context managers, so you can run: .. code:: python @@ -83,62 +116,55 @@ The connections and cursors act as context managers, so you can run: # and the connection closed -If you are working in an `asyncio` project you can use a very similar pattern: - -.. code:: python - async with await psycopg3.AsyncConnection.connect( - "dbname=test user=postgres") as aconn: - async with await aconn.cursor() as acur: - await acur.execute( - "INSERT INTO test (num, data) VALUES (%s, %s)", - (100, "abc'def")) - await acur.execute("SELECT * FROM test") - await acur.fetchone() - # will return (1, 100, "abc'def") +.. index:: + pair: Query; Parameters +.. _query-parameters: -The main entry points of Psycopg are: +Passing parameters to SQL queries +--------------------------------- -- The function `~psycopg3.connect()` creates a new database session and - returns a new `connection` instance. `psycopg3.AsyncConnection.connect()` - creates an asyncio connection instead. +TODO: lift from psycopg2 docs -- The `connection` class encapsulates a database session. It allows to: - - create new `cursor` instances using the `~connection.cursor()` method to - execute database commands and queries, - - terminate transactions using the methods `~connection.commit()` or - `~connection.rollback()`. +.. _transactions: -- The class `cursor` allows interaction with the database: +Transaction management +---------------------- - - send commands to the database using methods such as `~cursor.execute()` - and `~cursor.executemany()`, +TODO: - - retrieve data from the database :ref:`by iteration ` or - using methods such as `~cursor.fetchone()`, `~cursor.fetchmany()`, - `~cursor.fetchall()`. -.. index:: - pair: Query; Parameters +.. index:: async -.. _query-parameters: +Async operations +================ -Passing parameters to SQL queries ---------------------------------- +psycopg3 `~Connection` and `~Cursor` have counterparts `~AsyncConnection` and +`~AsyncCursor` supporting an `asyncio` interface. -TODO: lift from psycopg2 docs +The design of the asynchronous objects is pretty much the same of the sync +ones: in order to use them you will only have to scatter the ``async`` keyword +here and there. -.. _transactions: +.. code:: python -Transaction management ----------------------- + async with await psycopg3.AsyncConnection.connect( + "dbname=test user=postgres") as aconn: + async with await aconn.cursor() as acur: + await acur.execute( + "INSERT INTO test (num, data) VALUES (%s, %s)", + (100, "abc'def")) + await acur.execute("SELECT * FROM test") + await acur.fetchone() + # will return (1, 100, "abc'def") + async for record in acur: + print(record) -TODO: .. index:: @@ -162,14 +188,14 @@ of communication. .. _NOTIFY: https://www.postgresql.org/docs/current/static/sql-notify.html Because of the way sessions interact with notifications (see |NOTIFY|_ -documentation), you should keep the connection in `~connection.autocommit` +documentation), you should keep the connection in `~Connection.autocommit` mode if you wish to receive or send notifications in a timely manner. -Notifications are received as instances of `~psycopg3.Notify`. If you are -reserving a connection only to receive notifications, the simplest way is to -consume the `~psycopg3.Connection.notifies` generator. The generator can be -stopped using ``close()``. The following example will print notifications and -stop when one containing the ``stop`` message is received. +Notifications are received as instances of `Notify`. If you are reserving a +connection only to receive notifications, the simplest way is to consume the +`Connection.notifies` generator. The generator can be stopped using +``close()``. The following example will print notifications and stop when one +containing the ``stop`` message is received. .. code:: python @@ -201,9 +227,9 @@ You may get output from the Python process such as:: Notify(channel='mychan', payload='stop', pid=961823) there, I stopped -Alternatively, you can use `~psycopg3.Connection.add_notify_handler()` to -register a callback function, which will be invoked whenever a notification is -received, during the normal query processing; you will be then able to use the +Alternatively, you can use `~Connection.add_notify_handler()` to register a +callback function, which will be invoked whenever a notification is received, +during the normal query processing; you will be then able to use the connection normally. Please note that in this case notifications will not be received immediately, but only during a connection operation, such as a query. diff --git a/psycopg3/psycopg3/connection.py b/psycopg3/psycopg3/connection.py index 4d34116b3..366198934 100644 --- a/psycopg3/psycopg3/connection.py +++ b/psycopg3/psycopg3/connection.py @@ -103,6 +103,7 @@ class BaseConnection: @property def autocommit(self) -> bool: + """The autocommit state of the connection.""" return self._autocommit @autocommit.setter @@ -309,7 +310,9 @@ class Connection(BaseConnection): ) def notifies(self) -> Iterator[Notify]: - """Generate a stream of `Notify`""" + """ + Yield `Notify` objects as soon as they are received from the database. + """ while 1: with self.lock: ns = self.wait(notifies(self.pgconn)) @@ -455,5 +458,6 @@ class AsyncConnection(BaseConnection): ) async def set_autocommit(self, value: bool) -> None: + """Async version of the `autocommit` setter.""" async with self.lock: super()._set_autocommit(value)