Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: move mysql fingerprint
d-bytebase276787ddb27a
diff --git a/backend/plugin/db/mysql/sync.go b/backend/plugin/db/mysql/sync.goindex c7dd9fe0d8..b2ff067806 100644--- a/backend/plugin/db/mysql/sync.go+++ b/backend/plugin/db/mysql/sync.go@@ -22,6 +22,7 @@ import ("github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/plugin/db""github.com/bytebase/bytebase/backend/plugin/db/util"+ mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"parser "github.com/bytebase/bytebase/backend/plugin/parser/sql"storepb "github.com/bytebase/bytebase/proto/generated-go/store")@@ -621,7 +622,7 @@ func analyzeSlowLog(logs []*slowLog) (map[string]*storepb.SlowQueryStatistics, efor _, log := range logs {databaseList := extractDatabase(log.database, log.details.SqlText)- fingerprint, err := parser.GetSQLFingerprint(parser.MySQL, log.details.SqlText)+ fingerprint, err := mysqlparser.GetFingerprint(log.details.SqlText)if err != nil {return nil, errors.Wrapf(err, "get sql fingerprint failed, sql: %s", log.details.SqlText)}diff --git a/backend/plugin/parser/mysql/fingerprint.go b/backend/plugin/parser/mysql/fingerprint.gonew file mode 100644index 0000000000..1a03d8cc42--- /dev/null+++ b/backend/plugin/parser/mysql/fingerprint.go@@ -0,0 +1,170 @@+package mysql++import (+ "bytes"+ "regexp"+ "strings"++ "github.com/pkg/errors"+)++// GetFingerprint gets mysql query fingerprint.+// From https://github.com/percona/percona-toolkit/blob/af686fe186d1fca4c4392c8fa75c31a00c8fb273/bin/pt-query-digest#L2930+func GetFingerprint(query string) (string, error) {+ // Match SQL queries generated by mysqldump command.+ if matched, _ := regexp.MatchString(`\ASELECT /\*!40001 SQL_NO_CACHE \*/ \* FROM `, query); matched {+ return "mysqldump", nil+ }+ // Match SQL queries generated by Percona Toolkit.+ if matched, _ := regexp.MatchString(`/\*\w+\.\w+:[0-9]/[0-9]\*/`, query); matched {+ return "percona-toolkit", nil+ }+ // Match administrator commands.+ if matched, _ := regexp.MatchString(`\Aadministrator command: `, query); matched {+ return query, nil+ }+ // Match stored procedure call statements.+ if matched, _ := regexp.MatchString(`\A\s*(call\s+\S+)\(`, query); matched {+ return strings.ToLower(regexp.MustCompile(`\A\s*(call\s+\S+)\(`).FindStringSubmatch(query)[1]), nil+ }+ // Match INSERT INTO or REPLACE INTO statements.+ if beginning := regexp.MustCompile(`(?i)((?:INSERT|REPLACE)(?: IGNORE)?\s+INTO.+?VALUES\s*\(.*?\))\s*,\s*\(`).FindStringSubmatch(query); len(beginning) > 0 {+ query = beginning[1]+ }++ // Match multi-line comments and single-line comments, and remove them.+ mlcRe := regexp.MustCompile(`(?s)/\*.*?\*/`)+ olcRe := regexp.MustCompile(`(?m)--.*$`)+ query = mlcRe.ReplaceAllString(query, "")+ query = olcRe.ReplaceAllString(query, "")++ // Replace the database name in USE statements with a question mark (?).+ query = regexp.MustCompile(`(?i)\Ause \S+\z`).ReplaceAllString(query, "use ?")++ // Replace escape characters and special characters in SQL queries with a question mark (?).+ query = regexp.MustCompile(`([^\\])(\\')`).ReplaceAllString(query, "$1")+ query = regexp.MustCompile(`([^\\])(\\")`).ReplaceAllString(query, "$1")+ query = regexp.MustCompile(`\\\\`).ReplaceAllString(query, "")+ query = regexp.MustCompile(`\\'`).ReplaceAllString(query, "")+ query = regexp.MustCompile(`\\"`).ReplaceAllString(query, "")+ query = regexp.MustCompile(`([^\\])(".*?[^\\]?")`).ReplaceAllString(query, "$1?")+ query = regexp.MustCompile(`([^\\])('.*?[^\\]?')`).ReplaceAllString(query, "$1?")++ // Replace boolean values in SQL queries with a question mark (?).+ query = regexp.MustCompile(`\bfalse\b|\btrue\b`).ReplaceAllString(query, "?")++ // Replace MD5 values in SQL queries with a question mark (?).+ if matched, _ := regexp.MatchString(`([._-])[a-f0-9]{32}`, query); matched {+ query = regexp.MustCompile(`([._-])[a-f0-9]{32}`).ReplaceAllString(query, "$1?")+ }++ // Replace numbers in SQL queries with a question mark (?).+ if matched, _ := regexp.MatchString(`\b[0-9+-][0-9a-f.xb+-]*`, query); matched {+ query = regexp.MustCompile(`\b[0-9+-][0-9a-f.xb+-]*`).ReplaceAllString(query, "?")+ }++ // Replace special characters in SQL queries with a question mark (?).+ if matched, _ := regexp.MatchString(`[xb+-]\?`, query); matched {+ query = regexp.MustCompile(`[xb+-]\?`).ReplaceAllString(query, "?")+ } else {+ query = regexp.MustCompile(`[xb.+-]\?`).ReplaceAllString(query, "?")+ }++ // Remove spaces and line breaks in SQL queries.+ query = strings.TrimSpace(query)+ query = strings.TrimRight(query, "\n\r\f ")+ query = regexp.MustCompile(`\s+`).ReplaceAllString(query, " ")+ query = strings.ToLower(query)++ // Replace NULL values in SQL queries with a question mark (?).+ query = regexp.MustCompile(`\bnull\b`).ReplaceAllString(query, "?")++ // Replace IN and VALUES clauses in SQL queries with a question mark (?).+ query = regexp.MustCompile(`\b(in|values?)(?:[\s,]*\([\s?,]*\))+`).ReplaceAllString(query, "$1(?+)")++ var err error+ query, err = collapseUnion(query)+ if err != nil {+ return "", err+ }++ // Replace numbers in the LIMIT clause of SQL queries with a question mark (?).+ query = regexp.MustCompile(`\blimit \?(?:, ?\?| offset \?)?`).ReplaceAllString(query, "limit ?")++ // Remove ASC sorting in SQL queries.+ if matched, _ := regexp.MatchString(`\border by `, query); matched {+ ascRegexp := regexp.MustCompile(`(.+?)\s+asc`)+ for {+ if matched := ascRegexp.MatchString(query); matched {+ query = ascRegexp.ReplaceAllString(query, "$1")+ } else {+ break+ }+ }+ }++ return query, nil+}++func collapseUnion(query string) (string, error) {+ // The origin perl code is:+ // $query =~ s{ # Collapse UNION+ // \b(select\s.*?)(?:(\sunion(?:\sall)?)\s\1)++ // }+ // {$1 /*repeat$2*/}xg;+ // But Golang doesn't support \1(back-reference).+ // So we use the following code to replace it.+ unionRegexp := regexp.MustCompile(`\s(union all|union)\s`)+ parts := unionRegexp.Split(query, -1)+ if len(parts) == 1 {+ return query, nil+ }+ // Add a sentinel node to the end of the slice.+ // Because we remove all comments before, so all parts are different from sentinel node.+ parts = append(parts, "/*Sentinel Node*/")+ separators := unionRegexp.FindAllString(query, -1)+ if len(parts) != len(separators)+2 {+ return "", errors.Errorf("find %d parts, but %d separators", len(parts)-1, len(separators))+ }+ start := 0+ var buf bytes.Buffer+ if _, err := buf.WriteString(parts[start]); err != nil {+ return "", err+ }+ for i, part := range parts {+ if i == 0 {+ continue+ }+ if part == parts[start] {+ continue+ }+ if i == start+1 {+ // The i-th part is not equal to the front part.+ if _, err := buf.WriteString(separators[i-1]); err != nil {+ return "", err+ }+ } else {+ // deal with the same parts[start, i-1] and start < i-1.+ if _, err := buf.WriteString(" /*repeat"); err != nil {+ return "", err+ }+ // Write the last separator between the same parts[start, i-1].+ // In other words, the last separator is the separator between the i-th part and the (i-1)-th part.+ // So the index of the last separator is (i-1)-1.+ if _, err := buf.WriteString(separators[(i-1)-1]); err != nil {+ return "", err+ }+ if _, err := buf.WriteString("*/"); err != nil {+ return "", err+ }+ }+ start = i+ // Don't write the sentinel node.+ if i != len(parts)-1 {+ if _, err := buf.WriteString(parts[start]); err != nil {+ return "", err+ }+ }+ }+ return buf.String(), nil+}diff --git a/backend/plugin/parser/mysql/fingerprint_test.go b/backend/plugin/parser/mysql/fingerprint_test.gonew file mode 100644index 0000000000..2229dc330f--- /dev/null+++ b/backend/plugin/parser/mysql/fingerprint_test.go@@ -0,0 +1,115 @@+package mysql++import (+ "testing"++ "github.com/stretchr/testify/require"+)++func TestGetMySQLFingerprint(t *testing.T) {+ tests := []struct {+ stmt string+ want string+ }{+ {+ stmt: "-- this is comment\nSELECT * FROM `mytable`",+ want: "select * from `mytable`",+ },+ // Test mysqldump query.+ {+ stmt: "SELECT /*!40001 SQL_NO_CACHE */ * FROM `mytable`",+ want: "mysqldump",+ },+ // Test Percona Toolkit query.+ {+ stmt: "/*foo.bar:1/2*/ SELECT * FROM `mytable`",+ want: "percona-toolkit",+ },+ // Test administrator command.+ {+ stmt: "administrator command: SHOW STATUS",+ want: "administrator command: SHOW STATUS",+ },+ // Test stored procedure call statement.+ {+ stmt: "CALL my_stored_procedure(?, ?)",+ want: "call my_stored_procedure(?, ?)",+ },+ // Test INSERT INTO statement.+ {+ stmt: "INSERT INTO `mytable` (`id`, `name`) VALUES (1, 'John'), (2, 'Doe')",+ want: "insert into `mytable` (`id`, `name`) values(?+)",+ },+ // Test REPLACE INTO statement.+ {+ stmt: "REPLACE INTO `mytable` (`id`, `name`) VALUES (1, 'John'), (2, 'Doe')",+ want: "replace into `mytable` (`id`, `name`) values(?+)",+ },+ // Test multi-line comment.+ {+ stmt: "SELECT * FROM `mytable` /* WHERE `id` = 1 */",+ want: "select * from `mytable`",+ },+ // Test single-line comment.+ {+ stmt: "SELECT * FROM `mytable` -- WHERE `id` = 1",+ want: "select * from `mytable`",+ },+ // Test USE statement.+ {+ stmt: "USE `mydatabase`",+ want: "use ?",+ },+ // Test escape characters in SQL query.+ {+ stmt: "SELECT 'It\\'s raining' FROM `mytable`",+ want: "select ? from `mytable`",+ },+ // Test special characters in SQL query.+ {+ stmt: "SELECT 'Hello, \"world\"!' FROM `mytable`",+ want: "select ? from `mytable`",+ },+ // Test boolean values in SQL query.+ {+ stmt: "SELECT * FROM `mytable` WHERE `is_active` = true",+ want: "select * from `mytable` where `is_active` = ?",+ },+ // Test MD5 values in SQL query.+ {+ stmt: "SELECT * FROM `mytable` WHERE `password` = '5f4dcc3b5aa765d61d8327deb882cf99'",+ want: "select * from `mytable` where `password` = ?",+ },+ // Test numbers in SQL query.+ {+ stmt: "SELECT * FROM `mytable` WHERE `id` = 123",+ want: "select * from `mytable` where `id` = ?",+ },+ // Test special characters in SQL query.+ {+ stmt: "SELECT * FROM `mytable` WHERE `id` IN (1, 2, 3)",+ want: "select * from `mytable` where `id` in(?+)",+ },+ // Test repeated clauses in SQL query.+ {+ stmt: "SELECT * FROM `mytable` WHERE `id` = 1 UNION SELECT * FROM `mytable` WHERE `id` = 2 UNION ALL SELECT * FROM `mytable` WHERE `id` = 3",+ want: "select * from `mytable` where `id` = ? /*repeat union all */",+ },+ // Test LIMIT clause in SQL query.+ {+ stmt: "SELECT * FROM `mytable` LIMIT 10",+ want: "select * from `mytable` limit ?",+ },+ // Test ASC sorting in SQL query.+ {+ stmt: "SELECT * FROM `mytable` ORDER BY `id` ASC, `name` DESC",+ want: "select * from `mytable` order by `id`, `name` desc",+ },+ }++ for _, test := range tests {+ res, err := GetFingerprint(test.stmt)+ require.NoError(t, err, test.stmt)+ require.Equal(t, test.want, res, test.stmt)+ }+}diff --git a/backend/plugin/parser/sql/utils.go b/backend/plugin/parser/sql/utils.goindex dd5314f932..15b46224de 100644--- a/backend/plugin/parser/sql/utils.go+++ b/backend/plugin/parser/sql/utils.go@@ -67,176 +67,6 @@ func ExtractResourceList(engineType EngineType, currentDatabase string, currentS}}-// GetSQLFingerprint returns the fingerprint of the SQL.-func GetSQLFingerprint(engineType EngineType, sql string) (string, error) {- switch engineType {- case MySQL, TiDB, MariaDB:- return getMySQLFingerprint(sql)- default:- return "", errors.Errorf("engine type is not supported: %s", engineType)- }-}--// From https://github.com/percona/percona-toolkit/blob/af686fe186d1fca4c4392c8fa75c31a00c8fb273/bin/pt-query-digest#L2930-func getMySQLFingerprint(query string) (string, error) {- // Match SQL queries generated by mysqldump command.- if matched, _ := regexp.MatchString(`\ASELECT /\*!40001 SQL_NO_CACHE \*/ \* FROM `, query); matched {- return "mysqldump", nil- }- // Match SQL queries generated by Percona Toolkit.- if matched, _ := regexp.MatchString(`/\*\w+\.\w+:[0-9]/[0-9]\*/`, query); matched {- return "percona-toolkit", nil- }- // Match administrator commands.- if matched, _ := regexp.MatchString(`\Aadministrator command: `, query); matched {- return query, nil- }- // Match stored procedure call statements.- if matched, _ := regexp.MatchString(`\A\s*(call\s+\S+)\(`, query); matched {- return strings.ToLower(regexp.MustCompile(`\A\s*(call\s+\S+)\(`).FindStringSubmatch(query)[1]), nil- }- // Match INSERT INTO or REPLACE INTO statements.- if beginning := regexp.MustCompile(`(?i)((?:INSERT|REPLACE)(?: IGNORE)?\s+INTO.+?VALUES\s*\(.*?\))\s*,\s*\(`).FindStringSubmatch(query); len(beginning) > 0 {- query = beginning[1]- }-- // Match multi-line comments and single-line comments, and remove them.- mlcRe := regexp.MustCompile(`(?s)/\*.*?\*/`)- olcRe := regexp.MustCompile(`(?m)--.*$`)- query = mlcRe.ReplaceAllString(query, "")- query = olcRe.ReplaceAllString(query, "")-- // Replace the database name in USE statements with a question mark (?).- query = regexp.MustCompile(`(?i)\Ause \S+\z`).ReplaceAllString(query, "use ?")-- // Replace escape characters and special characters in SQL queries with a question mark (?).- query = regexp.MustCompile(`([^\\])(\\')`).ReplaceAllString(query, "$1")- query = regexp.MustCompile(`([^\\])(\\")`).ReplaceAllString(query, "$1")- query = regexp.MustCompile(`\\\\`).ReplaceAllString(query, "")- query = regexp.MustCompile(`\\'`).ReplaceAllString(query, "")- query = regexp.MustCompile(`\\"`).ReplaceAllString(query, "")- query = regexp.MustCompile(`([^\\])(".*?[^\\]?")`).ReplaceAllString(query, "$1?")- query = regexp.MustCompile(`([^\\])('.*?[^\\]?')`).ReplaceAllString(query, "$1?")-- // Replace boolean values in SQL queries with a question mark (?).- query = regexp.MustCompile(`\bfalse\b|\btrue\b`).ReplaceAllString(query, "?")-- // Replace MD5 values in SQL queries with a question mark (?).- if matched, _ := regexp.MatchString(`([._-])[a-f0-9]{32}`, query); matched {- query = regexp.MustCompile(`([._-])[a-f0-9]{32}`).ReplaceAllString(query, "$1?")- }-- // Replace numbers in SQL queries with a question mark (?).- if matched, _ := regexp.MatchString(`\b[0-9+-][0-9a-f.xb+-]*`, query); matched {- query = regexp.MustCompile(`\b[0-9+-][0-9a-f.xb+-]*`).ReplaceAllString(query, "?")- }-- // Replace special characters in SQL queries with a question mark (?).- if matched, _ := regexp.MatchString(`[xb+-]\?`, query); matched {- query = regexp.MustCompile(`[xb+-]\?`).ReplaceAllString(query, "?")- } else {- query = regexp.MustCompile(`[xb.+-]\?`).ReplaceAllString(query, "?")- }-- // Remove spaces and line breaks in SQL queries.- query = strings.TrimSpace(query)- query = strings.TrimRight(query, "\n\r\f ")- query = regexp.MustCompile(`\s+`).ReplaceAllString(query, " ")- query = strings.ToLower(query)-- // Replace NULL values in SQL queries with a question mark (?).- query = regexp.MustCompile(`\bnull\b`).ReplaceAllString(query, "?")-- // Replace IN and VALUES clauses in SQL queries with a question mark (?).- query = regexp.MustCompile(`\b(in|values?)(?:[\s,]*\([\s?,]*\))+`).ReplaceAllString(query, "$1(?+)")-- var err error- query, err = collapseUnion(query)- if err != nil {- return "", err- }-- // Replace numbers in the LIMIT clause of SQL queries with a question mark (?).- query = regexp.MustCompile(`\blimit \?(?:, ?\?| offset \?)?`).ReplaceAllString(query, "limit ?")-- // Remove ASC sorting in SQL queries.- if matched, _ := regexp.MatchString(`\border by `, query); matched {- ascRegexp := regexp.MustCompile(`(.+?)\s+asc`)- for {- if matched := ascRegexp.MatchString(query); matched {- query = ascRegexp.ReplaceAllString(query, "$1")- } else {- break- }- }- }-- return query, nil-}--func collapseUnion(query string) (string, error) {- // The origin perl code is:- // $query =~ s{ # Collapse UNION- // \b(select\s.*?)(?:(\sunion(?:\sall)?)\s\1)+- // }- // {$1 /*repeat$2*/}xg;- // But Golang doesn't support \1(back-reference).- // So we use the following code to replace it.- unionRegexp := regexp.MustCompile(`\s(union all|union)\s`)- parts := unionRegexp.Split(query, -1)- if len(parts) == 1 {- return query, nil- }- // Add a sentinel node to the end of the slice.- // Because we remove all comments before, so all parts are different from sentinel node.- parts = append(parts, "/*Sentinel Node*/")- separators := unionRegexp.FindAllString(query, -1)- if len(parts) != len(separators)+2 {- return "", errors.Errorf("find %d parts, but %d separators", len(parts)-1, len(separators))- }- start := 0- var buf bytes.Buffer- if _, err := buf.WriteString(parts[start]); err != nil {- return "", err- }- for i, part := range parts {- if i == 0 {- continue- }- if part == parts[start] {- continue- }- if i == start+1 {- // The i-th part is not equal to the front part.- if _, err := buf.WriteString(separators[i-1]); err != nil {- return "", err- }- } else {- // deal with the same parts[start, i-1] and start < i-1.- if _, err := buf.WriteString(" /*repeat"); err != nil {- return "", err- }- // Write the last separator between the same parts[start, i-1].- // In other words, the last separator is the separator between the i-th part and the (i-1)-th part.- // So the index of the last separator is (i-1)-1.- if _, err := buf.WriteString(separators[(i-1)-1]); err != nil {- return "", err- }- if _, err := buf.WriteString("*/"); err != nil {- return "", err- }- }- start = i- // Don't write the sentinel node.- if i != len(parts)-1 {- if _, err := buf.WriteString(parts[start]); err != nil {- return "", err- }- }- }- return buf.String(), nil-}-// SplitMultiSQL splits statement into a slice of the single SQL.func SplitMultiSQL(engineType EngineType, statement string) ([]base.SingleSQL, error) {var list []base.SingleSQL@@ -583,7 +413,7 @@ func TypeString(tp byte) string {func ExtractDatabaseList(engineType EngineType, statement string, fallbackNormalizedDatabaseName string) ([]string, error) {switch engineType {case MySQL, TiDB, MariaDB, OceanBase:- return tidbparser.ExtractMySQLDatabaseList(statement)+ return tidbparser.ExtractDatabaseList(statement)case Snowflake:return extractSnowSQLNormalizedDatabaseList(statement, fallbackNormalizedDatabaseName)case MSSQL:diff --git a/backend/plugin/parser/sql/utils_test.go b/backend/plugin/parser/sql/utils_test.goindex 755b43295b..74bad8a211 100644--- a/backend/plugin/parser/sql/utils_test.go+++ b/backend/plugin/parser/sql/utils_test.go@@ -143,151 +143,6 @@ func TestIsTiDBUnsupportStmt(t *testing.T) {}}-func TestMySQLExtractDatabaseList(t *testing.T) {- tests := []struct {- stmt string- want []string- }{- {- stmt: `- SELECT * FROM t;- SELECT * FROM db1.t;- SELECT * FROM db2.t;- SELECT * FROM db1.t;- `,- want: []string{"", "db1", "db2"},- },- {- stmt: `- SELECT 1;- `,- want: nil,- },- {- stmt: `SELECT * FROM t, db1.t1;`,- want: []string{"", "db1"},- },- {- stmt: `select * from t join db1.t as t1 where t.a != t1.a;`,- want: []string{"", "db1"},- },- }-- for _, test := range tests {- res, err := ExtractDatabaseList(MySQL, test.stmt, "")- require.NoError(t, err)- require.Equal(t, test.want, res)- }-}--func TestGetMySQLFingerprint(t *testing.T) {- tests := []struct {- stmt string- want string- }{- {- stmt: "-- this is comment\nSELECT * FROM `mytable`",- want: "select * from `mytable`",- },- // Test mysqldump query.- {- stmt: "SELECT /*!40001 SQL_NO_CACHE */ * FROM `mytable`",- want: "mysqldump",- },- // Test Percona Toolkit query.- {- stmt: "/*foo.bar:1/2*/ SELECT * FROM `mytable`",- want: "percona-toolkit",- },- // Test administrator command.- {- stmt: "administrator command: SHOW STATUS",- want: "administrator command: SHOW STATUS",- },- // Test stored procedure call statement.- {- stmt: "CALL my_stored_procedure(?, ?)",- want: "call my_stored_procedure(?, ?)",- },- // Test INSERT INTO statement.- {- stmt: "INSERT INTO `mytable` (`id`, `name`) VALUES (1, 'John'), (2, 'Doe')",- want: "insert into `mytable` (`id`, `name`) values(?+)",- },- // Test REPLACE INTO statement.- {- stmt: "REPLACE INTO `mytable` (`id`, `name`) VALUES (1, 'John'), (2, 'Doe')",- want: "replace into `mytable` (`id`, `name`) values(?+)",- },- // Test multi-line comment.- {- stmt: "SELECT * FROM `mytable` /* WHERE `id` = 1 */",- want: "select * from `mytable`",- },- // Test single-line comment.- {- stmt: "SELECT * FROM `mytable` -- WHERE `id` = 1",- want: "select * from `mytable`",- },- // Test USE statement.- {- stmt: "USE `mydatabase`",- want: "use ?",- },- // Test escape characters in SQL query.- {- stmt: "SELECT 'It\\'s raining' FROM `mytable`",- want: "select ? from `mytable`",- },- // Test special characters in SQL query.- {- stmt: "SELECT 'Hello, \"world\"!' FROM `mytable`",- want: "select ? from `mytable`",- },- // Test boolean values in SQL query.- {- stmt: "SELECT * FROM `mytable` WHERE `is_active` = true",- want: "select * from `mytable` where `is_active` = ?",- },- // Test MD5 values in SQL query.- {- stmt: "SELECT * FROM `mytable` WHERE `password` = '5f4dcc3b5aa765d61d8327deb882cf99'",- want: "select * from `mytable` where `password` = ?",- },- // Test numbers in SQL query.- {- stmt: "SELECT * FROM `mytable` WHERE `id` = 123",- want: "select * from `mytable` where `id` = ?",- },- // Test special characters in SQL query.- {- stmt: "SELECT * FROM `mytable` WHERE `id` IN (1, 2, 3)",- want: "select * from `mytable` where `id` in(?+)",- },- // Test repeated clauses in SQL query.- {- stmt: "SELECT * FROM `mytable` WHERE `id` = 1 UNION SELECT * FROM `mytable` WHERE `id` = 2 UNION ALL SELECT * FROM `mytable` WHERE `id` = 3",- want: "select * from `mytable` where `id` = ? /*repeat union all */",- },- // Test LIMIT clause in SQL query.- {- stmt: "SELECT * FROM `mytable` LIMIT 10",- want: "select * from `mytable` limit ?",- },- // Test ASC sorting in SQL query.- {- stmt: "SELECT * FROM `mytable` ORDER BY `id` ASC, `name` DESC",- want: "select * from `mytable` order by `id`, `name` desc",- },- }-- for _, test := range tests {- res, err := GetSQLFingerprint(MySQL, test.stmt)- require.NoError(t, err, test.stmt)- require.Equal(t, test.want, res, test.stmt)- }-}-func TestExtractPostgresResourceList(t *testing.T) {tests := []struct {statement stringdiff --git a/backend/plugin/parser/tidb/query.go b/backend/plugin/parser/tidb/query.goindex 048e89a5e1..d4c802166d 100644--- a/backend/plugin/parser/tidb/query.go+++ b/backend/plugin/parser/tidb/query.go@@ -46,8 +46,8 @@ func ExtractTiDBResourceList(currentDatabase string, sql string) ([]base.SchemaRreturn resourceList, nil}-// ExtractMySQLDatabaseList extracts mysql database list.-func ExtractMySQLDatabaseList(statement string) ([]string, error) {+// ExtractDatabaseList extracts mysql database list.+func ExtractDatabaseList(statement string) ([]string, error) {databaseMap := make(map[string]bool)// TODO(d): replace it with mysql parser.diff --git a/backend/plugin/parser/tidb/query_test.go b/backend/plugin/parser/tidb/query_test.gonew file mode 100644index 0000000000..53d01b0418--- /dev/null+++ b/backend/plugin/parser/tidb/query_test.go@@ -0,0 +1,44 @@+package tidb++import (+ "testing"++ "github.com/stretchr/testify/require"+)++func TestMySQLExtractDatabaseList(t *testing.T) {+ tests := []struct {+ stmt string+ want []string+ }{+ {+ stmt: `+ SELECT * FROM t;+ SELECT * FROM db1.t;+ SELECT * FROM db2.t;+ SELECT * FROM db1.t;+ `,+ want: []string{"", "db1", "db2"},+ },+ {+ stmt: `+ SELECT 1;+ `,+ want: nil,+ },+ {+ stmt: `SELECT * FROM t, db1.t1;`,+ want: []string{"", "db1"},+ },+ {+ stmt: `select * from t join db1.t as t1 where t.a != t1.a;`,+ want: []string{"", "db1"},+ },+ }++ for _, test := range tests {+ res, err := ExtractDatabaseList(test.stmt)+ require.NoError(t, err)+ require.Equal(t, test.want, res)+ }+}