diff --git a/database/mysql.go b/database/mysql.go index d3216cd8144b3afa22c2aba4c5c2eff584ea0b61..aebf304b6afec6f2b59f768ac9febded2b085e76 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 eb184263b559b0bb007e7176a6ac79025f5b76ea..cd9fa50df7eec4f3085745a06a3e91b6dbbfcdd4 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 3f2ff2d6cc8f257ffcade7ead1ca4042c0e884b9..6fb66a5e2f01e878ab235d7714bb18eb45225504 100644 --- a/database/testdata/TestRemoveSQLComments.golden +++ b/database/testdata/TestRemoveSQLComments.golden @@ -3,3 +3,4 @@ +