From 998fa0dfe1a1403109e581ddfabeec192cbba434 Mon Sep 17 00:00:00 2001 From: MHSanaei Date: Sun, 31 May 2026 21:45:41 +0200 Subject: [PATCH] fix(postgres): stop FK constraint from blocking inbound delete The schema was written for SQLite, which never enforces foreign keys, so relationships are managed in application code and deleting an inbound keeps its client_traffics by design. On Postgres GORM auto-created the fk_inbounds_client_stats constraint, which rejected those deletes with SQLSTATE 23503. Set DisableForeignKeyConstraintWhenMigrating so neither backend creates the constraint, and drop the already-created one on existing Postgres DBs via dropLegacyForeignKeys. Also revert the client_traffics deletion that c20ee00f added to DelInbound so traffic is preserved. --- database/db.go | 16 +++++++++++++++- web/service/inbound.go | 4 ---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/database/db.go b/database/db.go index 7aed0273..3a13845e 100644 --- a/database/db.go +++ b/database/db.go @@ -83,12 +83,26 @@ func initModels() error { return err } } + if err := dropLegacyForeignKeys(); err != nil { + return err + } if err := pruneOrphanedClientInbounds(); err != nil { return err } return nil } +func dropLegacyForeignKeys() error { + if !IsPostgres() { + return nil + } + if err := db.Exec("ALTER TABLE client_traffics DROP CONSTRAINT IF EXISTS fk_inbounds_client_stats").Error; err != nil { + log.Printf("Error dropping legacy foreign key fk_inbounds_client_stats: %v", err) + return err + } + return nil +} + func pruneOrphanedClientInbounds() error { res := db.Exec("DELETE FROM client_inbounds WHERE inbound_id NOT IN (SELECT id FROM inbounds)") if res.Error != nil { @@ -545,7 +559,7 @@ func InitDB(dbPath string) error { } else { gormLogger = logger.Discard } - c := &gorm.Config{Logger: gormLogger} + c := &gorm.Config{Logger: gormLogger, DisableForeignKeyConstraintWhenMigrating: true} var err error switch config.GetDBKind() { diff --git a/web/service/inbound.go b/web/service/inbound.go index 57157044..f75868cb 100644 --- a/web/service/inbound.go +++ b/web/service/inbound.go @@ -610,10 +610,6 @@ func (s *InboundService) DelInbound(id int) (bool, error) { logger.Debug("DelInbound: inbound not found, id:", id) } - if err := db.Where("inbound_id = ?", id).Delete(&xray.ClientTraffic{}).Error; err != nil { - return false, err - } - if err := s.clientService.DetachInbound(db, id); err != nil { return false, err }