Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(mybatis): support gitops sql-review for mybatis (#5911)
h3n4l996a14b2e4de
diff --git a/backend/plugin/parser/mybatis/configuration/parser.go b/backend/plugin/parser/mybatis/configuration/parser.gonew file mode 100644index 0000000000..f6696b3c1c--- /dev/null+++ b/backend/plugin/parser/mybatis/configuration/parser.go@@ -0,0 +1,81 @@+// Package configuration provides the parser for mybatis configuration xml file.+package configuration++import (+ "encoding/xml"+ "io"+ "strings"++ "github.com/pkg/errors"+)++// Configuration is the root element of mybatis configuration xml file.+type Configuration struct {+ Environments []Environment+}++// Environment is the element of environments in mybatis configuration xml file.+type Environment struct {+ ID string+ JDBCConnString string+}++// ParseConfiguration parses the mybatis configuration xml file likes below:+//+// <configuration>+//+// <environments default="development">+// <environment id="development">+// ...+// </environment>+// <environment id="test">+// ...+// </environment>+// </environments>+//+// </configuration>.+func ParseConfiguration(configurationXML string) (*Configuration, error) {+ type Environments struct {+ Environment []struct {+ ID string `xml:"id,attr"`+ Properties []struct {+ Name string `xml:"name,attr"`+ Value string `xml:"value,attr"`+ } `xml:"dataSource>property"`+ } `xml:"environment"`+ }++ reader := strings.NewReader(configurationXML)+ d := xml.NewDecoder(reader)+ for {+ token, err := d.Token()+ if err != nil {+ if err == io.EOF {+ return nil, nil+ }+ return nil, errors.Wrapf(err, "failed to read token")+ }+ switch t := token.(type) {+ case xml.StartElement:+ if t.Name.Local == "environments" {+ var environments Environments+ if err := d.DecodeElement(&environments, &t); err != nil {+ return nil, errors.Wrapf(err, "failed to decode environments")+ }+ var conf Configuration+ for _, environment := range environments.Environment {+ for _, property := range environment.Properties {+ if property.Name == "url" {+ conf.Environments = append(conf.Environments, Environment{+ ID: environment.ID,+ JDBCConnString: property.Value,+ })+ }+ }+ }+ return &conf, nil+ }+ default:+ }+ }+}diff --git a/backend/plugin/parser/mybatis/configuration/parser_test.go b/backend/plugin/parser/mybatis/configuration/parser_test.gonew file mode 100644index 0000000000..77b1c6ca12--- /dev/null+++ b/backend/plugin/parser/mybatis/configuration/parser_test.go@@ -0,0 +1,65 @@+package configuration++import (+ "testing"++ "github.com/stretchr/testify/require"+)++func TestExtractEnvironmentIDs(t *testing.T) {+ testCases := []struct {+ configuration string+ want *Configuration+ }{+ {+ configuration: `+<?xml version="1.0" encoding="UTF-8" ?>+<!DOCTYPE configuration+ PUBLIC "-//mybatis.org//DTD Config 3.0//EN"+ "https://mybatis.org/dtd/mybatis-3-config.dtd">+<configuration>+ <environments default="prod">+ <environment id="prod">+ <transactionManager type="JDBC"/>+ <dataSource type="POOLED">+ <property name="driver" value="${driver}"/>+ <property name="url" value="jdbc:mysql://localhost:3306/test"/>+ <property name="username" value="${username}"/>+ <property name="password" value="${password}"/>+ </dataSource>+ </environment>+ <environment id="test">+ <transactionManager type="JDBC"/>+ <dataSource type="POOLED">+ <property name="driver" value="${driver}"/>+ <property name="url" value="jdbc:mysql://localhost:3306/test"/>+ <property name="username" value="${username}"/>+ <property name="password" value="${password}"/>+ </dataSource>+ </environment>+ </environments>+ <mappers>+ <mapper resource="org/mybatis/example/BlogMapper.xml"/>+ </mappers>+</configuration>+`,+ want: &Configuration{+ Environments: []Environment{+ {+ ID: "prod",+ JDBCConnString: "jdbc:mysql://localhost:3306/test",+ },+ {+ ID: "test",+ JDBCConnString: "jdbc:mysql://localhost:3306/test",+ },+ },+ },+ },+ }+ for _, tc := range testCases {+ got, err := ParseConfiguration(tc.configuration)+ require.NoError(t, err)+ require.Equal(t, tc.want, got)+ }+}diff --git a/backend/plugin/parser/mybatis/ast/data_node.go b/backend/plugin/parser/mybatis/mapper/ast/data_node.gosimilarity index 100%rename from backend/plugin/parser/mybatis/ast/data_node.gorename to backend/plugin/parser/mybatis/mapper/ast/data_node.godiff --git a/backend/plugin/parser/mybatis/ast/dymamic_node.go b/backend/plugin/parser/mybatis/mapper/ast/dymamic_node.gosimilarity index 100%rename from backend/plugin/parser/mybatis/ast/dymamic_node.gorename to backend/plugin/parser/mybatis/mapper/ast/dymamic_node.godiff --git a/backend/plugin/parser/mybatis/ast/mapper_node.go b/backend/plugin/parser/mybatis/mapper/ast/mapper_node.gosimilarity index 100%rename from backend/plugin/parser/mybatis/ast/mapper_node.gorename to backend/plugin/parser/mybatis/mapper/ast/mapper_node.godiff --git a/backend/plugin/parser/mybatis/ast/node.go b/backend/plugin/parser/mybatis/mapper/ast/node.gosimilarity index 100%rename from backend/plugin/parser/mybatis/ast/node.gorename to backend/plugin/parser/mybatis/mapper/ast/node.godiff --git a/backend/plugin/parser/mybatis/ast/query_node.go b/backend/plugin/parser/mybatis/mapper/ast/query_node.gosimilarity index 100%rename from backend/plugin/parser/mybatis/ast/query_node.gorename to backend/plugin/parser/mybatis/mapper/ast/query_node.godiff --git a/backend/plugin/parser/mybatis/parser.go b/backend/plugin/parser/mybatis/mapper/parser.gosimilarity index 96%rename from backend/plugin/parser/mybatis/parser.gorename to backend/plugin/parser/mybatis/mapper/parser.goindex 18e2c5edaa..1ab7e80de8 100644--- a/backend/plugin/parser/mybatis/parser.go+++ b/backend/plugin/parser/mybatis/mapper/parser.go@@ -1,5 +1,5 @@-// Package mybatis defines the sql extractor for mybatis mapper xml.-package mybatis+// Package mapper defines the sql extractor for mybatis mapper xml.+package mapperimport ("encoding/xml"@@ -8,7 +8,7 @@ import ("github.com/pkg/errors"- "github.com/bytebase/bytebase/backend/plugin/parser/mybatis/ast"+ "github.com/bytebase/bytebase/backend/plugin/parser/mybatis/mapper/ast")// Parser is the mybatis mapper xml parser.diff --git a/backend/plugin/parser/mybatis/parser_test.go b/backend/plugin/parser/mybatis/mapper/parser_test.gosimilarity index 95%rename from backend/plugin/parser/mybatis/parser_test.gorename to backend/plugin/parser/mybatis/mapper/parser_test.goindex f626a82224..259f59d278 100644--- a/backend/plugin/parser/mybatis/parser_test.go+++ b/backend/plugin/parser/mybatis/mapper/parser_test.go@@ -1,5 +1,5 @@-// Package mybatis defines the sql extractor for mybatis mapper xml.-package mybatis+// Package mapper defines the sql extractor for mybatis mapper xml.+package mapperimport ("io"diff --git a/backend/plugin/parser/mybatis/test-data/test_dynamic_sql_mapper.yaml b/backend/plugin/parser/mybatis/mapper/test-data/test_dynamic_sql_mapper.yamlsimilarity index 100%rename from backend/plugin/parser/mybatis/test-data/test_dynamic_sql_mapper.yamlrename to backend/plugin/parser/mybatis/mapper/test-data/test_dynamic_sql_mapper.yamldiff --git a/backend/plugin/parser/mybatis/test-data/test_simple_mapper.yaml b/backend/plugin/parser/mybatis/mapper/test-data/test_simple_mapper.yamlsimilarity index 100%rename from backend/plugin/parser/mybatis/test-data/test_simple_mapper.yamlrename to backend/plugin/parser/mybatis/mapper/test-data/test_simple_mapper.yamldiff --git a/backend/server/webhook.go b/backend/server/webhook.goindex ffb5caee31..14ec0a6ff7 100644--- a/backend/server/webhook.go+++ b/backend/server/webhook.go@@ -11,8 +11,10 @@ import ("io""net/http""net/mail"+ "net/url""path""path/filepath"+ "regexp""sort""strings""sync"@@ -30,6 +32,8 @@ import ("github.com/bytebase/bytebase/backend/plugin/advisor"advisorDB "github.com/bytebase/bytebase/backend/plugin/advisor/db""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/vcs""github.com/bytebase/bytebase/backend/plugin/vcs/bitbucket""github.com/bytebase/bytebase/backend/plugin/vcs/github"@@ -343,6 +347,8 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusInternalServerError, err.Error())}+ token := c.Request().Header.Get("X-SQL-Review-Token")+filter := func(repo *api.Repository) (bool, error) {if !repo.EnableSQLReviewCI {log.Debug("Skip repository as the SQL review CI is not enabled.",@@ -360,13 +366,12 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {return false, nil}- token := c.Request().Header.Get("X-SQL-Review-Token")// We will use workspace id as token in integration test for skipping the check.if token == workspaceID {return true, nil}- return c.Request().Header.Get("X-SQL-Review-Token") == repo.WebhookSecretToken, nil+ return token == repo.WebhookSecretToken, nil}repositoryList, err := s.filterRepository(ctx, c.Param("id"), request.RepositoryID, filter)@@ -380,8 +385,8 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {Content: []string{},})}-repo := repositoryList[0]+prFiles, err := vcs.Get(repo.VCS.Type, vcs.ProviderConfig{}).ListPullRequestFile(ctx,common.OauthContext{@@ -399,60 +404,66 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to list pull request file").SetInternal(err)}- distinctFileList := []vcs.DistinctFileItem{}+ sqlFileName2Advice := s.sqlAdviceForSQLFiles(ctx, repositoryList, prFiles, setting.ExternalUrl)++ // If the commit file list contains the file which extension is xml and the content+ // contains "https://mybatis.org/dtd/mybatis-3-mapper.dtd", we will try to apply+ // sql-review to it.+ // To apply sql-review to it, proceed as follows:+ // 1. Look in the sibling and parent directories for directories containing similar+ // <!DOCTYPE configuration+ // PUBLIC "-//mybatis.org//DTD Config 3.0//EN"+ // "https://mybatis.org/dtd/mybatis-3-config.dtd">+ // of the xml file+ // 2. If we can find it, then we will extract the sql from the mapper xml+ // 3. match the environments in the configuration xml, look for the sql-review policy in the environment and apply it.+ var isMybatisMapperXMLRegex = regexp.MustCompile(`(?i)http(s)?://mybatis.org/dtd/mybatis-3-mapper.dtd`)++ mybatisMapperXMLFiles := make(map[string]string)+ var commitID stringfor _, prFile := range prFiles {- if prFile.IsDeleted {+ if !strings.HasSuffix(prFile.Path, ".xml") {continue}- distinctFileList = append(distinctFileList, vcs.DistinctFileItem{- FileName: prFile.Path,- Commit: vcs.Commit{- ID: prFile.LastCommitID,+ fileContent, err := vcs.Get(repo.VCS.Type, vcs.ProviderConfig{}).ReadFileContent(+ ctx,+ common.OauthContext{+ ClientID: repo.VCS.ApplicationID,+ ClientSecret: repo.VCS.Secret,+ AccessToken: repo.AccessToken,+ RefreshToken: repo.RefreshToken,+ Refresher: utils.RefreshToken(ctx, s.store, repo.WebURL),},- })+ repo.VCS.InstanceURL,+ repo.ExternalID,+ prFile.Path,+ prFile.LastCommitID,+ )+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to read file content").SetInternal(err)+ }+ if !isMybatisMapperXMLRegex.MatchString(fileContent) {+ continue+ }+ mybatisMapperXMLFiles[prFile.Path] = fileContent+ commitID = prFile.LastCommitID}-- sqlCheckAdvice := map[string][]advisor.Advice{}- var wg sync.WaitGroup-- repoID2FileItemList := groupFileInfoByRepo(distinctFileList, repositoryList)- for _, fileInfoListInRepo := range repoID2FileItemList {- for _, file := range fileInfoListInRepo {- wg.Add(1)- go func(file fileInfo) {- defer wg.Done()- adviceList, err := s.sqlAdviceForFile(ctx, file, setting.ExternalUrl)- if err != nil {- log.Error(- "Failed to take SQL review for file",- zap.String("file", file.item.FileName),- zap.String("external_id", file.repository.ExternalID),- zap.Error(err),- )- sqlCheckAdvice[file.item.FileName] = []advisor.Advice{- {- Status: advisor.Warn,- Code: advisor.Internal,- Title: "Failed to take SQL review",- Content: fmt.Sprintf("Failed to take SQL review for file %s with error %v", file.item.FileName, err),- Line: 1,- },- }- } else if adviceList != nil {- sqlCheckAdvice[file.item.FileName] = adviceList- }- }(file)+ if len(mybatisMapperXMLFiles) > 0 {+ mapperAdvices, err := s.sqlAdviceForMybatisMapperFiles(ctx, mybatisMapperXMLFiles, commitID, repo)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to get sql advice for mybatis mapper files").SetInternal(err)+ }+ for filename, mapperAdvice := range mapperAdvices {+ sqlFileName2Advice[filename] = mapperAdvice}}- wg.Wait()-response := &api.VCSSQLReviewResult{}switch repo.VCS.Type {case vcs.GitHub:- response = convertSQLAdviceToGitHubActionResult(sqlCheckAdvice)+ response = convertSQLAdviceToGitHubActionResult(sqlFileName2Advice)case vcs.GitLab:- response = convertSQLAdviceToGitLabCIResult(sqlCheckAdvice)+ response = convertSQLAdviceToGitLabCIResult(sqlFileName2Advice)}log.Debug("SQL review finished",@@ -467,6 +478,186 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {})}+func (s *Server) sqlAdviceForMybatisMapperFiles(ctx context.Context, mybatisMapperContent map[string]string, commitID string, repo *api.Repository) (map[string][]advisor.Advice, error) {+ if len(mybatisMapperContent) == 0 {+ return map[string][]advisor.Advice{}, nil+ }+ if commitID == "" {+ return nil, errors.Errorf("Unexpected empty commit id")+ }++ sqlCheckAdvices := make(map[string][]advisor.Advice)+ mybatisMapperXMLFileData, err := s.buildMybatisMapperXMLFileData(ctx, repo, commitID, mybatisMapperContent)+ if err != nil {+ return nil, errors.Wrapf(err, "Failed to build mybatis mapper xml file data")+ }+ var wg sync.WaitGroup+ for _, mybatisMapperXMLFile := range mybatisMapperXMLFileData {+ log.Debug("Mybatis mapper xml file data",+ zap.String("mapper file", mybatisMapperXMLFile.mapperPath),+ zap.String("config file", mybatisMapperXMLFile.configPath),+ )+ if mybatisMapperXMLFile.configContent == "" {+ continue+ }+ wg.Add(1)+ go func(datum *mybatisMapperXMLFileDatum) {+ defer wg.Done()+ adviceList, err := s.sqlAdviceForMybatisMapperFile(ctx, datum)+ if err != nil {+ log.Error(+ "Failed to take SQL review for file",+ zap.String("file", datum.mapperContent),+ zap.String("repository", repo.WebURL),+ zap.Error(err),+ )+ sqlCheckAdvices[datum.configPath] = []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.Internal,+ Title: "Failed to take SQL review",+ Content: fmt.Sprintf("Failed to take SQL review for file %s with error %v", datum.mapperPath, err),+ Line: 1,+ },+ }+ } else if len(adviceList) > 0 {+ sqlCheckAdvices[datum.mapperPath] = adviceList+ }+ }(mybatisMapperXMLFile)+ }+ wg.Wait()++ return sqlCheckAdvices, nil+}++func (s *Server) sqlAdviceForMybatisMapperFile(ctx context.Context, datum *mybatisMapperXMLFileDatum) ([]advisor.Advice, error) {+ var result []advisor.Advice+ var environmentIDs []string+ // If the configuration file is found, we extract the environment from the configuration file.+ conf, err := configparser.ParseConfiguration(datum.configContent)+ if err != nil {+ return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to extract environment ids").SetInternal(err)+ }++ for _, confEnv := range conf.Environments {+ environmentIDs = append(environmentIDs, confEnv.ID)+ environment, err := s.store.GetEnvironmentV2(ctx, &store.FindEnvironmentMessage{+ ResourceID: &confEnv.ID,+ })+ if err != nil {+ return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to get environment").SetInternal(err)+ }+ if environment == nil {+ continue+ }+ // If the environment is found, we extract the sql-review policy from the environment.+ policy, err := s.store.GetSQLReviewPolicy(ctx, environment.UID)+ if err != nil {+ if e, ok := err.(*common.Error); ok && e.Code == common.NotFound {+ log.Debug("Cannot found SQL review policy in environment", zap.String("Environment", confEnv.ID), zap.Error(err))+ continue+ }+ return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to get SQL review policy").SetInternal(err)+ }+ if policy == nil {+ continue+ }+ engineType, err := extractDBTypeFromJDBCConnectionString(confEnv.JDBCConnString)+ if err != nil {+ return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to extract db type").SetInternal(err)+ }+ if engineType == db.UnknownType {+ continue+ }+ emptyCatalog, err := store.NewEmptyCatalog(engineType)+ if err != nil {+ return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to get empty catalog").SetInternal(err)+ }++ mybatisSQLs, err := extractMybatisMapperSQL(datum.mapperContent)+ if err != nil {+ return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to extract mybatis mapper sql").SetInternal(err)+ }++ dbType, err := advisorDB.ConvertToAdvisorDBType(string(engineType))+ if err != nil {+ return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to convert to advisor db type").SetInternal(err)+ }+ adviceList, err := advisor.SQLReviewCheck(mybatisSQLs, policy.RuleList, advisor.SQLReviewCheckContext{+ Catalog: emptyCatalog,+ DbType: dbType,+ })+ if err != nil {+ return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to check sql review").SetInternal(err)+ }+ result = append(result, adviceList...)+ }+ if len(result) == 0 {+ return []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.NotFound,+ Title: fmt.Sprintf("SQL review policy not found for environment %s", strings.Join(environmentIDs, ",")),+ // TODO(zp): add link to doc.+ Content: "check doc for details.",+ Line: 1,+ },+ }, nil+ }+ return result, nil+}++func (s *Server) sqlAdviceForSQLFiles(ctx context.Context, repositoryList []*api.Repository, prFiles []*vcs.PullRequestFile, externalURL string) map[string][]advisor.Advice {+ distinctFileList := []vcs.DistinctFileItem{}+ for _, prFile := range prFiles {+ if prFile.IsDeleted {+ continue+ }+ distinctFileList = append(distinctFileList, vcs.DistinctFileItem{+ FileName: prFile.Path,+ Commit: vcs.Commit{+ ID: prFile.LastCommitID,+ },+ })+ }++ sqlCheckAdvice := map[string][]advisor.Advice{}+ var wg sync.WaitGroup++ repoID2FileItemList := groupFileInfoByRepo(distinctFileList, repositoryList)++ for _, fileInfoListInRepo := range repoID2FileItemList {+ for _, file := range fileInfoListInRepo {+ wg.Add(1)+ go func(file fileInfo) {+ defer wg.Done()+ adviceList, err := s.sqlAdviceForFile(ctx, file, externalURL)+ if err != nil {+ log.Error(+ "Failed to take SQL review for file",+ zap.String("file", file.item.FileName),+ zap.String("external_id", file.repository.ExternalID),+ zap.Error(err),+ )+ sqlCheckAdvice[file.item.FileName] = []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.Internal,+ Title: "Failed to take SQL review",+ Content: fmt.Sprintf("Failed to take SQL review for file %s with error %v", file.item.FileName, err),+ Line: 1,+ },+ }+ } else if adviceList != nil {+ sqlCheckAdvice[file.item.FileName] = adviceList+ }+ }(file)+ }+ }+ wg.Wait()+ return sqlCheckAdvice+}+func (s *Server) sqlAdviceForFile(ctx context.Context,fileInfo fileInfo,@@ -495,7 +686,7 @@ func (s *Server) sqlAdviceForFile(databases, err := s.findProjectDatabases(ctx, fileInfo.repository.ProjectID, fileInfo.migrationInfo.Database, fileInfo.migrationInfo.Environment)if err != nil {log.Debug(- "Failed to list databse migration info",+ "Failed to list database migration info",zap.Int("project", fileInfo.repository.ProjectID),zap.String("database", fileInfo.migrationInfo.Database),zap.String("environment", fileInfo.migrationInfo.Environment),@@ -1671,3 +1862,148 @@ func filterBitbucketBytebaseCommit(list []bitbucket.WebhookCommit) []bitbucket.W}return result}++// extractDBTypeFromJDBCConnectionString will extract the DB type from JDBC connection string. Only support MySQL and Postgres for now.+// It will return UnknownType if the DB type is not supported, and returns error if cannot parse the JDBC connection string.+func extractDBTypeFromJDBCConnectionString(jdbcURL string) (db.Type, error) {+ trimmed := strings.TrimPrefix(strings.TrimSpace(jdbcURL), "jdbc:")+ u, err := url.Parse(trimmed)+ if err != nil {+ return db.UnknownType, err+ }++ switch {+ case strings.HasPrefix(u.Scheme, "mysql"):+ return db.MySQL, nil+ case strings.HasPrefix(u.Scheme, "postgresql"):+ return db.Postgres, nil+ }+ return db.UnknownType, nil+}++// extractMybatisMapperSQL will extract the SQL from mybatis mapper XML.+func extractMybatisMapperSQL(mapperContent string) (string, error) {+ mybatisMapperParser := mapperparser.NewParser(mapperContent)+ mybatisMapperNode, err := mybatisMapperParser.Parse()+ if err != nil {+ return "", errors.Wrapf(err, "failed to parse mybatis mapper xml")+ }+ var sb strings.Builder+ err = mybatisMapperNode.RestoreSQL(mybatisMapperParser.GetRestoreContext(), &sb)+ if err != nil {+ return "", errors.Wrapf(err, "failed to restore mybatis mapper xml")+ }+ return sb.String(), nil+}++// mybatisMapperXMLFileDatum is the metadata of mybatis mapper XML file.+// It maintains the mybatis mapper XML file path, mapper XML file content, and the corresponding mybatis configuration XML content.+type mybatisMapperXMLFileDatum struct {+ // mapperPath is the git ls-tree syntax filepath of the mybatis mapper XML file.+ mapperPath string+ // mapperContent is the content of the mybatis mapper XML file.+ mapperContent string+ // configPath is the git ls-tree syntax filepath of the mybatis configuration XML file,+ // it is empty if the mybatis configuration XML file is not found.+ configPath string+ // configContent is the content of the mybatis configuration XML file,+ // it is empty if the mybatis configuration XML file is not found.+ configContent string+}++// buildMybatisMapperXMLFileData will build the mybatis mapper XML file data.+//+// ctx: the context.+// repo: the repository will be list file tree and get file content from.+// commitID: the commitID is the snapshot of the file tree and file content.+// mapperFiles: the map of the mybatis mapper XML file path and content.+func (s *Server) buildMybatisMapperXMLFileData(ctx context.Context, repo *api.Repository, commitID string, mapperFiles map[string]string) ([]*mybatisMapperXMLFileDatum, error) {+ if len(mapperFiles) == 0 {+ return []*mybatisMapperXMLFileDatum{}, nil+ }++ var mybatisMapperXMLFileData []*mybatisMapperXMLFileDatum+ // isMybatisConfigXMLRegex is the regex to match the mybatis configuration XML file, if it can match the file content,+ // we regard the file as the mybatis configuration XML file.+ var isMybatisConfigXMLRegex = regexp.MustCompile(`(?i)http(s)?://mybatis.org/dtd/mybatis-3-config.dtd`)+ // configPathCache is the cache of the mybatis configuration XML file directory,+ // the key is the mybatis mapper XML file ls-tree syntax directory, and value is the mybatis configuration XML file ls-tree syntax path.+ configPathCache := make(map[string]string)+ // configCache is the cache of the mybatis configuration XML file content,+ // the key is the mybatis configuration XML file ls-tree syntax path, and value is the mybatis configuration XML file content.+ // each value is configPathCache must be the key of configCache.+ configCache := make(map[string]string)++ for mapperFilePath, mapperFileContent := range mapperFiles {+ configPath := mapperFilePath+ datum := &mybatisMapperXMLFileDatum{+ mapperPath: mapperFilePath,+ mapperContent: mapperFileContent,+ }+ for {+ currentDir := filepath.Dir(configPath)+ // git ls-tree syntax filepath didn't support '.', so we need to replace it with "" to represent the root directory.+ if currentDir == "." {+ currentDir = ""+ }+ if configPath, ok := configPathCache[currentDir]; ok {+ datum.configPath = configPath+ datum.configContent = configCache[configPath]+ break+ }++ filesInDir, err := vcs.Get(repo.VCS.Type, vcs.ProviderConfig{}).FetchRepositoryFileList(+ ctx,+ common.OauthContext{+ ClientID: repo.VCS.ApplicationID,+ ClientSecret: repo.VCS.Secret,+ AccessToken: repo.AccessToken,+ RefreshToken: repo.RefreshToken,+ Refresher: utils.RefreshToken(ctx, s.store, repo.WebURL),+ },+ repo.VCS.InstanceURL,+ repo.ExternalID,+ commitID,+ currentDir,+ )+ if err != nil {+ return nil, errors.Wrapf(err, "failed to fetch repository file list for repository %q commitID %q directory %q", repo.WebURL, commitID, currentDir)+ }++ for _, file := range filesInDir {+ if file.Type != "blob" || !strings.HasSuffix(file.Path, ".xml") {+ continue+ }+ fileContent, err := vcs.Get(repo.VCS.Type, vcs.ProviderConfig{}).ReadFileContent(+ ctx,+ common.OauthContext{+ ClientID: repo.VCS.ApplicationID,+ ClientSecret: repo.VCS.Secret,+ AccessToken: repo.AccessToken,+ RefreshToken: repo.RefreshToken,+ Refresher: utils.RefreshToken(ctx, s.store, repo.WebURL),+ },+ repo.VCS.InstanceURL,+ repo.ExternalID,+ file.Path,+ commitID,+ )+ if err != nil {+ return nil, errors.Wrapf(err, "failed to read file content for repository %q commitID %q file %q", repo.WebURL, commitID, file.Path)+ }+ if !isMybatisConfigXMLRegex.MatchString(fileContent) {+ continue+ }+ configPathCache[currentDir] = file.Path+ configCache[file.Path] = fileContent+ datum.configPath = file.Path+ datum.configContent = fileContent+ }+ if currentDir == "" {+ break+ }+ }+ mybatisMapperXMLFileData = append(mybatisMapperXMLFileData, datum)+ }+ return mybatisMapperXMLFileData, nil+}diff --git a/backend/server/webhook_test.go b/backend/server/webhook_test.goindex 635c5b6cf9..6689769b9b 100644--- a/backend/server/webhook_test.go+++ b/backend/server/webhook_test.go@@ -338,3 +338,30 @@ func TestGetFileInfo(t *testing.T) {require.EqualError(t, err, "file change should be associated with exactly one project but found project-1, project-2")})}++func TestExtractDBTypeFromJDBCConnectionString(t *testing.T) {+ testCases := []struct {+ jdbcConnectionString string+ want db.Type+ wantErr bool+ }{+ {+ jdbcConnectionString: "jdbc:mysql://localhost:3306/bytebase?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC",+ want: db.MySQL,+ },+ {+ jdbcConnectionString: "jdbc:mysql+srv+loadbalance://localhost:3306/bytebase?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC",+ want: db.MySQL,+ },+ {+ jdbcConnectionString: "jdbc:postgresql://localhost:5432/bytebase?currentSchema=public&sslmode=disable",+ want: db.Postgres,+ },+ }++ for _, tc := range testCases {+ dbType, err := extractDBTypeFromJDBCConnectionString(tc.jdbcConnectionString)+ require.NoError(t, err)+ assert.Equal(t, tc.want, dbType)+ }+}diff --git a/backend/store/catalog.go b/backend/store/catalog.goindex ac0b8c40ff..b2a542e2c9 100644--- a/backend/store/catalog.go+++ b/backend/store/catalog.go@@ -22,16 +22,15 @@ type Catalog struct {func (s *Store) NewCatalog(ctx context.Context, databaseID int, engineType db.Type, syntaxMode advisor.SyntaxMode) (catalog.Catalog, error) {c := &Catalog{}+ if syntaxMode == advisor.SyntaxModeSDL {+ return NewEmptyCatalog(engineType)+ }+dbType, err := advisorDB.ConvertToAdvisorDBType(string(engineType))if err != nil {return nil, err}- if syntaxMode == advisor.SyntaxModeSDL {- c.Finder = catalog.NewEmptyFinder(&catalog.FinderContext{CheckIntegrity: true, EngineType: dbType})- return c, nil- }-databaseMeta, err := s.GetDBSchema(ctx, databaseID)if err != nil {return nil, err@@ -48,3 +47,15 @@ func (s *Store) NewCatalog(ctx context.Context, databaseID int, engineType db.Tyfunc (c *Catalog) GetFinder() *catalog.Finder {return c.Finder}++// NewEmptyCatalog creates a new empty database catalog.+func NewEmptyCatalog(engineType db.Type) (catalog.Catalog, error) {+ dbType, err := advisorDB.ConvertToAdvisorDBType(string(engineType))+ if err != nil {+ return nil, err+ }++ return &Catalog{+ catalog.NewEmptyFinder(&catalog.FinderContext{CheckIntegrity: false, EngineType: dbType}),+ }, nil+}