Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat: implement SyncSlowQuery for MySQL (#5428)

rebelicefd46774f1c63
diff --git a/backend/plugin/advisor/utils_for_tests.go b/backend/plugin/advisor/utils_for_tests.go
index 309a2654c6..384a03a3b9 100644
--- a/backend/plugin/advisor/utils_for_tests.go
+++ b/backend/plugin/advisor/utils_for_tests.go
@@ -342,6 +342,11 @@ func (*MockDriver) DeleteRole(_ context.Context, _ string) error {
return nil
}
+// SyncSlowQuery implements the Driver interface.
+func (*MockDriver) SyncSlowQuery(_ context.Context, _ time.Time) (map[string]map[string]*storepb.SlowQueryStatistics, error) {
+ return nil, nil
+}
+
// SetDefaultSQLReviewRulePayload sets the default payload for this rule.
func SetDefaultSQLReviewRulePayload(ruleTp SQLReviewRuleType) (string, error) {
var payload []byte
diff --git a/backend/plugin/db/clickhouse/sync.go b/backend/plugin/db/clickhouse/sync.go
index 1851c6804c..2ce5746627 100644
--- a/backend/plugin/db/clickhouse/sync.go
+++ b/backend/plugin/db/clickhouse/sync.go
@@ -9,6 +9,8 @@ import (
"google.golang.org/protobuf/types/known/wrapperspb"
+ "github.com/pkg/errors"
+
"github.com/bytebase/bytebase/backend/plugin/db"
"github.com/bytebase/bytebase/backend/plugin/db/util"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
@@ -175,3 +177,8 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*s
Schemas: []*storepb.SchemaMetadata{schemaMetadata},
}, nil
}
+
+// SyncSlowQuery syncs the slow query.
+func (*Driver) SyncSlowQuery(_ context.Context, _ time.Time) (map[string]map[string]*storepb.SlowQueryStatistics, error) {
+ return nil, errors.Errorf("not implemented")
+}
diff --git a/backend/plugin/db/driver.go b/backend/plugin/db/driver.go
index edde413048..707a984d40 100644
--- a/backend/plugin/db/driver.go
+++ b/backend/plugin/db/driver.go
@@ -10,6 +10,7 @@ import (
"regexp"
"strings"
"sync"
+ "time"
"github.com/pkg/errors"
@@ -53,6 +54,13 @@ const (
// BytebaseDatabase is the database installed in the controlled database server.
BytebaseDatabase = "bytebase"
+
+ // SlowQueryMaxLen is the max length of slow query.
+ SlowQueryMaxLen = 2048
+ // SlowQueryMaxSamplePerFingerprint is the max number of slow query samples per fingerprint.
+ SlowQueryMaxSamplePerFingerprint = 100
+ // SlowQueryMaxSamplePerDay is the max number of slow query samples per day.
+ SlowQueryMaxSamplePerDay = 10000
)
// User is the database user.
@@ -468,6 +476,11 @@ type Driver interface {
// SyncDBSchema syncs a single database schema.
SyncDBSchema(ctx context.Context, database string) (*storepb.DatabaseMetadata, error)
+ // Sync slow query logs
+ // SyncSlowQuery syncs the slow query logs.
+ // The returned map is keyed by database name, and the value is a map keyed by query fingerprint.
+ SyncSlowQuery(ctx context.Context, logDateTs time.Time) (map[string]map[string]*storepb.SlowQueryStatistics, error)
+
// Role
// CreateRole creates the role.
CreateRole(ctx context.Context, upsert *DatabaseRoleUpsertMessage) (*DatabaseRoleMessage, error)
diff --git a/backend/plugin/db/mongodb/sync.go b/backend/plugin/db/mongodb/sync.go
index eaa93ef0c5..6419efe49a 100644
--- a/backend/plugin/db/mongodb/sync.go
+++ b/backend/plugin/db/mongodb/sync.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"sort"
"strings"
+ "time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
@@ -303,3 +304,8 @@ func convertEmptyInterfaceToInt64(value any) (int64, error) {
return 0, errors.Errorf("cannot convert %v to int64", value)
}
}
+
+// SyncSlowQuery syncs the slow query.
+func (*Driver) SyncSlowQuery(_ context.Context, _ time.Time) (map[string]map[string]*storepb.SlowQueryStatistics, error) {
+ return nil, errors.Errorf("not implemented")
+}
diff --git a/backend/plugin/db/mssql/sync.go b/backend/plugin/db/mssql/sync.go
index 7e58edd25a..5e50b8c8cf 100644
--- a/backend/plugin/db/mssql/sync.go
+++ b/backend/plugin/db/mssql/sync.go
@@ -5,6 +5,7 @@ import (
"database/sql"
"fmt"
"sort"
+ "time"
"github.com/pkg/errors"
"google.golang.org/protobuf/types/known/wrapperspb"
@@ -311,3 +312,8 @@ func getViews(txn *sql.Tx) (map[string][]*storepb.ViewMetadata, error) {
return viewMap, nil
}
+
+// SyncSlowQuery syncs the slow query.
+func (*Driver) SyncSlowQuery(_ context.Context, _ time.Time) (map[string]map[string]*storepb.SlowQueryStatistics, error) {
+ return nil, errors.Errorf("not implemented")
+}
diff --git a/backend/plugin/db/mysql/sync.go b/backend/plugin/db/mysql/sync.go
index f820683716..747d7233e2 100644
--- a/backend/plugin/db/mysql/sync.go
+++ b/backend/plugin/db/mysql/sync.go
@@ -4,14 +4,21 @@ import (
"context"
"database/sql"
"fmt"
+ "math/rand"
"sort"
"strings"
+ "time"
+ "go.uber.org/zap"
"google.golang.org/protobuf/types/known/wrapperspb"
+ "github.com/pkg/errors"
+
"github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/log"
"github.com/bytebase/bytebase/backend/plugin/db"
"github.com/bytebase/bytebase/backend/plugin/db/util"
+ "github.com/bytebase/bytebase/backend/plugin/parser"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
@@ -450,3 +457,134 @@ func (driver *Driver) getForeignKeyList(ctx context.Context, databaseName string
return foreignKeysMap, nil
}
+
+type slowLog struct {
+ database string
+ details *storepb.SlowQueryDetails
+}
+
+// SyncSlowQuery syncs slow query from mysql.slow_log.
+func (driver *Driver) SyncSlowQuery(ctx context.Context, logDateTs time.Time) (map[string]map[string]*storepb.SlowQueryStatistics, error) {
+ logs := make([]*slowLog, 0, db.SlowQueryMaxSamplePerDay)
+ query := `
+ SELECT
+ start_time,
+ query_time,
+ lock_time,
+ rows_sent,
+ rows_examined,
+ db,
+ CONVERT(sql_text USING utf8) AS sql_text
+ FROM
+ mysql.slow_log
+ WHERE
+ start_time >= ?
+ AND start_time < ?
+ `
+
+ slowLogRows, err := driver.db.QueryContext(ctx, query, logDateTs.Format("2006-01-02"), logDateTs.AddDate(0, 0, 1).Format("2006-01-02"))
+ if err != nil {
+ return nil, util.FormatErrorWithQuery(err, query)
+ }
+ defer slowLogRows.Close()
+ for slowLogRows.Next() {
+ var log slowLog
+ if err := slowLogRows.Scan(
+ &log.details.StartTime,
+ &log.details.QueryTime,
+ &log.details.LockTime,
+ &log.details.RowsSent,
+ &log.details.RowsExamined,
+ &log.database,
+ &log.details.SqlText,
+ ); err != nil {
+ return nil, err
+ }
+
+ // Use Reservoir Sampling to sample slow logs.
+ // See https://en.wikipedia.org/wiki/Reservoir_sampling
+ if len(logs) < db.SlowQueryMaxSamplePerDay {
+ logs = append(logs, &log)
+ } else {
+ pos := rand.Intn(len(logs))
+ logs[pos] = &log
+ }
+ }
+
+ if err := slowLogRows.Err(); err != nil {
+ return nil, util.FormatErrorWithQuery(err, query)
+ }
+
+ return analyzeSlowLog(logs)
+}
+
+func analyzeSlowLog(logs []*slowLog) (map[string]map[string]*storepb.SlowQueryStatistics, error) {
+ result := make(map[string]map[string]*storepb.SlowQueryStatistics)
+
+ for _, log := range logs {
+ databaseList := extractDatabase(log.database, log.details.SqlText)
+ fingerprint, err := parser.GetSQLFingerprint(parser.MySQL, log.details.SqlText)
+ if err != nil {
+ return nil, errors.Wrapf(err, "get sql fingerprint failed, sql: %s", log.details.SqlText)
+ }
+ if len(fingerprint) > db.SlowQueryMaxLen {
+ fingerprint = fingerprint[:db.SlowQueryMaxLen]
+ }
+ if len(log.details.SqlText) > db.SlowQueryMaxLen {
+ log.details.SqlText = log.details.SqlText[:db.SlowQueryMaxLen]
+ }
+
+ for _, db := range databaseList {
+ var dbLog map[string]*storepb.SlowQueryStatistics
+ var exists bool
+ if dbLog, exists = result[db]; !exists {
+ dbLog = make(map[string]*storepb.SlowQueryStatistics)
+ result[db] = dbLog
+ }
+ dbLog[fingerprint] = mergeSlowLog(fingerprint, dbLog[fingerprint], log.details)
+ }
+ }
+ return result, nil
+}
+
+func mergeSlowLog(fingerprint string, statistics *storepb.SlowQueryStatistics, details *storepb.SlowQueryDetails) *storepb.SlowQueryStatistics {
+ if statistics == nil {
+ return &storepb.SlowQueryStatistics{
+ SqlFingerprint: fingerprint,
+ Count: 1,
+ LatestLogTime: details.StartTime,
+ Samples: []*storepb.SlowQueryDetails{details},
+ }
+ }
+ statistics.Count++
+ if statistics.LatestLogTime.AsTime().Before(details.StartTime.AsTime()) {
+ statistics.LatestLogTime = details.StartTime
+ }
+ if len(statistics.Samples) < db.SlowQueryMaxSamplePerFingerprint {
+ statistics.Samples = append(statistics.Samples, details)
+ } else {
+ // Use Reservoir Sampling to sample slow logs.
+ pos := rand.Intn(len(statistics.Samples))
+ statistics.Samples[pos] = details
+ }
+ return statistics
+}
+
+func extractDatabase(defaultDB string, sql string) []string {
+ list, err := parser.ExtractDatabaseList(parser.MySQL, sql)
+ if err != nil {
+ // If we can't extract the database, we just use the default database.
+ log.Debug("extract database failed", zap.Error(err), zap.String("sql", sql))
+ return []string{defaultDB}
+ }
+
+ var result []string
+ for _, db := range list {
+ if db == "" {
+ result = append(result, defaultDB)
+ } else {
+ result = append(result, db)
+ }
+ }
+ return result
+}
diff --git a/backend/plugin/db/oracle/sync.go b/backend/plugin/db/oracle/sync.go
index 22a069810a..21e7c9d5fd 100644
--- a/backend/plugin/db/oracle/sync.go
+++ b/backend/plugin/db/oracle/sync.go
@@ -3,6 +3,7 @@ package oracle
import (
"context"
"database/sql"
+ "time"
"github.com/pkg/errors"
"google.golang.org/protobuf/types/known/wrapperspb"
@@ -327,3 +328,8 @@ func getViews(txn *sql.Tx) (map[string][]*storepb.ViewMetadata, error) {
return viewMap, nil
}
+
+// SyncSlowQuery syncs the slow query.
+func (*Driver) SyncSlowQuery(_ context.Context, _ time.Time) (map[string]map[string]*storepb.SlowQueryStatistics, error) {
+ return nil, errors.Errorf("not implemented")
+}
diff --git a/backend/plugin/db/pg/sync.go b/backend/plugin/db/pg/sync.go
index 4c25650177..c0d03d21a1 100644
--- a/backend/plugin/db/pg/sync.go
+++ b/backend/plugin/db/pg/sync.go
@@ -7,6 +7,7 @@ import (
"regexp"
"sort"
"strings"
+ "time"
"github.com/pkg/errors"
"google.golang.org/protobuf/types/known/wrapperspb"
@@ -604,3 +605,8 @@ func getIndexMethodType(stmt string) string {
}
return matches[1]
}
+
+// SyncSlowQuery syncs the slow query.
+func (*Driver) SyncSlowQuery(_ context.Context, _ time.Time) (map[string]map[string]*storepb.SlowQueryStatistics, error) {
+ return nil, errors.Errorf("not implemented")
+}
diff --git a/backend/plugin/db/redis/sync.go b/backend/plugin/db/redis/sync.go
index 539de81bfd..0f119809da 100644
--- a/backend/plugin/db/redis/sync.go
+++ b/backend/plugin/db/redis/sync.go
@@ -4,6 +4,7 @@ import (
"context"
"strconv"
"strings"
+ "time"
"github.com/pkg/errors"
@@ -113,3 +114,8 @@ func (d *Driver) getDatabaseCount(ctx context.Context) (int, error) {
}
return count, nil
}
+
+// SyncSlowQuery syncs the slow query.
+func (*Driver) SyncSlowQuery(_ context.Context, _ time.Time) (map[string]map[string]*storepb.SlowQueryStatistics, error) {
+ return nil, errors.Errorf("not implemented")
+}
diff --git a/backend/plugin/db/redshift/sync.go b/backend/plugin/db/redshift/sync.go
index 0ac3c9d51d..9792ca917e 100644
--- a/backend/plugin/db/redshift/sync.go
+++ b/backend/plugin/db/redshift/sync.go
@@ -8,6 +8,7 @@ import (
"regexp"
"sort"
"strings"
+ "time"
"github.com/pkg/errors"
"go.uber.org/zap"
@@ -715,3 +716,8 @@ func (driver *Driver) getDatabases(ctx context.Context) ([]*storepb.DatabaseMeta
}
return databases, nil
}
+
+// SyncSlowQuery syncs the slow query.
+func (*Driver) SyncSlowQuery(_ context.Context, _ time.Time) (map[string]map[string]*storepb.SlowQueryStatistics, error) {
+ return nil, errors.Errorf("not implemented")
+}
diff --git a/backend/plugin/db/snowflake/sync.go b/backend/plugin/db/snowflake/sync.go
index e6d9b330b4..f60ad8651b 100644
--- a/backend/plugin/db/snowflake/sync.go
+++ b/backend/plugin/db/snowflake/sync.go
@@ -6,9 +6,12 @@ import (
"fmt"
"sort"
"strings"
+ "time"
"google.golang.org/protobuf/types/known/wrapperspb"
+ "github.com/pkg/errors"
+
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/plugin/db"
"github.com/bytebase/bytebase/backend/plugin/db/util"
@@ -290,3 +293,8 @@ func (driver *Driver) getTableSchema(ctx context.Context, database string) (map[
return tableMap, viewMap, nil
}
+
+// SyncSlowQuery syncs the slow query.
+func (*Driver) SyncSlowQuery(_ context.Context, _ time.Time) (map[string]map[string]*storepb.SlowQueryStatistics, error) {
+ return nil, errors.Errorf("not implemented")
+}
diff --git a/backend/plugin/db/spanner/sync.go b/backend/plugin/db/spanner/sync.go
index c76837b1a4..bc305296f5 100644
--- a/backend/plugin/db/spanner/sync.go
+++ b/backend/plugin/db/spanner/sync.go
@@ -3,6 +3,7 @@ package spanner
import (
"context"
"sort"
+ "time"
"cloud.google.com/go/spanner"
"cloud.google.com/go/spanner/admin/database/apiv1/databasepb"
@@ -354,3 +355,8 @@ func getView(ctx context.Context, tx *spanner.ReadOnlyTransaction) (map[string][
}
return viewMap, nil
}
+
+// SyncSlowQuery syncs the slow query.
+func (*Driver) SyncSlowQuery(_ context.Context, _ time.Time) (map[string]map[string]*storepb.SlowQueryStatistics, error) {
+ return nil, errors.Errorf("not implemented")
+}
diff --git a/backend/plugin/db/sqlite/sync.go b/backend/plugin/db/sqlite/sync.go
index 6071f4a627..87a44bdd52 100644
--- a/backend/plugin/db/sqlite/sync.go
+++ b/backend/plugin/db/sqlite/sync.go
@@ -5,6 +5,7 @@ import (
"database/sql"
"fmt"
"strings"
+ "time"
"github.com/pkg/errors"
"google.golang.org/protobuf/types/known/wrapperspb"
@@ -255,3 +256,8 @@ func getViews(txn *sql.Tx) ([]*storepb.ViewMetadata, error) {
return views, nil
}
+
+// SyncSlowQuery syncs the slow query.
+func (*Driver) SyncSlowQuery(_ context.Context, _ time.Time) (map[string]map[string]*storepb.SlowQueryStatistics, error) {
+ return nil, errors.Errorf("not implemented")
+}
diff --git a/backend/plugin/parser/utils.go b/backend/plugin/parser/utils.go
index cdf1a72938..e6c6ce5437 100644
--- a/backend/plugin/parser/utils.go
+++ b/backend/plugin/parser/utils.go
@@ -25,6 +25,176 @@ type SingleSQL struct {
Empty bool
}
+// 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(`--.*$`)
+ 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) ([]SingleSQL, error) {
var list []SingleSQL
diff --git a/backend/plugin/parser/utils_test.go b/backend/plugin/parser/utils_test.go
index 70d32c9add..75173e2bdc 100644
--- a/backend/plugin/parser/utils_test.go
+++ b/backend/plugin/parser/utils_test.go
@@ -215,3 +215,107 @@ func TestExtractDatabaseList(t *testing.T) {
require.Equal(t, test.want, res)
}
}
+
+func TestGetMySQLFingerprint(t *testing.T) {
+ tests := []struct {
+ stmt string
+ want string
+ }{
+ // 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)
+ }
+}