WITH summary(region, total) AS (SELECT region, SUM(amount) FROM sales GROUP BY region) SELECT * FROM summary
()
| 27 | |
| 28 | // WITH summary(region, total) AS (SELECT region, SUM(amount) FROM sales GROUP BY region) SELECT * FROM summary |
| 29 | func (p *Parser) parseWithStatement() (ast.Statement, error) { |
| 30 | withPos := p.currentLocation() |
| 31 | // Consume WITH |
| 32 | p.advance() |
| 33 | |
| 34 | // Check for RECURSIVE keyword |
| 35 | recursive := false |
| 36 | if p.isType(models.TokenTypeRecursive) { |
| 37 | recursive = true |
| 38 | p.advance() |
| 39 | } |
| 40 | |
| 41 | // Parse Common Table Expressions |
| 42 | ctes := []*ast.CommonTableExpr{} |
| 43 | |
| 44 | for { |
| 45 | cte, err := p.parseCommonTableExpr() |
| 46 | if err != nil { |
| 47 | return nil, goerrors.InvalidCTEError( |
| 48 | fmt.Sprintf("error parsing CTE definition: %v", err), |
| 49 | p.currentLocation(), |
| 50 | "", |
| 51 | ) |
| 52 | } |
| 53 | ctes = append(ctes, cte) |
| 54 | |
| 55 | // Check for more CTEs (comma-separated) |
| 56 | if p.isType(models.TokenTypeComma) { |
| 57 | p.advance() // Consume comma |
| 58 | continue |
| 59 | } |
| 60 | break |
| 61 | } |
| 62 | |
| 63 | // Create WITH clause |
| 64 | withClause := &ast.WithClause{ |
| 65 | Recursive: recursive, |
| 66 | CTEs: ctes, |
| 67 | Pos: withPos, |
| 68 | } |
| 69 | |
| 70 | // Parse the main statement that follows the WITH clause |
| 71 | mainStmt, err := p.parseMainStatementAfterWith() |
| 72 | if err != nil { |
| 73 | return nil, goerrors.InvalidCTEError( |
| 74 | fmt.Sprintf("error parsing statement after WITH clause: %v", err), |
| 75 | p.currentLocation(), |
| 76 | "", |
| 77 | ) |
| 78 | } |
| 79 | |
| 80 | // Attach WITH clause to the main statement |
| 81 | switch stmt := mainStmt.(type) { |
| 82 | case *ast.SelectStatement: |
| 83 | stmt.With = withClause |
| 84 | return stmt, nil |
| 85 | case *ast.SetOperation: |
| 86 | // For set operations, attach WITH to the left statement if it's a SELECT |
no test coverage detected