如何使用Slick在SQLite中启用外键验证

问题描述 投票:1回答:1

我想通过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)")
}
scala sqlite slick
1个回答
2
投票

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

如果你在幕后使用连接池,也许这就是为什么它不起作用。尝试在database config example中禁用。

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

© www.soinside.com 2019 - 2024. All rights reserved.