Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define table name at runtime using quill

Tags:

scala

quill.io

Im new at quill and im trying to define a table at runtime, but im getting a compilation error. Is there any workaround for this ? or its just impossible using quill ? The code example is :

case class ExampleCaseClass(id : String, version : String)
class Example (db: CassandraAsyncContext[SnakeCase] , table : String ) {
    import db._

    def selectByVarId = quote {
        (id: String, version: String) =>
            querySchema[ExampleCaseClass](table).filter(example => (example.id == id) && (example.version == version))
    }
}

and the error :

Error:(114, 36) Tree Error:(124, 25) Tree 'Example.this.db.querySchema[***.ExampleCaseClass](Example.this.table)' can't be parsed to 'Ast'
    def selectById = quote {
like image 882
oron Avatar asked Jun 04 '17 11:06

oron


1 Answers

From quill 3.+ use dynamicQuerySchema[Person]("Person") dynamic-query-api

    import io.getquill.{Literal, MirrorSqlDialect, SqlMirrorContext}
    import java.time.LocalDate

    final case class PersonId(value: Int) extends AnyVal

    final case class Person(
      id: PersonId,
      firstName: String,
      lastName: String,
      birthDate: LocalDate) 

    val context = new SqlMirrorContext(MirrorSqlDialect, Literal)
    
    val person = "Person"
    val person2 = "Person2"

    import context._
    
    val personContext = dynamicQuerySchema[Person](person)
    val person2Context = dynamicQuerySchema[Person](person2)
    val query = translate(personContext.filter(_.id == lift(PersonId(1))))
    val query2 = translate(person2Context.filter(_.id == lift(PersonId(1))))
    println(s"$query")
    println(s"$query2")

Output

SELECT v0.id, v0.firstName, v0.lastName, v0.birthDate, v0.addressId FROM Person v0 WHERE v0.id = 1
SELECT v0.id, v0.firstName, v0.lastName, v0.birthDate, v0.addressId FROM Person2 v0 WHERE v0.id = 1
like image 71
Andrzej Jozwik Avatar answered Nov 08 '22 15:11

Andrzej Jozwik