Created
July 1, 2012 15:45
-
-
Save jonifreeman/3028781 to your computer and use it in GitHub Desktop.
SQL macro
This file contains 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
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