]> git.ipfire.org Git - thirdparty/psycopg.git/commitdiff
Added json binary dumpers
authorDaniele Varrazzo <daniele.varrazzo@gmail.com>
Tue, 27 Oct 2020 16:17:21 +0000 (17:17 +0100)
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>
Wed, 28 Oct 2020 03:17:28 +0000 (04:17 +0100)
psycopg3/psycopg3/types/json.py
tests/types/test_json.py

index 0460aca9edc3447d1111101a3e93d34883f2a52e..eb81ef2bb41ce296ac75b04907668e54170ee762 100644 (file)
@@ -51,6 +51,7 @@ class _JsonDumper(Dumper):
 
 
 @Dumper.text(Json)
+@Dumper.binary(Json)
 class JsonDumper(_JsonDumper):
     _oid = JSON_OID
 
@@ -58,3 +59,11 @@ class JsonDumper(_JsonDumper):
 @Dumper.text(JsonB)
 class JsonBDumper(_JsonDumper):
     _oid = JSONB_OID
+
+
+@Dumper.binary(JsonB)
+class BinaryJsonBDumper(JsonBDumper):
+    def dump(
+        self, obj: _JsonWrapper, __encode: EncodeFunc = _encode_utf8
+    ) -> bytes:
+        return b"\x01" + __encode(obj.dumps())[0]
index 9fca64c34d976f15e5dfbf6adcb194ce4b549ead..8cb401fc3db13aec66f31ff028d9dc2682c699ae 100644 (file)
@@ -3,6 +3,7 @@ import json
 import pytest
 
 from psycopg3.types.json import Json, JsonB
+from psycopg3.adapt import Format
 
 samples = [
     "null",
@@ -17,18 +18,22 @@ samples = [
 
 
 @pytest.mark.parametrize("val", samples)
-def test_json_dump(conn, val):
+@pytest.mark.parametrize("fmt_in", [Format.TEXT, Format.BINARY])
+def test_json_dump(conn, val, fmt_in):
+    ph = "%s" if fmt_in == Format.TEXT else "%b"
     obj = json.loads(val)
     cur = conn.cursor()
-    cur.execute("select pg_typeof(%s) = 'json'::regtype", (Json(obj),))
+    cur.execute(f"select pg_typeof({ph}) = 'json'::regtype", (Json(obj),))
     assert cur.fetchone()[0] is True
-    cur.execute("select %s::text = %s::json::text", (Json(obj), val))
+    cur.execute(f"select {ph}::text = %s::json::text", (Json(obj), val))
     assert cur.fetchone()[0] is True
 
 
+@pytest.mark.parametrize("fmt_in", [Format.TEXT, Format.BINARY])
 @pytest.mark.parametrize("val", samples)
-def test_jsonb_dump(conn, val):
+def test_jsonb_dump(conn, val, fmt_in):
+    ph = "%s" if fmt_in == Format.TEXT else "%b"
     obj = json.loads(val)
     cur = conn.cursor()
-    cur.execute("select %s = %s::jsonb", (JsonB(obj), val))
+    cur.execute(f"select {ph} = %s::jsonb", (JsonB(obj), val))
     assert cur.fetchone()[0] is True