From f12c263c9d898936c269b3e6694b39de720312de Mon Sep 17 00:00:00 2001 From: Leon Zhang Date: Mon, 27 Apr 2020 11:03:42 +0800 Subject: [PATCH] add comment and test case for RemoveSQLComments --- database/mysql.go | 11 ++++++++--- database/mysql_test.go | 3 ++- database/testdata/TestRemoveSQLComments.golden | 1 + 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/database/mysql.go b/database/mysql.go index d3216cd..aebf304 100644 --- a/database/mysql.go +++ b/database/mysql.go @@ -252,9 +252,14 @@ func (db *Connector) IsView(tbName string) bool { // RemoveSQLComments 去除SQL中的注释 func RemoveSQLComments(sql string) string { buf := []byte(sql) - cmtReg := regexp.MustCompile(`("(""|[^"])*")|('(''|[^'])*')|(--[^\n\r]*)|(#.*)|(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)`) - - res := cmtReg.ReplaceAllFunc(buf, func(s []byte) []byte { + // ("(""|[^"])*") 双引号中的内容 + // ('(''|[^'])*') 单引号中的内容 + // (--[^\n\r]*) 双减号注释 + // (#.*) 井号注释 + // (/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/) 多行注释 + commentRegex := regexp.MustCompile(`("(""|[^"])*")|('(''|[^'])*')|(--[^\n\r]*)|(#.*)|(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)`) + + res := commentRegex.ReplaceAllFunc(buf, func(s []byte) []byte { if (s[0] == '"' && s[len(s)-1] == '"') || (s[0] == '\'' && s[len(s)-1] == '\'') || (string(s[:3]) == "/*!") { diff --git a/database/mysql_test.go b/database/mysql_test.go index eb18426..cd9fa50 100644 --- a/database/mysql_test.go +++ b/database/mysql_test.go @@ -146,17 +146,18 @@ func TestVersion(t *testing.T) { } func TestRemoveSQLComments(t *testing.T) { + // Notice: double dash without space not comment, eg. `--not comment` common.Log.Debug("Entering function: %s", common.GetFunctionName()) SQLs := []string{ `-- comment`, `--`, `# comment`, + `#comment`, `/* multi-line comment*/`, `-- -- comment`, } - err := common.GoldenDiff(func() { for _, sql := range SQLs { fmt.Println(RemoveSQLComments(sql)) diff --git a/database/testdata/TestRemoveSQLComments.golden b/database/testdata/TestRemoveSQLComments.golden index 3f2ff2d..6fb66a5 100644 --- a/database/testdata/TestRemoveSQLComments.golden +++ b/database/testdata/TestRemoveSQLComments.golden @@ -3,3 +3,4 @@ + -- GitLab