-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathschema.go
More file actions
62 lines (51 loc) · 1.19 KB
/
schema.go
File metadata and controls
62 lines (51 loc) · 1.19 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
package golang
import (
"fmt"
"strings"
)
func ApplySchema(query string) string {
tables := make(map[string]bool)
ctes := make(map[string]bool)
words := strings.Fields(query)
// Getting all the table names and CTEs
withinCTE := false
for i, word := range words {
upperWord := strings.ToUpper(word)
if upperWord == "WITH" {
withinCTE = true
continue
} else if withinCTE {
ctes[words[i]] = true
withinCTE = false
continue
}
if isSQLKeyword(upperWord) {
tables[nextNonKeyword(words, i)] = true
}
}
// Removing from tables the CTEs
for cte := range ctes {
delete(tables, cte)
}
// Replacing the table names with the placeholder
for table := range tables {
query = strings.ReplaceAll(query, " "+table, fmt.Sprintf(" `%%s`.%s", table))
}
return query
}
// Helper function to check if a word is a relevant SQL keyword
func isSQLKeyword(word string) bool {
switch word {
case "FROM", "JOIN", "UPDATE", "INTO":
return true
}
return false
}
func nextNonKeyword(words []string, currentIndex int) string {
for i := currentIndex + 1; i < len(words); i++ {
if !isSQLKeyword(words[i]) && words[i] != "AS" && words[i] != "(" {
return words[i]
}
}
return ""
}