mirror of
https://github.com/muety/wakapi.git
synced 2023-08-10 21:12:56 +03:00
chore: enable foreign key constraints for new sqlite databases
This commit is contained in:
parent
485dfe2888
commit
c5db2c235f
5
main.go
5
main.go
@ -119,8 +119,11 @@ func main() {
|
|||||||
var err error
|
var err error
|
||||||
db, err = gorm.Open(config.Db.GetDialector(), &gorm.Config{Logger: gormLogger})
|
db, err = gorm.Open(config.Db.GetDialector(), &gorm.Config{Logger: gormLogger})
|
||||||
if config.Db.Dialect == "sqlite3" {
|
if config.Db.Dialect == "sqlite3" {
|
||||||
db.Raw("PRAGMA foreign_keys = ON;")
|
db.Exec("PRAGMA foreign_keys = ON;")
|
||||||
|
if !utils.IsCleanDB(db) && !utils.HasConstraints(db) {
|
||||||
db.DisableForeignKeyConstraintWhenMigrating = true
|
db.DisableForeignKeyConstraintWhenMigrating = true
|
||||||
|
logbuch.Warn("using existing sqlite database without foreign key constraints and no ability to migrate, functionality may be limited")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.IsDev() {
|
if config.IsDev() {
|
||||||
|
32
utils/db.go
Normal file
32
utils/db.go
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/emvi/logbuch"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
func IsCleanDB(db *gorm.DB) bool {
|
||||||
|
if db.Dialector.Name() == "sqlite" {
|
||||||
|
var count int64
|
||||||
|
if err := db.Raw("SELECT count(*) from sqlite_master WHERE type = 'table'").Scan(&count).Error; err != nil {
|
||||||
|
logbuch.Error("failed to check if database is clean - '%v'", err)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return count == 0
|
||||||
|
}
|
||||||
|
logbuch.Warn("IsCleanDB is not yet implemented for dialect '%s'", db.Dialector.Name())
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func HasConstraints(db *gorm.DB) bool {
|
||||||
|
if db.Dialector.Name() == "sqlite" {
|
||||||
|
var count int64
|
||||||
|
if err := db.Raw("SELECT count(*) from sqlite_master WHERE sql LIKE '%CONSTRAINT%'").Scan(&count).Error; err != nil {
|
||||||
|
logbuch.Error("failed to check if database has constraints - '%v'", err)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return count != 0
|
||||||
|
}
|
||||||
|
logbuch.Warn("HasForeignKeyConstraints is not yet implemented for dialect '%s'", db.Dialector.Name())
|
||||||
|
return false
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user