首页 > 解决方案 > 做 INSERT INTO ... SELECT FROM 的鹅毛笔方式

问题描述

我正在尝试将简单INSERT INTO...SELECT FROM的查询翻译成 Quill 中的报价。首先,我没有找到一种内置的方法来做到这一点,所以最终尝试使用中缀查询

val rawQuery = quote { (secondTableValues: List[Int]) => {
        infix"""
                INSERT INTO my_table (second_table_id)
                VALUES (
                  ${secondTableValues.map(stid => (SELECT id FROM second_table where id = $stid)).mkString(",")}}
                )
          """.as[Insert[Any]]
    }}

databaseClient.run(rawQuery(List(1,2,3)))

但是,这不会编译,因为 Quill 无法为查询构建 Ast。

我最终做的是有一个原始查询而不是使用引号并使用executeAction.

所以两个问题

  1. 您将如何INSERT INTO...SELECT FROM以内置方式进行操作?
  2. 上面的版本有什么问题infix

标签: scalaquill.io

解决方案


  import io.getquill._

  val ctx = new SqlMirrorContext(MirrorSqlDialect, Literal)

  import ctx._

  case class Table1(id: Int)

  case class Table2(id: Int, name: String)


  def contains(list: List[Int]) = {
    //SELECT e.id,'hello' FROM Table1 e WHERE e.id IN (?)
    val q = quote(
      query[Table1].filter(e => liftQuery(list).contains(e.id)).map(e => Table2(e.id, "hello"))
    )
    //insert into table2 SELECT e.id, 'hello' FROM Table1 e WHERE e.id IN (?)
    // `${..}` is expect ast , not string
    quote(infix"insert into table2 ${q}".as[Insert[Any]])
  }


  // test
  val list = List(1)
  ctx.run(contains(list))

推荐阅读