ruiaylin / sqlparser

SqlParser implement in golang , from TiDB ( PingCap ) , you can use this module independently
Apache License 2.0
48 stars 12 forks source link

How do you use this? #1

Open clanstyles opened 7 years ago

clanstyles commented 7 years ago

I've gotten as far as ...

stmts, err := parser.New().Parse(query, "", "")
    if err != nil {
        return nil, err
    }

    for _, stmt := range stmts {
    }

I'm trying to compare the statements and see if it's an "insert" and then iterate over the values.

ruiaylin commented 7 years ago

Sorry for the late reply. I use this parser in mysql sql analyze system . SQL was parsed and be format. You can got the AST struct and to do the things you want , like sql parsing and rebuilt in some sharding middleware.

ruiaylin commented 7 years ago

@clanstyles
My way is like bellow , i wish it can give you a little help .

func ParserALLSQL(sql string) (absql string) {
    abSQL := ""
    parser := parser.New() 
    stmt, err := parser.ParseOneStmt(sql, "", "") 
    if err != nil {
        fmt.Println("... err: ", err)
        return sql
    }
    switch node := stmt.(type) {
    case *ast.InsertStmt:
        abSQL = AbstractINSSQL(node)
        ....
    default:
        abSQL = sql
    }
    return abSQL
}
// and the structure is : 
// InsertStmt is a statement to insert new rows into an existing table.
// See https://dev.mysql.com/doc/refman/5.7/en/insert.html
type InsertStmt struct {
    dmlNode
    IsReplace   bool
    Table       *TableRefsClause
    Columns     []*ColumnName
    Lists       [][]ExprNode
    Setlist     []*Assignment
    Priority    int
    OnDuplicate []*Assignment
    Select      ResultSetNode
}
// u can handle it youself and get the part you want
clanstyles commented 7 years ago

@ruiaylin thanks for the reply.

The SQL values are escaped. Is there a way to unescape it? I'm realizing that Go doesn't directly have any unescape logic because database/sql handles everything and it's not intentionally exposed.