Search code examples
scalaplayframeworkplayframework-2.0anorm

create dynamic SQL with anorm


i do not want to delete and reinsert every row, so I have used the following to try to use multiple rows with anorm:

SQL("""
            delete from PERSON_ROLES 
            WHERE person_id = {userId}
            and role_id not in ({rolescommastring})
            )
            """).on('userId -> userId,
                    'rolescommastring -> rolescommastring).execute()

The above yields a string that it doesn't like and i get :

c.j.b.PreparedStatementHandle - delete from PERSON_ROLES WHERE person_id = 1460 and role_id not in ( '1, 3, 8, 9' )

can i create dynamic sql with anorm?


Solution

  • Anorm doesn't support 'IN' clauses. It is same for most of the ORMs (like scala- slick) as prepared statements do not support IN clauses

    The process that I use is from https://groups.google.com/forum/#!topic/play-framework/qls6dhhdayc/discussion

    Basically something like this should work

    val params = List(1, 3, 8, 9) 
    val paramsList = for ( i <- 0 until params.size ) yield ("role_id" + i)
    
    SQL("""
            delete from PERSON_ROLES 
            WHERE person_id = {userId}
            and   role_id not in ({%s})
            )
            """.format(paramsList.mkString("},{"))).on('userId -> userId ++ 
                    paramsList.zip(params)).execute()