0
votes

I want to insert the literal '${a}' into a table using anorm 2.5.2, which means I want to execute the bare SQL query

INSERT INTO `db`.`table` (`a`) VALUES ('${a}');

without using any anorm / string interpolation. When I try to do the following

SQL("INSERT INTO `db`.`table` (`a`) VALUES ('${a}');").execute()

I get an anorm.Sql$MissingParameter: Missing parameter value exception because it tries to use anorm interpolation on ${a} but no value a is available in the scope.

How to escape the anorm / string interpolations $... and ${...}?

Escape a dollar sign in string interpolation doesn't seem to work here.

1
The string is not a String Interpolation, so you don't need to escape the $ in the first place. The problem is not caused by String Interpolation. - Clashsoft
I should have said anorm interpolation, or whatever you want to call it, to make it more obvious what I mean. Yes, I know it does not use Scala's string interpolation internally, since then the $$ escape should work, which it doesn't. I'll change the question to reflect that. - user2860570

1 Answers

0
votes

You can make ${a} the value of a parameter, i.e.

SQL("""INSERT INTO db.table (a) VALUES ({x})""").on("x" -> s"$${a}")

(s"$${a}" is the way to write "${a}" without getting a warning about possible missing interpolators).

The same can be written equivalently as

val lit = s"$${a}"
SQL"""INSERT INTO db.table (a) VALUES ($lit)"""

The below will probably work, but I am not sure:

SQL"INSERT INTO db.table (a) VALUES ('$${a}')"

It may also be worth asking if it's intentional behavior or a bug: when talking about parametrized SQL queries, it doesn't make sense to have a parameter inside '.