From: Daniele Varrazzo Date: Mon, 4 Sep 2023 00:09:18 +0000 (+0100) Subject: docs: add porting tips for cursor subclasses X-Git-Tag: pool-3.2.0~57 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=1aac5322696480766b3c05421de0435da211e2bc;p=thirdparty%2Fpsycopg.git docs: add porting tips for cursor subclasses --- diff --git a/docs/advanced/rows.rst b/docs/advanced/rows.rst index c23efe5c5..fcb89ce9a 100644 --- a/docs/advanced/rows.rst +++ b/docs/advanced/rows.rst @@ -92,7 +92,7 @@ Formally, these objects are represented by the `~psycopg.rows.RowFactory` and def __call__(self, values: Sequence[Any]) -> dict[str, Any]: return dict(zip(self.fields, values)) -or as a plain function: +or as nested functions: .. code:: python diff --git a/docs/api/rows.rst b/docs/api/rows.rst index 204f1eacb..d4c438242 100644 --- a/docs/api/rows.rst +++ b/docs/api/rows.rst @@ -9,7 +9,7 @@ The module exposes a few generic `~psycopg.RowFactory` implementation, which can be used to retrieve data from the database in more complex structures than the basic tuples. -Check out :ref:`row-factories` for information about how to use these objects. +Check out :ref:`row-factory-create` for information about how to use these objects. .. autofunction:: tuple_row .. autofunction:: dict_row diff --git a/docs/basic/from_pg2.rst b/docs/basic/from_pg2.rst index 79e07034a..c449c1031 100644 --- a/docs/basic/from_pg2.rst +++ b/docs/basic/from_pg2.rst @@ -272,6 +272,36 @@ Analogously you can use :sql:`IS DISTINCT FROM %s` as a parametric version of :sql:`IS NOT %s`. +.. _diff-cursors: + +Cursors subclasses +------------------ + +In `!psycopg2`, a few cursor subclasses allowed to return data in different +form than tuples. In Psycopg 3 the same can be achieved by setting a :ref:`row +factory `: + +- instead of `~psycopg2.extras.RealDictCursor` you can use + `~psycopg.rows.dict_row`; + +- instead of `~psycopg2.extras.NamedTupleCursor` you can use + `~psycopg.rows.namedtuple_row`. + +Other row factories are available in the `psycopg.rows` module. There isn't an +object behaving like `~psycopg2.extras.DictCursor` (whose results are +indexable both by column position and by column name). + +.. code:: + + from psycopg.rows import dict_row, namedtuple_row + + # By default, every cursor will return dicts. + conn = psycopg.connect(DSN, row_factory=dict_row) + + # You can set a row factory on a single cursor too. + cur = conn.cursor(row_factory=namedtuple_row) + + .. _diff-adapt: Different adaptation system