From: Denis Laxalde Date: Fri, 12 Feb 2021 16:03:47 +0000 (+0100) Subject: Start a 'psycopg3.rows' module with dict_row() X-Git-Tag: 3.0.dev0~106^2~13 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=1f214215092d700d14c90ecbd0a90688348e0ce6;p=thirdparty%2Fpsycopg.git Start a 'psycopg3.rows' module with dict_row() --- diff --git a/psycopg3/psycopg3/rows.py b/psycopg3/psycopg3/rows.py new file mode 100644 index 000000000..c330b2673 --- /dev/null +++ b/psycopg3/psycopg3/rows.py @@ -0,0 +1,23 @@ +""" +psycopg3 row factories +""" + +# Copyright (C) 2021 The Psycopg Team + +from typing import Any, Callable, Dict, Sequence + +from .cursor import BaseCursor +from .proto import ConnectionType + + +def dict_row( + cursor: BaseCursor[ConnectionType], +) -> Callable[[Sequence[Any]], Dict[str, Any]]: + """Row factory to represent rows as dicts.""" + + def make_row(values: Sequence[Any]) -> Dict[str, Any]: + assert cursor.description + titles = (c.name for c in cursor.description) + return dict(zip(titles, values)) + + return make_row diff --git a/tests/test_rows.py b/tests/test_rows.py new file mode 100644 index 000000000..d130965be --- /dev/null +++ b/tests/test_rows.py @@ -0,0 +1,13 @@ +from psycopg3 import rows + + +def test_dict_row(conn): + cur = conn.cursor(row_factory=rows.dict_row) + cur.execute("select 'bob' as name, 3 as id") + assert cur.fetchall() == [{"name": "bob", "id": 3}] + + cur.execute("select 'a' as letter; select 1 as number") + assert cur.fetchall() == [{"letter": "a"}] + assert cur.nextset() + assert cur.fetchall() == [{"number": 1}] + assert not cur.nextset()