This repository was archived by the owner on Mar 25, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmigration.go
More file actions
137 lines (104 loc) · 2.28 KB
/
migration.go
File metadata and controls
137 lines (104 loc) · 2.28 KB
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
134
135
136
137
package migrations
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/pkg/errors"
)
const (
MigrationTimeLayout = "20060102150405"
)
type Migration struct {
Name string
Version time.Time
Content struct {
Up string
Down string
}
}
func (m *Migration) VersionAsString() string {
return m.Version.Format(MigrationTimeLayout)
}
type Migrations []Migration
func (m Migrations) Len() int { return len(m) }
func (m Migrations) Less(i, j int) bool { return m[i].Version.Before(m[j].Version) }
func (m Migrations) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
func (m Migrations) Up(driver Driver, verbose bool) error {
if err := driver.CreateVersionsTable(); err != nil {
return err
}
for _, migration := range m {
if driver.HasExecuted(migration.VersionAsString()) {
continue
}
if verbose {
fmt.Println(migration.Content.Up)
}
if err := driver.Up(migration); err != nil {
return err
}
}
return nil
}
func (m Migrations) Down(driver Driver, verbose bool) error {
return errors.New("Dont use this, this project is archived")
}
func CreateFromDirectory(dir string) Migrations {
files, err := ioutil.ReadDir(dir)
if err != nil {
panic(err)
}
migrations := Migrations{}
for _, file := range files {
if file.IsDir() {
continue
}
if strings.HasSuffix(file.Name(), ".sql") {
migrations = append(migrations, newMigrationFromPath(path.Join(dir, file.Name())))
}
}
return migrations
}
func newMigrationFromPath(path string) Migration {
baseName := filepath.Base(path)
unparsedVersion := regexp.MustCompile("^\\d+").FindString(baseName)
version, err := time.Parse(MigrationTimeLayout, unparsedVersion)
if err != nil {
panic(err)
}
migration := Migration{
Name: baseName,
Version: version,
}
file, err := os.Open(path)
if err != nil {
panic(err)
}
defer func() {
_ = file.Close()
}()
scanner := bufio.NewScanner(file)
up := true
for scanner.Scan() {
line := scanner.Text()
switch true {
case strings.HasPrefix(line, "-- up"):
up = true
case strings.HasPrefix(line, "-- down"):
up = false
default:
if up {
migration.Content.Up += line + "\n"
} else {
migration.Content.Down += line + "\n"
}
}
}
return migration
}