Zheyuan Zhao commited on
Commit
de284a1
·
verified ·
1 Parent(s): e145226

Add design doc: pipe-sql-decompiler-design-doc.md

Browse files
Files changed (1) hide show
  1. docs/pipe-sql-decompiler-design-doc.md +1122 -0
docs/pipe-sql-decompiler-design-doc.md ADDED
@@ -0,0 +1,1122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Design Document: Standard SQL to Pipe SQL Decompiler
2
+
3
+ ## 1. Problem Statement
4
+
5
+ We need a deterministic program that transforms standard SQL queries into semantically equivalent GoogleSQL pipe syntax. This decompiler is the critical data generation component for fine-tuning small language models on pipe SQL (see companion document: *Large-Scale Incremental Pipe SQL Synthesis & Specialized Fine-Tuning*).
6
+
7
+ **Input**: A standard SQL query (any dialect) + optional schema definition.
8
+ **Output**: A semantically equivalent pipe SQL query in canonical GoogleSQL syntax.
9
+
10
+ **Requirements**:
11
+ - Deterministic: same input always produces same output.
12
+ - Semantics-preserving: the pipe SQL must return identical results on the same database.
13
+ - High coverage: handle 90%+ of queries in Spider 1.0 and BIRD-SQL benchmarks.
14
+ - Transparent failure: clearly report which SQL patterns could not be transformed.
15
+
16
+ ---
17
+
18
+ ## 2. Approach Evaluation
19
+
20
+ We evaluate four possible approaches before committing to an architecture.
21
+
22
+ ### 2.1 Approach A: LLM-Based Translation
23
+
24
+ Use a frontier LLM (GPT-4o, Claude) to translate standard SQL to pipe SQL.
25
+
26
+ | Criterion | Assessment |
27
+ |---|---|
28
+ | Correctness | Low — LLMs hallucinate syntax, invent non-existent operators, produce queries that don't execute |
29
+ | Determinism | None — non-deterministic by nature |
30
+ | Speed | ~1 query/sec (API-bound) |
31
+ | Cost | ~$0.01–0.05 per query; $500–2,500 for 50K queries |
32
+ | Validation required | Every single output must be execution-validated |
33
+ | Coverage | Moderate — struggles with complex nesting, correlated subqueries |
34
+
35
+ **Verdict**: Rejected as primary approach. Useful only as a fallback for edge cases the deterministic decompiler cannot handle.
36
+
37
+ ### 2.2 Approach B: Regex / String Rewriting
38
+
39
+ Apply pattern-matching rules to the SQL string (e.g., swap clause order, insert `|>` tokens).
40
+
41
+ | Criterion | Assessment |
42
+ |---|---|
43
+ | Correctness | Very low — SQL is not a regular language; regex cannot handle nesting, quoting, or context |
44
+ | Determinism | Yes |
45
+ | Speed | Fast |
46
+ | Coverage | Minimal — breaks on any non-trivial query (subqueries, CTEs, string literals containing SQL keywords) |
47
+
48
+ **Verdict**: Rejected. This is the approach used by DuckDB's community `psql` extension, which is self-described as "quick and dirty regex substitutions" and "mainly an experiment." Not suitable for production data generation.
49
+
50
+ ### 2.3 Approach C: AST-Based Transformation (SQLGlot)
51
+
52
+ Parse SQL into an Abstract Syntax Tree, apply structural transformations, emit pipe SQL.
53
+
54
+ | Criterion | Assessment |
55
+ |---|---|
56
+ | Correctness | High — AST captures full syntactic structure; transformations are provably structure-preserving |
57
+ | Determinism | Yes |
58
+ | Speed | ~1,000 queries/sec (pure Python AST manipulation) |
59
+ | Coverage | High — handles all SQL constructs that SQLGlot can parse (30+ dialects) |
60
+ | Extensibility | New patterns handled by adding transformation rules |
61
+
62
+ **Verdict**: Selected as the primary approach. SQLGlot provides the richest SQL AST available in open source, with built-in optimizer passes (qualify, unnest_subqueries) that directly support our transformation needs.
63
+
64
+ ### 2.4 Approach D: Relational Algebra IR
65
+
66
+ Parse SQL into a relational algebra representation (Scan → Filter → Project → Join → Aggregate → Sort), then emit pipe operators from the relational plan.
67
+
68
+ | Criterion | Assessment |
69
+ |---|---|
70
+ | Correctness | High — relational algebra is the formal foundation of both SQL and pipe syntax |
71
+ | Determinism | Yes |
72
+ | Implementation cost | Very high — requires building or integrating a full SQL-to-relational-algebra compiler (e.g., Apache Calcite) |
73
+ | Coverage | High in theory, but Calcite's Java ecosystem doesn't integrate with our Python pipeline |
74
+
75
+ **Verdict**: Theoretically elegant but impractical. The relational algebra approach adds a heavy dependency (Calcite is Java) and an unnecessary abstraction layer. SQLGlot's AST is close enough to relational algebra for our purposes — a `Select` node with `from_`, `joins`, `where`, `group`, `having`, `order`, `limit` maps directly to relational operators.
76
+
77
+ ### 2.5 Decision: AST-Based with SQLGlot (Approach C)
78
+
79
+ The AST-based approach using SQLGlot is the clear winner. It provides the best balance of correctness, speed, coverage, and implementation cost. The remainder of this document details this architecture.
80
+
81
+ ---
82
+
83
+ ## 3. SQLGlot Capabilities and Limitations
84
+
85
+ ### 3.1 What SQLGlot Provides
86
+
87
+ SQLGlot (v29.x) is a Python SQL parser/transpiler supporting 30+ dialects. It provides:
88
+
89
+ 1. **Unified AST**: All SQL dialects parse into the same `Expression` type hierarchy. A `Select` node is the same whether it came from PostgreSQL, MySQL, or BigQuery.
90
+
91
+ 2. **Rich type system**: 86 aggregate function types (`AggFunc` subclasses: `Count`, `Sum`, `Avg`, `Max`, `Min`, etc.), explicit node types for `Window`, `Join`, `Subquery`, `CTE`, `Union`, `Intersect`, `Except`, and all standard SQL constructs.
92
+
93
+ 3. **Optimizer passes** relevant to decompilation:
94
+ - `qualify()`: Resolves all column references to `table.column`, expands `SELECT *`, expands alias references. Requires schema for full resolution.
95
+ - `unnest_subqueries()`: Converts correlated subqueries into equivalent JOIN patterns. Critical for handling `WHERE EXISTS`, `WHERE IN (correlated)`, and scalar subqueries.
96
+ - `eliminate_ctes()`: Inlines single-use CTEs.
97
+ - `merge_subqueries()`: Flattens derived tables where possible.
98
+ - `simplify()`: Simplifies boolean expressions.
99
+
100
+ 4. **Scope analysis**: `optimizer.scope.build_scope()` / `traverse_scope()` provide scope-aware traversal that correctly distinguishes CTE references from table references and identifies correlated column references across subquery boundaries.
101
+
102
+ 5. **Pipe syntax parsing (one-directional)**: SQLGlot can parse pipe SQL and decompose it into CTE-based standard SQL. Supported pipe operators for parsing: `SELECT`, `WHERE`, `AGGREGATE`, `EXTEND`, `JOIN`, `ORDER BY`, `LIMIT`, `AS`, `PIVOT`, `UNPIVOT`, `TABLESAMPLE`, set operations.
103
+
104
+ 6. **AST manipulation API**:
105
+ - `expression.find(*types)` / `find_all(*types)` — locate nodes by type
106
+ - `expression.walk()` — iterate all descendants
107
+ - `expression.transform(fn)` — apply function to all nodes (DFS pre-order)
108
+ - `expression.replace(new)` — swap node in parent
109
+ - `expression.pop()` — remove from parent
110
+ - `expression.parent` / `find_ancestor(*types)` — navigate upward
111
+
112
+ ### 3.2 What SQLGlot Does NOT Provide
113
+
114
+ 1. **No pipe syntax generator**: There is no `Generator` that outputs `|>` operators. The `Generator` class has zero pipe-related output methods. No dialect produces pipe syntax.
115
+
116
+ 2. **No pipe AST nodes**: When pipe SQL is parsed, pipe nodes are destroyed at parse time and replaced with CTEs. There are no `PipeSelect`, `PipeWhere`, `PipeAggregate` expression types in the AST. The information is irreversibly lost.
117
+
118
+ 3. **No standard-to-pipe transformation**: There is no `to_pipe()`, `decompile()`, or reverse transformation of any kind.
119
+
120
+ **Consequence**: We must build both the transformation logic (AST → pipe structure) and the output generation (pipe structure → string) from scratch. SQLGlot provides the input parsing, qualification, and subquery unnesting; we provide everything after.
121
+
122
+ ---
123
+
124
+ ## 4. Architecture
125
+
126
+ ### 4.1 System Overview
127
+
128
+ ```
129
+ ┌──────────────┐
130
+ │ Input SQL │
131
+ │ (any dialect)│
132
+ └──────┬───────┘
133
+
134
+ ┌────────────▼────────────┐
135
+ │ sqlglot.parse_one() │
136
+ │ (dialect-aware parse) │
137
+ └────────────┬────────────┘
138
+
139
+ ┌────────────▼────────────┐
140
+ │ Pre-Processing │
141
+ │ ┌─ qualify() │
142
+ │ ├─ unnest_subqueries()│
143
+ │ ├─ merge_subqueries() │
144
+ │ └─ simplify() │
145
+ └────────────┬────────────┘
146
+
147
+ ┌────────────▼────────────┐
148
+ │ Classification │
149
+ │ (determine query type │
150
+ │ and complexity tier) │
151
+ └────────────┬────────────┘
152
+
153
+ ┌────────────▼────────────┐
154
+ │ Pipe Emitter │
155
+ │ (AST → pipe operator │
156
+ │ sequence) │
157
+ └────────────┬────────────┘
158
+
159
+ ┌────────────▼────────────┐
160
+ │ Pipe Serializer │
161
+ │ (pipe operators → │
162
+ │ formatted string) │
163
+ └────────────┬────────────┘
164
+
165
+ ┌────────────▼────────────┐
166
+ │ TransformResult │
167
+ │ ┌─ pipe_sql: str │
168
+ │ ├─ warnings: [] │
169
+ │ ├─ unsupported: [] │
170
+ │ └─ coverage: float │
171
+ └─────────────────────────┘
172
+ ```
173
+
174
+ ### 4.2 Module Decomposition
175
+
176
+ ```
177
+ pipe_decompiler/
178
+ ├── __init__.py
179
+ ├── decompiler.py # Top-level orchestrator
180
+ ├── preprocessor.py # SQLGlot qualify + unnest + simplify
181
+ ├── classifier.py # Query complexity classification
182
+ ├── emitter.py # Core AST → pipe operator sequence logic
183
+ ├── rules/
184
+ │ ├── __init__.py
185
+ │ ├── from_rule.py # FROM extraction
186
+ │ ├── join_rule.py # JOIN linearization
187
+ │ ├── where_rule.py # WHERE promotion
188
+ │ ├── aggregate_rule.py # GROUP BY + HAVING decomposition
189
+ │ ├── window_rule.py # Window function + QUALIFY handling
190
+ │ ├── subquery_rule.py # Subquery unrolling
191
+ │ ├── cte_rule.py # CTE handling
192
+ │ ├── setop_rule.py # UNION / INTERSECT / EXCEPT
193
+ │ ├── projection_rule.py # Final SELECT projection
194
+ │ └── terminal_rule.py # ORDER BY, LIMIT, DISTINCT
195
+ ├── serializer.py # Pipe operator sequence → formatted string
196
+ ├── result.py # TransformResult dataclass
197
+ └── tests/
198
+ ├── test_simple.py
199
+ ├── test_joins.py
200
+ ├── test_aggregation.py
201
+ ├── test_subqueries.py
202
+ ├── test_windows.py
203
+ ├── test_ctes.py
204
+ ├── test_setops.py
205
+ ├── test_edge_cases.py
206
+ └── test_execution.py # Differential execution tests
207
+ ```
208
+
209
+ ### 4.3 Data Flow Types
210
+
211
+ ```python
212
+ from dataclasses import dataclass, field
213
+ from typing import List, Optional
214
+ from enum import Enum
215
+
216
+ class PipeOpType(Enum):
217
+ FROM = "FROM"
218
+ SELECT = "SELECT"
219
+ EXTEND = "EXTEND"
220
+ WHERE = "WHERE"
221
+ AGGREGATE = "AGGREGATE"
222
+ JOIN = "JOIN"
223
+ ORDER_BY = "ORDER BY"
224
+ LIMIT = "LIMIT"
225
+ DISTINCT = "DISTINCT"
226
+ DROP = "DROP"
227
+ SET = "SET"
228
+ RENAME = "RENAME"
229
+ AS = "AS"
230
+ UNION = "UNION"
231
+ INTERSECT = "INTERSECT"
232
+ EXCEPT = "EXCEPT"
233
+
234
+ @dataclass
235
+ class PipeOperator:
236
+ """A single pipe operator in the output sequence."""
237
+ op_type: PipeOpType
238
+ sql_fragment: str # The SQL text for this operator (e.g., "AVG(salary) AS avg_sal GROUP BY department")
239
+ source_node: Optional[any] = None # Reference to originating AST node (for debugging)
240
+
241
+ @dataclass
242
+ class PipeQuery:
243
+ """An ordered sequence of pipe operators forming a complete query."""
244
+ operators: List[PipeOperator] = field(default_factory=list)
245
+ ctes: List['PipeQuery'] = field(default_factory=list) # Recursive: each CTE is itself a PipeQuery
246
+ cte_names: List[str] = field(default_factory=list)
247
+
248
+ @dataclass
249
+ class TransformResult:
250
+ """Output of the decompiler."""
251
+ pipe_sql: str # The final pipe SQL string
252
+ pipe_query: PipeQuery # Structured representation
253
+ warnings: List[str] = field(default_factory=list) # Patterns that needed approximation
254
+ unsupported: List[str] = field(default_factory=list) # Patterns that could not be transformed
255
+ coverage: float = 1.0 # 0.0 to 1.0 — fraction of query successfully transformed
256
+ ```
257
+
258
+ ---
259
+
260
+ ## 5. Pre-Processing Pipeline
261
+
262
+ ### 5.1 Why Pre-Processing Is Critical
263
+
264
+ Raw SQL from benchmarks contains ambiguities that make direct transformation unreliable. Pre-processing normalizes the AST into a form where transformation rules can operate without guesswork.
265
+
266
+ ### 5.2 Step 1: Parse
267
+
268
+ ```python
269
+ import sqlglot
270
+
271
+ ast = sqlglot.parse_one(sql, read=source_dialect, error_level=ErrorLevel.RAISE)
272
+ ```
273
+
274
+ The `read` parameter selects the source dialect parser (e.g., `"postgres"`, `"mysql"`, `"bigquery"`). For benchmark queries, `"sqlite"` (Spider) or `"bigquery"` (BIRD-SQL) is typical.
275
+
276
+ ### 5.3 Step 2: Qualify
277
+
278
+ ```python
279
+ from sqlglot.optimizer import qualify
280
+
281
+ qualified = qualify.qualify(
282
+ ast,
283
+ schema=schema, # dict mapping table names to column names/types
284
+ validate_qualify_columns=False, # Allow partial resolution if schema is incomplete
285
+ infer_schema=True, # Infer schema from query structure when possible
286
+ )
287
+ ```
288
+
289
+ **What this does**:
290
+ - Resolves `name` → `table.name` for all column references.
291
+ - Expands `SELECT *` → `SELECT table.col1, table.col2, ...`.
292
+ - Expands alias references (e.g., `WHERE total > 100` when `total` is a SELECT alias).
293
+ - Adds explicit table aliases (`FROM orders` → `FROM orders AS orders`).
294
+ - Quotes all identifiers for unambiguous parsing.
295
+
296
+ **Why it matters for decompilation**:
297
+ - Knowing which table owns each column is essential for correct JOIN linearization and aggregate/group-key classification.
298
+ - Star expansion is necessary to emit explicit `|> SELECT` projections.
299
+
300
+ **Limitations**:
301
+ - Requires schema for full resolution. Without it, ambiguous columns (appearing in multiple tables) remain unqualified.
302
+ - Does not resolve UDF/TVF output schemas or dynamic table references.
303
+
304
+ ### 5.4 Step 3: Unnest Subqueries (Selective)
305
+
306
+ ```python
307
+ from sqlglot.optimizer import unnest_subqueries
308
+
309
+ unnested = unnest_subqueries.unnest_subqueries(qualified)
310
+ ```
311
+
312
+ **What this does**: Converts correlated subqueries in `WHERE` into equivalent `LEFT JOIN` patterns.
313
+
314
+ **Example**:
315
+ ```sql
316
+ -- Before:
317
+ SELECT e.name FROM employees e
318
+ WHERE e.salary > (SELECT AVG(salary) FROM employees WHERE dept = e.dept)
319
+
320
+ -- After unnest:
321
+ SELECT e.name FROM employees e
322
+ LEFT JOIN (
323
+ SELECT AVG(salary) AS _col_0, dept AS _u_1
324
+ FROM employees GROUP BY dept
325
+ ) AS _u_0 ON _u_0._u_1 = e.dept
326
+ WHERE e.salary > _u_0._col_0
327
+ ```
328
+
329
+ The JOIN form converts cleanly to pipe syntax. Without unnesting, the correlated subquery would need to remain as-is inside a `|> WHERE`, which is valid but doesn't exploit the linear pipe structure.
330
+
331
+ **What it does NOT handle**:
332
+ - Multi-level correlated subqueries (inner subquery referencing two different outer scopes).
333
+ - Correlated subqueries with `LIMIT` / `OFFSET`.
334
+ - `NOT EXISTS` patterns may produce double negation (`NOT NOT ... IS NULL`), requiring simplification.
335
+
336
+ **Safety**: Run `simplify()` after `unnest_subqueries()` to clean up redundant boolean expressions.
337
+
338
+ ### 5.5 Step 4: Merge Subqueries (Selective)
339
+
340
+ ```python
341
+ from sqlglot.optimizer import merge_subqueries
342
+
343
+ merged = merge_subqueries.merge_subqueries(unnested)
344
+ ```
345
+
346
+ **What this does**: Flattens derived tables (subqueries in `FROM`) into the outer query where possible. This reduces nesting that pipe syntax can express linearly.
347
+
348
+ **Example**:
349
+ ```sql
350
+ -- Before:
351
+ SELECT * FROM (SELECT dept, AVG(salary) AS avg FROM emp GROUP BY dept) sub WHERE avg > 100
352
+
353
+ -- After merge (if safe):
354
+ SELECT dept, AVG(salary) AS avg FROM emp GROUP BY dept HAVING avg > 100
355
+ ```
356
+
357
+ The merged form is simpler to transform. However, not all derived tables can be safely merged (e.g., if the subquery contains LIMIT, DISTINCT, or window functions).
358
+
359
+ ### 5.6 Step 5: Simplify
360
+
361
+ ```python
362
+ from sqlglot.optimizer import simplify
363
+
364
+ simplified = simplify.simplify(merged)
365
+ ```
366
+
367
+ Cleans up boolean expression artifacts from previous optimizer passes (e.g., `NOT NOT x IS NULL` → `x IS NULL`, `TRUE AND x` → `x`).
368
+
369
+ ### 5.7 Passes to AVOID
370
+
371
+ The following SQLGlot optimizer passes should **not** be used because they change query semantics in ways that make pipe transformation harder or produce unexpected results:
372
+
373
+ | Pass | Why to avoid |
374
+ |---|---|
375
+ | `pushdown_predicates` | Moves WHERE conditions into JOINs, changing the natural clause boundaries we want to preserve |
376
+ | `optimize_joins` | Reorders joins for performance; we want to preserve the author's intended join order |
377
+ | `eliminate_joins` | Removes "unnecessary" joins; changes query structure |
378
+ | `pushdown_projections` | Removes unused columns early; we want to preserve the full column set until the final SELECT |
379
+
380
+ ---
381
+
382
+ ## 6. Query Classification
383
+
384
+ Before applying transformation rules, classify the query to determine which rules are needed and what complexity tier it belongs to.
385
+
386
+ ### 6.1 Complexity Tiers
387
+
388
+ | Tier | Characteristics | Example | Expected Coverage |
389
+ |---|---|---|---|
390
+ | **T1: Simple** | Single table, no joins, no subqueries, no aggregation | `SELECT name FROM users WHERE age > 21` | 100% |
391
+ | **T2: Aggregate** | Single table with GROUP BY / HAVING, no subqueries | `SELECT dept, COUNT(*) FROM emp GROUP BY dept HAVING COUNT(*) > 5` | 100% |
392
+ | **T3: Join** | Multi-table joins (any type), no subqueries | `SELECT ... FROM a JOIN b ON ... JOIN c ON ...` | 100% |
393
+ | **T4: Join + Aggregate** | Multi-table with joins and aggregation | `SELECT dept, SUM(amount) FROM orders JOIN customers ON ... GROUP BY dept` | 100% |
394
+ | **T5: Window** | Window functions and/or QUALIFY | `SELECT ..., ROW_NUMBER() OVER (...) AS rn ... QUALIFY rn = 1` | 100% |
395
+ | **T6: Subquery (simple)** | Non-correlated subqueries in WHERE (IN, EXISTS, scalar) | `WHERE id IN (SELECT id FROM vips)` | 95%+ |
396
+ | **T7: Subquery (correlated)** | Correlated subqueries (converted to JOINs by unnest) | `WHERE salary > (SELECT AVG(salary) FROM ... WHERE dept = outer.dept)` | 85%+ |
397
+ | **T8: CTE** | WITH clauses (non-recursive) | `WITH cte AS (...) SELECT ... FROM cte` | 95%+ |
398
+ | **T9: Set Operations** | UNION / INTERSECT / EXCEPT | `SELECT ... UNION ALL SELECT ...` | 100% |
399
+ | **T10: Complex** | Multiple of the above combined | Nested CTEs with correlated subqueries, window functions, and set operations | 70%+ |
400
+
401
+ ### 6.2 Classification Logic
402
+
403
+ ```python
404
+ def classify(ast: exp.Expression) -> Set[str]:
405
+ """Return set of feature tags for the query."""
406
+ features = set()
407
+
408
+ if ast.find(exp.Join):
409
+ features.add("join")
410
+ if ast.find(exp.Group):
411
+ features.add("aggregate")
412
+ if ast.find(exp.Having):
413
+ features.add("having")
414
+ if any(isinstance(n, exp.AggFunc) for n in ast.walk()):
415
+ features.add("agg_func")
416
+ if ast.find(exp.Window):
417
+ features.add("window")
418
+ if ast.args.get("qualify"):
419
+ features.add("qualify")
420
+ if ast.find(exp.Subquery):
421
+ features.add("subquery")
422
+ if ast.find(exp.CTE):
423
+ features.add("cte")
424
+ if isinstance(ast, (exp.Union, exp.Intersect, exp.Except)):
425
+ features.add("setop")
426
+ if ast.find(exp.Exists):
427
+ features.add("exists")
428
+ if any(isinstance(n, exp.In) and n.find(exp.Subquery) for n in ast.walk()):
429
+ features.add("in_subquery")
430
+
431
+ # Check for correlated subqueries using scope analysis
432
+ from sqlglot.optimizer.scope import traverse_scope
433
+ for scope in traverse_scope(ast):
434
+ if scope.external_columns:
435
+ features.add("correlated")
436
+ break
437
+
438
+ return features
439
+ ```
440
+
441
+ ---
442
+
443
+ ## 7. Transformation Rules
444
+
445
+ ### 7.1 Rule Application Order
446
+
447
+ Rules are applied in a fixed order that mirrors the logical data flow of a pipe query:
448
+
449
+ ```
450
+ 1. CTE handling — Extract and recursively transform CTEs
451
+ 2. Set operation handling — Decompose UNION/INTERSECT/EXCEPT
452
+ 3. FROM extraction — Extract the source table(s)
453
+ 4. JOIN linearization — Convert JOINs to sequential |> JOIN operators
454
+ 5. WHERE promotion — Convert pre-aggregation WHERE
455
+ 6. Expression analysis — Classify SELECT expressions into categories
456
+ 7. Pre-aggregation EXTEND — Emit computed columns needed before aggregation
457
+ 8. AGGREGATE emission — Emit |> AGGREGATE with GROUP BY
458
+ 9. Post-agg WHERE — Convert HAVING to |> WHERE
459
+ 10. Window EXTEND — Emit window functions as |> EXTEND
460
+ 11. Post-window WHERE — Convert QUALIFY to |> WHERE
461
+ 12. Final SELECT — Emit |> SELECT for final projection
462
+ 13. ORDER BY — Emit |> ORDER BY
463
+ 14. LIMIT / OFFSET — Emit |> LIMIT
464
+ 15. DISTINCT — Emit |> DISTINCT (if needed)
465
+ ```
466
+
467
+ This ordering is deterministic and canonical. When multiple valid orderings exist, this order is always used. This ensures identical input always produces identical output, which is critical for training data consistency.
468
+
469
+ ### 7.2 Rule 1: CTE Handling
470
+
471
+ **Input**: A `Select` node with `with_` argument containing CTE definitions.
472
+
473
+ **Strategy**: Preserve the WITH wrapper. Recursively decompile each CTE body and the main query independently.
474
+
475
+ ```python
476
+ def transform_ctes(ast: exp.Select) -> PipeQuery:
477
+ pipe_query = PipeQuery()
478
+
479
+ with_clause = ast.args.get("with_")
480
+ if with_clause:
481
+ for cte in with_clause.expressions:
482
+ cte_name = cte.alias
483
+ cte_body = cte.this # The inner Select/Union
484
+ cte_pipe = emit_pipe_query(cte_body) # Recursive call
485
+ pipe_query.ctes.append(cte_pipe)
486
+ pipe_query.cte_names.append(cte_name)
487
+
488
+ # Remove WITH from main query before processing
489
+ ast.set("with_", None)
490
+
491
+ # Process main query
492
+ main_pipe = emit_pipe_query(ast)
493
+ pipe_query.operators = main_pipe.operators
494
+ return pipe_query
495
+ ```
496
+
497
+ **Recursive CTEs**: Preserved as-is with `WITH RECURSIVE`. The recursive and base cases are each pipe-ified independently. The `UNION ALL` between them remains.
498
+
499
+ **Edge case — SELECT without FROM**: Queries like `SELECT 1 AS x, CURRENT_TIMESTAMP` have no table source. These cannot use the `FROM`-first pipe pattern and are emitted as standard SQL.
500
+
501
+ ### 7.3 Rule 2: Set Operation Handling
502
+
503
+ **Input**: A `Union`, `Intersect`, or `Except` node.
504
+
505
+ **Strategy**: The AST represents set operations as a binary tree (left-recursive). Linearize by walking the left spine.
506
+
507
+ ```python
508
+ def transform_setop(ast: exp.Union | exp.Intersect | exp.Except) -> PipeQuery:
509
+ # Collect all branches by walking the left spine
510
+ branches = []
511
+ ops = []
512
+ node = ast
513
+ while isinstance(node, (exp.Union, exp.Intersect, exp.Except)):
514
+ branches.append(node.expression) # Right branch
515
+ op_name = type(node).__name__.upper()
516
+ modifier = "" if node.args.get("distinct") else " ALL"
517
+ ops.append(f"{op_name}{modifier}")
518
+ node = node.this # Left branch
519
+ branches.append(node) # The leftmost SELECT
520
+ branches.reverse()
521
+ ops.reverse()
522
+
523
+ # First branch becomes the FROM
524
+ pipe_query = emit_pipe_query(branches[0])
525
+
526
+ # Subsequent branches become |> UNION/INTERSECT/EXCEPT operators
527
+ for i, (branch, op) in enumerate(zip(branches[1:], ops)):
528
+ branch_pipe = emit_pipe_query(branch)
529
+ branch_sql = serialize_pipe_query(branch_pipe)
530
+ pipe_query.operators.append(
531
+ PipeOperator(PipeOpType[op.split()[0]], f"({branch_sql})")
532
+ )
533
+
534
+ return pipe_query
535
+ ```
536
+
537
+ **Output example**:
538
+ ```sql
539
+ FROM t1 |> SELECT name
540
+ |> UNION ALL (FROM t2 |> SELECT name)
541
+ |> EXCEPT DISTINCT (FROM t3 |> SELECT name)
542
+ ```
543
+
544
+ ### 7.4 Rule 3: FROM Extraction
545
+
546
+ **Input**: A `Select` node with a `from_` argument.
547
+
548
+ **Strategy**: Extract the FROM clause as the first pipe operator.
549
+
550
+ ```python
551
+ def extract_from(ast: exp.Select) -> PipeOperator:
552
+ from_clause = ast.args.get("from_")
553
+ if not from_clause:
554
+ raise UnsupportedError("SELECT without FROM cannot be expressed in pipe syntax")
555
+
556
+ table_expr = from_clause.this # The table/subquery expression
557
+
558
+ # Handle derived tables (subqueries in FROM)
559
+ if isinstance(table_expr, exp.Subquery):
560
+ inner_pipe = emit_pipe_query(table_expr.this) # Recursive
561
+ inner_sql = serialize_pipe_query(inner_pipe)
562
+ alias = table_expr.alias
563
+ return PipeOperator(PipeOpType.FROM, f"({inner_sql}) AS {alias}")
564
+
565
+ return PipeOperator(PipeOpType.FROM, table_expr.sql())
566
+ ```
567
+
568
+ **Comma joins** (`FROM a, b, c`): SQLGlot parses these as implicit `CROSS JOIN`. They appear in `ast.args["joins"]` or as multiple expressions in the FROM clause. Handled by the JOIN rule.
569
+
570
+ ### 7.5 Rule 4: JOIN Linearization
571
+
572
+ **Input**: The `joins` list from the `Select` node.
573
+
574
+ **Strategy**: Emit each JOIN as a separate `|> JOIN` operator in order.
575
+
576
+ ```python
577
+ def linearize_joins(ast: exp.Select) -> List[PipeOperator]:
578
+ operators = []
579
+ for join in ast.args.get("joins", []):
580
+ join_type = []
581
+ if join.side: # LEFT, RIGHT, FULL
582
+ join_type.append(join.side)
583
+ if join.kind: # INNER, CROSS, SEMI, ANTI
584
+ join_type.append(join.kind)
585
+ join_type.append("JOIN")
586
+ join_type_str = " ".join(join_type)
587
+
588
+ table = join.this.sql() # Table or subquery being joined
589
+
590
+ # Handle subquery joins — recursively decompile
591
+ if isinstance(join.this, exp.Subquery):
592
+ inner_pipe = emit_pipe_query(join.this.this)
593
+ table = f"({serialize_pipe_query(inner_pipe)}) AS {join.this.alias}"
594
+
595
+ condition = ""
596
+ if join.args.get("on"):
597
+ condition = f" ON {join.args['on'].sql()}"
598
+ elif join.args.get("using"):
599
+ cols = ", ".join(col.sql() for col in join.args["using"])
600
+ condition = f" USING ({cols})"
601
+
602
+ operators.append(
603
+ PipeOperator(PipeOpType.JOIN, f"{join_type_str} {table}{condition}")
604
+ )
605
+ return operators
606
+ ```
607
+
608
+ **Self-joins**: Require `|> AS` before the JOIN to alias the left side:
609
+ ```sql
610
+ FROM employees |> AS e1
611
+ |> JOIN employees AS e2 ON e1.manager_id = e2.id
612
+ ```
613
+
614
+ The decompiler detects self-joins (same table appearing in FROM and a JOIN) and inserts `|> AS` automatically.
615
+
616
+ ### 7.6 Rule 5: WHERE Promotion
617
+
618
+ **Input**: The `where` argument from the `Select` node.
619
+
620
+ **Strategy**: Emit as `|> WHERE` immediately after FROM and JOINs.
621
+
622
+ ```python
623
+ def promote_where(ast: exp.Select) -> Optional[PipeOperator]:
624
+ where = ast.args.get("where")
625
+ if not where:
626
+ return None
627
+ return PipeOperator(PipeOpType.WHERE, where.this.sql())
628
+ ```
629
+
630
+ This is the simplest rule. The WHERE condition expression is emitted as-is.
631
+
632
+ **Subqueries in WHERE**: Non-correlated subqueries (`WHERE id IN (SELECT ...)`) are preserved inline. The inner subquery can optionally be recursively decompiled to pipe syntax:
633
+ ```sql
634
+ |> WHERE id IN (FROM vip_customers |> SELECT id)
635
+ ```
636
+
637
+ ### 7.7 Rule 6: Expression Analysis
638
+
639
+ **Purpose**: Classify each expression in the `SELECT` list into one of four categories. This classification drives rules 7–12.
640
+
641
+ ```python
642
+ from sqlglot import expressions as exp
643
+
644
+ def classify_select_expressions(ast: exp.Select) -> dict:
645
+ """Classify SELECT expressions into categories."""
646
+ result = {
647
+ "group_keys": [], # Expressions that appear in GROUP BY
648
+ "aggregates": [], # Expressions containing aggregate functions
649
+ "windows": [], # Expressions containing window functions
650
+ "plain": [], # Everything else (simple column refs, CASE, arithmetic)
651
+ }
652
+
653
+ group_exprs = set()
654
+ if ast.args.get("group"):
655
+ for g in ast.args["group"].expressions:
656
+ group_exprs.add(g.sql())
657
+
658
+ for expr in ast.expressions:
659
+ # Get the inner expression (unwrap Alias if present)
660
+ inner = expr.this if isinstance(expr, exp.Alias) else expr
661
+
662
+ has_agg = any(isinstance(n, exp.AggFunc) for n in inner.walk())
663
+ has_window = any(isinstance(n, exp.Window) for n in inner.walk())
664
+
665
+ if has_window:
666
+ result["windows"].append(expr)
667
+ elif has_agg:
668
+ result["aggregates"].append(expr)
669
+ elif inner.sql() in group_exprs or (isinstance(expr, exp.Alias) and expr.alias in group_exprs):
670
+ result["group_keys"].append(expr)
671
+ else:
672
+ result["plain"].append(expr)
673
+
674
+ return result
675
+ ```
676
+
677
+ ### 7.8 Rule 7: AGGREGATE Emission
678
+
679
+ **Input**: GROUP BY clause + aggregate expressions from the SELECT list + HAVING clause.
680
+
681
+ **Strategy**: Fuse grouping and aggregation into a single `|> AGGREGATE ... GROUP BY` operator. Convert HAVING to a subsequent `|> WHERE`.
682
+
683
+ ```python
684
+ def emit_aggregate(ast: exp.Select, classified: dict) -> List[PipeOperator]:
685
+ operators = []
686
+ group = ast.args.get("group")
687
+ if not group and not classified["aggregates"]:
688
+ return operators
689
+
690
+ # Build AGGREGATE clause
691
+ agg_parts = []
692
+ for expr in classified["aggregates"]:
693
+ agg_parts.append(expr.sql())
694
+
695
+ # Handle HAVING: may reference aggregates not in SELECT
696
+ having = ast.args.get("having")
697
+ extra_aggs = []
698
+ if having:
699
+ # Find aggregate functions in HAVING that aren't already in SELECT
700
+ for node in having.this.walk():
701
+ if isinstance(node, exp.AggFunc):
702
+ agg_sql = node.sql()
703
+ if not any(agg_sql in a for a in agg_parts):
704
+ alias = f"_having_{len(extra_aggs)}"
705
+ extra_aggs.append(f"{agg_sql} AS {alias}")
706
+ # Rewrite HAVING to reference the alias
707
+ node.replace(exp.Column(this=exp.to_identifier(alias)))
708
+
709
+ agg_parts.extend(extra_aggs)
710
+
711
+ agg_str = ", ".join(agg_parts)
712
+
713
+ # Build GROUP BY clause
714
+ group_parts = []
715
+ if group:
716
+ for g in group.expressions:
717
+ group_parts.append(g.sql())
718
+
719
+ group_str = " GROUP BY " + ", ".join(group_parts) if group_parts else ""
720
+
721
+ if agg_str or group_str:
722
+ operators.append(
723
+ PipeOperator(PipeOpType.AGGREGATE, f"{agg_str}{group_str}")
724
+ )
725
+
726
+ # Convert HAVING to post-AGGREGATE WHERE
727
+ if having:
728
+ operators.append(
729
+ PipeOperator(PipeOpType.WHERE, having.this.sql())
730
+ )
731
+
732
+ # If extra aggregates were synthesized for HAVING, add SELECT to remove them
733
+ if extra_aggs:
734
+ # Project only the original columns (exclude _having_* temporaries)
735
+ original_cols = [g.sql() for g in group.expressions] if group else []
736
+ original_cols += [e.alias if isinstance(e, exp.Alias) else e.sql() for e in classified["aggregates"]]
737
+ operators.append(
738
+ PipeOperator(PipeOpType.SELECT, ", ".join(original_cols))
739
+ )
740
+
741
+ return operators
742
+ ```
743
+
744
+ **Full-table aggregation** (no GROUP BY): Emitted as `|> AGGREGATE SUM(x) AS total` without a GROUP BY clause. Output is a single row.
745
+
746
+ **HAVING referencing aggregates not in SELECT**: The decompiler synthesizes temporary aggregate columns with `_having_N` aliases, adds a WHERE filter, then projects them away with a final SELECT. Example:
747
+
748
+ ```sql
749
+ -- Input:
750
+ SELECT department FROM emp GROUP BY department HAVING COUNT(*) > 10
751
+
752
+ -- Output:
753
+ FROM emp
754
+ |> AGGREGATE COUNT(*) AS _having_0 GROUP BY department
755
+ |> WHERE _having_0 > 10
756
+ |> SELECT department
757
+ ```
758
+
759
+ ### 7.9 Rule 8: Window Function Handling
760
+
761
+ **Input**: Window function expressions from the SELECT list + QUALIFY clause.
762
+
763
+ **Strategy**: Emit window functions as `|> EXTEND` operators. Convert QUALIFY to `|> WHERE`.
764
+
765
+ ```python
766
+ def emit_windows(classified: dict, ast: exp.Select) -> List[PipeOperator]:
767
+ operators = []
768
+
769
+ for expr in classified["windows"]:
770
+ operators.append(
771
+ PipeOperator(PipeOpType.EXTEND, expr.sql())
772
+ )
773
+
774
+ # Convert QUALIFY to post-window WHERE
775
+ qualify = ast.args.get("qualify")
776
+ if qualify:
777
+ operators.append(
778
+ PipeOperator(PipeOpType.WHERE, qualify.this.sql())
779
+ )
780
+
781
+ return operators
782
+ ```
783
+
784
+ **Window functions in non-windowed queries**: If the query has window functions but no GROUP BY, the EXTEND operators appear after the WHERE (if any).
785
+
786
+ **Multiple window functions**: Each can be a separate EXTEND or combined into one:
787
+ ```sql
788
+ -- Combined (single EXTEND):
789
+ |> EXTEND ROW_NUMBER() OVER (...) AS rn, SUM(amount) OVER (...) AS running_total
790
+
791
+ -- Separate (multiple EXTENDs):
792
+ |> EXTEND ROW_NUMBER() OVER (...) AS rn
793
+ |> EXTEND SUM(amount) OVER (...) AS running_total
794
+ ```
795
+
796
+ The decompiler uses the combined form by default for brevity.
797
+
798
+ ### 7.10 Rule 9: Final SELECT Projection
799
+
800
+ **Input**: The remaining SELECT expressions after aggregates and windows have been extracted.
801
+
802
+ **Strategy**: If the pipe operators so far already produce exactly the desired columns in the desired order, omit the SELECT. Otherwise, emit `|> SELECT` to project to the final column set.
803
+
804
+ ```python
805
+ def emit_final_select(ast: exp.Select, classified: dict, preceding_ops: List[PipeOperator]) -> Optional[PipeOperator]:
806
+ # Determine if a final SELECT is needed
807
+ # After AGGREGATE, output is group_keys + aggregate aliases
808
+ # After EXTEND, output adds window columns
809
+ # If the desired output matches, no SELECT needed
810
+
811
+ has_aggregate = any(op.op_type == PipeOpType.AGGREGATE for op in preceding_ops)
812
+
813
+ if not has_aggregate and not classified["windows"]:
814
+ # Simple query: the SELECT defines the entire projection
815
+ select_exprs = [e.sql() for e in ast.expressions]
816
+ return PipeOperator(PipeOpType.SELECT, ", ".join(select_exprs))
817
+
818
+ # After AGGREGATE + EXTEND, check if we need to reorder or drop columns
819
+ desired = [e.alias if isinstance(e, exp.Alias) else e.sql() for e in ast.expressions]
820
+ # Compare with what the pipeline produces... (implementation detail)
821
+
822
+ # If mismatch, emit SELECT
823
+ return PipeOperator(PipeOpType.SELECT, ", ".join(desired))
824
+ ```
825
+
826
+ **SELECT DISTINCT**: If the original query has `SELECT DISTINCT`, emit either `|> SELECT DISTINCT ...` or `|> SELECT ... |> DISTINCT`.
827
+
828
+ ### 7.11 Rule 10: Terminal Operators
829
+
830
+ ```python
831
+ def emit_terminals(ast: exp.Select) -> List[PipeOperator]:
832
+ operators = []
833
+
834
+ order = ast.args.get("order")
835
+ if order:
836
+ order_parts = [o.sql() for o in order.expressions]
837
+ operators.append(PipeOperator(PipeOpType.ORDER_BY, ", ".join(order_parts)))
838
+
839
+ limit = ast.args.get("limit")
840
+ if limit:
841
+ limit_str = limit.this.sql()
842
+ offset = ast.args.get("offset")
843
+ if offset:
844
+ limit_str += f" OFFSET {offset.this.sql()}"
845
+ operators.append(PipeOperator(PipeOpType.LIMIT, limit_str))
846
+
847
+ return operators
848
+ ```
849
+
850
+ ---
851
+
852
+ ## 8. Serialization
853
+
854
+ ### 8.1 Pipe Query to String
855
+
856
+ ```python
857
+ def serialize_pipe_query(query: PipeQuery, indent: int = 0) -> str:
858
+ lines = []
859
+
860
+ # Emit CTEs
861
+ if query.ctes:
862
+ cte_defs = []
863
+ for name, cte_query in zip(query.cte_names, query.ctes):
864
+ cte_sql = serialize_pipe_query(cte_query, indent=indent + 2)
865
+ cte_defs.append(f"{name} AS (\n{cte_sql}\n)")
866
+ lines.append("WITH " + ",\n ".join(cte_defs))
867
+
868
+ # Emit operators
869
+ for i, op in enumerate(query.operators):
870
+ if i == 0:
871
+ # First operator (FROM) — no pipe prefix
872
+ lines.append(f"{op.op_type.value} {op.sql_fragment}")
873
+ else:
874
+ lines.append(f"|> {op.op_type.value} {op.sql_fragment}")
875
+
876
+ prefix = " " * indent
877
+ return "\n".join(prefix + line for line in lines)
878
+ ```
879
+
880
+ ### 8.2 Formatting Conventions
881
+
882
+ - One operator per line.
883
+ - `|>` prefix aligned at the same indentation level.
884
+ - Multi-line operator arguments (e.g., long AGGREGATE with many columns) indented by 4 spaces.
885
+ - Subqueries within operators indented by an additional 2 spaces.
886
+
887
+ ---
888
+
889
+ ## 9. Column Visibility Tracking
890
+
891
+ ### 9.1 Why Track Column Visibility
892
+
893
+ The decompiler must know the active column set after each pipe operator to:
894
+ 1. Determine whether a final `|> SELECT` is needed.
895
+ 2. Verify that emitted operators reference valid columns.
896
+ 3. Handle `HAVING` references to aggregates not in `SELECT`.
897
+ 4. Detect when `|> AS` is needed before a self-join.
898
+
899
+ ### 9.2 Visibility Model
900
+
901
+ ```python
902
+ @dataclass
903
+ class ColumnState:
904
+ """Tracks visible columns at a point in the pipe."""
905
+ columns: Dict[str, str] # name -> type (or "unknown")
906
+ table_aliases: Dict[str, List[str]] # alias -> [column names]
907
+
908
+ def apply_operator(state: ColumnState, op: PipeOperator) -> ColumnState:
909
+ """Compute new column state after applying a pipe operator."""
910
+ match op.op_type:
911
+ case PipeOpType.FROM:
912
+ return schema_lookup(op.sql_fragment)
913
+ case PipeOpType.SELECT:
914
+ return ColumnState(
915
+ columns={col: infer_type(col) for col in parse_select_list(op.sql_fragment)},
916
+ table_aliases={} # SELECT destroys aliases
917
+ )
918
+ case PipeOpType.EXTEND:
919
+ new_state = copy(state)
920
+ for col in parse_extend_list(op.sql_fragment):
921
+ new_state.columns[col.alias] = infer_type(col)
922
+ return new_state
923
+ case PipeOpType.AGGREGATE:
924
+ # Only group keys + aggregate aliases survive
925
+ return ColumnState(
926
+ columns=parse_aggregate_output(op.sql_fragment),
927
+ table_aliases={} # AGGREGATE destroys aliases
928
+ )
929
+ case PipeOpType.WHERE | PipeOpType.ORDER_BY | PipeOpType.LIMIT | PipeOpType.DISTINCT:
930
+ return state # No schema change
931
+ case PipeOpType.JOIN:
932
+ new_state = copy(state)
933
+ right_cols = schema_lookup(parse_join_table(op.sql_fragment))
934
+ new_state.columns.update(right_cols.columns)
935
+ return new_state
936
+ case PipeOpType.DROP:
937
+ new_state = copy(state)
938
+ for col in parse_drop_list(op.sql_fragment):
939
+ new_state.columns.pop(col, None)
940
+ return new_state
941
+ ```
942
+
943
+ Key invariants from the GoogleSQL spec:
944
+ - **SELECT** and **AGGREGATE** create new column scopes (destroy previous aliases).
945
+ - **EXTEND**, **WHERE**, **ORDER BY**, **LIMIT**, **DISTINCT** preserve the existing scope.
946
+ - **JOIN** merges left and right column sets.
947
+ - **DROP** removes columns but table aliases can still access originals (a subtlety we don't need for decompilation).
948
+
949
+ ---
950
+
951
+ ## 10. Edge Cases and Limitations
952
+
953
+ ### 10.1 Patterns That Cannot Be Pipe-ified
954
+
955
+ | Pattern | Reason | Handling |
956
+ |---|---|---|
957
+ | `SELECT 1 AS x` (no FROM) | No table source for pipe entry | Emit as standard SQL; flag in `unsupported` |
958
+ | `INSERT / UPDATE / DELETE / MERGE` | DML, not queries | Out of scope; reject |
959
+ | `CREATE TABLE AS SELECT` | DDL wrapper | Pipe-ify the inner SELECT; preserve the DDL wrapper |
960
+
961
+ ### 10.2 Patterns That Require Special Care
962
+
963
+ | Pattern | Challenge | Strategy |
964
+ |---|---|---|
965
+ | **Recursive CTEs** | Cannot flatten; recursive reference is self-referential | Preserve WITH RECURSIVE; pipe-ify base and recursive cases independently |
966
+ | **HAVING referencing aggregates not in SELECT** | Pipe AGGREGATE only produces columns listed in AGGREGATE and GROUP BY | Synthesize temporary aggregate aliases, filter, then project away |
967
+ | **Multi-level aggregation** (aggregation of aggregation) | Standard SQL requires nesting; pipe eliminates this naturally | Emit two sequential `\|> AGGREGATE` operators — pipe syntax's strength |
968
+ | **Implicit CROSS JOINs** (`FROM a, b`) | No explicit JOIN keyword | Convert to `\|> CROSS JOIN b` |
969
+ | **Self-joins** | Pipe input table needs a name for ON condition | Insert `\|> AS alias` before the JOIN |
970
+ | **Correlated subqueries that unnest failed to convert** | Complex correlation patterns | Preserve as-is inside `\|> WHERE`; flag in `warnings` |
971
+ | **EXISTS / NOT EXISTS** | After unnesting, may produce `LEFT JOIN ... WHERE ... IS [NOT] NULL` | Clean up double negation with simplify() |
972
+ | **DISTINCT ON (expr)** (PostgreSQL-specific) | Not available in GoogleSQL pipe syntax | Convert to `\|> EXTEND ROW_NUMBER() OVER (PARTITION BY expr ORDER BY ...) AS rn \|> WHERE rn = 1` (SQLGlot's `eliminate_distinct_on` handles this) |
973
+ | **Aggregated window functions** (`SUM(COUNT(*)) OVER ()`) | Requires two-stage pipeline | Split: `\|> AGGREGATE COUNT(*) AS cnt GROUP BY x \|> EXTEND SUM(cnt) OVER () AS total` |
974
+ | **Scalar subqueries in SELECT** | `SELECT (SELECT MAX(x) FROM t2) AS max_x, ...` | Preserve as-is within `\|> SELECT`; optionally convert to `\|> JOIN` + `\|> EXTEND` |
975
+
976
+ ### 10.3 Coverage Estimate by Benchmark
977
+
978
+ Based on analysis of Spider 1.0 and BIRD-SQL query distributions:
979
+
980
+ | Query Category | % of Benchmark | Estimated Decompiler Coverage |
981
+ |---|---|---|
982
+ | Simple (T1) | ~25% | 100% |
983
+ | Aggregate (T2) | ~20% | 100% |
984
+ | Join (T3–T4) | ~25% | 100% |
985
+ | Window (T5) | ~5% | 100% |
986
+ | Subquery (T6–T7) | ~15% | 90%+ (after unnesting) |
987
+ | CTE (T8) | ~5% | 95%+ |
988
+ | Set ops (T9) | ~3% | 100% |
989
+ | Complex (T10) | ~2% | 75%+ |
990
+ | **Weighted total** | **100%** | **~96%** |
991
+
992
+ ---
993
+
994
+ ## 11. Testing Strategy
995
+
996
+ ### 11.1 Layer 1: Unit Tests (Per-Rule)
997
+
998
+ Each transformation rule has a dedicated test file with input/output pairs covering:
999
+ - Minimal cases (the simplest query that exercises the rule).
1000
+ - Boundary cases (empty GROUP BY, single-column SELECT, self-join).
1001
+ - Negative cases (queries that should NOT trigger the rule).
1002
+
1003
+ ```python
1004
+ def test_simple_where():
1005
+ assert decompile("SELECT name FROM users WHERE age > 21") == \
1006
+ "FROM users\n|> WHERE age > 21\n|> SELECT name"
1007
+
1008
+ def test_aggregate_with_having():
1009
+ assert decompile("SELECT dept, COUNT(*) AS cnt FROM emp GROUP BY dept HAVING cnt > 5") == \
1010
+ "FROM emp\n|> AGGREGATE COUNT(*) AS cnt GROUP BY dept\n|> WHERE cnt > 5"
1011
+ ```
1012
+
1013
+ ### 11.2 Layer 2: Round-Trip Tests
1014
+
1015
+ Parse the output pipe SQL with SQLGlot (which converts pipe → standard SQL via CTEs), then compare the resulting standard SQL with the original input for semantic equivalence.
1016
+
1017
+ ```python
1018
+ def test_roundtrip(standard_sql):
1019
+ pipe_sql = decompile(standard_sql)
1020
+ roundtripped = sqlglot.transpile(pipe_sql, read="bigquery", write="bigquery")[0]
1021
+ # roundtripped is CTE-based standard SQL
1022
+ assert semantically_equivalent(standard_sql, roundtripped)
1023
+ ```
1024
+
1025
+ ### 11.3 Layer 3: Differential Execution Tests
1026
+
1027
+ Execute both the original standard SQL and the decompiled pipe SQL (transpiled back to standard via SQLGlot) against a real database and compare result sets.
1028
+
1029
+ **Test database**: Use the Spider 1.0 SQLite databases. For each benchmark query:
1030
+
1031
+ ```python
1032
+ def test_execution(benchmark_query, db_path):
1033
+ pipe_sql = decompile(benchmark_query.sql)
1034
+ standard_from_pipe = sqlglot.transpile(pipe_sql, read="bigquery", write="sqlite")[0]
1035
+
1036
+ conn = sqlite3.connect(db_path)
1037
+ result_original = pd.read_sql(benchmark_query.sql, conn)
1038
+ result_pipe = pd.read_sql(standard_from_pipe, conn)
1039
+
1040
+ # Sort both by all columns, compare
1041
+ assert_frame_equal(
1042
+ result_original.sort_values(list(result_original.columns)).reset_index(drop=True),
1043
+ result_pipe.sort_values(list(result_pipe.columns)).reset_index(drop=True),
1044
+ )
1045
+ ```
1046
+
1047
+ ### 11.4 Layer 4: Benchmark Coverage Tests
1048
+
1049
+ Run the decompiler over all queries in Spider 1.0 (~7K train + ~1K dev) and BIRD-SQL (~9.4K train + ~1.5K dev). Report:
1050
+ - Success rate (queries that decompile without errors).
1051
+ - Warning rate (queries that decompile with warnings).
1052
+ - Failure rate (queries that cannot be decompiled).
1053
+ - Execution match rate (pipe output matches original on the database).
1054
+
1055
+ Target: 90%+ success rate, 95%+ execution match rate on successful decompilations.
1056
+
1057
+ ### 11.5 Layer 5: Property-Based Fuzzing
1058
+
1059
+ Use Hypothesis (Python) to generate random SQL ASTs and verify the decompiler never crashes:
1060
+
1061
+ ```python
1062
+ from hypothesis import given, strategies as st
1063
+
1064
+ @given(sql=sql_ast_strategy())
1065
+ def test_never_crashes(sql):
1066
+ result = decompile(sql)
1067
+ assert isinstance(result, TransformResult)
1068
+ # May have warnings/unsupported, but should never raise
1069
+ ```
1070
+
1071
+ ---
1072
+
1073
+ ## 12. Performance Considerations
1074
+
1075
+ ### 12.1 Expected Throughput
1076
+
1077
+ | Stage | Time per query | Notes |
1078
+ |---|---|---|
1079
+ | Parse | ~0.2ms | SQLGlot recursive descent parser |
1080
+ | Qualify | ~0.5ms | Schema lookup + column resolution |
1081
+ | Unnest subqueries | ~0.3ms | Only runs on queries with correlated subqueries |
1082
+ | Transformation rules | ~0.2ms | Pure AST manipulation |
1083
+ | Serialization | ~0.1ms | String formatting |
1084
+ | **Total** | **~1.3ms** | **~770 queries/sec** |
1085
+
1086
+ For 50K queries: ~65 seconds total. Well within practical limits.
1087
+
1088
+ ### 12.2 Memory
1089
+
1090
+ Each query is processed independently. Memory usage is proportional to AST size (~10KB per typical query). No persistent state between queries.
1091
+
1092
+ ---
1093
+
1094
+ ## 13. Implementation Roadmap
1095
+
1096
+ ### Phase 1: Core Rules (Week 1–2)
1097
+ - Implement rules 1–5 (CTE, set ops, FROM, JOIN, WHERE) and rule 10 (terminals).
1098
+ - Handle Tiers T1, T3, T9.
1099
+ - Unit tests for each rule.
1100
+ - Target: 50% of benchmark queries decompile successfully.
1101
+
1102
+ ### Phase 2: Aggregation + Windows (Week 2–3)
1103
+ - Implement rules 6–9 (expression analysis, AGGREGATE, windows, final SELECT).
1104
+ - Handle Tiers T2, T4, T5.
1105
+ - Target: 80% of benchmark queries.
1106
+
1107
+ ### Phase 3: Subqueries + Edge Cases (Week 3–4)
1108
+ - Integrate `unnest_subqueries` pre-processing.
1109
+ - Implement subquery handling in WHERE, SELECT, and FROM.
1110
+ - Handle Tiers T6, T7, T8.
1111
+ - Target: 90%+ of benchmark queries.
1112
+
1113
+ ### Phase 4: Validation + Hardening (Week 4–5)
1114
+ - Differential execution tests against Spider 1.0 and BIRD-SQL databases.
1115
+ - Property-based fuzzing.
1116
+ - Fix edge cases surfaced by testing.
1117
+ - Target: 95%+ execution match rate.
1118
+
1119
+ ### Phase 5: Integration (Week 5–6)
1120
+ - Integrate with the data augmentation pipeline.
1121
+ - Generate trajectory-decomposed JSONL training files.
1122
+ - Produce the final corpus of 50K+ validated pipe SQL queries.