norm
norm copied to clipboard
Code generation fails for query with a conditional parameter
Consider the query
SELECT
COUNT(*)
FROM some_table
WHERE
CASE
WHEN :username IS NULL THEN 1 = 1 ELSE username = :username
END
The following exception is thrown during code generation:
org.postgresql.util.PSQLException: ERROR: could not determine data type of parameter $1
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2532)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2267)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:312)
at org.postgresql.jdbc.PgPreparedStatement.getParameterMetaData(PgPreparedStatement.java:1585)
at norm.analyzer.SqlAnalyzer.sqlModel(SqlAnalyzer.kt:23)
at norm.api.NormApi.generate(NormApi.kt:22)
at norm.cli.NormCli$run$1$2$1.invoke(NormCli.kt:80)
at norm.cli.NormCli$run$1$2$1.invoke(NormCli.kt:28)
at norm.fs.IO.process(IO.kt:22)
at norm.cli.NormCli$run$1.invoke(NormCli.kt:80)
at norm.cli.NormCli$run$1.invoke(NormCli.kt:28)
at norm.util.PGKt.withPGConnection(PG.kt:14)
at norm.cli.NormCli.run(NormCli.kt:68)
at com.github.ajalt.clikt.parsers.Parser.parse(Parser.kt:168)
at com.github.ajalt.clikt.parsers.Parser.parse(Parser.kt:16)
at com.github.ajalt.clikt.core.CliktCommand.parse(CliktCommand.kt:258)
at com.github.ajalt.clikt.core.CliktCommand.parse$default(CliktCommand.kt:255)
at com.github.ajalt.clikt.core.CliktCommand.main(CliktCommand.kt:273)
at com.github.ajalt.clikt.core.CliktCommand.main(CliktCommand.kt:298)
at norm.cli.NormCliKt.main(NormCli.kt:20)
Possible workaround (for postgres) - cast the parameter in the query
SELECT
COUNT(*)
FROM some_table
WHERE
CASE
WHEN CAST(:username AS VARCHAR) IS NULL THEN 1 = 1 ELSE username = CAST(:username AS VARCHAR)
END