package mariadb import ( "database/sql" "errors" "fmt" "strings" "gorm.io/gorm" ) // RestoreSnapshot restores and checks a snapshot on a dedicated connection. // The same maintenance exclusion as migration is required throughout recovery. func RestoreSnapshot(db *gorm.DB, path string) error { m, err := readSnapshot(path, nil) if err != nil { return err } var schema string if err := freshDB(db).Raw("SELECT DATABASE()").Scan(&schema).Error; err != nil { return fmt.Errorf("read restore destination: %w", err) } if schema != m.Schema { return fmt.Errorf("snapshot schema does not match restore destination") } if err := restoreSnapshotTables(db, path, m); err != nil { return err } return compareSnapshot(db, m) } func restoreSnapshotTables(db *gorm.DB, path string, m *snapshotManifest) (err error) { current, err := snapshotInventory(db) if err != nil { return err } var foreignKeys int var sqlMode string if err := freshDB(db).Raw("SELECT @@foreign_key_checks, @@sql_mode").Row().Scan(&foreignKeys, &sqlMode); err != nil { return fmt.Errorf("read restore session policy: %w", err) } if err := freshDB(db).Exec("SET FOREIGN_KEY_CHECKS=0").Error; err != nil { return fmt.Errorf("disable FK checks for restore: %w", err) } defer func() { if restoreErr := freshDB(db).Exec("SET sql_mode=?", sqlMode).Error; restoreErr != nil { err = errors.Join(err, fmt.Errorf("restore SQL mode: %w", restoreErr)) } if restoreErr := freshDB(db).Exec("SET FOREIGN_KEY_CHECKS=?", foreignKeys).Error; restoreErr != nil { err = errors.Join(err, fmt.Errorf("restore FK policy: %w", restoreErr)) } }() // Preserve explicit zero auto-increment IDs and legacy zero dates. Exact // schema/data comparison detects any coercion before the source is changed. if err := freshDB(db).Exec("SET sql_mode='NO_AUTO_VALUE_ON_ZERO'").Error; err != nil { return fmt.Errorf("set snapshot insert mode: %w", err) } for i := len(current.Tables) - 1; i >= 0; i-- { if err := freshDB(db).Exec("DROP TABLE " + quoteIdentifier(current.Tables[i].Name)).Error; err != nil { return fmt.Errorf("drop restore table %s: %w", current.Tables[i].Name, err) } } for _, table := range m.Tables { if err := freshDB(db).Exec(table.Create).Error; err != nil { return fmt.Errorf("restore schema for %s: %w", table.Name, err) } } var prefix, rowSQL, tableName string var args []any var groups []string var bytes int flush := func() error { if len(groups) == 0 { return nil } // Bind through database/sql: GORM expands a byte slice after '('. // Direct execution also keeps restored values out of SQL logs. if _, err := db.Statement.ConnPool.ExecContext(db.Statement.Context, prefix+strings.Join(groups, ","), args...); err != nil { return fmt.Errorf("restore rows in %s: %w", tableName, err) } args, groups, bytes = nil, nil, 0 return nil } _, err = readSnapshot(path, func(table snapshotTable, values []sql.RawBytes) error { if tableName != table.Name { if err := flush(); err != nil { return err } tableName = table.Name columns, placeholders := make([]string, len(values)), make([]string, len(values)) for i := range values { columns[i], placeholders[i] = quoteIdentifier(table.Columns[i]), "?" } prefix = "INSERT INTO " + quoteIdentifier(tableName) + " (" + strings.Join(columns, ",") + ") VALUES " rowSQL = "(" + strings.Join(placeholders, ",") + ")" } for _, value := range values { if value == nil { args = append(args, nil) } else { args = append(args, []byte(value)) bytes += len(value) } } groups = append(groups, rowSQL) if len(groups) >= 250 || len(args)+len(values) > 60000 || bytes >= 1<<20 { return flush() } return nil }) if err == nil { err = flush() } if err != nil { return err } return restoreSnapshotTriggers(db, m) }