From: Daniele Varrazzo Date: Sun, 23 Aug 2020 17:23:23 +0000 (+0100) Subject: Added date text dumper X-Git-Tag: 3.0.dev0~441 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=0f1adf57b568a6c7ff11e22d11839d5e1eb71145;p=thirdparty%2Fpsycopg.git Added date text dumper --- diff --git a/psycopg3/psycopg3/types/__init__.py b/psycopg3/psycopg3/types/__init__.py index e0ce65c36..bbdd8a8b7 100644 --- a/psycopg3/psycopg3/types/__init__.py +++ b/psycopg3/psycopg3/types/__init__.py @@ -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 index 000000000..1ce37f8d1 --- /dev/null +++ b/psycopg3/psycopg3/types/date.py @@ -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 index 000000000..112d5b3d5 --- /dev/null +++ b/tests/types/test_date.py @@ -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]