Skip to content

Instantly share code, notes, and snippets.

@jonifreeman
Created July 1, 2012 15:45
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonifreeman/3028781 to your computer and use it in GitHub Desktop.
Save jonifreeman/3028781 to your computer and use it in GitHub Desktop.
SQL macro
object Sql {
import scala.reflect.makro._
import language.experimental.macros
case class Query[R](/*sql: String*/)
def execute[R](q: Query[R]): Seq[R] = sys.error("implement me")
def sqlImpl(c: Context)(s: c.Expr[String]): c.Expr[Any] = {
import c.universe._
val Literal(Constant(sql: String)) = s.tree
// Real impl would parse SQL and infer types from db schema
if (sql.contains("id,name")) c.reify(Query[(Long, String)]())
else c.reify(Query[Long]())
}
def sql(s: String) = macro sqlImpl
}
scala> import Sql._
import Sql._
scala> sql("select id,name from user")
res0: Sql.Query[(Long, String)] = Query()
scala> sql("select id from user")
res1: Sql.Query[Long] = Query()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment