-
Notifications
You must be signed in to change notification settings - Fork 15
/
source.go
105 lines (83 loc) · 2.57 KB
/
source.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 migration
import (
"fmt"
"io"
"strings"
"sync"
)
// Source is an interface that defines how a source can find and read migration files.
type Source interface {
ListMigrationFiles() ([]string, error)
GetMigrationFile(file string) (io.Reader, error)
}
// GolangMigrationSource implements migration.Source
type GolangMigrationSource struct {
sync.Mutex
migrations map[string]func() error
}
// NewGolangMigrationSource creates a source for storing Go functions as migrations.
func NewGolangMigrationSource() *GolangMigrationSource {
return &GolangMigrationSource{
migrations: map[string]func() error{},
}
}
// AddMigration adds a new migration to the source. The file parameter follows the same conventions as you would use
// for a physical file for other types of migrations, however you should omit the file extension. Example: 1_init.up
// and 1_init.down
func (s *GolangMigrationSource) AddMigration(file string, direction Direction, migration func() error) {
s.Lock()
defer s.Unlock()
if direction == Up {
file += ".up"
} else if direction == Down {
file += ".down"
}
s.migrations[file+".go"] = migration
}
// GetMigration gets a golang migration
func (s *GolangMigrationSource) GetMigration(file string) func() error {
s.Lock()
defer s.Unlock()
return s.migrations[file+".go"]
}
// ListMigrationFiles lists the available migrations in the source
func (s *GolangMigrationSource) ListMigrationFiles() ([]string, error) {
var keys []string
s.Lock()
defer s.Unlock()
for key := range s.migrations {
keys = append(keys, key)
}
return keys, nil
}
// GetMigrationFile retrieves a migration given the filename.
func (s *GolangMigrationSource) GetMigrationFile(file string) (io.Reader, error) {
s.Lock()
defer s.Unlock()
_, ok := s.migrations[file]
if !ok {
return nil, fmt.Errorf("migration %s does not exist", file)
}
return strings.NewReader(""), nil
}
// MemoryMigrationSource is a MigrationSource that uses migration sources in memory. It is mainly
// used for testing.
type MemoryMigrationSource struct {
Files map[string]string
}
// ListMigrationFiles returns a list of memory migration files
func (m MemoryMigrationSource) ListMigrationFiles() ([]string, error) {
var files []string
for file := range m.Files {
files = append(files, file)
}
return files, nil
}
// GetMigrationFile gets a memory migration file
func (m MemoryMigrationSource) GetMigrationFile(name string) (io.Reader, error) {
content, ok := m.Files[name]
if !ok {
return nil, fmt.Errorf("the migration file %s does not exist", name)
}
return strings.NewReader(content), nil
}