Преглед изворни кода

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.
MHSanaei пре 9 часа
родитељ
комит
998fa0dfe1
2 измењених фајлова са 15 додато и 5 уклоњено
  1. 15 1
      database/db.go
  2. 0 4
      web/service/inbound.go

+ 15 - 1
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() {

+ 0 - 4
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
 	}