forked from eure/kamimai
/
migration.go
105 lines (88 loc) · 2.2 KB
/
migration.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
103
104
105
package core
import (
"io/ioutil"
"os"
"github.com/Fs02/kamimai/internal/cast"
)
type (
// A Migration manages migration files.
Migration struct {
version uint64
name string
}
// A Migrations collects Migration for sorting.
Migrations []*Migration
)
//////////////////////////////
// Migration
//////////////////////////////
// NewMigration returns a new Migration pointer that can be chained with builder methods to
// set multiple configuration values inline without using pointers.
func NewMigration() *Migration {
return &Migration{}
}
// WithVersion sets a config version value returning a Config pointer
// for chaining.
func (m *Migration) WithVersion(v interface{}) *Migration {
m.version = cast.Uint64(v)
return m
}
// Version returns a migration version value.
func (m Migration) Version() uint64 {
return m.version
}
// Read reads from file until an error or EOF and returns the data it read.
// A successful call returns err == nil, not err == EOF. Because ReadAll is
// defined to read from src until EOF, it does not treat an EOF from Read
// as an error to be reported.
func (m Migration) Read() ([]byte, error) {
file, err := os.Open(m.name)
if err != nil {
return nil, err
}
return ioutil.ReadAll(file)
}
// Name returns a file name.
func (m Migration) Name() string {
return m.name
}
//////////////////////////////
// Migrations
//////////////////////////////
func (m Migrations) index(mig Migration) int {
for i, v := range m {
if v.version == mig.version {
return i
}
}
return int(notFoundIndex)
}
func (m Migrations) first() *Migration {
if m.Len() == 0 {
return nil
}
return m[0]
}
func (m Migrations) last() *Migration {
c := m.Len()
if c == 0 {
return nil
}
return m[c-1]
}
// Len is the number of elements in the collection.
// Required by Sort Interface{}
func (m Migrations) Len() int {
return len(m)
}
// Less reports whether the element with
// index i should sort before the element with index j.
// Required by Sort Interface{}
func (m Migrations) Less(i, j int) bool {
return m[i].version < m[j].version
}
// Swap swaps the elements with indexes i and j.
// Required by Sort Interface{}
func (m Migrations) Swap(i, j int) {
m[i], m[j] = m[j], m[i]
}