From e5d0e987e138ebe98ce2693dfcf333a4a67a8e04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sybren=20A=2E=20St=C3=BCvel?= Date: Mon, 13 Jun 2022 15:42:41 +0200 Subject: [PATCH] Manager: enforce DB foreign key checks at startup SQLite disables foreign key checks by default, so Flamenco has to enable them explicitly. --- internal/manager/persistence/db.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/internal/manager/persistence/db.go b/internal/manager/persistence/db.go index 9f5bbf4b..58dc2001 100644 --- a/internal/manager/persistence/db.go +++ b/internal/manager/persistence/db.go @@ -5,6 +5,7 @@ package persistence import ( "context" + "fmt" "time" "github.com/rs/zerolog/log" @@ -83,6 +84,19 @@ func openDBWithConfig(dsn string, config *gorm.Config) (*DB, error) { sqlDB.SetMaxIdleConns(1) // Max num of connections in the idle connection pool. sqlDB.SetMaxOpenConns(1) // Max num of open connections to the database. + // Enable foreign key checks. + log.Trace().Msg("enabling SQLite foreign key checks") + if tx := gormDB.Exec("PRAGMA foreign_keys = 1"); tx.Error != nil { + return nil, fmt.Errorf("enabling foreign keys: %w", tx.Error) + } + var fkEnabled int + if tx := gormDB.Raw("PRAGMA foreign_keys").Scan(&fkEnabled); tx.Error != nil { + return nil, fmt.Errorf("checking whether the database has foreign key checks enabled: %w", tx.Error) + } + if fkEnabled == 0 { + log.Error().Msg("SQLite database does not want to enable foreign keys, this may cause data loss") + } + db := DB{ gormDB: gormDB, }