Trouble with Anorm: dynamic SQL composition

129 views
Skip to first unread message

Wesley Bitomski

unread,
Feb 8, 2013, 5:16:43 PM2/8/13
to play-fr...@googlegroups.com
Hey all, I've got an interesting problem regarding using Anorm safely for query composition.

I've got a strange situation.  In Play 2.1 RC2, I've got a model method that needs to handle up to 10 different search parameters whose cardinality/combination I have no control over.  I solved this with some complex list manipulations in a monad that output both a composed query tupled with a map of parameter -> value pairs.  This works great.  The query comes out perfectly, with potentially procedurally generated params, and a Map that pairs all those params with the appropriate values.  Basically I'm trying to escape writing 1024 different methods to handle every potential combination of those 10 possible parameters.  Using parameterized SQL is non-negotiable, I have to use it for security reasons.

Now I've got to bind params to values.  Experimenting with Anorm, I find that I can get away with this:

SQL("select id, some_field from my_table where id = {id} and some_field = {some_field}")
  .on('id -> id)
  .on('some_field -> some_field)
  ...

So I try this:
(SQL(generatedQuery) /: keyValueMap.toList)((q, kv) => q.on(kv._1 -> kv._2)) ...

which causes a type error fixed with:
(SQL(generatedQuery) /: keyValueMap.toList)((q, kv) => q.on(kv._1 -> kv._2).sql) ...

which assures that NONE of my params are bound, aside from the last on in the Map.  I figured that left-folding would work, since it's ideally the same as chain-calling the same method on an object with slightly different arguments, but it doesn't for the SimpleSql/SqlQuery objects, and a work-around escapes me.  Is this expected behavior?  If so, how am I supposed to do this?
Reply all
Reply to author
Forward
0 new messages