Skip to content

Commit

Permalink
add comment and test case for RemoveSQLComments
Browse files Browse the repository at this point in the history
  • Loading branch information
martianzhang committed Apr 27, 2020
1 parent 1f50907 commit f12c263
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 4 deletions.
11 changes: 8 additions & 3 deletions database/mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -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]) == "/*!") {
Expand Down
3 changes: 2 additions & 1 deletion database/mysql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
1 change: 1 addition & 0 deletions database/testdata/TestRemoveSQLComments.golden
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@




0 comments on commit f12c263

Please sign in to comment.