Skip to content

Commit

Permalink
Fix Vtexplains StripComments
Browse files Browse the repository at this point in the history
Signed-off-by: Saif Alharthi <saif@saifalharthi.me>

Modify for better readability

Signed-off-by: Saif Alharthi <saif@saifalharthi.me>

Make sure anything inside qoutations will not be removed

Signed-off-by: Saif Alharthi <saif@saifalharthi.me>

Modity test for readablity

Signed-off-by: Saif Alharthi <saif@saifalharthi.me>
  • Loading branch information
saifalharthi committed Mar 28, 2020
1 parent 490bac1 commit 1ddeee0
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
16 changes: 16 additions & 0 deletions go/vt/sqlparser/comments.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,12 @@ func StripComments(sql string) string {
if end <= 1 {
break
}
if start > end {
start, end = end, start
}
if containsQuotations(sql, start, end) {
break
}
sql = sql[:start] + sql[end+2:]
}

Expand All @@ -186,6 +192,16 @@ func StripComments(sql string) string {
return sql
}

func containsQuotations(sql string, start, end int) bool {
indexBefore, indexAfter := start-1, end+2
// Check Boundaries
if indexBefore < 0 || indexAfter >= len(sql) {
return false
}
// Check if the character the index before comments start and end substring is a single or double quotation
return (sql[indexBefore] == '\'' && sql[indexAfter] == '\'') || (sql[indexBefore] == '"' && sql[indexAfter] == '"')
}

// ExtractMysqlComment extracts the version and SQL from a comment-only query
// such as /*!50708 sql here */
func ExtractMysqlComment(sql string) (version string, innerSQL string) {
Expand Down
15 changes: 15 additions & 0 deletions go/vt/sqlparser/comments_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,21 @@ a`,
}, {
input: `-- foo bar`,
outSQL: "",
}, {
input: "select * from customer where name like '*//*'",
outSQL: "select * from customer where name like '*//*'",
}, {
input: "select * from customer where name like '*/%/*'",
outSQL: "select * from customer where name like '*/%/*'",
}, {
input: "select * from customer where name like '*/%/*'",
outSQL: "select * from customer where name like '*/%/*'",
}, {
input: "insert into customer values(1, '*//*')",
outSQL: "insert into customer values(1, '*//*')",
}, {
input: "insert into t5 (col) values('/**/')",
outSQL: "insert into t5 (col) values('/**/')",
}}
for _, testCase := range testCases {
gotSQL := StripComments(testCase.input)
Expand Down

0 comments on commit 1ddeee0

Please sign in to comment.