Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: support line mapping to point the precise line number in mybatis mapper xml (#5917)
h3n4l087d172498ce
diff --git a/backend/plugin/parser/mybatis/mapper/ast/data_node.go b/backend/plugin/parser/mybatis/mapper/ast/data_node.goindex 67b39f037e..a6f6d09935 100644--- a/backend/plugin/parser/mybatis/mapper/ast/data_node.go+++ b/backend/plugin/parser/mybatis/mapper/ast/data_node.go@@ -21,12 +21,17 @@ type TextNode struct {}// RestoreSQL implements Node interface.-func (n *TextNode) RestoreSQL(_ *RestoreContext, w io.Writer) error {+func (n *TextNode) RestoreSQL(ctx *RestoreContext, w io.Writer) error {if len(n.Text) == 0 {return nil}- if _, err := w.Write([]byte(n.Text)); err != nil {- return err+ for _, b := range []byte(n.Text) {+ if b == '\n' {+ ctx.CurrentLastLine+++ }+ if _, err := w.Write([]byte{b}); err != nil {+ return err+ }}return nil}diff --git a/backend/plugin/parser/mybatis/mapper/ast/node.go b/backend/plugin/parser/mybatis/mapper/ast/node.goindex 30f465f334..86245a8eb1 100644--- a/backend/plugin/parser/mybatis/mapper/ast/node.go+++ b/backend/plugin/parser/mybatis/mapper/ast/node.go@@ -3,6 +3,7 @@ package astimport ("io"+ "sort")// Node is the interface implemented by all AST node types.@@ -23,6 +24,10 @@ type RestoreContext struct {// Variable is the map of variable, key is the name of the variable, value is the value of the variable.// It will be used to restore the ${} element.Variable map[string]string+ // SQLLastLineToOriginalLineMapping is the map of the last line number from SQL statement to the line number of the original SQL statement in Mybatis mapper xml.+ SQLLastLineToOriginalLineMapping map[int]int+ // CurrentLastLine is used for internal calculation.+ CurrentLastLine int}var (@@ -35,6 +40,12 @@ type RootNode struct {Children []Node}+// MybatisSQLLineMapping represents the line mapping of the SQL statement in Mybatis mapper xml.+type MybatisSQLLineMapping struct {+ SQLLastLine int+ OriginalEleLine int+}+// RestoreSQL implements Node interface.func (n *RootNode) RestoreSQL(ctx *RestoreContext, w io.Writer) error {for _, node := range n.Children {@@ -45,6 +56,27 @@ func (n *RootNode) RestoreSQL(ctx *RestoreContext, w io.Writer) error {return nil}+// RestoreSQLWithLineMapping restores the SQL statement and returns the sorted(SQL last line ascending) line mapping of the SQL statement in Mybatis mapper xml.+func (n *RootNode) RestoreSQLWithLineMapping(ctx *RestoreContext, w io.Writer) ([]*MybatisSQLLineMapping, error) {+ for _, node := range n.Children {+ if err := node.RestoreSQL(ctx, w); err != nil {+ return nil, err+ }+ }+ // building line mapping+ var lineMapping []*MybatisSQLLineMapping+ for sqlLastLine, originalEleLine := range ctx.SQLLastLineToOriginalLineMapping {+ lineMapping = append(lineMapping, &MybatisSQLLineMapping{+ SQLLastLine: sqlLastLine,+ OriginalEleLine: originalEleLine,+ })+ }+ sort.Slice(lineMapping, func(i, j int) bool {+ return lineMapping[i].SQLLastLine < lineMapping[j].SQLLastLine+ })+ return lineMapping, nil+}+// AddChild adds a child to the root node.func (n *RootNode) AddChild(child Node) {n.Children = append(n.Children, child)diff --git a/backend/plugin/parser/mybatis/mapper/ast/query_node.go b/backend/plugin/parser/mybatis/mapper/ast/query_node.goindex cdbd7c089f..3279a12453 100644--- a/backend/plugin/parser/mybatis/mapper/ast/query_node.go+++ b/backend/plugin/parser/mybatis/mapper/ast/query_node.go@@ -33,12 +33,13 @@ type QueryNode struct {Type QueryNodeType// Children is the children of the query node.Children []Node+ // Line is the line of the <select><update><delete><insert> tag.+ Line int}// RestoreSQL implements Node interface.func (n *QueryNode) RestoreSQL(ctx *RestoreContext, w io.Writer) error {var sb strings.Builder-for _, node := range n.Children {if err := node.RestoreSQL(ctx, &sb); err != nil {return err@@ -52,9 +53,16 @@ func (n *QueryNode) RestoreSQL(ctx *RestoreContext, w io.Writer) error {if _, err := w.Write([]byte(trimmed)); err != nil {return err}- if _, err := w.Write([]byte(";\n")); err != nil {+ if !strings.HasSuffix(trimmed, ";") {+ if _, err := w.Write([]byte(";")); err != nil {+ return err+ }+ }+ if _, err := w.Write([]byte("\n")); err != nil {return err}+ ctx.SQLLastLineToOriginalLineMapping[ctx.CurrentLastLine] = n.Line+ ctx.CurrentLastLine++return nil}@@ -77,7 +85,7 @@ func (*QueryNode) isChildAcceptable(child Node) bool {}// NewQueryNode creates a new query node.-func NewQueryNode(startEle *xml.StartElement) *QueryNode {+func NewQueryNode(startEle *xml.StartElement, line int) *QueryNode {n := &QueryNode{}switch startEle.Name.Local {case "select":@@ -95,5 +103,6 @@ func NewQueryNode(startEle *xml.StartElement) *QueryNode {n.ID = attr.Value}}+ n.Line = linereturn n}diff --git a/backend/plugin/parser/mybatis/mapper/parser.go b/backend/plugin/parser/mybatis/mapper/parser.goindex 1ab7e80de8..7314d51f0f 100644--- a/backend/plugin/parser/mybatis/mapper/parser.go+++ b/backend/plugin/parser/mybatis/mapper/parser.go@@ -16,7 +16,7 @@ type Parser struct {d *xml.Decoderbuf []runecursor uint- currentLine uint+ currentLine intsqlMap map[string]*ast.SQLNode}@@ -25,23 +25,26 @@ func NewParser(stmt string) *Parser {reader := strings.NewReader(stmt)d := xml.NewDecoder(reader)return &Parser{- d: d,- cursor: 0,- buf: nil,- sqlMap: make(map[string]*ast.SQLNode),+ d: d,+ cursor: 0,+ buf: nil,+ sqlMap: make(map[string]*ast.SQLNode),+ currentLine: 1,}}// GetRestoreContext returns the restore context.func (p *Parser) GetRestoreContext() *ast.RestoreContext {return &ast.RestoreContext{- SQLMap: p.sqlMap,- Variable: make(map[string]string),+ SQLMap: p.sqlMap,+ Variable: make(map[string]string),+ SQLLastLineToOriginalLineMapping: make(map[int]int),+ CurrentLastLine: 1,}}// Parse parses the mybatis mapper xml statements, building AST without recursion, returns the root node of the AST.-func (p *Parser) Parse() (ast.Node, error) {+func (p *Parser) Parse() (*ast.RootNode, error) {root := &ast.RootNode{}// To avoid recursion, we use stack to store the start element and node, and consume the token one by one.// The length of start element stack is always equal to the length of node stack - 1, because the root nod@@ -108,6 +111,18 @@ func (p *Parser) Parse() (ast.Node, error) {p.currentLine++}}+ case xml.Directive:+ for _, b := range ele {+ if b == '\n' {+ p.currentLine+++ }+ }+ case xml.ProcInst:+ for _, b := range ele.Inst {+ if b == '\n' {+ p.currentLine+++ }+ }}}}@@ -115,12 +130,12 @@ func (p *Parser) Parse() (ast.Node, error) {// newNodeByStartElement returns the node related to the startElement, for example, returns QueryNode for// start element which name is "select", "update", "insert", "delete". If the startElement is unacceptable,// returns an emptyNode instead.-func (*Parser) newNodeByStartElement(startElement *xml.StartElement) ast.Node {+func (p *Parser) newNodeByStartElement(startElement *xml.StartElement) ast.Node {switch startElement.Name.Local {case "mapper":return ast.NewMapperNode(startElement)case "select", "update", "insert", "delete":- return ast.NewQueryNode(startElement)+ return ast.NewQueryNode(startElement, p.currentLine)case "if":return ast.NewIfNode(startElement)case "choose":diff --git a/backend/plugin/parser/mybatis/mapper/parser_test.go b/backend/plugin/parser/mybatis/mapper/parser_test.goindex 259f59d278..9201571c2e 100644--- a/backend/plugin/parser/mybatis/mapper/parser_test.go+++ b/backend/plugin/parser/mybatis/mapper/parser_test.go@@ -10,6 +10,8 @@ import (pg_query "github.com/pganalyze/pg_query_go/v2""github.com/stretchr/testify/require""gopkg.in/yaml.v3"++ "github.com/bytebase/bytebase/backend/plugin/parser/mybatis/mapper/ast")// TestData is the test data for mybatis parser. It contains the xml and the expected sql.@@ -71,3 +73,54 @@ func TestParser(t *testing.T) {runTest(t, filepath, false)}}++func TestRestoreWithLineMapping(t *testing.T) {+ testCases := []struct {+ xml string+ sql string+ lineMapping []*ast.MybatisSQLLineMapping+ }{+ {+ xml: `<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">+<mapper namespace="com.bytebase.test">+ <sql id="sometable">+ ${prefix}Table+ </sql>+ <sql id="someinclude">+ from+ <include refid="${include_target}"/>+ </sql>+ <select id="select" resultType="map">+ select+ field1, field2, field3+ <include refid="someinclude">+ <property name="prefix" value="Some"/>+ <property name="include_target" value="sometable"/>+ </include>+ </select>+</mapper>+ `,+ sql: `select+ field1, field2, field3 from SomeTable;+`,+ lineMapping: []*ast.MybatisSQLLineMapping{+ {+ SQLLastLine: 2,+ OriginalEleLine: 11,+ },+ },+ },+ }+ for _, tc := range testCases {+ parser := NewParser(tc.xml)+ node, err := parser.Parse()+ require.NoError(t, err)+ require.NotNil(t, node)+ var sb strings.Builder+ lineMapping, err := node.RestoreSQLWithLineMapping(parser.GetRestoreContext(), &sb)+ require.NoError(t, err)+ require.Equal(t, tc.sql, sb.String())+ require.Equal(t, tc.lineMapping, lineMapping)+ }+}diff --git a/backend/plugin/parser/mybatis/mapper/test-data/test_dynamic_sql_mapper.yaml b/backend/plugin/parser/mybatis/mapper/test-data/test_dynamic_sql_mapper.yamlindex dad044d3b1..90184bebc0 100644--- a/backend/plugin/parser/mybatis/mapper/test-data/test_dynamic_sql_mapper.yaml+++ b/backend/plugin/parser/mybatis/mapper/test-data/test_dynamic_sql_mapper.yaml@@ -245,3 +245,44 @@sql: |selectfield1, field2, field3 from SomeTable;+- xml: |-+ <mapper namespace="com.bytebase.test">+ <sql id="sometable">+ ${prefix}Table+ </sql>+ <sql id="someinclude">+ FROM+ <include refid="${include_target}"/>+ </sql>+ <select id="selectUsers" parameterType="int" resultType="hashmap">+ SELECT * FROM users;+ </select>+ <select id="selectSuccess" resultType="map">+ SELECT * FROM users+ <where>+ <if test="id != null">+ AND id = #{id}+ </if>+ <if test="name != null">+ AND name = #{name}+ </if>+ </where>+ </select>+ <insert id="insert">+ INSERT INTO users (id, name) VALUES (#{id}, #{name})+ </insert>+ <select id="select" resultType="map">+ SELECT+ *+ <include refid="someinclude">+ <property name="prefix" value="Some"/>+ <property name="include_target" value="sometable"/>+ </include>+ </select>+ </mapper>+ sql: |+ SELECT * FROM users;+ SELECT * FROM users WHERE id = ? AND name = ?;+ INSERT INTO users (id, name) VALUES (?, ?);+ SELECT+ * FROM SomeTable;diff --git a/backend/server/webhook.go b/backend/server/webhook.goindex 14ec0a6ff7..16f5db44ee 100644--- a/backend/server/webhook.go+++ b/backend/server/webhook.go@@ -34,6 +34,7 @@ import ("github.com/bytebase/bytebase/backend/plugin/db"configparser "github.com/bytebase/bytebase/backend/plugin/parser/mybatis/configuration"mapperparser "github.com/bytebase/bytebase/backend/plugin/parser/mybatis/mapper"+ "github.com/bytebase/bytebase/backend/plugin/parser/mybatis/mapper/ast""github.com/bytebase/bytebase/backend/plugin/vcs""github.com/bytebase/bytebase/backend/plugin/vcs/bitbucket""github.com/bytebase/bytebase/backend/plugin/vcs/github"@@ -574,7 +575,7 @@ func (s *Server) sqlAdviceForMybatisMapperFile(ctx context.Context, datum *mybatreturn nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to get empty catalog").SetInternal(err)}- mybatisSQLs, err := extractMybatisMapperSQL(datum.mapperContent)+ mybatisSQLs, lineMapping, err := extractMybatisMapperSQL(datum.mapperContent)if err != nil {return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to extract mybatis mapper sql").SetInternal(err)}@@ -590,7 +591,16 @@ func (s *Server) sqlAdviceForMybatisMapperFile(ctx context.Context, datum *mybatif err != nil {return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to check sql review").SetInternal(err)}- result = append(result, adviceList...)+ // Remap the line number to the original file.+ for _, advice := range adviceList {+ for _, line := range lineMapping {+ if advice.Line <= line.SQLLastLine {+ advice.Line = line.OriginalEleLine+ break+ }+ }+ result = append(result, advice)+ }}if len(result) == 0 {return []advisor.Advice{@@ -1882,18 +1892,18 @@ func extractDBTypeFromJDBCConnectionString(jdbcURL string) (db.Type, error) {}// extractMybatisMapperSQL will extract the SQL from mybatis mapper XML.-func extractMybatisMapperSQL(mapperContent string) (string, error) {+func extractMybatisMapperSQL(mapperContent string) (string, []*ast.MybatisSQLLineMapping, error) {mybatisMapperParser := mapperparser.NewParser(mapperContent)mybatisMapperNode, err := mybatisMapperParser.Parse()if err != nil {- return "", errors.Wrapf(err, "failed to parse mybatis mapper xml")+ return "", nil, errors.Wrapf(err, "failed to parse mybatis mapper xml")}var sb strings.Builder- err = mybatisMapperNode.RestoreSQL(mybatisMapperParser.GetRestoreContext(), &sb)+ lineMapping, err := mybatisMapperNode.RestoreSQLWithLineMapping(mybatisMapperParser.GetRestoreContext(), &sb)if err != nil {- return "", errors.Wrapf(err, "failed to restore mybatis mapper xml")+ return "", nil, errors.Wrapf(err, "failed to restore mybatis mapper xml")}- return sb.String(), nil+ return sb.String(), lineMapping, nil}// mybatisMapperXMLFileDatum is the metadata of mybatis mapper XML file.