Skip to main content

reddb_server/storage/query/executors/
cte.rs

1//! CTE (Common Table Expression) executor.
2//!
3//! Implements the `WITH … AS (…) SELECT …` SQL standard form. CTEs
4//! are materialised as temporary result sets that the main query can
5//! reference by name. Recursive CTEs (`WITH RECURSIVE`) use the
6//! classic iterative-fixpoint shape:
7//!
8//! 1. Execute the non-recursive (base) part once.
9//! 2. Repeat: execute the recursive part with the previous iteration's
10//!    rows visible as the CTE.
11//! 3. Stop when no new rows are produced (or guard limits trip).
12//!
13//! Today only non-recursive CTEs are wired through the runtime —
14//! `inline_ctes` rejects `WITH RECURSIVE` with a clear error. The
15//! iterative-fixpoint code in `CteExecutor` is reachable only via
16//! direct unit tests and is the basis for the future recursive wire-
17//! up (#41 follow-up).
18//!
19//! # Example
20//!
21//! ```ignore
22//! WITH active AS (
23//!     SELECT id, name FROM users WHERE status = 'active'
24//! )
25//! SELECT * FROM active
26//! ```
27
28use std::collections::{HashMap, HashSet};
29
30use super::super::unified::{ExecutionError, UnifiedRecord, UnifiedResult};
31use reddb_rql::ast::{
32    CteDefinition, Expr, Filter, Projection, QueryExpr, QueryWithCte, SelectItem, TableSource,
33};
34use reddb_types::Value;
35
36/// Maximum recursion depth to prevent infinite loops
37const MAX_RECURSION_DEPTH: usize = 1000;
38
39/// Maximum total rows across all iterations
40const MAX_RECURSIVE_ROWS: usize = 100_000;
41
42/// CTE execution context holding materialized CTE results
43#[derive(Debug, Clone, Default)]
44pub struct CteContext {
45    /// Materialized CTE results by name
46    tables: HashMap<String, UnifiedResult>,
47    /// Track which CTEs are currently being evaluated (for cycle detection)
48    evaluating: HashSet<String>,
49    /// Statistics
50    stats: CteStats,
51}
52
53impl CteContext {
54    /// Create a new CTE context
55    pub fn new() -> Self {
56        Self::default()
57    }
58
59    /// Get a materialized CTE result by name
60    pub fn get(&self, name: &str) -> Option<&UnifiedResult> {
61        self.tables.get(name)
62    }
63
64    /// Store a materialized CTE result
65    pub fn store(&mut self, name: String, result: UnifiedResult) {
66        self.tables.insert(name, result);
67    }
68
69    /// Check if a CTE is being evaluated (for recursion detection)
70    pub fn is_evaluating(&self, name: &str) -> bool {
71        self.evaluating.contains(name)
72    }
73
74    /// Mark a CTE as being evaluated
75    pub fn start_evaluating(&mut self, name: &str) {
76        self.evaluating.insert(name.to_string());
77    }
78
79    /// Mark a CTE as done evaluating
80    pub fn done_evaluating(&mut self, name: &str) {
81        self.evaluating.remove(name);
82    }
83
84    /// Get execution statistics
85    pub fn stats(&self) -> &CteStats {
86        &self.stats
87    }
88}
89
90/// Statistics about CTE execution
91#[derive(Debug, Clone, Default)]
92pub struct CteStats {
93    /// Number of CTEs executed
94    pub ctes_executed: usize,
95    /// Number of recursive iterations
96    pub recursive_iterations: usize,
97    /// Total rows produced by CTEs
98    pub rows_produced: usize,
99    /// Execution time in microseconds
100    pub exec_time_us: u64,
101}
102
103/// CTE Executor
104pub struct CteExecutor<F>
105where
106    F: Fn(&QueryExpr, &CteContext) -> Result<UnifiedResult, ExecutionError>,
107{
108    /// Function to execute a query with CTE context
109    execute_fn: F,
110}
111
112impl<F> CteExecutor<F>
113where
114    F: Fn(&QueryExpr, &CteContext) -> Result<UnifiedResult, ExecutionError>,
115{
116    /// Create a new CTE executor
117    pub fn new(execute_fn: F) -> Self {
118        Self { execute_fn }
119    }
120
121    /// Execute a query with CTEs
122    pub fn execute(&self, query: &QueryWithCte) -> Result<UnifiedResult, ExecutionError> {
123        let start = std::time::Instant::now();
124        let mut ctx = CteContext::new();
125
126        // Materialize all CTEs in order
127        if let Some(ref with_clause) = query.with_clause {
128            for cte in &with_clause.ctes {
129                self.materialize_cte(cte, &mut ctx)?;
130            }
131        }
132
133        // Execute the main query with CTE context
134        let result = (self.execute_fn)(&query.query, &ctx)?;
135
136        ctx.stats.exec_time_us = start.elapsed().as_micros() as u64;
137        Ok(result)
138    }
139
140    /// Materialize a single CTE
141    fn materialize_cte(
142        &self,
143        cte: &CteDefinition,
144        ctx: &mut CteContext,
145    ) -> Result<(), ExecutionError> {
146        if ctx.is_evaluating(&cte.name) {
147            return Err(ExecutionError::new(format!(
148                "Circular CTE reference: {}",
149                cte.name
150            )));
151        }
152
153        // Check if already materialized
154        if ctx.get(&cte.name).is_some() {
155            return Ok(());
156        }
157
158        ctx.start_evaluating(&cte.name);
159
160        let result = if cte.recursive {
161            self.execute_recursive_cte(cte, ctx)?
162        } else {
163            // Simple CTE: execute once
164            let result = (self.execute_fn)(&cte.query, ctx)?;
165            self.project_columns(&result, &cte.columns)
166        };
167
168        ctx.stats.ctes_executed += 1;
169        ctx.stats.rows_produced += result.len();
170        ctx.store(cte.name.clone(), result);
171        ctx.done_evaluating(&cte.name);
172
173        Ok(())
174    }
175
176    /// Execute a recursive CTE using iterative fixpoint
177    fn execute_recursive_cte(
178        &self,
179        cte: &CteDefinition,
180        ctx: &mut CteContext,
181    ) -> Result<UnifiedResult, ExecutionError> {
182        // For recursive CTEs, we need to handle UNION ALL structure
183        // The query should be: base_query UNION ALL recursive_query
184        //
185        // Algorithm:
186        // 1. Execute base query -> working_table
187        // 2. result_table = working_table
188        // 3. While working_table not empty:
189        //    a. Execute recursive query with CTE = working_table
190        //    b. new_rows = result - already_seen
191        //    c. working_table = new_rows
192        //    d. result_table += new_rows
193        // 4. Return result_table
194
195        // For simplicity in first implementation, we execute the full query
196        // iteratively, building up the working table
197
198        let mut all_results = UnifiedResult::with_columns(cte.columns.clone());
199        let mut working_table = UnifiedResult::with_columns(cte.columns.clone());
200        let mut seen_rows: HashSet<u64> = HashSet::new();
201        let mut iteration = 0;
202
203        // First iteration: execute the full query (base case)
204        let initial = (self.execute_fn)(&cte.query, ctx)?;
205        let initial = self.project_columns(&initial, &cte.columns);
206
207        for record in &initial.records {
208            let hash = self.hash_record(record);
209            if seen_rows.insert(hash) {
210                working_table.push(record.clone());
211                all_results.push(record.clone());
212            }
213        }
214
215        // Store initial results so recursive references can see them
216        ctx.store(cte.name.clone(), working_table.clone());
217
218        // Iterate until fixpoint
219        while !working_table.is_empty() && iteration < MAX_RECURSION_DEPTH {
220            iteration += 1;
221            ctx.stats.recursive_iterations += 1;
222
223            if all_results.len() > MAX_RECURSIVE_ROWS {
224                return Err(ExecutionError::new(format!(
225                    "Recursive CTE '{}' exceeded maximum rows ({})",
226                    cte.name, MAX_RECURSIVE_ROWS
227                )));
228            }
229
230            // Execute query with current CTE contents
231            let new_results = (self.execute_fn)(&cte.query, ctx)?;
232            let new_results = self.project_columns(&new_results, &cte.columns);
233
234            // Find genuinely new rows
235            let mut new_working_table = UnifiedResult::with_columns(cte.columns.clone());
236            for record in &new_results.records {
237                let hash = self.hash_record(record);
238                if seen_rows.insert(hash) {
239                    new_working_table.push(record.clone());
240                    all_results.push(record.clone());
241                }
242            }
243
244            working_table = new_working_table;
245
246            // Update CTE table for next iteration
247            ctx.store(cte.name.clone(), all_results.clone());
248        }
249
250        if iteration >= MAX_RECURSION_DEPTH && !working_table.is_empty() {
251            return Err(ExecutionError::new(format!(
252                "Recursive CTE '{}' exceeded maximum recursion depth ({})",
253                cte.name, MAX_RECURSION_DEPTH
254            )));
255        }
256
257        Ok(all_results)
258    }
259
260    /// Project result columns according to CTE column list
261    fn project_columns(&self, result: &UnifiedResult, columns: &[String]) -> UnifiedResult {
262        if columns.is_empty() {
263            return result.clone();
264        }
265
266        let mut projected = UnifiedResult::with_columns(columns.to_vec());
267
268        for record in &result.records {
269            let mut new_record = UnifiedRecord::new();
270
271            // Map result columns to CTE columns
272            for (i, col) in columns.iter().enumerate() {
273                // Try to find value by position first, then by name
274                let value = result
275                    .columns
276                    .get(i)
277                    .and_then(|orig_col| record.get(orig_col))
278                    .cloned()
279                    .or_else(|| record.get(col).cloned())
280                    .unwrap_or(Value::Null);
281
282                new_record.set(col, value);
283            }
284
285            projected.push(new_record);
286        }
287
288        projected
289    }
290
291    /// Hash a record for deduplication
292    fn hash_record(&self, record: &UnifiedRecord) -> u64 {
293        use std::collections::hash_map::DefaultHasher;
294        use std::hash::{Hash, Hasher};
295
296        let mut hasher = DefaultHasher::new();
297
298        // Hash all values in deterministic order
299        let mut keys = record.column_names();
300        keys.sort();
301
302        for key in &keys {
303            (**key).hash(&mut hasher);
304            if let Some(value) = record.get(key) {
305                Self::hash_value(value, &mut hasher);
306            }
307        }
308
309        hasher.finish()
310    }
311
312    /// Hash a Value for deduplication
313    fn hash_value(value: &Value, hasher: &mut impl std::hash::Hasher) {
314        use std::hash::Hash;
315
316        match value {
317            Value::Null => 0u8.hash(hasher),
318            Value::Cron(value) => {
319                reddb_types::DataType::Cron.to_byte().hash(hasher);
320                value.hash(hasher);
321            }
322            Value::Temperature(temperature) => {
323                56u8.hash(hasher);
324                temperature.hash(hasher);
325            }
326            Value::Boolean(b) => {
327                1u8.hash(hasher);
328                b.hash(hasher);
329            }
330            Value::Integer(i) => {
331                2u8.hash(hasher);
332                i.hash(hasher);
333            }
334            Value::UnsignedInteger(u) => {
335                3u8.hash(hasher);
336                u.hash(hasher);
337            }
338            Value::Float(f) => {
339                4u8.hash(hasher);
340                f.to_bits().hash(hasher);
341            }
342            Value::Text(s) => {
343                5u8.hash(hasher);
344                s.hash(hasher);
345            }
346            Value::Blob(b) => {
347                6u8.hash(hasher);
348                b.hash(hasher);
349            }
350            Value::Timestamp(t) => {
351                7u8.hash(hasher);
352                t.hash(hasher);
353            }
354            Value::Duration(d) => {
355                8u8.hash(hasher);
356                d.hash(hasher);
357            }
358            Value::IpAddr(addr) => {
359                9u8.hash(hasher);
360                match addr {
361                    std::net::IpAddr::V4(v4) => v4.octets().hash(hasher),
362                    std::net::IpAddr::V6(v6) => v6.octets().hash(hasher),
363                }
364            }
365            Value::MacAddr(mac) => {
366                10u8.hash(hasher);
367                mac.hash(hasher);
368            }
369            Value::Vector(v) => {
370                11u8.hash(hasher);
371                v.len().hash(hasher);
372                for f in v {
373                    f.to_bits().hash(hasher);
374                }
375            }
376            Value::Json(j) => {
377                12u8.hash(hasher);
378                j.hash(hasher);
379            }
380            Value::Uuid(u) => {
381                13u8.hash(hasher);
382                u.hash(hasher);
383            }
384            Value::NodeRef(n) => {
385                14u8.hash(hasher);
386                n.hash(hasher);
387            }
388            Value::EdgeRef(e) => {
389                15u8.hash(hasher);
390                e.hash(hasher);
391            }
392            Value::VectorRef(coll, id) => {
393                16u8.hash(hasher);
394                coll.hash(hasher);
395                id.hash(hasher);
396            }
397            Value::RowRef(table, id) => {
398                17u8.hash(hasher);
399                table.hash(hasher);
400                id.hash(hasher);
401            }
402            Value::Color(rgb) => {
403                18u8.hash(hasher);
404                rgb.hash(hasher);
405            }
406            Value::Email(s) => {
407                19u8.hash(hasher);
408                s.hash(hasher);
409            }
410            Value::Url(s) => {
411                20u8.hash(hasher);
412                s.hash(hasher);
413            }
414            Value::Phone(n) => {
415                21u8.hash(hasher);
416                n.hash(hasher);
417            }
418            Value::Semver(v) => {
419                22u8.hash(hasher);
420                v.hash(hasher);
421            }
422            Value::Cidr(ip, prefix) => {
423                23u8.hash(hasher);
424                ip.hash(hasher);
425                prefix.hash(hasher);
426            }
427            Value::Date(d) => {
428                24u8.hash(hasher);
429                d.hash(hasher);
430            }
431            Value::Time(t) => {
432                25u8.hash(hasher);
433                t.hash(hasher);
434            }
435            Value::Decimal(v) => {
436                26u8.hash(hasher);
437                v.hash(hasher);
438            }
439            Value::DecimalText(v) => {
440                52u8.hash(hasher);
441                v.hash(hasher);
442            }
443            Value::EnumValue(i) => {
444                27u8.hash(hasher);
445                i.hash(hasher);
446            }
447            Value::Array(elems) => {
448                28u8.hash(hasher);
449                elems.len().hash(hasher);
450                for elem in elems {
451                    Self::hash_value(elem, hasher);
452                }
453            }
454            Value::TimestampMs(v) => {
455                29u8.hash(hasher);
456                v.hash(hasher);
457            }
458            Value::Ipv4(v) => {
459                30u8.hash(hasher);
460                v.hash(hasher);
461            }
462            Value::Ipv6(bytes) => {
463                31u8.hash(hasher);
464                bytes.hash(hasher);
465            }
466            Value::Subnet(ip, mask) => {
467                32u8.hash(hasher);
468                ip.hash(hasher);
469                mask.hash(hasher);
470            }
471            Value::Port(v) => {
472                33u8.hash(hasher);
473                v.hash(hasher);
474            }
475            Value::Latitude(v) => {
476                34u8.hash(hasher);
477                v.hash(hasher);
478            }
479            Value::Longitude(v) => {
480                35u8.hash(hasher);
481                v.hash(hasher);
482            }
483            Value::GeoPoint(lat, lon) => {
484                36u8.hash(hasher);
485                lat.hash(hasher);
486                lon.hash(hasher);
487            }
488            Value::Country2(c) => {
489                37u8.hash(hasher);
490                c.hash(hasher);
491            }
492            Value::Country3(c) => {
493                38u8.hash(hasher);
494                c.hash(hasher);
495            }
496            Value::Lang2(c) => {
497                39u8.hash(hasher);
498                c.hash(hasher);
499            }
500            Value::Lang5(c) => {
501                40u8.hash(hasher);
502                c.hash(hasher);
503            }
504            Value::Currency(c) => {
505                41u8.hash(hasher);
506                c.hash(hasher);
507            }
508            Value::AssetCode(code) => {
509                50u8.hash(hasher);
510                code.hash(hasher);
511            }
512            Value::Money {
513                asset_code,
514                minor_units,
515                scale,
516            } => {
517                51u8.hash(hasher);
518                asset_code.hash(hasher);
519                minor_units.hash(hasher);
520                scale.hash(hasher);
521            }
522            Value::ColorAlpha(rgba) => {
523                42u8.hash(hasher);
524                rgba.hash(hasher);
525            }
526            Value::BigInt(v) => {
527                43u8.hash(hasher);
528                v.hash(hasher);
529            }
530            Value::KeyRef(col, key) => {
531                44u8.hash(hasher);
532                col.hash(hasher);
533                key.hash(hasher);
534            }
535            Value::DocRef(col, id) => {
536                45u8.hash(hasher);
537                col.hash(hasher);
538                id.hash(hasher);
539            }
540            Value::TableRef(name) => {
541                46u8.hash(hasher);
542                name.hash(hasher);
543            }
544            Value::PageRef(page_id) => {
545                47u8.hash(hasher);
546                page_id.hash(hasher);
547            }
548            Value::Secret(bytes) => {
549                48u8.hash(hasher);
550                bytes.hash(hasher);
551            }
552            Value::Password(hash) => {
553                49u8.hash(hasher);
554                hash.hash(hasher);
555            }
556        }
557    }
558}
559
560/// Helper to parse UNION structure for recursive CTEs
561pub fn split_union_parts(query: &QueryExpr) -> Option<(QueryExpr, QueryExpr)> {
562    // UNION support is not represented in the current AST; recursive queries execute
563    // the full body expression each iteration.
564    let _ = query;
565    None
566}
567
568// ─────────────────────────────────────────────────────────────────────
569// CTE inlining (#41) — non-recursive
570//
571// Rewrites a `QueryWithCte` into a plain `QueryExpr` by walking the
572// AST and substituting every `TableSource::Name(name)` (or legacy
573// `TableQuery.table` field) that matches a CTE name with
574// `TableSource::Subquery(cte.query)`. After this pass the runtime's
575// existing subquery-in-FROM machinery executes the result with no
576// CTE-specific dispatch needed.
577//
578// Recursive CTEs are rejected up-front — the iterative fixpoint
579// strategy is implemented in `CteExecutor` but is not wired into the
580// runtime yet (separate slice).
581// ─────────────────────────────────────────────────────────────────────
582
583/// Inline a `QueryWithCte`'s WITH clause into its inner query. Returns
584/// the rewritten `QueryExpr` ready for dispatch. Recursive CTEs are
585/// rejected with a clear error.
586pub fn inline_ctes(query: QueryWithCte) -> Result<QueryExpr, ExecutionError> {
587    let Some(with_clause) = query.with_clause else {
588        return Ok(query.query);
589    };
590    if with_clause.has_recursive {
591        return Err(ExecutionError::new(
592            "WITH RECURSIVE is not yet supported by the executor; \
593             non-recursive WITH clauses run today, recursive support \
594             is tracked separately"
595                .to_string(),
596        ));
597    }
598
599    // Inline each CTE into its successors first so chained CTEs
600    // (`WITH a AS (...), b AS (... a ...)`) end up with fully resolved
601    // bodies before they're substituted into the outer query.
602    let mut resolved: HashMap<String, QueryExpr> = HashMap::new();
603    for cte in &with_clause.ctes {
604        let mut body = (*cte.query).clone();
605        rewrite(&mut body, &resolved);
606        resolved.insert(cte.name.clone(), body);
607    }
608
609    let mut outer = query.query;
610    rewrite(&mut outer, &resolved);
611    Ok(outer)
612}
613
614/// Walk a `QueryExpr` and replace any table reference whose name
615/// matches a key in `ctes` with the inlined CTE body. Recurses
616/// through `Join` and nested `Subquery` sources so CTE refs inside
617/// JOINs and subqueries resolve too. Mirrors the view-rewrite
618/// convention: when the outer table reference carries filter / limit
619/// / offset constraints we wrap the body in a `Subquery` to preserve
620/// them; otherwise we replace the whole `Table` node verbatim with
621/// the CTE body so dispatchers that key off `QueryExpr::Table` (like
622/// the JOIN executor) see the right shape.
623fn rewrite(expr: &mut QueryExpr, ctes: &HashMap<String, QueryExpr>) {
624    match expr {
625        QueryExpr::Table(tq) => {
626            let lookup_name = match &tq.source {
627                Some(TableSource::Subquery(_)) => None,
628                Some(TableSource::Name(n)) => Some(n.clone()),
629                // Table-valued functions are not CTE references (issue #795);
630                // the inline-graph form likewise references no CTE (issue #799).
631                Some(TableSource::Function { .. } | TableSource::InlineGraphFunction { .. }) => {
632                    None
633                }
634                None => Some(tq.table.clone()),
635            };
636
637            if let Some(name) = lookup_name {
638                if let Some(body) = ctes.get(&name) {
639                    let outer_has_constraints = tq.filter.is_some()
640                        || tq.where_expr.is_some()
641                        || tq.limit.is_some()
642                        || tq.offset.is_some()
643                        || !tq.columns.is_empty()
644                        || !tq.select_items.is_empty()
645                        || !tq.group_by.is_empty()
646                        || !tq.order_by.is_empty();
647
648                    if outer_has_constraints {
649                        // Outer ref carries projections / filters /
650                        // limits — keep those by wrapping the body in
651                        // a subquery source. Sentinel name so legacy
652                        // `table` consumers can't resolve it against
653                        // the real schema.
654                        tq.source = Some(TableSource::Subquery(Box::new(body.clone())));
655                        tq.table = format!("__cte_{name}");
656                    } else {
657                        // Bare `FROM cte` (possibly with alias) —
658                        // replace verbatim so JOIN / dispatch paths
659                        // see the CTE body's natural shape.
660                        *expr = body.clone();
661                    }
662                    return;
663                }
664            }
665
666            match tq.source.as_mut() {
667                Some(TableSource::Subquery(body)) => rewrite(body, ctes),
668                Some(TableSource::InlineGraphFunction { nodes, edges, .. }) => {
669                    rewrite(nodes, ctes);
670                    rewrite(edges, ctes);
671                }
672                _ => {}
673            }
674            rewrite_table_query_parts(tq, ctes);
675        }
676        QueryExpr::Join(jq) => {
677            rewrite(&mut jq.left, ctes);
678            rewrite(&mut jq.right, ctes);
679            if let Some(filter) = jq.filter.as_mut() {
680                rewrite_filter(filter, ctes);
681            }
682            for item in &mut jq.order_by {
683                if let Some(expr) = item.expr.as_mut() {
684                    rewrite_expr(expr, ctes);
685                }
686            }
687            for item in &mut jq.return_items {
688                rewrite_select_item(item, ctes);
689            }
690            for projection in &mut jq.return_ {
691                rewrite_projection(projection, ctes);
692            }
693        }
694        QueryExpr::Graph(gq) => {
695            if let Some(filter) = gq.filter.as_mut() {
696                rewrite_filter(filter, ctes);
697            }
698            for projection in &mut gq.return_ {
699                rewrite_projection(projection, ctes);
700            }
701        }
702        _ => {}
703    }
704}
705
706fn rewrite_table_query_parts(
707    tq: &mut reddb_rql::ast::TableQuery,
708    ctes: &HashMap<String, QueryExpr>,
709) {
710    for item in &mut tq.select_items {
711        rewrite_select_item(item, ctes);
712    }
713    for projection in &mut tq.columns {
714        rewrite_projection(projection, ctes);
715    }
716    if let Some(expr) = tq.where_expr.as_mut() {
717        rewrite_expr(expr, ctes);
718    }
719    if let Some(filter) = tq.filter.as_mut() {
720        rewrite_filter(filter, ctes);
721    }
722    for expr in &mut tq.group_by_exprs {
723        rewrite_expr(expr, ctes);
724    }
725    if let Some(expr) = tq.having_expr.as_mut() {
726        rewrite_expr(expr, ctes);
727    }
728    if let Some(filter) = tq.having.as_mut() {
729        rewrite_filter(filter, ctes);
730    }
731    for item in &mut tq.order_by {
732        if let Some(expr) = item.expr.as_mut() {
733            rewrite_expr(expr, ctes);
734        }
735    }
736}
737
738fn rewrite_select_item(item: &mut SelectItem, ctes: &HashMap<String, QueryExpr>) {
739    if let SelectItem::Expr { expr, .. } = item {
740        rewrite_expr(expr, ctes);
741    }
742}
743
744fn rewrite_projection(projection: &mut Projection, ctes: &HashMap<String, QueryExpr>) {
745    match projection {
746        Projection::Function(_, args) => {
747            for arg in args {
748                rewrite_projection(arg, ctes);
749            }
750        }
751        Projection::Expression(filter, _) => rewrite_filter(filter, ctes),
752        Projection::Window { args, window, .. } => {
753            for arg in args {
754                rewrite_projection(arg, ctes);
755            }
756            for expr in &mut window.partition_by {
757                rewrite_expr(expr, ctes);
758            }
759            for item in &mut window.order_by {
760                rewrite_expr(&mut item.expr, ctes);
761            }
762        }
763        Projection::All
764        | Projection::Column(_)
765        | Projection::Alias(_, _)
766        | Projection::Field(_, _) => {}
767    }
768}
769
770fn rewrite_filter(filter: &mut Filter, ctes: &HashMap<String, QueryExpr>) {
771    match filter {
772        Filter::CompareExpr { lhs, rhs, .. } => {
773            rewrite_expr(lhs, ctes);
774            rewrite_expr(rhs, ctes);
775        }
776        Filter::And(left, right) | Filter::Or(left, right) => {
777            rewrite_filter(left, ctes);
778            rewrite_filter(right, ctes);
779        }
780        Filter::Not(inner) => rewrite_filter(inner, ctes),
781        Filter::Compare { .. }
782        | Filter::CompareFields { .. }
783        | Filter::IsNull(_)
784        | Filter::IsNotNull(_)
785        | Filter::In { .. }
786        | Filter::Between { .. }
787        | Filter::Like { .. }
788        | Filter::StartsWith { .. }
789        | Filter::EndsWith { .. }
790        | Filter::Contains { .. } => {}
791    }
792}
793
794fn rewrite_expr(expr: &mut Expr, ctes: &HashMap<String, QueryExpr>) {
795    match expr {
796        Expr::BinaryOp { lhs, rhs, .. } => {
797            rewrite_expr(lhs, ctes);
798            rewrite_expr(rhs, ctes);
799        }
800        Expr::UnaryOp { operand, .. } => rewrite_expr(operand, ctes),
801        Expr::Cast { inner, .. } => rewrite_expr(inner, ctes),
802        Expr::FunctionCall { args, .. } => {
803            for arg in args {
804                rewrite_expr(arg, ctes);
805            }
806        }
807        Expr::Case {
808            branches, else_, ..
809        } => {
810            for (condition, value) in branches {
811                rewrite_expr(condition, ctes);
812                rewrite_expr(value, ctes);
813            }
814            if let Some(value) = else_ {
815                rewrite_expr(value, ctes);
816            }
817        }
818        Expr::IsNull { operand, .. } => rewrite_expr(operand, ctes),
819        Expr::InList { target, values, .. } => {
820            rewrite_expr(target, ctes);
821            for value in values {
822                rewrite_expr(value, ctes);
823            }
824        }
825        Expr::Between {
826            target, low, high, ..
827        } => {
828            rewrite_expr(target, ctes);
829            rewrite_expr(low, ctes);
830            rewrite_expr(high, ctes);
831        }
832        Expr::Subquery { query, .. } => rewrite(&mut query.query, ctes),
833        Expr::WindowFunctionCall { args, window, .. } => {
834            for arg in args {
835                rewrite_expr(arg, ctes);
836            }
837            for expr in &mut window.partition_by {
838                rewrite_expr(expr, ctes);
839            }
840            for item in &mut window.order_by {
841                rewrite_expr(&mut item.expr, ctes);
842            }
843        }
844        Expr::Literal { .. } | Expr::Column { .. } | Expr::Parameter { .. } => {}
845    }
846}
847
848// ============================================================================
849// Tests
850// ============================================================================
851
852#[cfg(test)]
853mod tests {
854    use super::*;
855    use reddb_rql::ast::CteQueryBuilder;
856    use reddb_rql::ast::WithClause;
857
858    fn mock_execute(
859        _query: &QueryExpr,
860        _ctx: &CteContext,
861    ) -> Result<UnifiedResult, ExecutionError> {
862        // Simple mock that returns empty result
863        Ok(UnifiedResult::empty())
864    }
865
866    #[test]
867    fn test_cte_context() {
868        let mut ctx = CteContext::new();
869
870        // Test empty context
871        assert!(ctx.get("test").is_none());
872        assert!(!ctx.is_evaluating("test"));
873
874        // Test storing results
875        let result = UnifiedResult::with_columns(vec!["col1".to_string()]);
876        ctx.store("test".to_string(), result);
877        assert!(ctx.get("test").is_some());
878
879        // Test evaluation tracking
880        ctx.start_evaluating("other");
881        assert!(ctx.is_evaluating("other"));
882        ctx.done_evaluating("other");
883        assert!(!ctx.is_evaluating("other"));
884    }
885
886    #[test]
887    fn test_simple_cte_execution() {
888        let executor = CteExecutor::new(|_query, _ctx| {
889            let mut result = UnifiedResult::with_columns(vec!["id".to_string()]);
890            let mut record = UnifiedRecord::new();
891            record.set("id", Value::Integer(1));
892            result.push(record);
893            Ok(result)
894        });
895
896        // Create a simple CTE query
897        let cte = CteDefinition {
898            name: "test_cte".to_string(),
899            columns: vec!["id".to_string()],
900            query: Box::new(QueryExpr::table("dummy").build()),
901            recursive: false,
902        };
903
904        let with_clause = WithClause::new().add(cte);
905        let query = QueryWithCte::with_ctes(with_clause, QueryExpr::table("test_cte").build());
906
907        let result = executor.execute(&query);
908        assert!(result.is_ok());
909    }
910
911    #[test]
912    fn test_cte_builder() {
913        let query = CteQueryBuilder::new()
914            .cte_with_columns(
915                "nums",
916                vec!["n".to_string()],
917                QueryExpr::table("numbers").build(),
918            )
919            .build(QueryExpr::table("nums").build());
920
921        assert!(query.with_clause.is_some());
922        let with_clause = query.with_clause.unwrap();
923        assert_eq!(with_clause.ctes.len(), 1);
924        assert_eq!(with_clause.ctes[0].name, "nums");
925    }
926
927    #[test]
928    fn test_recursive_cte_builder() {
929        let query = CteQueryBuilder::new()
930            .recursive_cte("paths", QueryExpr::table("connections").build())
931            .build(QueryExpr::table("paths").build());
932
933        assert!(query.with_clause.is_some());
934        let with_clause = query.with_clause.unwrap();
935        assert!(with_clause.has_recursive);
936        assert!(with_clause.ctes[0].recursive);
937    }
938
939    #[test]
940    fn test_circular_reference_detection() {
941        let mut ctx = CteContext::new();
942        ctx.start_evaluating("cte_a");
943
944        // Simulate trying to evaluate cte_a while it's being evaluated
945        assert!(ctx.is_evaluating("cte_a"));
946    }
947
948    #[test]
949    fn test_cte_stats() {
950        let ctx = CteContext::new();
951        let stats = ctx.stats();
952
953        assert_eq!(stats.ctes_executed, 0);
954        assert_eq!(stats.recursive_iterations, 0);
955        assert_eq!(stats.rows_produced, 0);
956    }
957
958    #[test]
959    fn test_hash_record() {
960        let executor = CteExecutor::new(mock_execute);
961
962        let mut record1 = UnifiedRecord::new();
963        record1.set("id", Value::Integer(1));
964        record1.set("name", Value::text("test".to_string()));
965
966        let mut record2 = UnifiedRecord::new();
967        record2.set("id", Value::Integer(1));
968        record2.set("name", Value::text("test".to_string()));
969
970        let mut record3 = UnifiedRecord::new();
971        record3.set("id", Value::Integer(2));
972        record3.set("name", Value::text("test".to_string()));
973
974        // Same content should have same hash
975        assert_eq!(
976            executor.hash_record(&record1),
977            executor.hash_record(&record2)
978        );
979
980        // Different content should have different hash
981        assert_ne!(
982            executor.hash_record(&record1),
983            executor.hash_record(&record3)
984        );
985    }
986
987    #[test]
988    fn test_hash_various_value_types() {
989        let executor = CteExecutor::new(mock_execute);
990
991        // Test hashing different value types
992        let mut record = UnifiedRecord::new();
993        record.set("null_val", Value::Null);
994        record.set("bool_val", Value::Boolean(true));
995        record.set("int_val", Value::Integer(42));
996        record.set("float_val", Value::Float(2.5));
997        record.set("text_val", Value::text("hello".to_string()));
998        record.set("blob_val", Value::Blob(vec![1, 2, 3]));
999        record.set("timestamp_val", Value::Timestamp(1234567890));
1000        record.set("duration_val", Value::Duration(5000));
1001
1002        // Should not panic
1003        let hash = executor.hash_record(&record);
1004        assert!(hash > 0);
1005    }
1006
1007    #[test]
1008    fn test_project_columns() {
1009        let executor = CteExecutor::new(mock_execute);
1010
1011        let mut original =
1012            UnifiedResult::with_columns(vec!["a".to_string(), "b".to_string(), "c".to_string()]);
1013
1014        let mut record = UnifiedRecord::new();
1015        record.set("a", Value::Integer(1));
1016        record.set("b", Value::Integer(2));
1017        record.set("c", Value::Integer(3));
1018        original.push(record);
1019
1020        // Project to different column names
1021        let projected = executor.project_columns(&original, &["x".to_string(), "y".to_string()]);
1022
1023        assert_eq!(projected.columns, vec!["x", "y"]);
1024        assert_eq!(projected.len(), 1);
1025    }
1026
1027    #[test]
1028    fn test_empty_columns_projection() {
1029        let executor = CteExecutor::new(mock_execute);
1030
1031        let original = UnifiedResult::with_columns(vec!["a".to_string()]);
1032
1033        // Empty columns should return original
1034        let projected = executor.project_columns(&original, &[]);
1035        assert_eq!(projected.columns, original.columns);
1036    }
1037
1038    #[test]
1039    fn test_cte_with_multiple_definitions() {
1040        let executor = CteExecutor::new(|query, ctx| {
1041            // Return different results based on which CTE is being queried
1042            match query {
1043                QueryExpr::Table(t) if t.table == "base" => {
1044                    let mut result = UnifiedResult::with_columns(vec!["id".to_string()]);
1045                    let mut record = UnifiedRecord::new();
1046                    record.set("id", Value::Integer(1));
1047                    result.push(record);
1048                    Ok(result)
1049                }
1050                QueryExpr::Table(t) if t.table == "cte1" => {
1051                    // Should be able to see cte1 in context
1052                    if ctx.get("cte1").is_some() {
1053                        Ok(ctx.get("cte1").unwrap().clone())
1054                    } else {
1055                        Ok(UnifiedResult::empty())
1056                    }
1057                }
1058                _ => Ok(UnifiedResult::empty()),
1059            }
1060        });
1061
1062        let cte1 = CteDefinition {
1063            name: "cte1".to_string(),
1064            columns: vec!["id".to_string()],
1065            query: Box::new(QueryExpr::table("base").build()),
1066            recursive: false,
1067        };
1068
1069        let cte2 = CteDefinition {
1070            name: "cte2".to_string(),
1071            columns: vec!["id".to_string()],
1072            query: Box::new(QueryExpr::table("cte1").build()),
1073            recursive: false,
1074        };
1075
1076        let with_clause = WithClause::new().add(cte1).add(cte2);
1077        let query = QueryWithCte::with_ctes(with_clause, QueryExpr::table("cte2").build());
1078
1079        let result = executor.execute(&query);
1080        assert!(result.is_ok());
1081    }
1082}