package database import ( "errors" "gorm.io/gorm" ) const PostgresMaintenanceSchema = "xui_maintenance" const postgresRestoreStateTable = PostgresMaintenanceSchema + ".restore_pending" var ErrPostgresRestorePending = errors.New("PostgreSQL restore migration is pending") func postgresRestorePending(scan func(string, *bool) error) (bool, error) { var exists bool if err := scan("SELECT to_regclass('"+postgresRestoreStateTable+"') IS NOT NULL", &exists); err != nil || !exists { return false, err } var pending bool err := scan("SELECT EXISTS (SELECT 1 FROM "+postgresRestoreStateTable+")", &pending) return pending, err } // PostgresRestorePending reads recovery state from the panel's PostgreSQL schema. func PostgresRestorePending(db *gorm.DB) (bool, error) { return postgresRestorePending(func(query string, result *bool) error { return db.Raw(query).Scan(result).Error }) } // MarkPostgresRestorePending records interrupted work outside the tables copied // by restore. The caller must hold the maintenance execution fence. func MarkPostgresRestorePending(db *gorm.DB) error { if err := migratePostgresRestoreState(db); err != nil { return err } if err := checkPostgresRestoreSchema(db); err != nil { return err } return db.Exec("INSERT INTO " + postgresRestoreStateTable + " (id, app_schema) VALUES (1, current_schema()) ON CONFLICT DO NOTHING").Error } // PendingPostgresRestoreForSchema refuses repair from an unrelated search path. func PendingPostgresRestoreForSchema(db *gorm.DB) (bool, error) { pending, err := PostgresRestorePending(db) if err != nil || !pending { return pending, err } return true, checkPostgresRestoreSchema(db) } func checkPostgresRestoreSchema(db *gorm.DB) error { var otherSchema bool err := db.Raw("SELECT EXISTS (SELECT 1 FROM " + postgresRestoreStateTable + " WHERE app_schema IS DISTINCT FROM current_schema())").Scan(&otherSchema).Error if err == nil && otherSchema { return errors.New("PostgreSQL restore is pending for a different application schema; use its original search_path to recover") } return err } // ClearPostgresRestorePending is only safe after repair succeeds under the fence. func ClearPostgresRestorePending(db *gorm.DB) error { pending, err := PendingPostgresRestoreForSchema(db) if err != nil || !pending { return err } return db.Exec("DELETE FROM " + postgresRestoreStateTable + " WHERE id = 1").Error }