Expand takes a SQL query, and if it contains * in SELECT or RETURNING clause, expands it to use explicit column names. Returns the expanded query string.
(ctx context.Context, query string)
| 41 | // Expand takes a SQL query, and if it contains * in SELECT or RETURNING clause, |
| 42 | // expands it to use explicit column names. Returns the expanded query string. |
| 43 | func (e *Expander) Expand(ctx context.Context, query string) (string, error) { |
| 44 | // Parse the query |
| 45 | stmts, err := e.parser.Parse(strings.NewReader(query)) |
| 46 | if err != nil { |
| 47 | return "", fmt.Errorf("failed to parse query: %w", err) |
| 48 | } |
| 49 | |
| 50 | if len(stmts) == 0 { |
| 51 | return query, nil |
| 52 | } |
| 53 | |
| 54 | stmt := stmts[0].Raw.Stmt |
| 55 | |
| 56 | // Check if there's any star in the statement (including CTEs, subqueries, etc.) |
| 57 | if !hasStarAnywhere(stmt) { |
| 58 | return query, nil |
| 59 | } |
| 60 | |
| 61 | // Expand all stars in the statement recursively |
| 62 | if err := e.expandNode(ctx, stmt); err != nil { |
| 63 | return "", err |
| 64 | } |
| 65 | |
| 66 | // Format the modified AST back to SQL |
| 67 | expanded := ast.Format(stmts[0].Raw, e.dialect) |
| 68 | |
| 69 | return expanded, nil |
| 70 | } |
| 71 | |
| 72 | // expandNode recursively expands * in all parts of the statement |
| 73 | func (e *Expander) expandNode(ctx context.Context, node ast.Node) error { |