Skip to content

pingcap tidb parser 解析 sql

go
package main

import (
	"bytes"
	"log"

	"github.com/pingcap/tidb/parser"
	"github.com/pingcap/tidb/parser/ast"
	_ "github.com/pingcap/tidb/parser/test_driver"
)

func main() {
	sql1 := "SELECT content, author FROM user WHERE id = 1001 AND title LIKE 'title%'"

	p := parser.New()
	stmt, err := p.ParseOneStmt(sql1, "", "")
	if err != nil {
		panic(err)
	}
	for _, v := range stmt.(*ast.SelectStmt).Fields.Fields {
		colExpr := v.Expr.(*ast.ColumnNameExpr)
		log.Printf("field: %v", colExpr.Name)
	}

	writerL := bytes.NewBufferString("")
	writerR := bytes.NewBufferString("")
	writerOP := bytes.NewBufferString("")
	// stmt.(*ast.SelectStmt).Where.Format(writer)
	// log.Printf("select Where: %v", writer.String())
	// log.Printf("select Where: %v", stmt.(*ast.SelectStmt).Where)
	stmt.(*ast.SelectStmt).Where.(*ast.BinaryOperationExpr).L.Format(writerL)
	log.Printf("select Where: %v", writerL.String())
	stmt.(*ast.SelectStmt).Where.(*ast.BinaryOperationExpr).R.Format(writerR)
	log.Printf("select Where: %v", writerR.String())
	stmt.(*ast.SelectStmt).Where.(*ast.BinaryOperationExpr).Op.Format(writerOP)
	log.Printf("select Where: %v", writerOP.String())

	// wcns := &WhereColumnNames{}
	// stmt.Accept(wcns)
	// fmt.Printf("wcns %v", wcns)
}

type WhereColumnNames struct {
	allColNames []string
	selColNames []string
}

func (w *WhereColumnNames) Enter(in ast.Node) (ast.Node, bool) {
	// all fields in sql (select and where)
	if name, ok := in.(*ast.ColumnName); ok {
		w.allColNames = append(w.allColNames, name.Name.O)
	}

	// select fields
	if name, ok := in.(*ast.SelectField); ok {
		w.selColNames = append(w.selColNames, name.Text())
	}

	return in, false
}

func (w *WhereColumnNames) Leave(in ast.Node) (ast.Node, bool) {
	return in, true
}