1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
//! Lazy iterator-based query execution infrastructure
//!
//! This module provides a foundation for streaming query execution using iterators
//! instead of materializing results. This reduces memory usage and enables early
//! termination for LIMIT queries.
//!
//! # Architecture
//!
//! The core trait is `RowIterator`, which extends `Iterator<Item = Result<Row, ExecutorError>>`
//! with additional query-specific methods. All query operators (scan, filter, project, join)
//! are implemented as iterators that can be composed.
//!
//! # Benefits
//!
//! - **Memory efficiency**: O(max_single_table) instead of O(product)
//! - **Streaming**: Rows flow through pipeline without buffering
//! - **Early termination**: LIMIT 10 only computes 10 rows
//! - **Composability**: Iterators naturally chain together
//!
//! # Example
//!
//! ```text
//! // Create a table scan iterator
//! let scan_iter = TableScanIterator::new(schema, rows);
//!
//! // Add a filter
//! let filter_iter = FilterIterator::new(scan_iter, predicate, evaluator);
//!
//! // Add a projection
//! let project_iter = ProjectionIterator::new(filter_iter, projection_fn);
//!
//! // Consume only what we need (e.g., LIMIT 10)
//! for row in project_iter.take(10) {
//! println!("{:?}", row?);
//! }
//! ```
//!
//! # Phase C Integration (Proof of Concept)
//!
//! The proof-of-concept tests in `tests/phase_c.rs` demonstrate how to build an iterator
//! pipeline for simple SELECT queries (without ORDER BY, DISTINCT, or window functions).
//! This serves as a proof-of-concept for full integration into the executor.
use crate::;
// Module declarations
// Re-export public types
pub use FilterIterator;
pub use TableScanIterator;
/// Core trait for row-producing iterators in the query execution pipeline
///
/// This trait extends the standard Iterator trait with query-specific metadata
/// and methods. All query operators (scans, filters, joins, projections) implement
/// this trait to enable composable, streaming query execution.
///
/// # Why not just use Iterator?
///
/// While we could use `Iterator<Item = Result<Row, ExecutorError>>` directly,
/// this trait adds query-specific capabilities:
/// - Access to the output schema (for type checking and column resolution)
/// - Size hints for query optimization
/// - Future: Statistics, cost estimates, etc.
// Implement RowIterator for Box<dyn RowIterator> to allow boxing
// Note: Box<T> already implements Iterator if T implements Iterator,
// so we only need to implement the RowIterator trait methods
// ============================================================================
// Phase C: Integration Strategy & Status
// ============================================================================
//
// ## PHASE C STATUS: PROOF-OF-CONCEPT COMPLETE ✓
//
// What's Complete:
// - ✅ Core iterator infrastructure (TableScanIterator, FilterIterator, ProjectionIterator)
// - ✅ Lazy join execution (LazyNestedLoopJoin supporting all SQL join types)
// - ✅ Evaluator bug fixed (CSE cache was incorrectly caching column references)
// - ✅ End-to-end pipeline validated (19/19 tests passing)
// - ✅ Integration strategy documented below
// - ✅ Materialization decision logic (can_use_iterator_execution in nonagg.rs)
//
// ## Integration Strategy for Phase D (Production)
//
// ### Step 1: Add Iterator Execution Path (nonagg.rs)
//
// ```text
// pub(super) fn execute_without_aggregation(...) -> Result<Vec<Row>, ExecutorError> {
// // Decision point: simple queries use iterators
// if Self::can_use_iterator_execution(stmt) {
// return self.execute_with_iterators(stmt, from_result);
// }
//
// // Complex queries use existing materialized path
// // (ORDER BY, DISTINCT, window functions)
// // ... existing code ...
// }
// ```
//
// ### Step 2: Implement Iterator Execution (demonstrated by tests)
//
// The test_phase_c_proof_of_concept_*() functions in `tests/phase_c.rs` demonstrate
// the complete pattern:
// 1. Create TableScanIterator from FROM results
// 2. Chain FilterIterator for WHERE clause
// 3. Apply LIMIT via .take(n) for early termination
// 4. Materialize only final results via .collect()
// 5. Project columns on materialized rows
//
// ### Step 3: Benefits (Validated by Tests)
//
// - **Memory**: Only final result set is materialized (not intermediate JOINs)
// - **Performance**: LIMIT 10 on 1000 rows processes only 10 (not 1000!)
// - **Composability**: Iterator chain naturally (scan → filter → join → limit)
//
// ## Next: Phase D - Production Integration
//
// 1. Refactor scan.rs to optionally return Box<dyn RowIterator>
// 2. Implement execute_with_iterators() using pattern from tests
// 3. Add benchmarks (iterator vs materialized execution)
// 4. Expand to more query types (currently simple SELECT/WHERE/LIMIT)
/// Proof-of-concept function demonstrating iterator-based query execution
///
/// This function shows how to build an iterator pipeline for simple SELECT queries
/// (without ORDER BY, DISTINCT, or window functions). It serves as a template for
/// full integration into the executor.
///
/// # Pipeline Construction
///
/// The pipeline is built in stages:
/// 1. **FROM**: Start with TableScanIterator or LazyNestedLoopJoin
/// 2. **WHERE**: Add FilterIterator for predicates
/// 3. **SELECT**: Add ProjectionIterator for column selection
/// 4. **LIMIT**: Use standard `.take(n)` for early termination
///
/// # Example Usage
///
/// ```text
/// // Build iterator for: SELECT name, age FROM users WHERE age > 18 LIMIT 10
/// let iterator = build_simple_query_iterator(
/// users_schema,
/// users_rows,
/// Some(age_gt_18_expr), // WHERE age > 18
/// projection_fn, // SELECT name, age
/// Some(10), // LIMIT 10
/// )?;
///
/// // Consume results lazily
/// let results: Vec<_> = iterator.collect::<Result<Vec<_>, _>>()?;
/// ```
///
/// # Limitations
///
/// This proof-of-concept does NOT handle:
/// - ORDER BY (requires materialization for sorting)
/// - DISTINCT (requires materialization for deduplication)
/// - Window functions (requires materialization for partitioning)
/// - Aggregation (requires materialization for grouping)
///
/// For queries with these features, the executor must materialize the iterator
/// before applying the operation.
///
/// # Full Integration Path (Phase C Continuation)
///
/// To fully integrate this into the executor:
///
/// 1. **Modify `execute_from()` signature**: ```rust fn execute_from() -> Result<Box<dyn
/// RowIterator>, ExecutorError> ```
///
/// 2. **Add materialization decision logic**: ```rust fn needs_materialization(stmt: &SelectStmt)
/// -> bool { stmt.order_by.is_some() || stmt.distinct || has_window_functions(&stmt.select_list)
/// || has_aggregates(&stmt.select_list) } ```
///
/// 3. **Hybrid execution in `execute_without_aggregation()`**: ```rust let iter =
/// build_query_iterator(from_result)?;
///
/// if needs_materialization(stmt) {
/// let rows = iter.collect::<Result<Vec<_>, _>>()?;
/// apply_order_by(rows, &stmt.order_by)
/// } else {
/// iter.take(stmt.limit.unwrap_or(usize::MAX))
/// .collect::<Result<Vec<_>, _>>()
/// }
/// ```
///
/// 4. **Update all FROM clause execution**:
/// - `execute_from_clause()` returns iterator
/// - `nested_loop_join()` uses `LazyNestedLoopJoin`
/// - `execute_table_scan()` uses `TableScanIterator`
///
/// This proof-of-concept validates the approach and provides a clear path forward.