]> git.ipfire.org Git - thirdparty/psycopg.git/commitdiff
Added date text dumper
authorDaniele Varrazzo <daniele.varrazzo@gmail.com>
Sun, 23 Aug 2020 17:23:23 +0000 (18:23 +0100)
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>
Wed, 28 Oct 2020 03:19:24 +0000 (04:19 +0100)
psycopg3/psycopg3/types/__init__.py
psycopg3/psycopg3/types/date.py [new file with mode: 0644]
tests/types/test_date.py [new file with mode: 0644]

index e0ce65c36084a1ce6f306fe539cf0b526678e11a..bbdd8a8b7ed204440cca6803f4c43ecc121dfcdc 100644 (file)
@@ -8,7 +8,7 @@ psycopg3 types package
 from .oids import builtins
 
 # Register default adapters
-from . import array, json, composite, numeric, text  # noqa
+from . import array, composite, date, json, numeric, text  # noqa
 
 # Register associations with array oids
 array.register_all_arrays()
diff --git a/psycopg3/psycopg3/types/date.py b/psycopg3/psycopg3/types/date.py
new file mode 100644 (file)
index 0000000..1ce37f8
--- /dev/null
@@ -0,0 +1,27 @@
+"""
+Adapters for date/time types.
+"""
+
+# Copyright (C) 2020 The Psycopg Team
+
+import codecs
+from datetime import date
+
+from ..adapt import Dumper
+from .oids import builtins
+
+
+@Dumper.text(date)
+class DateDumper(Dumper):
+
+    _encode = codecs.lookup("ascii").encode
+    DATE_OID = builtins["date"].oid
+
+    def dump(self, obj: date) -> bytes:
+        # NOTE: whatever the PostgreSQL DateStyle input format (DMY, MDY, YMD)
+        # the YYYY-MM-DD is always understood correctly.
+        return self._encode(str(obj))[0]
+
+    @property
+    def oid(self) -> int:
+        return self.DATE_OID
diff --git a/tests/types/test_date.py b/tests/types/test_date.py
new file mode 100644 (file)
index 0000000..112d5b3
--- /dev/null
@@ -0,0 +1,36 @@
+import datetime as dt
+import pytest
+
+
+@pytest.mark.parametrize(
+    "val, expr",
+    [
+        (dt.date(1, 1, 1), "'0001-01-01'::date"),
+        (dt.date(1000, 1, 1), "'1000-01-01'::date"),
+        (dt.date(2000, 1, 1), "'2000-01-01'::date"),
+        (dt.date(2000, 12, 31), "'2000-12-31'::date"),
+        (dt.date(3000, 1, 1), "'3000-01-01'::date"),
+    ],
+)
+def test_dump_date(conn, val, expr):
+    cur = conn.cursor()
+    cur.execute("select %s = %%s" % expr, (val,))
+    assert cur.fetchone()[0] is True
+
+
+@pytest.mark.xfail  # TODO: binary dump
+@pytest.mark.parametrize(
+    "val, expr", [(dt.date(2000, 1, 1), "'2000-01-01'::date")]
+)
+def test_dump_date_binary(conn, val, expr):
+    cur = conn.cursor()
+    cur.execute("select %s = %%b" % expr, (val,))
+    assert cur.fetchone()[0] is True
+
+
+@pytest.mark.parametrize("datestyle_in", ["DMY", "MDY", "YMD"])
+def test_dump_date_datestyle(conn, datestyle_in):
+    cur = conn.cursor()
+    cur.execute(f"set datestyle = ISO, {datestyle_in}")
+    cur.execute("select '2000-01-02'::date = %s", (dt.date(2000, 1, 2),))
+    assert cur.fetchone()[0]