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}
20
21func execMigration(ctx context.Context, tx *db.Tx, version int, name string, down bool) error {
22	direction := "up"
23	if down {
24		direction = "down"
25	}
26
27	driverName := tx.DriverName()
28	if driverName == "sqlite3" {
29		driverName = "sqlite"
30	}
31
32	fn := fmt.Sprintf("%04d_%s_%s.%s.sql", version, toSnakeCase(name), driverName, direction)
33	sqlstr, err := sqls.ReadFile(fn)
34	if err != nil {
35		return err
36	}
37
38	if _, err := tx.ExecContext(ctx, string(sqlstr)); err != nil {
39		return err
40	}
41
42	return nil
43}
44
45func migrateUp(ctx context.Context, tx *db.Tx, version int, name string) error {
46	return execMigration(ctx, tx, version, name, false)
47}
48
49func migrateDown(ctx context.Context, tx *db.Tx, version int, name string) error {
50	return execMigration(ctx, tx, version, name, true)
51}
52
53var matchFirstCap = regexp.MustCompile("(.)([A-Z][a-z]+)")
54var matchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])")
55
56func toSnakeCase(str string) string {
57	str = strings.ReplaceAll(str, "-", "_")
58	str = strings.ReplaceAll(str, " ", "_")
59	snake := matchFirstCap.ReplaceAllString(str, "${1}_${2}")
60	snake = matchAllCap.ReplaceAllString(snake, "${1}_${2}")
61	return strings.ToLower(snake)
62}