77 lines
2.5 KiB
Go
77 lines
2.5 KiB
Go
package models
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type migrationVerification struct {
|
|
description string
|
|
query string
|
|
}
|
|
|
|
func parseMigrationVerifications(script string) ([]migrationVerification, error) {
|
|
var checks []migrationVerification
|
|
for _, line := range strings.Split(script, "\n") {
|
|
line = strings.TrimSpace(line)
|
|
if !strings.HasPrefix(line, "-- verify:") {
|
|
continue
|
|
}
|
|
description, query, ok := strings.Cut(strings.TrimPrefix(line, "-- verify:"), "|")
|
|
description, query = strings.TrimSpace(description), strings.TrimSpace(query)
|
|
if !ok || description == "" || query == "" {
|
|
return nil, fmt.Errorf("invalid migration verify header")
|
|
}
|
|
checks = append(checks, migrationVerification{description: description, query: query})
|
|
}
|
|
return checks, nil
|
|
}
|
|
|
|
func applySQLMigrationFile(db *gorm.DB, filename, content string) error {
|
|
checks, err := parseMigrationVerifications(content)
|
|
if err != nil {
|
|
return fmt.Errorf("parse migration %s: %w", filename, err)
|
|
}
|
|
statements, err := splitSQLStatements(content)
|
|
if err != nil {
|
|
return fmt.Errorf("parse migration %s SQL: %w", filename, err)
|
|
}
|
|
return db.Connection(func(conn *gorm.DB) error {
|
|
return applySQLMigrationOnSession(conn, filename, statements, checks)
|
|
})
|
|
}
|
|
|
|
func applySQLMigrationOnSession(conn *gorm.DB, filename string, statements []string, checks []migrationVerification) error {
|
|
if err := executeMigrationStatements(conn, filename, statements); err != nil {
|
|
return err
|
|
}
|
|
// Each query gets a fresh statement on the pinned connection: chaining
|
|
// Raw/Create on conn itself leaks the previous query's state (with two
|
|
// verify checks the history insert targeted a table named "rows").
|
|
fresh := func() *gorm.DB { return conn.Session(&gorm.Session{NewDB: true}) }
|
|
for _, check := range checks {
|
|
rows, err := fresh().Raw(check.query).Rows()
|
|
if err != nil {
|
|
return fmt.Errorf("verify migration %s (%s): %w", filename, check.description, err)
|
|
}
|
|
failed := rows.Next()
|
|
rowErr := rows.Err()
|
|
closeErr := rows.Close()
|
|
if rowErr != nil {
|
|
return fmt.Errorf("read migration verification %s (%s): %w", filename, check.description, rowErr)
|
|
}
|
|
if closeErr != nil {
|
|
return fmt.Errorf("close migration verification %s (%s): %w", filename, check.description, closeErr)
|
|
}
|
|
if failed {
|
|
return fmt.Errorf("verify migration %s failed: %s", filename, check.description)
|
|
}
|
|
}
|
|
if err := fresh().Create(&SQLSchemaMigration{Filename: filename}).Error; err != nil {
|
|
return fmt.Errorf("record migration %s: %w", filename, err)
|
|
}
|
|
return nil
|
|
}
|