forked from DavidHuie/gomigrate
-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
58 lines (48 loc) · 1.42 KB
/
utils.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package gomigrate
import (
"path/filepath"
"regexp"
"strconv"
)
var (
upMigrationFile = regexp.MustCompile(`(\d+)_([\w-]+)_up\.sql`)
downMigrationFile = regexp.MustCompile(`(\d+)_([\w-]+)_down\.sql`)
subMigrationSplit = regexp.MustCompile(`;\s*`)
allWhitespace = regexp.MustCompile(`^\s*$`)
)
// Returns the migration number, type and base name, so 1, "up", "migration" from "01_migration_up.sql"
func parseMigrationPath(path string) (uint64, migrationType, string, error) {
filebase := filepath.Base(path)
matches := upMigrationFile.FindAllSubmatch([]byte(filebase), -1)
if matches != nil {
return parseMatches(matches, upMigration)
}
matches = downMigrationFile.FindAllSubmatch([]byte(filebase), -1)
if matches != nil {
return parseMatches(matches, downMigration)
}
return 0, "", "", InvalidMigrationFile
}
// Parses matches given by a migration file regex.
func parseMatches(matches [][][]byte, mType migrationType) (uint64, migrationType, string, error) {
num := matches[0][1]
name := matches[0][2]
parsedNum, err := strconv.ParseUint(string(num), 10, 64)
if err != nil {
return 0, "", "", err
}
return parsedNum, mType, string(name), nil
}
// This type is used to sort migration ids.
type uint64slice []uint64
func (u uint64slice) Len() int {
return len(u)
}
func (u uint64slice) Less(a, b int) bool {
return u[a] < u[b]
}
func (u uint64slice) Swap(a, b int) {
tempA := u[a]
u[a] = u[b]
u[b] = tempA
}