From: Daniele Varrazzo Date: Sat, 1 Jun 2024 11:06:38 +0000 (+0200) Subject: docs: add documentation about none-returning dumpers X-Git-Tag: 3.2.0~20^2 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=refs%2Fpull%2F642%2Fhead;p=thirdparty%2Fpsycopg.git docs: add documentation about none-returning dumpers --- diff --git a/docs/advanced/adapt.rst b/docs/advanced/adapt.rst index 66a8edbcf..9880e4d2f 100644 --- a/docs/advanced/adapt.rst +++ b/docs/advanced/adapt.rst @@ -146,6 +146,34 @@ you only need to implement the `~psycopg.abc.Dumper.dump()` method:: +.. _adapt-example-null-str: + +Example: converting empty strings to NULL +----------------------------------------- + +.. versionchanged:: 3.2 + + The `dump()` method can also return `!None`, which will be stored as + :sql:`NULL` in the database. + +If you prefer to store missing values as :sql:`NULL`, in the database, but +your input may contain empty strings, you can subclass the stock string dumper +to return `!None` upon empty or whitespace-only strings:: + + >>> from psycopg.types.string import StrDumper + + >>> class NullStrDumper(StrDumper): + ... def dump(self, obj): + ... if not obj or obj.isspace(): + ... return None + ... return super().dump(obj) + + >>> conn.adapters.register_dumper(str, NullStrDumper) + + >>> conn.execute("select %s, %s, %s, %s", ("foo", "", "bar", " ")).fetchone() + ('foo', None, 'bar', None) + + .. _adapt-example-float: Example: PostgreSQL numeric to Python float diff --git a/docs/api/abc.rst b/docs/api/abc.rst index 9514e9b06..27ff8baa1 100644 --- a/docs/api/abc.rst +++ b/docs/api/abc.rst @@ -25,6 +25,11 @@ checking. The format returned by dump shouldn't contain quotes or escaped values. + .. versionchanged:: 3.2 + + `!dump()` can also return `!None`, to represent a :sql:`NULL` in + the database. + .. automethod:: quote .. tip:: diff --git a/docs/api/adapt.rst b/docs/api/adapt.rst index e47816ce0..db3b2b540 100644 --- a/docs/api/adapt.rst +++ b/docs/api/adapt.rst @@ -28,6 +28,11 @@ Dumpers and loaders .. automethod:: dump + .. versionchanged:: 3.2 + + `!dump()` can also return `!None`, to represent a :sql:`NULL` in + the database. + .. attribute:: format :type: psycopg.pq.Format :value: TEXT