Skip to content

Commit

Permalink
parser: don't cut off end-of-line comments
Browse files Browse the repository at this point in the history
Previously, the parser (actually the scanner) removed comments that came
at the end of a statement from the raw sql that was returned along with
the parsed AST. This behavior is now removed.

Release note: None
  • Loading branch information
jordanlewis committed Aug 29, 2022
1 parent 76a121e commit ce18c4b
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 6 deletions.
8 changes: 6 additions & 2 deletions pkg/sql/parser/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,6 @@ func (p *Parser) scanOneStmt() (sql string, tokens []sqlSymType, done bool) {
return p.scanner.In()[startPos:], tokens, true
}
preValID = lval.id
posBeforeScan := p.scanner.Pos()
p.scanner.Scan(&lval)

if preValID == BEGIN && lval.id == ATOMIC {
Expand All @@ -174,7 +173,12 @@ func (p *Parser) scanOneStmt() (sql string, tokens []sqlSymType, done bool) {
curFuncBodyCnt--
}
if lval.id == 0 || (curFuncBodyCnt == 0 && lval.id == ';') {
return p.scanner.In()[startPos:posBeforeScan], tokens, (lval.id == 0)
endPos := p.scanner.Pos()
if lval.id == ';' {
// Don't include the ending semicolon, if there is one, in the raw SQL.
endPos--
}
return p.scanner.In()[startPos:endPos], tokens, (lval.id == 0)
}
lval.pos -= startPos
tokens = append(tokens, lval)
Expand Down
9 changes: 5 additions & 4 deletions pkg/sql/parser/parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -643,10 +643,11 @@ func TestParseSQL(t *testing.T) {
{in: ``, exp: nil},
{in: `SELECT 1`, exp: []string{`SELECT 1`}},
{in: `SELECT 1;`, exp: []string{`SELECT 1`}},
{in: `SELECT 1 /* comment */`, exp: []string{`SELECT 1`}},
{in: `/* comment */ SELECT 1`, exp: []string{`SELECT 1 /* comment */`}},
{in: `SELECT 1 /* comment */`, exp: []string{`SELECT 1 /* comment */`}},
{in: `SELECT 1;SELECT 2`, exp: []string{`SELECT 1`, `SELECT 2`}},
{in: `SELECT 1 /* comment */ ;SELECT 2`, exp: []string{`SELECT 1`, `SELECT 2`}},
{in: `SELECT 1 /* comment */ ; /* comment */ SELECT 2`, exp: []string{`SELECT 1`, `SELECT 2`}},
{in: `SELECT 1 /* comment */ ;SELECT 2`, exp: []string{`SELECT 1 /* comment */ `, `SELECT 2`}},
{in: `SELECT 1 /* comment */ ; /* comment */ SELECT 2`, exp: []string{`SELECT 1 /* comment */ `, `/* comment */ SELECT 2`}},
}
var p parser.Parser // Verify that the same parser can be reused.
for _, d := range testData {
Expand All @@ -660,7 +661,7 @@ func TestParseSQL(t *testing.T) {
res = append(res, stmts[i].SQL)
}
if !reflect.DeepEqual(res, d.exp) {
t.Errorf("expected \n%v\n, but found %v", res, d.exp)
t.Errorf("expected \n%v\n, but found %v", d.exp, res)
}
})
}
Expand Down

0 comments on commit ce18c4b

Please sign in to comment.