]> git.ipfire.org Git - thirdparty/psycopg.git/commitdiff
Start a 'psycopg3.rows' module with dict_row()
authorDenis Laxalde <denis.laxalde@dalibo.com>
Fri, 12 Feb 2021 16:03:47 +0000 (17:03 +0100)
committerDenis Laxalde <denis.laxalde@dalibo.com>
Fri, 12 Feb 2021 16:08:02 +0000 (17:08 +0100)
psycopg3/psycopg3/rows.py [new file with mode: 0644]
tests/test_rows.py [new file with mode: 0644]

diff --git a/psycopg3/psycopg3/rows.py b/psycopg3/psycopg3/rows.py
new file mode 100644 (file)
index 0000000..c330b26
--- /dev/null
@@ -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 (file)
index 0000000..d130965
--- /dev/null
@@ -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()