3

I'm trying to create a generic counter update method for a particular table.

My table has many columns that are simply counters, and in my application I need to increment/decrement these counters.

I was trying to create a method like this:

private def updateCounter(column: String, id: Int, incr: Int)(implicit session: Session): Unit = {
  sqlu"update table1 set $column = $column + $incr where id=$id".first
}

I would then create a method that would call this (I don't want to expose this method outside of this Dao class).

I am getting this error:

[PSQLException: ERROR: syntax error at or near "$1" Position: 20]
Blankman
  • 259,732
  • 324
  • 769
  • 1,199

1 Answers1

12

Try replacing $column by #$column. $ is used for bind variables which is not suitable for identifiers like column or table names, whereas #$ is a mere string replacement like the s"" string interpolation.

Also make sure that your column variable is not vulnerable to SQL injections.

Jacek Laskowski
  • 72,696
  • 27
  • 242
  • 420
Dimitri
  • 1,786
  • 14
  • 22