Skip to content

Commit 65934c3

Browse files
authored
Merge pull request #2300 from albertoadami/add-support-for-array-json
Add instancies for Array[Json] on Postgres
2 parents 10fcae9 + bf3e5da commit 65934c3

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

modules/postgres-circe/src/main/scala/doobie/postgres/circe/Instances.scala

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,17 @@ object Instances {
3434
).temap(a =>
3535
parse(a.getValue).leftMap(_.show))
3636

37+
private implicit val showString: Show[Array[String]] = Show.show(_.mkString("Array(", ", ", ")"))
38+
39+
implicit val arrayJsonGet: Get[Array[Json]] =
40+
Get.Advanced.array[String](NonEmptyList.of("jsonb[]", "_jsonb"))
41+
.temap(_.toList.traverse(jsonStr =>
42+
parse(jsonStr).leftMap(_.getMessage)).map(_.toArray))
43+
44+
implicit val arrayJsonPut: Put[Array[Json]] =
45+
Put.Advanced.array[String](NonEmptyList.of("_jsonb"), "jsonb")
46+
.tcontramap(_.map(_.noSpaces))
47+
3748
def pgEncoderPutT[A: Encoder]: Put[A] =
3849
Put[Json].tcontramap(_.asJson)
3950

modules/postgres-circe/src/test/scala/doobie/postgres/circe/PGJsonSuite.scala

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,11 @@ class PGJsonSuite extends munit.CatsEffectSuite {
4848
testInOut("jsonb", Json.obj("something" -> Json.fromString("Yellow")), xa)
4949
}
5050

51+
{
52+
import doobie.postgres.circe.jsonb.implicits.*
53+
testInOut("jsonb[]", List(Json.obj("a" -> Json.fromInt(1)), Json.obj("b" -> Json.fromInt(2))), xa)
54+
}
55+
5156
// Explicit Type Checks
5257

5358
test("json should check ok for read") {
@@ -75,6 +80,19 @@ class PGJsonSuite extends munit.CatsEffectSuite {
7580
a.map(_.parameterTypeErrors).assertEquals(Nil)
7681
}
7782

83+
test("array[jsonb] should check ok for read") {
84+
import doobie.postgres.circe.jsonb.implicits.*
85+
val a = sql"""select ARRAY['{"a":1}', '{"b":2}']::jsonb[]""".query[Array[Json]].analysis.transact(xa)
86+
a.map(_.columnTypeErrors).assertEquals(Nil)
87+
}
88+
89+
test("array[jsonb] should check ok for write") {
90+
import doobie.postgres.circe.jsonb.implicits.*
91+
val arr = Array(Json.obj("a" -> Json.fromInt(1)), Json.obj("b" -> Json.fromInt(2)))
92+
val a = sql"select ${arr} :: jsonb[]".query[Array[Json]].analysis.transact(xa)
93+
a.map(_.parameterTypeErrors).assertEquals(Nil)
94+
}
95+
7896
// Encoder / Decoders
7997
private case class Foo(x: Json)
8098
private object Foo {

0 commit comments

Comments
 (0)