-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsql-lexer.go
96 lines (81 loc) · 2.39 KB
/
sql-lexer.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
package main
import (
"fmt"
"strings"
)
type keyword struct {
selectKeyword string
fromKeyword string
}
const (
selectKeywordVal = "SELECT"
fromKeywordVal = "FROM"
)
type symbol struct {
asteriskSymbol rune
semicolonSymbol rune
commaSymbol rune
}
const (
asteriskSymbolVal = '*'
semicolonSymbolVal = ';'
commaSymbolVal = ','
)
func LexSQL(query string, keywords keyword, symbols symbol) (tokens []string, columns []string, table []string) {
query = strings.ToUpper(query)
selectIndex := strings.Index(query, keywords.selectKeyword)
fromIndex := strings.Index(query, keywords.fromKeyword)
semicolonIndex := strings.Index(query, string(symbols.semicolonSymbol))
if selectIndex == -1 || fromIndex == -1 || semicolonIndex == -1 {
return nil, nil, nil
}
tokens = append(tokens, keywords.selectKeyword)
tokens = append(tokens, keywords.fromKeyword)
// tokens = append(token,string(symbol.semicolonSymbol))
columnstr := strings.TrimSpace(query[selectIndex+len(keywords.selectKeyword) : fromIndex])
tablestr := strings.TrimSpace(query[fromIndex+len(keywords.fromKeyword) : semicolonIndex])
if columnstr == string(symbols.asteriskSymbol) {
columns = append(columns, string(symbols.asteriskSymbol))
tokens = append(tokens, string(symbols.asteriskSymbol))
} else {
columns = strings.Split(columnstr, string(symbols.commaSymbol))
for i := range columns {
columns[i] = strings.TrimSpace(columns[i])
tokens = append(tokens, columns[i])
}
}
table = append(table, strings.TrimSpace(tablestr))
tokens = append(tokens, strings.TrimSpace(tablestr))
tokens = append(tokens, string(symbols.semicolonSymbol))
return tokens, columns, table
}
func main() {
keywords := keyword{
selectKeyword: selectKeywordVal,
fromKeyword: fromKeywordVal,
}
symbols := symbol{
asteriskSymbol: asteriskSymbolVal,
semicolonSymbol: semicolonSymbolVal,
commaSymbol: commaSymbolVal,
}
query := "SELECT * FROM Table_name ;"
tokens, columns, table := LexSQL(query, keywords, symbols)
fmt.Println(" ")
fmt.Println("Tokens: ")
fmt.Println(" ")
for _, c := range tokens {
fmt.Println(c)
}
fmt.Println(" ")
fmt.Println("Columns: ")
for _, c := range columns {
fmt.Println(c)
}
fmt.Println(" ")
fmt.Println("Table: ")
for _, c := range table {
fmt.Println(c)
}
fmt.Println(" ")
}