Skip to content

Commit 04766ad

Browse files
authored
Merge pull request #6 from CovenantSQL/fix/versioned-comment-stack
Scan consecutive executable comments without recursive stack growth
2 parents d5b849f + 53ccd84 commit 04766ad

2 files changed

Lines changed: 31 additions & 2 deletions

File tree

‎token.go‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,7 @@ func (tkn *Tokenizer) Error(err string) {
363363
// Scan scans the tokenizer for the next token and returns
364364
// the token type and an optional value.
365365
func (tkn *Tokenizer) Scan() (int, []byte) {
366+
scanAgain:
366367
if tkn.specialComment != nil {
367368
// Enter specialComment scan mode.
368369
// for scanning such kind of comment: /*! MySQL-specific code */
@@ -446,7 +447,10 @@ func (tkn *Tokenizer) Scan() (int, []byte) {
446447
tkn.next()
447448
switch tkn.lastChar {
448449
case '!':
449-
return tkn.scanMySQLSpecificComment()
450+
if typ, val := tkn.scanMySQLSpecificComment(); typ != 0 {
451+
return typ, val
452+
}
453+
goto scanAgain
450454
default:
451455
return tkn.scanCommentType2()
452456
}
@@ -769,7 +773,7 @@ func (tkn *Tokenizer) scanMySQLSpecificComment() (int, []byte) {
769773
}
770774
_, sql := ExtractMysqlComment(buffer.String())
771775
tkn.specialComment = NewStringTokenizer(sql)
772-
return tkn.Scan()
776+
return 0, nil
773777
}
774778

775779
func (tkn *Tokenizer) consumeNext(buffer *bytes2.Buffer) {

‎token_test.go‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,34 @@ package sqlparser
1818

1919
import (
2020
"fmt"
21+
"os"
22+
"os/exec"
23+
"runtime/debug"
24+
"strings"
2125
"testing"
2226
)
2327

28+
func TestVersionedCommentStack(t *testing.T) {
29+
if os.Getenv("SQLPARSER_STACK_TEST") == "1" {
30+
debug.SetMaxStack(256 << 10)
31+
input := strings.Repeat("/*! */", 10000) + "select 1"
32+
queries, statements, err := ParseMultiple(NewStringTokenizer(input))
33+
if err != nil {
34+
t.Fatal(err)
35+
}
36+
if len(queries) != 1 || queries[0] != input || len(statements) != 1 || String(statements[0]) != "select 1" {
37+
t.Fatalf("unexpected parse result: %v, %v", queries, statements)
38+
}
39+
return
40+
}
41+
// A stack overflow terminates the process, so constrain only a child.
42+
cmd := exec.Command(os.Args[0], "-test.run=^TestVersionedCommentStack$")
43+
cmd.Env = append(os.Environ(), "SQLPARSER_STACK_TEST=1")
44+
if output, err := cmd.CombinedOutput(); err != nil {
45+
t.Fatalf("bounded-stack parsing failed: %v\n%s", err, output)
46+
}
47+
}
48+
2449
func TestLiteralID(t *testing.T) {
2550
testcases := []struct {
2651
in string

0 commit comments

Comments
 (0)