如何使用 Slick 在 SQLite 中启用外键验证
How to enable foreign key validation in SQLite with Slick
我想通过 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.
或者尝试 running a plain SQL statement 在 运行 您的查询之前使用 pragma 命令 PRAGMA foreign_keys = ON
。
我想通过 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.
或者尝试 running a plain SQL statement 在 运行 您的查询之前使用 pragma 命令 PRAGMA foreign_keys = ON
。