package models import ( "fmt" "io/fs" "regexp" "gorm.io/gorm" ) func planSQLMigrations(db *gorm.DB, migrations fs.FS) ([]plannedSQLMigration, error) { states, err := SQLMigrationStatus(db, migrations) if err != nil { return nil, err } var plans []plannedSQLMigration unsupported := regexp.MustCompile(`(?i)\b(?:CREATE|DROP|ALTER)\s+(?:DATABASE|SCHEMA|VIEW|TRIGGER|PROCEDURE|FUNCTION|EVENT)\b|\b(?:USE|DELIMITER|GRANT|REVOKE)\s|\bSET\s+(?:GLOBAL|SQL_MODE)\b|\bENGINE\s*=\s*(?:MyISAM|Aria|MEMORY|BLACKHOLE)\b`) for _, state := range states { if state.AppliedAt != nil { continue } content, err := fs.ReadFile(migrations, state.Filename) if err != nil { return nil, fmt.Errorf("read migration %s: %w", state.Filename, err) } statements, err := splitSQLStatements(string(content)) if err != nil { return nil, fmt.Errorf("parse migration %s: %w", state.Filename, err) } checks, err := parseMigrationVerifications(string(content)) if err != nil { return nil, fmt.Errorf("migration %s verify headers: %w", state.Filename, err) } if len(checks) == 0 { return nil, fmt.Errorf("migration %s needs verify headers", state.Filename) } for _, stmt := range statements { if unsupported.MatchString(stmt) { return nil, fmt.Errorf("migration %s contains SQL outside supported table recovery", state.Filename) } } plans = append(plans, plannedSQLMigration{state.Filename, statements, checks}) } return plans, nil }