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.
This commit is contained in:
MHSanaei
2026-05-31 21:45:41 +02:00
parent f02018cfb7
commit 998fa0dfe1
2 changed files with 15 additions and 5 deletions

View File

@@ -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() {

View File

@@ -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
}