From bd88e7938da5d54da6fd0fd42fb8cce8bc60724b Mon Sep 17 00:00:00 2001 From: Fabrice Lecomte Date: Sun, 18 Jul 2021 03:59:47 +0200 Subject: [PATCH] apply "replaceNamedArgByQuestionMark" on exec() function --- .../fr/postgresjson/connexion/Connection.kt | 52 ++++++++++--------- .../kotlin/fr/postgresjson/RequesterTest.kt | 22 ++++++++ 2 files changed, 50 insertions(+), 24 deletions(-) diff --git a/src/main/kotlin/fr/postgresjson/connexion/Connection.kt b/src/main/kotlin/fr/postgresjson/connexion/Connection.kt index 2ea6760..023dabc 100644 --- a/src/main/kotlin/fr/postgresjson/connexion/Connection.kt +++ b/src/main/kotlin/fr/postgresjson/connexion/Connection.kt @@ -172,7 +172,7 @@ class Connection( override fun exec(sql: String, values: List): QueryResult { val compiledValues = compileArgs(values) return stopwatchQuery(sql, compiledValues) { - connect().sendPreparedStatement(sql, compiledValues).join() + connect().sendPreparedStatement(replaceNamedArgByQuestionMark(sql), compiledValues).join() } } @@ -215,37 +215,41 @@ class Connection( private fun replaceArgs(sql: String, values: Map, block: ParametersQuery.() -> T): T { val paramRegex = "(? + val orderedArgs = paramRegex.findAll(sql).map { match -> val name = match.groups[1]!!.value values[name] ?: values[name.trimStart('_')] ?: queryError("""Parameter "$name" missing""", sql, values) }.toList() - var newSql = sql - values.forEach { (key, _) -> - val regex = ":_?$key".toRegex() - newSql = newSql.replace(regex, "?") - } + return block(ParametersQuery(replaceNamedArgByQuestionMark(sql), orderedArgs)) + } - return block(ParametersQuery(newSql, newArgs)) + private fun replaceNamedArgByQuestionMark(sql: String): String = + "(?): String { + var i = 0 + + /* The regular expression matches a question mark "?" alone, not preceded or followed by another question mark */ + return """(? replaceArgsIntoSql(sql: String, values: List, block: (String) -> T): T { - /* The regular expression matches a question mark "?" alone, not preceded or followed by another question mark */ - val paramRegex = """(?()?.name) + } + @Test fun `call exec on function`() { val resources = this::class.java.getResource("/sql/function/Test")?.toURI() @@ -181,6 +192,17 @@ class RequesterTest : TestAbstract() { } } + @Test + fun `call sendQuery with same name of arguments as list`() { + val resources = this::class.java.getResource("/sql/query")?.toURI() + Requester(connection, queriesDirectory = resources) + .getQuery("selectMultipleWithSameArgs") + .sendQuery(listOf("myName", "myName2")).run { + assertEquals("myName", rows[0].getString("firstName")) + assertEquals("myName2", rows[0].getString("secondName")) + } + } + @Test fun `call sendQuery with arguments on not same orders`() { val resources = this::class.java.getResource("/sql/query")?.toURI()