Skip to content

Instantly share code, notes, and snippets.

@cvogt
Created December 20, 2013 12:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cvogt/8054159 to your computer and use it in GitHub Desktop.
Save cvogt/8054159 to your computer and use it in GitHub Desktop.
This code implements a facility for Slick 1.0.1 to inject custom SQL instead of the Slick produced SQL to be used when running a query
import scala.slick.lifted._
import scala.slick.ast._
import scala.slick.driver._
/** Extends QueryInvoker to allow overriding used SQL statement when executing a query */
trait OverridingInvoker extends BasicDriver{
// get the extended QueryInvoker into the .simple._ implicits
override val Implicit: Implicits = new Implicits
override val simple: Implicits with SimpleQL = new Implicits with SimpleQL
class Implicits extends super.Implicits {
override implicit def queryToQueryInvoker[T, U](q: Query[T, _ <: U]): QueryInvoker[T, U] = new QueryInvoker(q)
}
// extended QueryInvoker
class QueryInvoker[Q, R](q: Query[Q, _ <: R]) extends super.QueryInvoker[Q, R](q) {
def overrideSql(sql: String) = new PatchedQueryInvoker(sql,q)
}
// QueryInvoker that patches the used SQL
class PatchedQueryInvoker[P,U](sql:String, q: Query[P,U]) extends QueryInvoker(q){
override def getStatement = sql
}
}
// Create a custom MySQL driver patching in the Overriding invoker
object CustomMySQLDriver extends MySQLDriver with OverridingInvoker
object Main extends App{
// Import stuff from the patched driver instead of the default
import CustomMySQLDriver.simple._
// please fill in jdbc connection url and driver
Database.forURL("...", driver = "...") withSession {
// tamper with SQL statement
val munged = Query(Suppliers).selectStatement + " where SUP_ID = 49"
// inject munged version
println(Query(Suppliers).overrideSql(munged).list)
}
}
@cvogt
Copy link
Author

cvogt commented May 14, 2014

Updated code for Slick 2.0 can be found in here: https://gist.github.com/cvogt/d9049c63fc395654c4b4

@cvogt
Copy link
Author

cvogt commented May 17, 2014

There is a PR to add this feature natively to Slick 2.1 slick/slick#810

@RSchulz
Copy link

RSchulz commented Jun 4, 2014

Hi, Chris,

Thanks a million for doing the 2.0 port. We were just starting a new project using 2.0 and I'd instructed my colleague to work on porting the 1.0 code you supplied. Fortunately, he found this.

I hear through the grapevine you've got a new gig. Good luck!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment