MCPcopy
hub / github.com/sqlc-dev/sqlc / Expand

Method Expand

internal/x/expander/expander.go:43–70  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

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.
43func (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
73func (e *Expander) expandNode(ctx context.Context, node ast.Node) error {

Callers 4

parseQueryMethod · 0.80
TestExpandPostgreSQLFunction · 0.80
TestExpandMySQLFunction · 0.80
TestExpandSQLiteFunction · 0.80

Calls 4

expandNodeMethod · 0.95
FormatFunction · 0.92
hasStarAnywhereFunction · 0.85
ParseMethod · 0.65

Tested by 3

TestExpandPostgreSQLFunction · 0.64
TestExpandMySQLFunction · 0.64
TestExpandSQLiteFunction · 0.64