Created
June 26, 2011 15:05
-
-
Save szeiger/1047681 to your computer and use it in GitHub Desktop.
Lift a Scala function to a database function for H2, using Code.lift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.scalaquery.demo | |
import scala.reflect._ | |
import org.scalaquery.ql._ | |
import org.scalaquery.ql.extended.{ExtendedTable => Table} | |
import org.scalaquery.ql.extended.H2Driver.Implicit._ | |
import org.scalaquery.simple.StaticQuery.updateNA | |
import org.scalaquery.session.Database | |
import org.scalaquery.session.Database.threadLocalSession | |
object LiftFunction extends App { | |
// H2 expects user-defined functions as public static methods | |
def mixedCase(s: String): String = s grouped 2 map { g => | |
g(0).toUpper + (if(g.length == 1) "" else g(1).toLower.toString) | |
} mkString | |
// We use an embedded DB, so the function above is automatically on the class-path | |
Database.forURL("jdbc:h2:mem:test1", driver = "org.h2.Driver") withSession { | |
// Define a table and populate it with some values | |
object Users extends Table[String]("USERS") { | |
def name = column[String]("NAME") | |
def * = name | |
} | |
Users.ddl.create | |
Users.insert("szeiger") | |
Users.insert("guest") | |
// Lift a public static method to a DB function | |
def createAlias[T1, R: TypeMapper](code: Code[T1 => R]) = { | |
// Get the FQN of the method from the AST | |
val Block(_, Function(_, Apply(Select(_, Method(n, _)), _))) = code.tree | |
// Define the function in the DB | |
updateNA("create alias if not exists \""+n+"\" for \""+n+"\"").execute | |
// Return a ScalaQuery function for it | |
SimpleFunction.unary[T1, R]("\""+n+"\"") | |
} | |
// Lift the mixedCase Scala function to a DB function | |
val mixedCaseDB = createAlias(Code.lift(mixedCase _)) | |
// Use it in a query and print the statement + results | |
val q = for { | |
u <- Users | |
} yield mixedCaseDB(u.name) | |
println("q: " + q.selectStatement) | |
q.foreach(println) | |
} | |
} | |
/* | |
[info] Running org.scalaquery.demo.LiftFunction | |
q: SELECT "org.scalaquery.demo.LiftFunction.mixedCase"("t1"."NAME") FROM "USERS" "t1" | |
SzEiGeR | |
GuEsT | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment