Migrate profile IDs in history database when merging profiles

This commit is contained in:
Patrick Pacher 2023-10-20 11:55:18 +02:00 committed by Daniel
parent b20565adc3
commit b2b6217265
4 changed files with 28 additions and 0 deletions

View file

@ -432,6 +432,15 @@ func (db *Database) RemoveHistoryForProfile(ctx context.Context, profileID strin
}))
}
// MigrateProfileID migrates the given profile IDs in the history database.
// This needs to be done when profiles are deleted and replaced by a different profile.
func (db *Database) MigrateProfileID(ctx context.Context, from string, to string) error {
return db.ExecuteWrite(ctx, "UPDATE history.connections SET profile = :to WHERE profile = :from", orm.WithNamedArgs(map[string]any{
":from": from,
":to": to,
}))
}
// dumpTo is a simple helper method that dumps all rows stored in the SQLite database
// as JSON to w.
// Any error aborts dumping rows and is returned.

View file

@ -272,6 +272,21 @@ func (m *module) start() error {
}
}
// Migrate profile IDs in history database when profiles are migrated/merged.
if err := m.RegisterEventHook(
"profiles",
"profile migrated",
"migrate profile IDs in history database",
func(ctx context.Context, data interface{}) error {
if profileIDs, ok := data.([]string); ok && len(profileIDs) == 2 {
return m.Store.MigrateProfileID(ctx, profileIDs[0], profileIDs[1])
}
return nil
},
); err != nil {
return err
}
return nil
}

View file

@ -77,10 +77,12 @@ func MergeProfiles(name string, primary *Profile, secondaries ...*Profile) (newP
if err := primary.delete(); err != nil {
return nil, fmt.Errorf("failed to delete primary profile %s: %w", primary.ScopedID(), err)
}
module.TriggerEvent(MigratedEvent, []string{primary.ScopedID(), newProfile.ScopedID()})
for _, sp := range secondaries {
if err := sp.delete(); err != nil {
return nil, fmt.Errorf("failed to delete secondary profile %s: %w", sp.ScopedID(), err)
}
module.TriggerEvent(MigratedEvent, []string{sp.ScopedID(), newProfile.ScopedID()})
}
return newProfile, nil

View file

@ -22,12 +22,14 @@ var (
const (
ConfigChangeEvent = "profile config change"
DeletedEvent = "profile deleted"
MigratedEvent = "profile migrated"
)
func init() {
module = modules.Register("profiles", prep, start, stop, "base", "updates")
module.RegisterEvent(ConfigChangeEvent, true)
module.RegisterEvent(DeletedEvent, true)
module.RegisterEvent(MigratedEvent, true)
}
func prep() error {