From fb281b20a9ffdfa2e650de0210ed192314454d39 Mon Sep 17 00:00:00 2001 From: Daniele Varrazzo Date: Tue, 27 Oct 2020 17:17:21 +0100 Subject: [PATCH] Added json binary dumpers --- psycopg3/psycopg3/types/json.py | 9 +++++++++ tests/types/test_json.py | 15 ++++++++++----- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/psycopg3/psycopg3/types/json.py b/psycopg3/psycopg3/types/json.py index 0460aca9e..eb81ef2bb 100644 --- a/psycopg3/psycopg3/types/json.py +++ b/psycopg3/psycopg3/types/json.py @@ -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] diff --git a/tests/types/test_json.py b/tests/types/test_json.py index 9fca64c34..8cb401fc3 100644 --- a/tests/types/test_json.py +++ b/tests/types/test_json.py @@ -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 -- 2.47.3