Skip to content

Commit

Permalink
fix: db
Browse files Browse the repository at this point in the history
  • Loading branch information
zijiren233 committed Jan 12, 2025
1 parent 66527d5 commit acd1f18
Showing 1 changed file with 30 additions and 12 deletions.
42 changes: 30 additions & 12 deletions internal/db/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,19 +135,37 @@ func autoMigrate(dst ...any) error {
log.Info("migrating database...")
switch conf.Conf.Database.Type {
case conf.DatabaseTypeMysql:
// if conf.Conf.Database.Type == conf.DatabaseTypeMysql {
// if err := db.Exec("SET FOREIGN_KEY_CHECKS = 0").Error; err != nil {
// return err
// }
// defer func() {
// err := db.Exec("SET FOREIGN_KEY_CHECKS = 1").Error
// if err != nil {
// log.Fatalf("failed to set foreign key checks: %s", err.Error())
// }
// }()
// }
if err := db.Exec("SET FOREIGN_KEY_CHECKS = 0").Error; err != nil {
return err
}
defer func() {
err := db.Exec("SET FOREIGN_KEY_CHECKS = 1").Error
if err != nil {
log.Fatalf("failed to set foreign key checks: %s", err.Error())
}
}()
return db.Set("gorm:table_options", "ENGINE=InnoDB CHARSET=utf8mb4").AutoMigrate(dst...)
case conf.DatabaseTypeSqlite3, conf.DatabaseTypePostgres:
case conf.DatabaseTypeSqlite3:
if err := db.Exec("PRAGMA foreign_keys = OFF").Error; err != nil {
return err
}
defer func() {
err := db.Exec("PRAGMA foreign_keys = ON").Error
if err != nil {
log.Fatalf("failed to set foreign key checks: %s", err.Error())
}
}()
return db.AutoMigrate(dst...)
case conf.DatabaseTypePostgres:
if err := db.Exec("SET CONSTRAINTS ALL DEFERRED").Error; err != nil {
return err
}
defer func() {
err := db.Exec("SET CONSTRAINTS ALL IMMEDIATE").Error
if err != nil {
log.Fatalf("failed to set foreign key checks: %s", err.Error())
}
}()
return db.AutoMigrate(dst...)
default:
return fmt.Errorf("unknown database type: %s", conf.Conf.Database.Type)
Expand Down

0 comments on commit acd1f18

Please sign in to comment.