1package migrate
2
3import (
4 "context"
5 "embed"
6 "fmt"
7 "regexp"
8 "strings"
9
10 "github.com/charmbracelet/soft-serve/server/db"
11)
12
13//go:embed *.sql
14var sqls embed.FS
15
16// Keep this in order of execution, oldest to newest.
17var migrations = []Migration{
18 createTables,
19 createLFSTables,
20 passwordTokens,
21}
22
23func execMigration(ctx context.Context, tx *db.Tx, version int, name string, down bool) error {
24 direction := "up"
25 if down {
26 direction = "down"
27 }
28
29 driverName := tx.DriverName()
30 if driverName == "sqlite3" {
31 driverName = "sqlite"
32 }
33
34 fn := fmt.Sprintf("%04d_%s_%s.%s.sql", version, toSnakeCase(name), driverName, direction)
35 sqlstr, err := sqls.ReadFile(fn)
36 if err != nil {
37 return err
38 }
39
40 if _, err := tx.ExecContext(ctx, string(sqlstr)); err != nil {
41 return err
42 }
43
44 return nil
45}
46
47func migrateUp(ctx context.Context, tx *db.Tx, version int, name string) error {
48 return execMigration(ctx, tx, version, name, false)
49}
50
51func migrateDown(ctx context.Context, tx *db.Tx, version int, name string) error {
52 return execMigration(ctx, tx, version, name, true)
53}
54
55var matchFirstCap = regexp.MustCompile("(.)([A-Z][a-z]+)")
56var matchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])")
57
58func toSnakeCase(str string) string {
59 str = strings.ReplaceAll(str, "-", "_")
60 str = strings.ReplaceAll(str, " ", "_")
61 snake := matchFirstCap.ReplaceAllString(str, "${1}_${2}")
62 snake = matchAllCap.ReplaceAllString(snake, "${1}_${2}")
63 return strings.ToLower(snake)
64}