/
parser.go
394 lines (337 loc) · 11.2 KB
/
parser.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
package sqlparser
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"log"
"os"
"strings"
"sync"
"github.com/mfridman/interpolate"
)
type Direction string
const (
DirectionUp Direction = "up"
DirectionDown Direction = "down"
)
func FromBool(b bool) Direction {
if b {
return DirectionUp
}
return DirectionDown
}
func (d Direction) String() string {
return string(d)
}
func (d Direction) ToBool() bool {
return d == DirectionUp
}
type parserState int
const (
start parserState = iota // 0
gooseUp // 1
gooseStatementBeginUp // 2
gooseStatementEndUp // 3
gooseDown // 4
gooseStatementBeginDown // 5
gooseStatementEndDown // 6
)
type stateMachine struct {
state parserState
verbose bool
}
func newStateMachine(begin parserState, verbose bool) *stateMachine {
return &stateMachine{
state: begin,
verbose: verbose,
}
}
func (s *stateMachine) get() parserState {
return s.state
}
func (s *stateMachine) set(new parserState) {
s.print("set %d => %d", s.state, new)
s.state = new
}
const (
grayColor = "\033[90m"
resetColor = "\033[00m"
)
func (s *stateMachine) print(msg string, args ...interface{}) {
msg = "StateMachine: " + msg
if s.verbose {
log.Printf(grayColor+msg+resetColor, args...)
}
}
const scanBufSize = 4 * 1024 * 1024
var bufferPool = sync.Pool{
New: func() interface{} {
buf := make([]byte, scanBufSize)
return &buf
},
}
// Split given SQL script into individual statements and return
// SQL statements for given direction (up=true, down=false).
//
// The base case is to simply split on semicolons, as these
// naturally terminate a statement.
//
// However, more complex cases like pl/pgsql can have semicolons
// within a statement. For these cases, we provide the explicit annotations
// 'StatementBegin' and 'StatementEnd' to allow the script to
// tell us to ignore semicolons.
func ParseSQLMigration(r io.Reader, direction Direction, debug bool) (stmts []string, useTx bool, err error) {
scanBufPtr := bufferPool.Get().(*[]byte)
scanBuf := *scanBufPtr
defer bufferPool.Put(scanBufPtr)
scanner := bufio.NewScanner(r)
scanner.Buffer(scanBuf, scanBufSize)
stateMachine := newStateMachine(start, debug)
useTx = true
useEnvsub := false
var buf bytes.Buffer
for scanner.Scan() {
line := scanner.Text()
if debug {
log.Println(line)
}
if stateMachine.get() == start && strings.TrimSpace(line) == "" {
continue
}
// Check for annotations.
// All annotations must be in format: "-- +goose [annotation]"
if strings.HasPrefix(strings.TrimSpace(line), "--") && strings.Contains(line, "+goose") {
var cmd annotation
cmd, err = extractAnnotation(line)
if err != nil {
return nil, false, fmt.Errorf("failed to parse annotation line %q: %w", line, err)
}
switch cmd {
case annotationUp:
switch stateMachine.get() {
case start:
stateMachine.set(gooseUp)
default:
return nil, false, fmt.Errorf("duplicate '-- +goose Up' annotations; stateMachine=%d, see https://github.com/pressly/goose#sql-migrations", stateMachine.state)
}
continue
case annotationDown:
switch stateMachine.get() {
case gooseUp, gooseStatementEndUp:
// If we hit a down annotation, but the buffer is not empty, we have an unfinished SQL query from a
// previous up annotation. This is an error, because we expect the SQL query to be terminated by a semicolon
// and the buffer to have been reset.
if bufferRemaining := strings.TrimSpace(buf.String()); len(bufferRemaining) > 0 {
return nil, false, missingSemicolonError(stateMachine.state, direction, bufferRemaining)
}
stateMachine.set(gooseDown)
default:
return nil, false, fmt.Errorf("must start with '-- +goose Up' annotation, stateMachine=%d, see https://github.com/pressly/goose#sql-migrations", stateMachine.state)
}
continue
case annotationStatementBegin:
switch stateMachine.get() {
case gooseUp, gooseStatementEndUp:
stateMachine.set(gooseStatementBeginUp)
case gooseDown, gooseStatementEndDown:
stateMachine.set(gooseStatementBeginDown)
default:
return nil, false, fmt.Errorf("'-- +goose StatementBegin' must be defined after '-- +goose Up' or '-- +goose Down' annotation, stateMachine=%d, see https://github.com/pressly/goose#sql-migrations", stateMachine.state)
}
continue
case annotationStatementEnd:
switch stateMachine.get() {
case gooseStatementBeginUp:
stateMachine.set(gooseStatementEndUp)
case gooseStatementBeginDown:
stateMachine.set(gooseStatementEndDown)
default:
return nil, false, errors.New("'-- +goose StatementEnd' must be defined after '-- +goose StatementBegin', see https://github.com/pressly/goose#sql-migrations")
}
case annotationNoTransaction:
useTx = false
continue
case annotationEnvsubOn:
useEnvsub = true
continue
case annotationEnvsubOff:
useEnvsub = false
continue
default:
return nil, false, fmt.Errorf("unknown annotation: %q", cmd)
}
}
// Once we've started parsing a statement the buffer is no longer empty,
// we keep all comments up until the end of the statement (the buffer will be reset).
// All other comments in the file are ignored.
if buf.Len() == 0 {
// This check ensures leading comments and empty lines prior to a statement are ignored.
if strings.HasPrefix(strings.TrimSpace(line), "--") || line == "" {
stateMachine.print("ignore comment")
continue
}
}
switch stateMachine.get() {
case gooseStatementEndDown, gooseStatementEndUp:
// Do not include the "+goose StatementEnd" annotation in the final statement.
default:
if useEnvsub {
expanded, err := interpolate.Interpolate(&envWrapper{}, line)
if err != nil {
return nil, false, fmt.Errorf("variable substitution failed: %w:\n%s", err, line)
}
line = expanded
}
// Write SQL line to a buffer.
if _, err := buf.WriteString(line + "\n"); err != nil {
return nil, false, fmt.Errorf("failed to write to buf: %w", err)
}
}
// Read SQL body one by line, if we're in the right direction.
//
// 1) basic query with semicolon; 2) psql statement
//
// Export statement once we hit end of statement.
switch stateMachine.get() {
case gooseUp, gooseStatementBeginUp, gooseStatementEndUp:
if direction == DirectionDown {
buf.Reset()
stateMachine.print("ignore down")
continue
}
case gooseDown, gooseStatementBeginDown, gooseStatementEndDown:
if direction == DirectionUp {
buf.Reset()
stateMachine.print("ignore up")
continue
}
default:
return nil, false, fmt.Errorf("failed to parse migration: unexpected state %d on line %q, see https://github.com/pressly/goose#sql-migrations", stateMachine.state, line)
}
switch stateMachine.get() {
case gooseUp:
if endsWithSemicolon(line) {
stmts = append(stmts, cleanupStatement(buf.String()))
buf.Reset()
stateMachine.print("store simple Up query")
}
case gooseDown:
if endsWithSemicolon(line) {
stmts = append(stmts, cleanupStatement(buf.String()))
buf.Reset()
stateMachine.print("store simple Down query")
}
case gooseStatementEndUp:
stmts = append(stmts, cleanupStatement(buf.String()))
buf.Reset()
stateMachine.print("store Up statement")
stateMachine.set(gooseUp)
case gooseStatementEndDown:
stmts = append(stmts, cleanupStatement(buf.String()))
buf.Reset()
stateMachine.print("store Down statement")
stateMachine.set(gooseDown)
}
}
if err := scanner.Err(); err != nil {
return nil, false, fmt.Errorf("failed to scan migration: %w", err)
}
// EOF
switch stateMachine.get() {
case start:
return nil, false, errors.New("failed to parse migration: must start with '-- +goose Up' annotation, see https://github.com/pressly/goose#sql-migrations")
case gooseStatementBeginUp, gooseStatementBeginDown:
return nil, false, errors.New("failed to parse migration: missing '-- +goose StatementEnd' annotation")
}
if bufferRemaining := strings.TrimSpace(buf.String()); len(bufferRemaining) > 0 {
return nil, false, missingSemicolonError(stateMachine.state, direction, bufferRemaining)
}
return stmts, useTx, nil
}
type annotation string
const (
annotationUp annotation = "Up"
annotationDown annotation = "Down"
annotationStatementBegin annotation = "StatementBegin"
annotationStatementEnd annotation = "StatementEnd"
annotationNoTransaction annotation = "NO TRANSACTION"
annotationEnvsubOn annotation = "ENVSUB ON"
annotationEnvsubOff annotation = "ENVSUB OFF"
)
var supportedAnnotations = map[annotation]struct{}{
annotationUp: {},
annotationDown: {},
annotationStatementBegin: {},
annotationStatementEnd: {},
annotationNoTransaction: {},
annotationEnvsubOn: {},
annotationEnvsubOff: {},
}
var (
errEmptyAnnotation = errors.New("empty annotation")
errInvalidAnnotation = errors.New("invalid annotation")
)
// extractAnnotation extracts the annotation from the line.
// All annotations must be in format: "-- +goose [annotation]"
// Allowed annotations: Up, Down, StatementBegin, StatementEnd, NO TRANSACTION, ENVSUB ON, ENVSUB OFF
func extractAnnotation(line string) (annotation, error) {
// If line contains leading whitespace - return error.
if strings.HasPrefix(line, " ") || strings.HasPrefix(line, "\t") {
return "", fmt.Errorf("%q contains leading whitespace: %w", line, errInvalidAnnotation)
}
// Extract the annotation from the line, by removing the leading "--"
cmd := strings.ReplaceAll(line, "--", "")
// Extract the annotation from the line, by removing the leading "+goose"
cmd = strings.Replace(cmd, "+goose", "", 1)
if strings.Contains(cmd, "+goose") {
return "", fmt.Errorf("%q contains multiple '+goose' annotations: %w", cmd, errInvalidAnnotation)
}
// Remove leading and trailing whitespace from the annotation command.
cmd = strings.TrimSpace(cmd)
if cmd == "" {
return "", errEmptyAnnotation
}
a := annotation(cmd)
for s := range supportedAnnotations {
if strings.EqualFold(string(s), string(a)) {
return s, nil
}
}
return "", fmt.Errorf("%q not supported: %w", cmd, errInvalidAnnotation)
}
func missingSemicolonError(state parserState, direction Direction, s string) error {
return fmt.Errorf("failed to parse migration: state %d, direction: %v: unexpected unfinished SQL query: %q: missing semicolon?",
state,
direction,
s,
)
}
type envWrapper struct{}
var _ interpolate.Env = (*envWrapper)(nil)
func (e *envWrapper) Get(key string) (string, bool) {
return os.LookupEnv(key)
}
func cleanupStatement(input string) string {
return strings.TrimSpace(input)
}
// Checks the line to see if the line has a statement-ending semicolon
// or if the line contains a double-dash comment.
func endsWithSemicolon(line string) bool {
scanBufPtr := bufferPool.Get().(*[]byte)
scanBuf := *scanBufPtr
defer bufferPool.Put(scanBufPtr)
prev := ""
scanner := bufio.NewScanner(strings.NewReader(line))
scanner.Buffer(scanBuf, scanBufSize)
scanner.Split(bufio.ScanWords)
for scanner.Scan() {
word := scanner.Text()
if strings.HasPrefix(word, "--") {
break
}
prev = word
}
return strings.HasSuffix(prev, ";")
}