Using DB Function (TRIM(LEADING '0' from column)) in Slick

霸气de小男生 提交于 2019-12-06 09:37:59

The slightly odd syntax of TRIM(LEADING means you have to drop to using a SimpleExpression and use the QueryBuilder that gives you access to.

val trimLeading = SimpleExpression.binary[String, String, String] {
  (trimChar, str, queryBuilder) =>
    import slick.util.MacroSupport._
    import queryBuilder._
    b"TRIM(LEADING $trimChar FROM $str)"
}

and here is an example that exercises it

import com.typesafe.config.ConfigFactory
import slick.backend.DatabaseConfig
import slick.driver.JdbcProfile
import scala.concurrent.duration.Duration
import scala.concurrent.Await

object TrimLeading extends App {
  def trimLeadingExample(dbConfig: DatabaseConfig[JdbcProfile]): Unit = {
    import dbConfig.driver.api._
    val trimLeading = SimpleExpression.binary[String, String, String] {
      (trimChar, str, queryBuilder) =>
        import slick.util.MacroSupport._
        import queryBuilder._
        b"TRIM(LEADING $trimChar FROM $str)"
    }

    class ZeroTable(tag: Tag) extends Table[String](tag, "ZeroTable") {
      def zeros = column[String]("zeros")
      def * = zeros
    }
    val zeroTable = TableQuery[ZeroTable]
    exec(zeroTable.schema.create)
    exec(zeroTable ++= Seq("000000x", "00x", "000000000x", "00000x", "00xx"))

    exec(zeroTable.
          filter(s => trimLeading("0", s.zeros) === "x").
          map(s => trimLeading("0", s.zeros)).result).foreach(println)
    exec(zeroTable.schema.drop)
    def exec[T](action: DBIO[T]): T = Await.result(dbConfig.db.run(action), Duration.Inf)
  }
  val configStr =
    """
      |  driver = "freeslick.OracleProfile$"
      |  db {
      |    driver = oracle.jdbc.OracleDriver
      |    url="jdbc:oracle:thin:@//localhost:49161/xe"
      |    properties = {
      |      databaseName = "freeslicktest"
      |      user = "system"
      |      password = "oracle"
      |    }
      |  }
    """.stripMargin
  trimLeadingExample(DatabaseConfig.forConfig[JdbcProfile]("", ConfigFactory.parseString(configStr)))
}

and from the logs, the statement is

*** (s.jdbc.JdbcBackend.statement) Preparing statement: select TRIM(LEADING '0' FROM "zeros") from "ZeroTable" where TRIM(LEADING '0' FROM "zeros") = 'x'

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