forked from dinedal/textql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sql_mod.go
59 lines (53 loc) · 1.46 KB
/
sql_mod.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
package sqlparser
// Magicify runs the SQL passed in, and a table name, throught a customized
// TextQL SQL Parser. This provides the following functionality:
// - Queries that do not start with SELECT are implictly mapped to SELECT statements
// - Queries that are missing a FROM, have the FROM inserted with tableName
func Magicify(sql string, tableName string) string {
if tableName == "" {
return sql
}
statement, err := Parse(sql)
if err != nil {
return sql
}
switch statement := statement.(type) {
case *Select:
replaceFromInSelect(statement, tableName)
return generateQuery(statement)
default:
return sql
}
}
func replaceFromInSelect(statement *Select, tableName string) {
if statement.From == nil {
tableName := &TableName{[]byte("[" + tableName + "]"), nil}
aliasedTableExpr := AliasedTableExpr{tableName, nil, nil}
tableExprs := TableExprs{&aliasedTableExpr}
statement.From = &From{Type: AST_FROM, Expr: tableExprs}
} else {
for _, expr := range statement.From.Expr {
switch expr := expr.(type) {
case *AliasedTableExpr:
switch subQuery := expr.Expr.(type) {
case *Subquery:
switch selectSubQuery := subQuery.Select.(type) {
case *Select:
replaceFromInSelect(selectSubQuery, tableName)
default:
return
}
default:
return
}
default:
return
}
}
}
}
func generateQuery(statement Statement) string {
buf := NewTrackedBuffer(nil)
statement.Format(buf)
return buf.String()
}