我想通过Slick在SQLite中启用外键验证。我正在使用Slick 3.3.0。我该怎么做呢?

目前,我正在通过DatabaseConfig[SQLiteProfile]连接到SQLite,方法是

 DatabaseConfig.forConfig(path = configKey, classLoader = getClass.getClassLoader)


我的配置如下所示:

{
  "dataSourceClass": "slick.jdbc.DatabaseUrlDataSource",
  "db": {
    "driver": "org.sqlite.JDBC",

    "properties": {
      "foreign_keys": true
    },
    "url": "jdbc:sqlite:/path/to/mydb.sqlite?foreign_keys=on"
  },
  "profile": "slick.jdbc.SQLiteProfile$"
}


我尝试将?foreign_keys=ON添加到我的JDBC URL的末尾。我还尝试过将properties对象从db对象移到根级别。

如果我直接通过JDBC与数据库进行交互,则可以使它正常工作:

package test

import java.sql.DriverManager

object Main extends App {

  val connection = DriverManager.getConnection(
    "jdbc:sqlite:/path/to/mydb.sqlite?foreign_keys=on")
  val statement = connection.createStatement()

  // this line throws, because table_with_fk is a table
  // with foreign keys into a different table
  statement.executeUpdate(
    "insert into table_with_fk values (0, 0, 0, 0, 0, 0, 0, 0)")
}

最佳答案

根据play framework - SQLite: Enable Foreign Key,SQLite要求您在连接级别启用此功能。这与您的示例一致(您正在将外键选项传递给getConnection

如果您在后台使用连接池,那么也许这就是为什么它不起作用。尝试像database config example中一样禁用。

或者,在运行查询之前,使用pragma命令PRAGMA foreign_keys = ON尝试running a plain SQL statement

关于scala - 如何使用Slick在SQLite中启用外键验证,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55382319/

10-12 00:28
查看更多