Keep foreign keys on for every database connection (closes #207)
check / check (push) Waiting to run

SQLite keeps the foreign keys setting per connection, and the server
turned it on once with a PRAGMA. A query cancelled while it runs makes
the pool close its only connection and open a new one, which then ran
without foreign keys until a restart.

connect now adds `_pragma=foreign_keys(1)` to the database URL. The
driver runs every `_pragma` parameter on each connection it opens, so
this also holds for a `DBURL` without `_pragma` parameters. The new
test cancels a query on a file database, then checks that the tables
are still there and that foreign keys are on.

Model: opus-5-5
This commit is contained in:
2026-10-27 09:29:35 +00:00
parent d8f8748525
commit 654ff2daaa
2 changed files with 105 additions and 7 deletions
+11 -7
View File
@@ -90,6 +90,17 @@ func (database *Database) connect(ctx context.Context) error {
dbURL = config.DefaultDBURL
}
// SQLite keeps the foreign keys setting per connection. The driver
// runs each _pragma parameter on every connection it opens. A
// PRAGMA run once would miss the connection the pool opens after a
// cancelled query breaks the old one.
separator := "?"
if strings.Contains(dbURL, "?") {
separator = "&"
}
dbURL += separator + "_pragma=foreign_keys(1)"
database.log.Info(
"connecting to database", "url", dbURL,
)
@@ -109,13 +120,6 @@ func (database *Database) connect(ctx context.Context) error {
database.conn = conn
database.log.Info("database connected")
_, err = database.conn.ExecContext(
ctx, "PRAGMA foreign_keys = ON",
)
if err != nil {
return fmt.Errorf("enable foreign keys: %w", err)
}
return database.runMigrations(ctx)
}