From 11b0a6858a8a84c5a4a4bbbe4bf401a32503b517 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vladim=C3=ADr=20Zahradn=C3=ADk?= Date: Sat, 4 Jun 2022 14:22:33 +0200 Subject: [PATCH] Better json func, and tests --- postgres/literal.go | 9 +++++++-- postgres/literal_test.go | 5 +++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/postgres/literal.go b/postgres/literal.go index 929e394..e3a95b3 100644 --- a/postgres/literal.go +++ b/postgres/literal.go @@ -66,8 +66,13 @@ func String(value string) StringExpression { } // Json creates new json literal expression -func Json(value string) StringExpression { - return StringExp(CAST(jet.String(value)).AS("json")) +func Json(value interface{}) StringExpression { + switch value.(type) { + case string, []byte: + default: + panic("Bytea parameter value has to be of the type string or []byte") + } + return StringExp(CAST(jet.Literal(value)).AS("json")) } // UUID is a helper function to create string literal expression from uuid object diff --git a/postgres/literal_test.go b/postgres/literal_test.go index 5c5160e..9fef055 100644 --- a/postgres/literal_test.go +++ b/postgres/literal_test.go @@ -67,6 +67,11 @@ func TestBytea(t *testing.T) { assertSerialize(t, Bytea([]byte("Some byte array")), `$1::bytea`, []byte("Some byte array")) } +func TestJson(t *testing.T) { + assertSerialize(t, Json("{\"key\": \"value\"}"), `$1::json`, "{\"key\": \"value\"}") + assertSerialize(t, Json([]byte("{\"key\": \"value\"}")), `$1::json`, []byte("{\"key\": \"value\"}")) +} + func TestDate(t *testing.T) { assertSerialize(t, Date(2014, time.January, 2), `$1::date`, "2014-01-02") assertSerialize(t, DateT(time.Now()), `$1::date`)