This repository has been archived by the owner on Apr 14, 2022. It is now read-only.
forked from asticode/go-astipatch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpatcher_sql.go
268 lines (236 loc) · 6.21 KB
/
patcher_sql.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
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package astipatch
import (
"bytes"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/jmoiron/sqlx"
"github.com/molotovtv/go-astilog"
)
// Vars
var (
sqlQuerySeparator = []byte(";")
)
// patcherSQL represents a SQL patcher
type patcherSQL struct {
conn *sqlx.DB
patches map[string]*patchSQL // Indexed by name
patchesNames []string
storer Storer
}
// patchSQL represents a SQL patch
type patchSQL struct {
queries [][]byte
rollbacks [][]byte
}
// NewPatcherSQL creates a new SQL patcher
func NewPatcherSQL(conn *sqlx.DB, s Storer) Patcher {
return &patcherSQL{
conn: conn,
patches: make(map[string]*patchSQL),
patchesNames: []string{},
storer: s,
}
}
// Init implements the Patcher interface
func (p *patcherSQL) Init() error {
return p.storer.Init()
}
// Load loads the patches
func (p *patcherSQL) Load(c Configuration) (err error) {
astilog.Debug("Loading patches")
if c.PatchesDirectoryPath != "" {
astilog.Debugf("Patches directory is %s", c.PatchesDirectoryPath)
if err = filepath.Walk(c.PatchesDirectoryPath, func(path string, info os.FileInfo, _ error) (err error) {
// Log
astilog.Debugf("Processing %s", path)
// Skip directories
if info.IsDir() {
return
}
// Skip none .sql files
if filepath.Ext(path) != ".sql" {
astilog.Debugf("Skipping non .sql file %s", path)
return
}
// Retrieve name and whether it's a rollback
var name = strings.TrimSuffix(filepath.Base(path), filepath.Ext(path))
var rollback bool
if strings.HasSuffix(name, rollbackSuffix) {
rollback = true
name = strings.TrimSuffix(name, rollbackSuffix)
}
// Read file
var b []byte
if b, err = ioutil.ReadFile(path); err != nil {
return
}
// Split on query separator and clean queries
var items, queries = bytes.Split(b, sqlQuerySeparator), [][]byte{}
for _, item := range items {
item = bytes.TrimSpace(item)
if len(item) > 0 {
queries = append(queries, item)
}
}
// No queries to add
if len(queries) == 0 {
astilog.Debug("No queries to add")
return
}
// Add/update patch
if _, ok := p.patches[name]; !ok {
p.patches[name] = &patchSQL{}
}
if len(p.patches[name].queries) == 0 && !rollback {
p.patchesNames = append(p.patchesNames, name)
}
if rollback {
p.patches[name].rollbacks = append(p.patches[name].rollbacks, queries...)
astilog.Debugf("Adding %d rollback(s) to patch %s", len(queries), name)
} else {
p.patches[name].queries = append(p.patches[name].queries, queries...)
astilog.Debugf("Adding %d querie(s) to patch %s", len(queries), name)
}
return
}); err != nil {
return
}
}
return
}
// Patch implements the Patcher interface
func (p *patcherSQL) Patch() (err error) {
// Get patches to run
var patchesToRun []string
if patchesToRun, err = p.storer.Delta(p.patchesNames); err != nil {
return
}
// No patches to run
if len(patchesToRun) == 0 {
astilog.Debug("No patches to run")
return
}
// Patch
if err = p.patch(patchesToRun); err != nil {
return
}
// Insert batch
astilog.Debug("Inserting batch")
if err = p.storer.InsertBatch(patchesToRun); err != nil {
return
}
return
}
// patch executes a set of query
func (p *patcherSQL) patch(patchesToRun []string) (err error) {
// Start transaction
var tx *sqlx.Tx
if tx, err = p.conn.Beginx(); err != nil {
return
}
astilog.Debug("Beginning transaction")
// Commit/Rollback
var rollbacks []string
defer func(err *error, rollbacks *[]string) {
if *err != nil {
// Rollback transaction
astilog.Debug("Rollbacking transaction")
if e := tx.Rollback(); e != nil {
astilog.Errorf("%s while rolling back transaction", e)
}
// Run manual rollbacks
if len(*rollbacks) > 0 {
astilog.Debug("Running manual rollbacks")
if e := p.rollback(*rollbacks); e != nil {
astilog.Errorf("%s while running manual rollbacks", e)
}
}
} else {
astilog.Debug("Committing transaction")
if e := tx.Commit(); e != nil {
astilog.Errorf("%s while committing transaction", e)
}
}
}(&err, &rollbacks)
// Loop through patches to run
for _, patch := range patchesToRun {
// Loop through queries
for _, query := range p.patches[patch].queries {
// Exec
astilog.Debugf("Running query %s of patch %s", string(query), patch)
if _, err = tx.Exec(string(query)); err != nil {
astilog.Errorf("%s while executing %s", err, string(query))
return
}
}
// Add rollbacks in case of errors
for _, rollback := range p.patches[patch].rollbacks {
rollbacks = append(rollbacks, string(rollback))
}
}
return
}
// Rollback implements the Patcher interface
func (p *patcherSQL) Rollback() (err error) {
// Get patches to rollback
var patchesToRollback []string
if patchesToRollback, err = p.storer.LastBatch(); err != nil {
return
}
// No patches to rollback
if len(patchesToRollback) == 0 {
astilog.Debug("No patches to rollback")
return
}
// Get rollback queries
var queries []string
for _, patch := range patchesToRollback {
for _, rollback := range p.patches[patch].rollbacks {
queries = append(queries, string(rollback))
}
}
// Rollback
if err = p.rollback(queries); err != nil {
return
}
// Delete last batch
astilog.Debug("Deleting last batch")
if err = p.storer.DeleteLastBatch(); err != nil {
return
}
return
}
// rollback executes a set of query in reverse order
func (p *patcherSQL) rollback(queries []string) (err error) {
// Start transaction
var tx *sqlx.Tx
if tx, err = p.conn.Beginx(); err != nil {
return
}
astilog.Debug("Beginning transaction")
// Commit/Rollback
defer func(err *error) {
if *err != nil {
astilog.Debug("Rollbacking transaction")
if e := tx.Rollback(); e != nil {
astilog.Errorf("%s while rolling back transaction", e)
}
} else {
astilog.Debug("Committing transaction")
if e := tx.Commit(); e != nil {
astilog.Errorf("%s while committing transaction", e)
}
}
}(&err)
// Loop through patches to rollback in reverse order
for i := len(queries) - 1; i >= 0; i-- {
astilog.Debugf("Running rollback %s", queries[i])
if _, err = tx.Exec(queries[i]); err != nil {
astilog.Errorf("%s while executing %s", err, queries[i])
return
}
}
return
}