]> git.ipfire.org Git - thirdparty/psycopg.git/commitdiff
docs: add documentation about none-returning dumpers 642/head
authorDaniele Varrazzo <daniele.varrazzo@gmail.com>
Sat, 1 Jun 2024 11:06:38 +0000 (13:06 +0200)
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>
Sun, 2 Jun 2024 12:30:08 +0000 (14:30 +0200)
docs/advanced/adapt.rst
docs/api/abc.rst
docs/api/adapt.rst

index 66a8edbcf49c4d6b8788a55cedd9fdb14fc7abb1..9880e4d2fcf44868532bb3cd8968dab6305398f2 100644 (file)
@@ -146,6 +146,34 @@ you only need to implement the `~psycopg.abc.Dumper.dump()` method::
         <TypeInfo: hstore (oid: 770082, array oid: 770087)>
 
 
+.. _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
index 9514e9b0608fbf63ad69c53b3d70241652f04895..27ff8baa1b786ace9d27b18243a87306a0dae647 100644 (file)
@@ -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::
index e47816ce03189770e48d3ad982e31d9a51cc4f12..db3b2b540d0dfef822a78bb031d8b75af0d1ecf1 100644 (file)
@@ -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