/
migrations.go
43 lines (33 loc) · 940 Bytes
/
migrations.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package database
import (
"fmt"
"os"
"path/filepath"
"gorm.io/gorm"
)
func MigrateTypes(db *gorm.DB, migrationsPath string) error {
path := filepath.Join(migrationsPath, "types.sql")
tx := db.Begin()
if tx.Error != nil {
return fmt.Errorf("failed to start transaction: %w", tx.Error)
}
if err := executeFromSQLFile(tx, path); err != nil {
tx.Rollback()
return fmt.Errorf("failed to execute types migration: %w", err)
}
if err := tx.Commit().Error; err != nil {
return fmt.Errorf("failed to commit types migration transaction: %w", err)
}
return nil
}
func executeFromSQLFile(db *gorm.DB, path string) error {
content, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf("failed to read file %s: %w", path, err)
}
statements := string(content)
if execErr := db.Exec(statements).Error; execErr != nil {
return fmt.Errorf("failed to execute SQL from file %s: %w", path, execErr)
}
return nil
}