-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathsql_script_parser.go
More file actions
78 lines (67 loc) · 1.96 KB
/
sql_script_parser.go
File metadata and controls
78 lines (67 loc) · 1.96 KB
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
package dsunit
import (
"bufio"
"io"
"strings"
)
//parseSQLScript parses sql script and breaks it down to submittable sql statements
func ParseSQLScript(reader io.Reader) []string {
var result = make([]string, 0)
scanner := bufio.NewScanner(reader)
var command, delimiter = "", ";"
var pending = ""
for scanner.Scan() {
line := strings.Trim(scanner.Text(), " \t")
if len(line) == 0 || strings.HasPrefix(line, "--") || (strings.HasPrefix(line, "/*") && strings.HasSuffix(line, "*/")) {
pending += line
continue
}
if pending != "" {
result = append(result, pending+"\n")
}
var inInSingleQuote, isInDoubleQuote bool = false, false
positionOfDelimiter := strings.Index(strings.ToLower(line), delimiterKeyword)
if positionOfDelimiter != -1 {
delimiter = strings.Trim(line[positionOfDelimiter+len(delimiterKeyword):], " \t")
continue
}
for i := 0; i < len(line); i++ {
aChar := line[i : i+1]
if aChar == "'" && i > 0 && line[i-1:i] != "\\" {
inInSingleQuote = !inInSingleQuote
}
if aChar == "\"" {
isInDoubleQuote = !isInDoubleQuote
}
hasDelimiter, indexIncrease := hasDelimiter(line, delimiter, i)
if hasDelimiter && !inInSingleQuote && !isInDoubleQuote {
i = i + indexIncrease
command = strings.Trim(command, " \t\"")
commans := normalizeCommand(command)
result = append(result, commans...)
command = ""
} else {
command = command + aChar
}
}
command = command + "\n"
}
return result
}
func normalizeCommand(command string) []string {
lowerCommand := strings.ToLower(command)
if !strings.Contains(lowerCommand, "begin") {
return []string{command}
}
var result = make([]string, 0)
positionOfEnd := strings.LastIndex(lowerCommand, "end")
if positionOfEnd != -1 {
endPosition := positionOfEnd + 3
block := string(command[:endPosition])
result = append(result, block)
if endPosition+1 < len(command) {
result = append(result, command[endPosition+1:])
}
}
return result
}