Skip to content

Commit

Permalink
parser: fix statement parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
asdine committed Nov 26, 2023
1 parent 389b2dc commit acfecdc
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 18 deletions.
51 changes: 35 additions & 16 deletions internal/sql/parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,28 +80,37 @@ func (p *Parser) ParseQuery() (query.Query, error) {

// ParseQuery parses a Genji SQL string and returns a Query.
func (p *Parser) Parse(fn func(statement.Statement) error) error {
semi := true

for {
if tok, pos, lit := p.ScanIgnoreWhitespace(); tok == scanner.EOF {
err := p.skipMany(scanner.SEMICOLON)
if err != nil {
return err
}

end, err := p.parseOptional(scanner.EOF)
if err != nil {
return err
}
if end {
return nil
} else if tok == scanner.SEMICOLON {
semi = true
} else {
if !semi {
return newParseError(scanner.Tokstr(tok, lit), []string{";"}, pos)
}
p.Unscan()
s, err := p.ParseStatement()
if err != nil {
return err
}
}

s, err := p.ParseStatement()
if err != nil {
return err
}

tok, pos, lit := p.ScanIgnoreWhitespace()
switch tok {
case scanner.EOF:
return fn(s)
case scanner.SEMICOLON:
err = fn(s)
if err != nil {
return err
}

semi = false
default:
p.Unscan()
return newParseError(scanner.Tokstr(tok, lit), []string{";"}, pos)
}
}
}
Expand Down Expand Up @@ -142,6 +151,16 @@ func (p *Parser) ParseStatement() (statement.Statement, error) {
}, pos)
}

func (p *Parser) skipMany(tok scanner.Token) error {
for {
t, _, _ := p.ScanIgnoreWhitespace()
if t != tok {
p.Unscan()
return nil
}
}
}

// parseCondition parses the "WHERE" clause of the query, if it exists.
func (p *Parser) parseCondition() (expr.Expr, error) {
// Check if the WHERE token exists.
Expand Down
4 changes: 2 additions & 2 deletions internal/sql/parser/select.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,13 @@ func (p *Parser) parseSelectStatement() (*statement.SelectStmt, error) {
// Parse limit: "LIMIT expr"
stmt.LimitExpr, err = p.parseLimit()
if err != nil {
return nil, err
return nil, errors.Wrap(err, "failed to parse LIMIT clause")
}

// Parse offset: "OFFSET expr"
stmt.OffsetExpr, err = p.parseOffset()
if err != nil {
return nil, err
return nil, errors.Wrap(err, "failed to parse OFFSET clause")
}

return stmt, nil
Expand Down

0 comments on commit acfecdc

Please sign in to comment.