scala - 做 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
.
所以两个问题
- 您将如何
INSERT INTO...SELECT FROM
以内置方式进行操作? - 上面的版本有什么问题
infix
?
解决方案
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))
推荐阅读
- listview - 如何在 ListView onClick 中将图像切换为文本
- python - 在Python中将JSON字符串数组转换为对象数组
- android - Google Git 上的 Android 源代码库的结构是什么?
- php - 如果已经在输入值中,如何不回显一个值?
- ruby-on-rails - 我应该如何将 React 与 Rails 集成?
- javascript - 我如何填充画布而不是圆圈
- jquery - 获取隐藏字段的值
- postgresql - 为什么插入主键不影响顺序?
- javascript - 使用 ajax 和 javascript 更新 innerHTML 值
- javascript - 即使在剑道网格列中,如何调用按钮单击java脚本模具