rows – row factory implementations¶
The module exposes a few generic
RowFactory implementation, which
can be used to retrieve data from the database in more complex structures than
the basic tuples.
Check out Row factories for information about how to use these objects.
Row factory to represent rows as simple tuples.
Row factory to represent rows as dictionaries.
The dictionary keys are taken from the column names of the returned columns.
Row factory to represent rows as
The field names are taken from the column names of the returned columns, with some mangling to deal with invalid names.
Generate a row factory to represent rows as instances of the class cls.
The class must support every output column name as a keyword parameter.
Type[~T]) – The class to return for each row. It must support the fields returned by the query as keyword arguments.
- Return type
This is not a row factory, but rather a factory of row factories. Specifying
row_factory=class_row(MyClass)will create connections and cursors returning
MyClassobjects on fetch.
from dataclasses import dataclass import psycopg from psycopg.rows import class_row @dataclass class Person: first_name: str last_name: str age: int = None conn = psycopg.connect() cur = conn.cursor(row_factory=class_row(Person)) cur.execute("select 'John' as first_name, 'Smith' as last_name").fetchone() # Person(first_name='John', last_name='Smith', age=None)
Generate a row factory calling func with positional parameters for every row.
Generate a row factory calling func with keyword parameters for every row.
Formal rows protocols¶
These objects can be used to describe your own rows adapter for static typing checks, such as mypy.
- class psycopg.rows.RowMaker¶
Callable protocol taking a sequence of value and returning an object.
The sequence of value is what is returned from a database query, already adapted to the right Python types. The return value is the object that your program would like to receive: by default (
tuple_row()) it is a simple tuple, but it may be any type of object.
RowMakerfunctions are returned by
- __call__(values: Sequence[Any]) Row ¶
Convert a sequence of values from the database to a finished object.
- class psycopg.rows.RowFactory¶
RowFactoryis typically called when a
Cursorreceives a result. This way it can inspect the cursor state (for instance the
descriptionattribute) and help a
RowMakerto create a complete object.
For instance the
RowFactoryuses the names of the column to define the dictionary key and returns a
RowMakerfunction which would use the values to create a dictionary for each record.
Note that it’s easy to implement an object implementing both
AsyncRowFactory: usually, everything you need to implement a row factory is
to access the cursor’s
description, which is provided by
both the cursor flavours.