From 55193d6d80f26ecf8246686301bcb884d7fcd566 Mon Sep 17 00:00:00 2001 From: Jakub Strojewski Date: Tue, 19 Nov 2024 14:50:33 +0000 Subject: [PATCH] Make null param error more informative (#809) --- .../core/src/main/scala/doobie/util/put.scala | 4 ++-- .../test/scala/doobie/util/WriteSuite.scala | 23 +++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/modules/core/src/main/scala/doobie/util/put.scala b/modules/core/src/main/scala/doobie/util/put.scala index 2588c8ce9..2d4f8d3dd 100644 --- a/modules/core/src/main/scala/doobie/util/put.scala +++ b/modules/core/src/main/scala/doobie/util/put.scala @@ -56,7 +56,7 @@ sealed abstract class Put[A]( ) {} def unsafeSetNonNullable(ps: PreparedStatement, n: Int, a: A): Unit = - if (a == null) sys.error("oops, null") + if (a == null) sys.error("Expected non-nullable param. Use Option to describe nullable values.") else put.fi.apply(ps, n, (put.k(a))) def unsafeSetNullable(ps: PreparedStatement, n: Int, oa: Option[A]): Unit = @@ -66,7 +66,7 @@ sealed abstract class Put[A]( } def unsafeUpdateNonNullable(rs: ResultSet, n: Int, a: A): Unit = - if (a == null) sys.error("oops, null") + if (a == null) sys.error("Expected non-nullable param. Use Option to describe nullable values.") else update.fi.apply(rs, n, (update.k(a))) def unsafeUpdateNullable(rs: ResultSet, n: Int, oa: Option[A]): Unit = diff --git a/modules/core/src/test/scala/doobie/util/WriteSuite.scala b/modules/core/src/test/scala/doobie/util/WriteSuite.scala index f90cdf885..6e75b6f59 100644 --- a/modules/core/src/test/scala/doobie/util/WriteSuite.scala +++ b/modules/core/src/test/scala/doobie/util/WriteSuite.scala @@ -122,4 +122,27 @@ class WriteSuite extends munit.FunSuite with WriteSuitePlatform { .unsafeRunSync() } + test("Write should yield correct error when Some(null) inserted") { + interceptMessage[RuntimeException]("Expected non-nullable param. Use Option to describe nullable values.") { + testNullPut(("a", Some(null))) + } + } + + test("Write should yield correct error when null inserted into non-nullable field") { + interceptMessage[RuntimeException]("Expected non-nullable param. Use Option to describe nullable values.") { + testNullPut((null, Some("b"))) + } + } + + private def testNullPut(input: (String, Option[String])): Int = { + import doobie.implicits.* + + (for { + _ <- sql"create temp table t0 (a text, b text null)".update.run + n <- Update[(String, Option[String])]("insert into t0 (a, b) values (?, ?)").run(input) + } yield n) + .transact(xa) + .unsafeRunSync() + } + }