Using `Option[BigDecimal]` with Anorm?

亡梦爱人 提交于 2019-12-24 05:51:36

问题


Given:

build.sbt

$cat build.sbt
scalaVersion := "2.11.8"

libraryDependencies += "com.typesafe.play" % "anorm_2.11" % "2.5.1"

REPL

import anorm._

val x: Option[BigDecimal] = Some(42)
val none: Option[BigDecimal] = None

// invoke Oracle function `f`
scala> SQL""" select f(#$x) from dual """.sql.statement
res0: String = " select f(Some(42)) from dual "

scala> SQL""" select f(#$none) from dual """.sql.statement
res1: String = " select f(None) from dual "

I'd like for res0 to equal: select f(42) from dual, and for res1 to equal select f(NULL) from dual.

How can I modify my SQL code to fit my desired results?

I imported anorm._, per https://stackoverflow.com/a/22531320/409976, however, it did not give my desired result.


回答1:


Using $ interpolation, just use SQL""" select f($x) from dual """.

You can do it with #$, but you certainly shouldn't (#$ should only be used when you can't do what you want with $: e.g. for interpolating table or column names):

def invokeF(x: Option[BigDecimal]) = {
  val xInSql = x.fold("NULL")(_.toString) // can be inlined to get even less readable
  SQL""" select f(#$xInSql) from dual """
}


来源:https://stackoverflow.com/questions/40489039/using-optionbigdecimal-with-anorm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!