aboutsummaryrefslogtreecommitdiffstats
path: root/internal/sqlparse/sqlparse.go
blob: a43d354e3c6bf641e5a1decaeaf8c7e94dfda744 (plain) (blame)
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package sqlparse

import (
	"bufio"
	"fmt"
	"io"
	"strings"
)

type SqlParser interface {
	Parse(reader io.Reader) (Migration, error)
}

type Migration struct {
	UpgradeScript   MigrationScript
	DowngradeScript MigrationScript
	Dependencies    []string
}

type MigrationScript struct {
	Contents string
	Options  ExecutionOptions
}

type ExecutionOptions struct {
	UseTransaction bool
}

const (
	unknownSection = iota
	upgradeScriptSection
	downgradeScriptSection
)

const (
	upgradeScriptDeliminator   = "-- migrate:up"
	downgradeScriptDeliminator = "-- migrate:down"
	dependsDirective           = "-- depends:"
	transactionOptionName      = "transaction"
)

type sqlParser struct{}

// NewSqlParser creates a new SqlParser which can
// parse out a migration script.
func NewSqlParser() SqlParser {
	return &sqlParser{}
}

// Parse parses out the migration's upgrade and downgrade scripts,
// any custom execution options with those scripts, and migration dependencies.
// It returns the upgrade script, downgrade script, dependencies, and any error if one occurred.
func (sp *sqlParser) Parse(reader io.Reader) (Migration, error) {
	migration := Migration{Dependencies: []string{}}

	scanner := bufio.NewScanner(reader)
	currentSection := unknownSection
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		loweredLine := strings.ToLower(line)

		if strings.HasPrefix(loweredLine, upgradeScriptDeliminator) {
			currentSection = upgradeScriptSection
			migration.UpgradeScript.Options = parseExecutionOptions(line)
		} else if strings.HasPrefix(loweredLine, downgradeScriptDeliminator) {
			currentSection = downgradeScriptSection
			migration.DowngradeScript.Options = parseExecutionOptions(line)
		} else if currentSection == upgradeScriptSection {
			migration.UpgradeScript.Contents += line + "\n"
		} else if currentSection == downgradeScriptSection {
			migration.DowngradeScript.Contents += line + "\n"
		}

		if strings.HasPrefix(loweredLine, dependsDirective) {
			migration.Dependencies = append(migration.Dependencies, parseDependencies(line)...)
		}

	}

	if err := scanner.Err(); err != nil {
		return Migration{}, fmt.Errorf(
			"parsing sql file encountered an error: %w",
			err,
		)
	}

	return migration, nil
}

// parseExecutionOptions extracts the execution options for a
// upgrade or downgrade migration script.
func parseExecutionOptions(line string) ExecutionOptions {
	options := ExecutionOptions{UseTransaction: true}

	parts := strings.SplitSeq(line, " ")
	for part := range parts {
		part = strings.ToLower(part)
		if strings.Contains(part, fmt.Sprintf("%s:", transactionOptionName)) {
			option := strings.Split(part, ":")[1]
			options.UseTransaction = option != "false"
		}
	}

	return options
}

// parseDependencies extracts migration dependencies from a depends directive.
// Expected format: -- depends: 001, 002, 003
func parseDependencies(line string) []string {
	dependencies := []string{}

	loweredLine := strings.ToLower(line)
	prefixIdx := strings.Index(loweredLine, dependsDirective)
	if prefixIdx == -1 {
		return dependencies
	}

	depsStr := line[prefixIdx+len(dependsDirective):]
	depsStr = strings.TrimSpace(depsStr)
	if depsStr == "" {
		return dependencies
	}

	deps := strings.SplitSeq(depsStr, ",")
	for dep := range deps {
		dep = strings.TrimSpace(dep)
		if dep != "" {
			dependencies = append(dependencies, dep)
		}
	}

	return dependencies
}