forked from libgo/migrate
/
file.go
102 lines (80 loc) · 1.83 KB
/
file.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
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
package file
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strconv"
"github.com/libgo/logx"
"github.com/izhaohu/migrate/source"
)
func init() {
source.Register("file", &File{})
}
type File struct {
migrations source.Migrations
}
var (
re = regexp.MustCompile(`^([0-9]+)_([0-9a-zA-Z\.]*)_?(.*)?\.sql$`)
)
func (f *File) Open(uri string) (source.Reader, error) {
migrations := make(source.Migrations)
//scan directory
err := filepath.Walk(uri, func(path string, f os.FileInfo, err error) error {
if f == nil {
return err
}
if f.IsDir() {
return nil
}
module, ver, sql, err := read(path)
if err != nil {
return fmt.Errorf("file: %v, err: %v", path, err)
}
if _, ok := migrations[module]; !ok {
migrations[module] = &source.Migration{MaxVer: 0, Version: 0, Sql: map[int]string{}}
}
migrations[module].Sql[ver] = sql
migrations[module].SetMax(ver)
return nil
})
if err != nil {
return nil, err
}
rr := &File{
migrations: migrations,
}
return rr, nil
}
func read(file string) (source.Module, int, string, error) {
logx.Debugf("migrate: reading file: '%s'", file)
_, f := filepath.Split(file)
m := re.FindStringSubmatch(f)
if len(m) == 0 {
return "", 0, "", fmt.Errorf("not a valid migration file")
}
v, err := strconv.Atoi(m[1])
if err != nil {
return "", 0, "", fmt.Errorf("not a valid migration file")
}
fi, err := os.Open(file)
if err != nil {
return "", 0, "", err
}
defer fi.Close()
sql, err := ioutil.ReadAll(fi)
if err != nil {
return "", 0, "", err
}
return source.Module(m[2]), v, string(sql), nil
}
func (f *File) Goto(m source.Module, v int) error {
return f.migrations.Goto(m, v)
}
func (f *File) Next(m source.Module) (string, int, error) {
return f.migrations.Next(m)
}
func (f *File) List() []source.Module {
return f.migrations.List()
}