Skip to content

Commit

Permalink
add api to get query list, and support skip invalid query
Browse files Browse the repository at this point in the history
  • Loading branch information
sjjian committed Apr 7, 2022
1 parent 1c4141e commit fc7a0f8
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
17 changes: 17 additions & 0 deletions ast/mapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,20 @@ func (m *Mapper) GetStmt(ctx *Context) (string, error) {
}
return strings.TrimSuffix(buff.String(), "\n"), nil
}

func (m *Mapper) GetStmts(ctx *Context, skipErrorQuery bool) ([]string, error) {
var stmts []string
ctx.Sqls = m.SqlNodes
for _, a := range m.QueryNodes {
data, err := a.GetStmt(ctx)
if err == nil {
stmts = append(stmts, data)
continue
}
if skipErrorQuery {
continue
}
return nil, err
}
return stmts, nil
}
25 changes: 25 additions & 0 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ package parser

import (
"encoding/xml"
"fmt"
"io"
"strings"

"github.com/actiontech/mybatis-mapper-2-sql/ast"
)

// ParseXML is a parser for parse all query in XML to string.
func ParseXML(data string) (string, error) {
r := strings.NewReader(data)
d := xml.NewDecoder(r)
Expand All @@ -25,6 +27,29 @@ func ParseXML(data string) (string, error) {
return stmt, nil
}

// ParseXMLQuery is a parser for parse all query in XML to []string one by one;
// you can set `skipErrorQuery` true to ignore invalid query.
func ParseXMLQuery(data string, skipErrorQuery bool) ([]string, error) {
r := strings.NewReader(data)
d := xml.NewDecoder(r)
n, err := parse(d, nil)
if err != nil {
return nil, err
}
if n == nil {
return nil, nil
}
m, ok := n.(*ast.Mapper)
if !ok {
return nil, fmt.Errorf("the mapper is not found")
}
stmts, err := m.GetStmts(ast.NewContext(), skipErrorQuery)
if err != nil {
return nil, err
}
return stmts, nil
}

func parse(d *xml.Decoder, start *xml.StartElement) (node ast.Node, err error) {
if start != nil {
node, err = scan(start)
Expand Down

0 comments on commit fc7a0f8

Please sign in to comment.