-
Notifications
You must be signed in to change notification settings - Fork 0
/
migration.go
83 lines (63 loc) · 1.5 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
package postgres_backend
import (
"errors"
"fmt"
"sort"
"time"
)
type Migration struct {
filename string
content string
date time.Time
}
func (m Migration) String() string {
return fmt.Sprintf("%s at %s", m.filename, m.date)
}
type Migrations []Migration
func (m Migrations) Len() int { return len(m) }
func (m Migrations) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
//Returns a new Migration array with the provided dates filtered out
func (m Migrations) FilterDates(t []time.Time) (nm Migrations) {
//Find the indices of the migrations which have already
//been applied
removalIndexes := []int{}
for idx, im := range m {
for _, it := range t {
if im.date == it {
removalIndexes = append(removalIndexes, idx)
}
}
}
nm = m[:]
//Same length, return an empty set
if len(removalIndexes) == len(nm) {
return Migrations{}
}
//Swap & slice
for _, idx := range removalIndexes {
l := len(m) - 1
nm.Swap(idx, l)
nm = m[:l]
}
return nm
}
// Sort by date
type ByAge struct{ Migrations }
func (s ByAge) Less(i, j int) bool {
return s.Migrations[i].date.Nanosecond() < s.Migrations[j].date.Nanosecond()
}
func globMigrations() (m Migrations, err error) {
const longForm = "2006-01-02T15-04-05Z"
if len(MigrationTuples) == 0 {
return m, errors.New("No migrations found!")
}
for key, value := range MigrationTuples {
t, err := time.Parse(longForm, key)
if err != nil {
return m, err
}
m = append(m, Migration{key, value, t})
}
sort.Sort(ByAge{m})
return m, nil
}