首页 > 解决方案 > 如何使用 Slick 在 SQLite 中启用外键验证

问题描述

我想通过 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)")
}

标签: scalasqliteslick

解决方案


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

如果您在幕后使用连接池,也许这就是它不起作用的原因。尝试在数据库配置示例中禁用。

或者,在运行查询之前尝试使用 pragma 命令运行普通 SQL 语句PRAGMA foreign_keys = ON


推荐阅读