Skip to content

Instantly share code, notes, and snippets.

@latavin243
Created January 25, 2024 04:01
Show Gist options
  • Save latavin243/74fc1223cf10bc8ab9d773403d30aaec to your computer and use it in GitHub Desktop.
Save latavin243/74fc1223cf10bc8ab9d773403d30aaec to your computer and use it in GitHub Desktop.
package main
/*
Prerequisites:
go get -v github.com/pingcap/parser@3a18f1e
go get -v github.com/pingcap/tidb/types/parser_driver@328b6d0
*/
import (
"fmt"
"github.com/pingcap/parser"
"github.com/pingcap/parser/ast"
_ "github.com/pingcap/tidb/types/parser_driver"
)
const sqlSample = `select itemid, sum(sales) as sum_sales, count(userid) as pv, count(distinct userid) as uv
from stat_mydata_shop_20211010 as table_metrics
where dt>20211010 and dt <20211017 and shopid=123456
group by itemid
order by sum_pv desc
limit 10 offset 5`
type visitor struct{}
var _ ast.Visitor = (*visitor)(nil)
func (v *visitor) Enter(in ast.Node) (out ast.Node, skipChildren bool) {
fmt.Printf("%T\t%+v\n", in, in)
return in, false
}
func (v *visitor) Leave(in ast.Node) (out ast.Node, ok bool) { return in, true }
func main() {
fmt.Printf("raw sql:\n%s\n\n", sqlSample)
p := parser.New()
stmtNodes, _, err := p.Parse(sqlSample, "", "")
if err != nil {
fmt.Printf("parse error: %v\n", err.Error())
panic(err)
return
}
for _, stmtNode := range stmtNodes {
v := visitor{}
stmtNode.Accept(&v)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment