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.
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
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
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
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,
.. automethod:: rollback
.. automethod:: notifies
.. automethod:: set_client_encoding
+ .. automethod:: set_autocommit
-.. autoclass:: psycopg3.Notify
+.. autoclass:: Notify
+.. currentmodule:: psycopg3
+
+
.. index::
pair: Example; Usage
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 <cursor-iterable>` 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
# 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 <cursor-iterable>` 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::
.. _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
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.