-
Notifications
You must be signed in to change notification settings - Fork 0
/
conv.go
42 lines (36 loc) · 860 Bytes
/
conv.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
package sqltableconv
import (
"vitess.io/vitess/go/vt/sqlparser"
)
// ConvFunc conv func
type ConvFunc func(string) string
// Conv conv SQL
func Conv(query string, f ConvFunc) (string, error) {
if f == nil {
return query, nil
}
stmt, err := sqlparser.Parse(query)
if err != nil {
return "", err
}
post := func(cursor *sqlparser.Cursor) bool {
switch n := cursor.Node().(type) {
case sqlparser.TableIdent:
if n.String() != "" {
cursor.Replace(sqlparser.NewTableIdent(f(n.String())))
}
case sqlparser.TableName:
if n.Name.String() != "" {
cursor.Replace(sqlparser.TableName{
Name: sqlparser.NewTableIdent(f(n.Name.String())),
Qualifier: n.Qualifier,
})
}
}
return true
}
s := sqlparser.Rewrite(stmt, nil, post)
buf := sqlparser.NewTrackedBuffer(nil)
s.Format(buf)
return buf.String(), nil
}