From 797825966df13f96e85fe1381e805e193778f20f Mon Sep 17 00:00:00 2001 From: Fabrice Lecomte Date: Mon, 17 Jun 2019 14:44:30 +0200 Subject: [PATCH] feature: serialize entity arg before send the request --- .../kotlin/fr/postgresjson/connexion/Connection.kt | 14 ++++++++++++-- src/test/kotlin/fr/postgresjson/ConnectionTest.kt | 10 ++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/main/kotlin/fr/postgresjson/connexion/Connection.kt b/src/main/kotlin/fr/postgresjson/connexion/Connection.kt index 9108304..2ce3371 100644 --- a/src/main/kotlin/fr/postgresjson/connexion/Connection.kt +++ b/src/main/kotlin/fr/postgresjson/connexion/Connection.kt @@ -30,7 +30,7 @@ class Connection( } fun ?> selectOne(sql: String, typeReference: TypeReference, values: List = emptyList()): R? { - val future = connect().sendPreparedStatement(sql, values) + val future = connect().sendPreparedStatement(sql, compileArgs(values)) val json = future.get().rows[0].getString(0) return if (json === null) { null @@ -42,7 +42,7 @@ class Connection( inline fun ?> selectOne(sql: String, values: List = emptyList()): R? = selectOne(sql, object: TypeReference() {}, values) fun ?>> select(sql: String, typeReference: TypeReference, values: List = emptyList()): R { - val future = connect().sendPreparedStatement(sql, values) + val future = connect().sendPreparedStatement(sql, compileArgs(values)) val json = future.get().rows[0].getString(0) return if (json === null) { listOf?>() as R @@ -52,6 +52,16 @@ class Connection( } inline fun ?>> select(sql: String, values: List = emptyList()): R = select(sql, object : TypeReference() {}, values) + + private fun compileArgs(values: List): List { + return values.map { + if (it is EntityI<*>) { + serializer.serialize(it) + } else { + it + } + } + } } class Requester ( diff --git a/src/test/kotlin/fr/postgresjson/ConnectionTest.kt b/src/test/kotlin/fr/postgresjson/ConnectionTest.kt index be06db6..5a7c213 100644 --- a/src/test/kotlin/fr/postgresjson/ConnectionTest.kt +++ b/src/test/kotlin/fr/postgresjson/ConnectionTest.kt @@ -53,4 +53,14 @@ class ConnectionTest(): TestAbstract() { assertNotNull(result) assertEquals("myName", result!!.name) } + + @Test + fun callRequestWithArgsEntity() { + val o = ObjTest("myName") + val obj: ObjTest? = connection.selectOne("select json_build_object('id', 1, 'name', ?::json->>'name')", listOf(o)) + assertTrue(obj !== null) + assertTrue(obj is ObjTest) + assertTrue(obj!!.id == 1) + assertTrue(obj.name == "myName") + } } \ No newline at end of file