diff --git a/hscontrol/db/db.go b/hscontrol/db/db.go index 0d9120c2..553d7f0e 100644 --- a/hscontrol/db/db.go +++ b/hscontrol/db/db.go @@ -521,6 +521,27 @@ func NewHeadscaleDatabase( }, Rollback: func(db *gorm.DB) error { return nil }, }, + { + // Add a constraint to routes ensuring they cannot exist without a node. + ID: "202501221827", + Migrate: func(tx *gorm.DB) error { + // Remove any invalid routes associated with a node that does not exist. + if tx.Migrator().HasTable(&types.Route{}) && tx.Migrator().HasTable(&types.Node{}) { + err := tx.Exec("delete from routes where node_id not in (select id from nodes)").Error + if err != nil { + return err + } + } + + err := tx.AutoMigrate(&types.Route{}) + if err != nil { + return err + } + + return nil + }, + Rollback: func(db *gorm.DB) error { return nil }, + }, }, ) diff --git a/hscontrol/types/routes.go b/hscontrol/types/routes.go index 4ef3621f..f98c037d 100644 --- a/hscontrol/types/routes.go +++ b/hscontrol/types/routes.go @@ -13,7 +13,7 @@ import ( type Route struct { gorm.Model - NodeID uint64 + NodeID uint64 `gorm:"not null"` Node *Node // TODO(kradalby): change this custom type to netip.Prefix