package mariadb import ( "crypto/rand" "encoding/hex" "errors" "fmt" "io" "reflect" "gorm.io/gorm" ) // CheckSnapshot compares restored schema and all writable row values. func CheckSnapshot(db *gorm.DB, path string) error { m, err := readSnapshot(path, nil) if err != nil { return err } return compareSnapshot(db, m) } // VerifySnapshot proves restore readiness in an isolated temporary database. func VerifySnapshot(db *gorm.DB, path string) (err error) { m, err := readSnapshot(path, nil) if err != nil { return err } var random [12]byte if _, err := rand.Read(random[:]); err != nil { return fmt.Errorf("name verification schema: %w", err) } scratch := "qfs_verify_" + hex.EncodeToString(random[:]) var original string if err := freshDB(db).Raw("SELECT DATABASE()").Scan(&original).Error; err != nil { return fmt.Errorf("read original schema: %w", err) } if err := freshDB(db).Exec("CREATE DATABASE " + quoteIdentifier(scratch) + " COLLATE " + quoteIdentifier(m.Collation)).Error; err != nil { return fmt.Errorf("create restore verification schema: %w", err) } defer func() { if e := freshDB(db).Exec("USE " + quoteIdentifier(original)).Error; e != nil { err = errors.Join(err, fmt.Errorf("return to original schema: %w", e)) } if e := freshDB(db).Exec("DROP DATABASE " + quoteIdentifier(scratch)).Error; e != nil { err = errors.Join(err, fmt.Errorf("remove verification schema %s: %w", scratch, e)) } }() if err := freshDB(db).Exec("USE " + quoteIdentifier(scratch)).Error; err != nil { return fmt.Errorf("select verification schema: %w", err) } if err := restoreSnapshotTables(db, path, m); err != nil { return err } return compareSnapshot(db, m) } func compareSnapshot(db *gorm.DB, m *snapshotManifest) error { current, err := snapshotInventory(db) if err != nil { return err } if !reflect.DeepEqual(current.Triggers, m.Triggers) { return fmt.Errorf("restored trigger metadata mismatch") } if len(current.Tables) != len(m.Tables) { return fmt.Errorf("restored table count mismatch") } for i := range m.Tables { want, got := m.Tables[i], current.Tables[i] if err := snapshotRows(db, &got, io.Discard); err != nil { return err } if want.Name != got.Name || want.Create != got.Create || want.Rows != got.Rows || want.Digest != got.Digest { return fmt.Errorf("restored snapshot mismatch in %s (name=%t schema=%t rows=%t digest=%t)", want.Name, want.Name == got.Name, want.Create == got.Create, want.Rows == got.Rows, want.Digest == got.Digest) } } return nil }