uqa-engine 0.1.9

Engine: schema-aware table store, catalog restore, transactions
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! SQL SELECT, set-operation, `CtePlan`, ordering, and projection execution.

use std::cell::Cell;
use std::fmt::Write as _;
use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

use smallvec::SmallVec;
use uqa_core::DocId;
pub(in crate::sql) use uqa_execution::ProjectionTarget;
use uqa_execution::{
    eval_scalar, ExecResult, ExpressionEvaluator, ScalarEvalContext, ScalarExpr, ScalarFrameBound,
    SharedExpressionEvaluator,
};
use uqa_planner::{
    AccessPathPlan, ComputePlan, CtePlan, ProjectionPlan, QueryBlockPlan, QueryPlan,
    RelationalPlan, SourcePlan, UnifiedPlan,
};

use super::from_rows::execute_lateral_subquery_output;
use super::scalar::{
    eval_physical_scalar, PhysicalEvalContext, PhysicalOuterRow, PhysicalSubqueryRunner,
};
use super::volatility::{expr_contains_volatile_function, query_contains_volatile_function};
use super::{
    contains_aggregate, doc_id_value, engine_func_intercept, execute_function,
    execute_function_with_top_k, execute_mixed_where, expect_column_name, has_aggregate,
    has_window, optimize_engine_plan, prepare_window_plan, projection_label_at, BTreeMap, BTreeSet,
    BinaryOp, ColumnPrune, ColumnType, Engine, PhysicalAggregateExecutor, PhysicalWindowExecutor,
    QualifierFilters, ResultRow, SQLError, SQLParam, SQLResult, ScoredEntry, SetOpKind, Value,
    DOC_ID_COLUMN, SCORE_COLUMN, TABLE_OID_COLUMN, XMIN_COLUMN,
};

mod cte_execution;
mod evaluation;
mod expression_shape;
mod facet_projection;
mod filter_pushdown;
mod foreign_access;
mod grouping_sets;
mod physical_plan;
mod query_block;
mod recursive_cte;
mod row_lock_recheck;
mod row_lock_retry_cache;
mod row_locking;
mod schema_binding;
mod scored_input;
mod set_projection;
mod table_access;

pub(in crate::sql) use cte_execution::*;
pub(crate) use evaluation::CteScope;
pub(in crate::sql) use evaluation::{
    expr_contains_subquery, prepare_correlated_exists_predicate, DirectColumnKey,
    EngineExpressionEvaluator, ScopedEngineHook,
};
pub(in crate::sql) use expression_shape::*;
pub(in crate::sql) use facet_projection::*;
pub(in crate::sql) use filter_pushdown::*;
pub(in crate::sql) use foreign_access::*;
pub(in crate::sql) use grouping_sets::*;
pub(in crate::sql) use physical_plan::*;
pub(in crate::sql) use query_block::*;
pub(in crate::sql) use recursive_cte::*;
pub(in crate::sql) use row_lock_recheck::*;
pub(crate) use row_lock_retry_cache::{RetryRowOverride, RowLockRetryCache};
pub(in crate::sql) use row_locking::*;
pub(in crate::sql) use schema_binding::*;
pub(in crate::sql) use scored_input::*;
pub(in crate::sql) use set_projection::*;
pub(in crate::sql) use table_access::*;

// -------------------------------------------------------------------------
// SELECT
// -------------------------------------------------------------------------

type PhysicalProjection = (uqa_execution::ProjectionTarget, ScalarExpr);
/// Public output label paired with the bound expression that addresses its physical value after relational binding. Positional expressions preserve repeated labels without inventing SQL-visible names.
type OutputColumnMapping = (String, ScalarExpr);

#[derive(Clone, Copy)]
pub(in crate::sql) struct SingleRelation<'a> {
    pub storage_name: &'a str,
    pub qualifier: &'a str,
}

/// Execute the physical relational plan directly. CTEs, set-operation
/// branches, values, and query blocks recurse through plan children; query
/// blocks select physical access and row operators without reconstructing a
/// parser statement.
pub(crate) fn execute_query_plan(
    engine: &Engine,
    plan: &QueryPlan,
    params: &[SQLParam],
) -> Result<SQLResult, SQLError> {
    let mut ctes = CteScope::new_for_current_routine();
    execute_query_plan_with_ctes(engine, plan, params, &mut ctes)
}

pub(in crate::sql) trait QueryRowConsumer {
    fn begin(
        &self,
        engine: &Engine,
        columns: &[String],
        schema: &uqa_execution::RowSchema,
    ) -> Result<(), SQLError>;

    fn consume(
        &self,
        engine: &Engine,
        row: uqa_execution::OwnedPhysicalRow,
    ) -> Result<QueryConsumerControl, SQLError>;
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub(in crate::sql) enum QueryConsumerControl {
    Continue,
    Stop,
}

struct SetOperationRowConsumer {
    downstream: Rc<dyn QueryRowConsumer>,
    columns: Vec<String>,
    schema: uqa_execution::RowSchema,
    offset: Cell<u64>,
    remaining: Cell<Option<u64>>,
    stopped: Cell<bool>,
}

impl SetOperationRowConsumer {
    fn new(
        downstream: Rc<dyn QueryRowConsumer>,
        schema: uqa_execution::RowSchema,
        offset: u64,
        limit: Option<u64>,
    ) -> Self {
        Self {
            columns: schema.columns().to_vec(),
            downstream,
            schema,
            offset: Cell::new(offset),
            remaining: Cell::new(limit),
            stopped: Cell::new(limit == Some(0)),
        }
    }

    fn stopped(&self) -> bool {
        self.stopped.get()
    }
}

impl QueryRowConsumer for SetOperationRowConsumer {
    fn begin(
        &self,
        engine: &Engine,
        columns: &[String],
        _schema: &uqa_execution::RowSchema,
    ) -> Result<(), SQLError> {
        if columns.len() != self.columns.len() {
            return Err(SQLError::TypeMismatch(format!(
                "set-operation input width {} does not match output width {}",
                columns.len(),
                self.columns.len()
            )));
        }
        self.downstream.begin(engine, &self.columns, &self.schema)
    }

    fn consume(
        &self,
        engine: &Engine,
        row: uqa_execution::OwnedPhysicalRow,
    ) -> Result<QueryConsumerControl, SQLError> {
        if self.stopped() {
            return Ok(QueryConsumerControl::Stop);
        }
        if self.offset.get() > 0 {
            self.offset.set(self.offset.get() - 1);
            return Ok(QueryConsumerControl::Continue);
        }
        if self.remaining.get() == Some(0) {
            self.stopped.set(true);
            return Ok(QueryConsumerControl::Stop);
        }
        let projections = {
            let view = row.view();
            self.schema
                .column_types()
                .iter()
                .enumerate()
                .map(|(position, target_type)| {
                    let source_type = row.schema.column_type(position);
                    if target_type
                        .as_ref()
                        .is_some_and(|target_type| source_type != Some(target_type))
                    {
                        let value = view.value_at(position).cloned().unwrap_or(Value::Null);
                        return coerce_common_context_value(
                            value,
                            source_type,
                            target_type.as_ref(),
                        )
                        .map(uqa_execution::RowProjectionValue::Owned);
                    }
                    Ok(row.schema.physical_slot(position).map_or(
                        uqa_execution::RowProjectionValue::Owned(Value::Null),
                        uqa_execution::RowProjectionValue::InputSlot,
                    ))
                })
                .collect::<Result<Vec<_>, SQLError>>()?
        };
        let control = self.downstream.consume(
            engine,
            uqa_execution::OwnedPhysicalRow::new(
                self.schema.clone(),
                row.row
                    .project_with_values(projections)
                    .without_lock_origins(),
            ),
        )?;
        if matches!(control, QueryConsumerControl::Stop) {
            self.stopped.set(true);
            return Ok(control);
        }
        if let Some(remaining) = self.remaining.get() {
            let remaining = remaining - 1;
            self.remaining.set(Some(remaining));
            if remaining == 0 {
                self.stopped.set(true);
                return Ok(QueryConsumerControl::Stop);
            }
        }
        Ok(QueryConsumerControl::Continue)
    }
}

#[derive(Clone)]
pub(super) enum QueryOutputMode {
    Rows,
    SharedSpill,
    ExistsKeySet,
    RowConsumer(Rc<dyn QueryRowConsumer>),
}

pub(super) enum QueryRows {
    Rows {
        named: Vec<ResultRow>,
        positional: Option<Vec<Vec<Value>>>,
    },
    SharedSpill(uqa_execution::SharedSpill),
    ExistsKeySet(uqa_execution::CanonicalRowHashSet),
}

pub(super) struct QueryOutput {
    pub(super) columns: Vec<String>,
    pub(super) column_types: Vec<Option<uqa_sql::ast::ColumnType>>,
    /// Physical columns include internal row metadata that is available to a
    /// parent query block but never exposed through [`SQLResult`].
    pub(super) internal_columns: Vec<String>,
    pub(super) internal_types: Vec<Option<uqa_sql::ast::ColumnType>>,
    pub(super) rows: QueryRows,
}

impl QueryOutput {
    pub(super) fn into_cursor(self) -> Result<super::SQLCursor, SQLError> {
        match self.rows {
            QueryRows::SharedSpill(rows) => {
                super::SQLCursor::from_spill(self.columns, self.column_types, rows)
            }
            QueryRows::Rows { .. } | QueryRows::ExistsKeySet(_) => Err(SQLError::Internal(
                "cursor query unexpectedly used unbounded row materialization".into(),
            )),
        }
    }

    pub(super) fn into_sql_result(self) -> Result<SQLResult, SQLError> {
        let (rows, positional_rows) = match self.rows {
            QueryRows::Rows { named, positional } => (named, positional),
            QueryRows::SharedSpill(rows) => {
                let mut scan = uqa_execution::SharedSpillScan::new(rows);
                (
                    uqa_execution::physical::run_to_rows(&mut scan)
                        .map_err(physical_exec_error)?
                        .1,
                    None,
                )
            }
            QueryRows::ExistsKeySet(_) => {
                return Err(SQLError::Internal(
                    "EXISTS key-set output cannot become a SQL result".into(),
                ));
            }
        };
        Ok(SQLResult::from_typed_rows_with_positions(
            self.columns,
            self.column_types,
            rows,
            positional_rows,
        ))
    }

    pub(super) fn into_operator<'a>(self) -> Box<dyn uqa_execution::PhysicalOperator + 'a> {
        match self.rows {
            QueryRows::Rows { named, .. } => Box::new(uqa_execution::TableScan::from_typed_rows(
                self.internal_columns,
                self.internal_types,
                named,
            )),
            QueryRows::SharedSpill(rows) => Box::new(uqa_execution::SharedSpillScan::new(rows)),
            QueryRows::ExistsKeySet(_) => {
                panic!("EXISTS key-set output cannot become a physical operator")
            }
        }
    }

    pub(super) fn into_public_operator<'a>(self) -> Box<dyn uqa_execution::PhysicalOperator + 'a> {
        let columns = self.columns.clone();
        let public_width = columns.len();
        let operator = self.into_operator();
        let positions = columns
            .into_iter()
            .enumerate()
            .map(|(position, column)| (column, position))
            .collect();
        debug_assert!(operator.row_schema().len() >= public_width);
        Box::new(uqa_execution::ColumnSelection::with_positions(
            operator, positions,
        ))
    }

    fn into_subquery_result(self) -> Result<uqa_execution::SubqueryResult, SQLError> {
        let QueryOutput {
            columns,
            column_types: _,
            internal_columns,
            internal_types,
            rows,
        } = self;
        let rows: Box<
            dyn Iterator<Item = Result<uqa_execution::OwnedPhysicalRow, SQLError>> + Send,
        > = match rows {
            QueryRows::Rows { named, .. } => {
                let schema = uqa_execution::RowSchema::with_types(internal_columns, internal_types);
                Box::new(named.into_iter().map(move |row| {
                    Ok(uqa_execution::OwnedPhysicalRow::new(
                        schema.clone(),
                        uqa_execution::PhysicalRow::from_result_row(&schema, row),
                    ))
                }))
            }
            QueryRows::SharedSpill(rows) => Box::new(
                rows.read_rows()
                    .map_err(physical_exec_error)?
                    .map(|row| row.map_err(physical_exec_error)),
            ),
            QueryRows::ExistsKeySet(_) => {
                return Err(SQLError::Internal(
                    "EXISTS key-set output cannot become a scalar subquery result".into(),
                ));
            }
        };
        Ok(uqa_execution::SubqueryResult { columns, rows })
    }
}

/// Execute a physical query plan while preserving the caller's CTE scope.
pub(super) fn execute_query_plan_with_ctes(
    engine: &Engine,
    plan: &QueryPlan,
    params: &[SQLParam],
    ctes: &mut CteScope,
) -> Result<SQLResult, SQLError> {
    execute_query_plan_output(engine, plan, params, ctes, QueryOutputMode::Rows)?.into_sql_result()
}

pub(super) fn execute_query_plan_output(
    engine: &Engine,
    plan: &QueryPlan,
    params: &[SQLParam],
    ctes: &mut CteScope,
    output_mode: QueryOutputMode,
) -> Result<QueryOutput, SQLError> {
    let mut visible_ctes = ctes.enter_visible_ctes(plan.ctes.iter().map(|cte| cte.name.as_str()));
    let ctes = &mut *visible_ctes;
    if !plan.ctes.is_empty() {
        let ordered_ctes = ordered_plan_ctes(plan)?;
        let reachable = reachable_plan_cte_names(plan);
        let single_reference = single_reference_plan_cte_names(plan);
        let recursive = ordered_ctes
            .iter()
            .copied()
            .filter(|cte| cte_references_own_name(cte))
            .map(|cte| cte.name.as_str())
            .collect::<BTreeSet<_>>();
        for cte in ordered_ctes.iter().copied().filter(|cte| {
            !recursive.contains(cte.name.as_str())
                && reachable.contains(&cte.name)
                && match cte.materialization {
                    uqa_sql::ast::CteMaterialization::Default => {
                        single_reference.contains(&cte.name)
                    }
                    uqa_sql::ast::CteMaterialization::Materialized => false,
                    uqa_sql::ast::CteMaterialization::NotMaterialized => true,
                }
                && matches!(
                    query_contains_volatile_function(engine, &cte.query),
                    Ok(false)
                )
        }) {
            ctes.insert_deferred(cte.clone());
        }
        let filters = cte_output_filters(engine, plan);
        materialize_plan_ctes_with_filters(
            engine,
            ordered_ctes.into_iter().filter(|cte| {
                reachable.contains(&cte.name)
                    && (recursive.contains(cte.name.as_str())
                        || matches!(
                            cte.materialization,
                            uqa_sql::ast::CteMaterialization::Materialized
                        )
                        || (matches!(
                            cte.materialization,
                            uqa_sql::ast::CteMaterialization::Default
                        ) && !single_reference.contains(&cte.name))
                        || !matches!(
                            query_contains_volatile_function(engine, &cte.query),
                            Ok(false)
                        ))
            }),
            params,
            ctes,
            &filters,
        )?;
    }
    match &plan.root {
        RelationalPlan::QueryBlock(block) => {
            execute_query_block_output(engine, block, params, ctes, output_mode)
        }
        RelationalPlan::SetOp {
            kind,
            all,
            left,
            right,
            order_by,
            limit,
            with_ties,
            offset,
            subqueries,
        } => {
            let set_schema = bind_query_plan_schema(engine, plan, params, ctes, None)?;
            let streaming_consumer = match &output_mode {
                QueryOutputMode::RowConsumer(downstream)
                    if matches!((*kind, *all), (SetOpKind::Union, true))
                        && order_by.is_empty()
                        && !*with_ties =>
                {
                    Some(Rc::clone(downstream))
                }
                _ => None,
            };
            if let Some(downstream) = streaming_consumer {
                let columns = set_schema.columns().to_vec();
                let column_types = set_schema.column_types().to_vec();
                let (resolved_offset, resolved_limit) = {
                    let scoped_ctes = ctes.enter_scalar_subqueries(subqueries);
                    (
                        resolve_limit_offset_with_ctes(
                            offset.as_deref(),
                            engine,
                            params,
                            "OFFSET",
                            &scoped_ctes,
                        )?
                        .unwrap_or(0),
                        resolve_limit_offset_with_ctes(
                            limit.as_deref(),
                            engine,
                            params,
                            "LIMIT",
                            &scoped_ctes,
                        )?,
                    )
                };
                let consumer = Rc::new(SetOperationRowConsumer::new(
                    Rc::clone(&downstream),
                    set_schema.clone(),
                    resolved_offset,
                    resolved_limit,
                ));
                if consumer.stopped() {
                    downstream.begin(engine, &columns, &set_schema)?;
                } else {
                    let mut child_ctes = ctes.enter_lock_identity_emission(false);
                    execute_query_plan_output(
                        engine,
                        left,
                        params,
                        &mut child_ctes,
                        QueryOutputMode::RowConsumer(consumer.clone()),
                    )?;
                    if !consumer.stopped() {
                        execute_query_plan_output(
                            engine,
                            right,
                            params,
                            &mut child_ctes,
                            QueryOutputMode::RowConsumer(consumer),
                        )?;
                    }
                }
                return Ok(QueryOutput {
                    columns: columns.clone(),
                    column_types: column_types.clone(),
                    internal_columns: columns,
                    internal_types: column_types,
                    rows: QueryRows::Rows {
                        named: Vec::new(),
                        positional: None,
                    },
                });
            }
            // Materialize each child directly into a disk-backed, repeatable
            // stream before starting the next child. A nested set operation
            // therefore never owns two cardinality-sized `SQLResult.rows`
            // vectors, and its external merge consumes batches under
            // `work_mem`.
            let (lhs, rhs) = {
                let mut child_ctes = ctes.enter_lock_identity_emission(false);
                let lhs = execute_query_plan_output(
                    engine,
                    left,
                    params,
                    &mut child_ctes,
                    QueryOutputMode::SharedSpill,
                )?;
                let rhs = execute_query_plan_output(
                    engine,
                    right,
                    params,
                    &mut child_ctes,
                    QueryOutputMode::SharedSpill,
                )?;
                (lhs, rhs)
            };
            let columns = lhs.columns.clone();
            let left: Box<dyn uqa_execution::PhysicalOperator + '_> = lhs.into_public_operator();
            let right: Box<dyn uqa_execution::PhysicalOperator + '_> = rhs.into_public_operator();
            let operation: Box<dyn uqa_execution::PhysicalOperator + '_> = Box::new(
                uqa_execution::ExternalSetOperation::new_with_types(
                    left,
                    right,
                    *kind,
                    *all,
                    set_schema.column_types().to_vec(),
                    physical_work_mem_bytes(engine)?,
                )
                .map_err(physical_exec_error)?,
            );
            if !order_by.is_empty() || limit.is_some() || offset.is_some() {
                let synthetic = QueryBlockPlan {
                    projections: Vec::new(),
                    from: None,
                    r#where: None,
                    compute: ComputePlan::Project,
                    group_by: Vec::new(),
                    grouping_sets: Vec::new(),
                    group_distinct: false,
                    having: None,
                    order_by: order_by.clone(),
                    limit: limit.as_deref().cloned(),
                    with_ties: *with_ties,
                    offset: offset.as_deref().cloned(),
                    distinct: false,
                    distinct_on: Vec::new(),
                    subqueries: subqueries.clone(),
                    access: AccessPathPlan::Row,
                    locking: Vec::new(),
                };
                let ordering_scope = ctes.enter_scalar_subqueries(subqueries);
                let evaluator = EngineExpressionEvaluator::shared(engine, params, &ordering_scope);
                let output = identity_order_columns(&columns);
                let operation = attach_order_limit(
                    operation,
                    &synthetic,
                    &output,
                    engine,
                    params,
                    &ordering_scope,
                    evaluator,
                    None,
                )?;
                return collect_query_operator(engine, columns, operation, output_mode);
            }
            collect_query_operator(engine, columns, operation, output_mode)
        }
        RelationalPlan::Values { rows, subqueries } => {
            {
                let scoped_ctes = ctes.enter_scalar_subqueries(subqueries);
                let type_resolver = ScopedEngineHook::new(engine, &scoped_ctes);
                validate_values_set_contexts(
                    engine,
                    &type_resolver,
                    rows,
                    &uqa_execution::RowSchema::default(),
                    params,
                )?;
            }
            execute_plan_values_output(engine, rows, subqueries, params, ctes, output_mode)
        }
    }
}

pub(super) fn collect_query_operator<'a>(
    engine: &Engine,
    columns: Vec<String>,
    mut operator: Box<dyn uqa_execution::PhysicalOperator + 'a>,
    output_mode: QueryOutputMode,
) -> Result<QueryOutput, SQLError> {
    let internal_schema = operator.row_schema().clone();
    let internal_columns = internal_schema.columns().to_vec();
    let internal_types = internal_schema.column_types().to_vec();
    let column_types = columns
        .iter()
        .enumerate()
        .map(|(index, column)| {
            if internal_schema.columns().get(index) == Some(column) {
                internal_schema.column_type(index).cloned()
            } else {
                internal_schema
                    .position(column)
                    .and_then(|position| internal_schema.column_type(position).cloned())
            }
        })
        .collect();
    let rows = match output_mode {
        QueryOutputMode::Rows => {
            let has_duplicate_labels = {
                let mut seen = std::collections::BTreeSet::new();
                columns.iter().any(|column| !seen.insert(column))
            };
            if has_duplicate_labels {
                let batches = uqa_execution::physical::run_to_batches(operator.as_mut())
                    .map_err(physical_exec_error)?;
                let mut named = Vec::new();
                let mut positional = Vec::new();
                for batch in batches {
                    let columnar =
                        uqa_execution::ColumnarBatch::from_batch(&columns, batch.clone());
                    positional.extend(columnar.into_positional_rows());
                    named.extend(batch.into_result_rows());
                }
                QueryRows::Rows {
                    named,
                    positional: Some(positional),
                }
            } else {
                QueryRows::Rows {
                    named: uqa_execution::physical::run_to_rows(operator.as_mut())
                        .map_err(physical_exec_error)?
                        .1,
                    positional: None,
                }
            }
        }
        QueryOutputMode::SharedSpill => {
            let mut buffer =
                uqa_execution::SpillBuffer::new(physical_work_mem_bytes(engine)?.max(1));
            if let Err(error) = operator.open() {
                return Err(close_after_physical_failure(
                    operator.as_mut(),
                    error,
                    "open",
                ));
            }
            loop {
                let batch = match operator.next() {
                    Ok(batch) => batch,
                    Err(error) => {
                        return Err(close_after_physical_failure(
                            operator.as_mut(),
                            error,
                            "execution",
                        ));
                    }
                };
                let Some(batch) = batch else {
                    break;
                };
                if let Err(error) = buffer.push(batch) {
                    return Err(close_after_physical_failure(
                        operator.as_mut(),
                        error,
                        "spill buffering",
                    ));
                }
            }
            operator.close().map_err(physical_exec_error)?;
            QueryRows::SharedSpill(
                buffer
                    .into_shared(internal_schema)
                    .map_err(physical_exec_error)?,
            )
        }
        QueryOutputMode::ExistsKeySet => {
            if operator.row_schema().len() < columns.len() {
                return Err(SQLError::Internal(format!(
                    "decorrelated EXISTS result has {} columns for {} keys",
                    operator.row_schema().len(),
                    columns.len()
                )));
            }
            let key_positions = (0..columns.len()).collect::<Vec<_>>();
            let mut keys = uqa_execution::CanonicalRowHashSet::new();
            if let Err(error) = operator.open() {
                return Err(close_after_physical_failure(
                    operator.as_mut(),
                    error,
                    "open EXISTS key input",
                ));
            }
            loop {
                let batch = match operator.next() {
                    Ok(batch) => batch,
                    Err(error) => {
                        return Err(close_after_physical_failure(
                            operator.as_mut(),
                            error,
                            "collect EXISTS keys",
                        ));
                    }
                };
                let Some(batch) = batch else {
                    break;
                };
                for row in &batch.rows {
                    let view = batch.schema.view(row);
                    let mut key = SmallVec::<[&Value; 4]>::with_capacity(key_positions.len());
                    let mut contains_null = false;
                    for position in &key_positions {
                        let Some(value) = view.value_at(*position) else {
                            contains_null = true;
                            break;
                        };
                        if matches!(value, Value::Null) {
                            contains_null = true;
                            break;
                        }
                        key.push(value);
                    }
                    if !contains_null {
                        if let Err(error) = keys.insert_borrowed(&key) {
                            return Err(close_after_physical_failure(
                                operator.as_mut(),
                                error,
                                "hash EXISTS keys",
                            ));
                        }
                    }
                }
            }
            operator.close().map_err(physical_exec_error)?;
            QueryRows::ExistsKeySet(keys)
        }
        QueryOutputMode::RowConsumer(consumer) => {
            consumer.begin(engine, &columns, &internal_schema)?;
            if let Err(error) = operator.open() {
                return Err(close_after_physical_failure(
                    operator.as_mut(),
                    error,
                    "open row consumer input",
                ));
            }
            'consume: loop {
                let batch = match operator.next() {
                    Ok(batch) => batch,
                    Err(error) => {
                        return Err(close_after_physical_failure(
                            operator.as_mut(),
                            error,
                            "execute row consumer input",
                        ));
                    }
                };
                let Some(batch) = batch else {
                    break;
                };
                let uqa_execution::Batch { schema, rows } = batch;
                for row in rows {
                    let row = uqa_execution::OwnedPhysicalRow::new(schema.clone(), row);
                    match consumer.consume(engine, row) {
                        Ok(QueryConsumerControl::Continue) => {}
                        Ok(QueryConsumerControl::Stop) => break 'consume,
                        Err(error) => {
                            return Err(close_after_physical_failure(
                                operator.as_mut(),
                                uqa_execution::ExecError::SQL(error),
                                "consume query row",
                            ));
                        }
                    }
                }
            }
            operator.close().map_err(physical_exec_error)?;
            QueryRows::Rows {
                named: Vec::new(),
                positional: None,
            }
        }
    };
    Ok(QueryOutput {
        columns,
        column_types,
        internal_columns,
        internal_types,
        rows,
    })
}

/// Collect decorrelated EXISTS keys directly from the filtered input. Direct
/// column expressions stay as borrowed physical values; non-trivial key
/// expressions are evaluated into an inline buffer. In either case there is
/// no projected `PhysicalRow` materialization between the input and hash set.
pub(in crate::sql) fn collect_exists_key_operator<'a>(
    columns: Vec<String>,
    mut operator: Box<dyn uqa_execution::PhysicalOperator + 'a>,
    projections: &[ProjectionPlan],
    evaluator: SharedExpressionEvaluator<'a>,
) -> Result<QueryOutput, SQLError> {
    let internal_columns = operator.schema().to_vec();
    let internal_types = operator.row_schema().column_types().to_vec();
    let column_types = projections
        .iter()
        .map(|projection| {
            uqa_execution::scalar_type(
                &projection.expr,
                operator.row_schema(),
                evaluator.parameters(),
            )
            .ok()
            .flatten()
        })
        .collect();
    let direct_columns = projections
        .iter()
        .map(|projection| DirectColumnKey::compile(&projection.expr))
        .collect::<Option<Vec<_>>>();
    let mut keys = uqa_execution::CanonicalRowHashSet::new();
    if let Err(error) = operator.open() {
        return Err(close_after_physical_failure(
            operator.as_mut(),
            error,
            "open EXISTS key input",
        ));
    }
    loop {
        let batch = match operator.next() {
            Ok(batch) => batch,
            Err(error) => {
                return Err(close_after_physical_failure(
                    operator.as_mut(),
                    error,
                    "collect EXISTS key input",
                ));
            }
        };
        let Some(batch) = batch else {
            break;
        };
        for row in &batch.rows {
            let view = batch.schema.view(row);
            let inserted = if let Some(direct_columns) = direct_columns.as_ref() {
                let mut key = SmallVec::<[&Value; 4]>::with_capacity(direct_columns.len());
                let mut contains_null = false;
                for column in direct_columns {
                    let Some(value) = column.value(&view) else {
                        contains_null = true;
                        break;
                    };
                    if matches!(value, Value::Null) {
                        contains_null = true;
                        break;
                    }
                    key.push(value);
                }
                if contains_null {
                    Ok(false)
                } else {
                    keys.insert_borrowed(&key)
                }
            } else {
                let mut key = SmallVec::<[Value; 4]>::with_capacity(projections.len());
                let mut contains_null = false;
                for projection in projections {
                    let value =
                        match evaluator.evaluate_physical(&projection.expr, &batch.schema, row) {
                            Ok(value) => value,
                            Err(error) => {
                                return Err(close_after_physical_failure(
                                    operator.as_mut(),
                                    error,
                                    "evaluate EXISTS key",
                                ));
                            }
                        };
                    if matches!(value, Value::Null) {
                        contains_null = true;
                        break;
                    }
                    key.push(value);
                }
                if contains_null {
                    Ok(false)
                } else {
                    keys.insert_values(&key)
                }
            };
            if let Err(error) = inserted {
                return Err(close_after_physical_failure(
                    operator.as_mut(),
                    error,
                    "hash EXISTS key",
                ));
            }
        }
    }
    operator.close().map_err(physical_exec_error)?;
    Ok(QueryOutput {
        internal_columns,
        internal_types,
        column_types,
        columns,
        rows: QueryRows::ExistsKeySet(keys),
    })
}

fn execute_query_block_output(
    engine: &Engine,
    block: &QueryBlockPlan,
    params: &[SQLParam],
    ctes: &mut CteScope,
    output_mode: QueryOutputMode,
) -> Result<QueryOutput, SQLError> {
    let inherited_lock_identities = ctes.lock_identities.emit;
    let mut scoped_ctes = ctes.enter_scalar_subqueries(&block.subqueries);
    let row_identity_barrier = block.distinct
        || !block.distinct_on.is_empty()
        || matches!(block.compute, ComputePlan::Aggregate | ComputePlan::Window);
    scoped_ctes.lock_identities.emit =
        !block.locking.is_empty() || (inherited_lock_identities && !row_identity_barrier);
    scoped_ctes.lock_identities.retain_after_lock =
        inherited_lock_identities && !row_identity_barrier;
    let defer_distinct_limit = should_defer_distinct_limit(block);
    let mut execution = select_execution_stmt(block, defer_distinct_limit);
    let outer = scoped_ctes.row_lock_outer_row().map(|row| &row.schema);
    if let Some(source) = execution.from.as_mut() {
        bind_source_plan_schema_for_execution(engine, source, params, &scoped_ctes, outer)?;
    }
    run_query_block_with_prepared_exists_output(
        engine,
        block,
        &execution,
        params,
        &mut scoped_ctes,
        output_mode,
    )
}

pub(super) struct SetSpillExecution<'a> {
    kind: SetOpKind,
    all: bool,
    columns: Vec<String>,
    lhs: uqa_execution::SharedSpill,
    rhs: uqa_execution::SharedSpill,
    order_plan: Option<&'a QueryBlockPlan>,
    output_mode: QueryOutputMode,
}

impl<'a> SetSpillExecution<'a> {
    pub(super) fn new(
        kind: SetOpKind,
        all: bool,
        columns: Vec<String>,
        lhs: uqa_execution::SharedSpill,
        rhs: uqa_execution::SharedSpill,
        order_plan: Option<&'a QueryBlockPlan>,
        output_mode: QueryOutputMode,
    ) -> Self {
        Self {
            kind,
            all,
            columns,
            lhs,
            rhs,
            order_plan,
            output_mode,
        }
    }
}

pub(super) fn combine_set_spills_with_order_output(
    engine: &Engine,
    execution: SetSpillExecution<'_>,
    params: &[SQLParam],
    ctes: &CteScope,
) -> Result<QueryOutput, SQLError> {
    use uqa_execution::{ExternalSetOperation, PhysicalOperator};

    let public_positions = || {
        execution
            .columns
            .iter()
            .cloned()
            .enumerate()
            .map(|(position, column)| (column, position))
            .collect::<Vec<_>>()
    };
    let left: Box<dyn PhysicalOperator> = Box::new(uqa_execution::ColumnSelection::with_positions(
        Box::new(uqa_execution::SharedSpillScan::new(execution.lhs)),
        public_positions(),
    ));
    let right: Box<dyn PhysicalOperator> =
        Box::new(uqa_execution::ColumnSelection::with_positions(
            Box::new(uqa_execution::SharedSpillScan::new(execution.rhs)),
            public_positions(),
        ));
    let mut operation: Box<dyn PhysicalOperator + '_> = Box::new(
        ExternalSetOperation::new(
            left,
            right,
            execution.kind,
            execution.all,
            physical_work_mem_bytes(engine)?,
        )
        .map_err(physical_exec_error)?,
    );
    if let Some(order_plan) = execution.order_plan {
        let output = identity_order_columns(&execution.columns);
        operation = attach_order_limit(
            operation,
            order_plan,
            &output,
            engine,
            params,
            ctes,
            EngineExpressionEvaluator::shared(engine, params, ctes),
            None,
        )?;
    }
    collect_query_operator(engine, execution.columns, operation, execution.output_mode)
}

fn execute_plan_values_output(
    engine: &Engine,
    rows: &[Vec<ScalarExpr>],
    subqueries: &[QueryPlan],
    params: &[SQLParam],
    ctes: &CteScope,
    output_mode: QueryOutputMode,
) -> Result<QueryOutput, SQLError> {
    if rows.is_empty() {
        let scan: Box<dyn uqa_execution::PhysicalOperator + '_> =
            Box::new(uqa_execution::TableScan::from_physical_rows(
                uqa_execution::RowSchema::default(),
                Vec::new(),
            ));
        return collect_query_operator(engine, Vec::new(), scan, output_mode);
    }
    let columns: Vec<String> = (0..rows[0].len())
        .map(|index| format!("column{}", index + 1))
        .collect();
    let column_types = values_types_in_scope(engine, rows, subqueries, None, params, ctes)?;
    let empty_schema = uqa_execution::RowSchema::default();
    let hook = ScopedEngineHook::new(engine, ctes);
    let context = PhysicalEvalContext::new(None, params)
        .with_function_hook(&hook)
        .with_subquery_runner(&hook);
    let schema = uqa_execution::RowSchema::with_types(columns.clone(), column_types.clone());
    let consumer = match &output_mode {
        QueryOutputMode::RowConsumer(consumer) => {
            consumer.begin(engine, &columns, &schema)?;
            Some(consumer)
        }
        QueryOutputMode::Rows | QueryOutputMode::SharedSpill | QueryOutputMode::ExistsKeySet => {
            None
        }
    };
    let mut output = consumer.is_none().then(|| Vec::with_capacity(rows.len()));
    for source in rows {
        if source.len() != columns.len() {
            return Err(SQLError::TypeMismatch(format!(
                "VALUES row width {} does not match first row width {}",
                source.len(),
                columns.len()
            )));
        }
        let mut values = Vec::with_capacity(source.len());
        for (index, expression) in source.iter().enumerate() {
            let source_type = uqa_execution::common_context_expression_type(
                expression,
                &empty_schema,
                params,
                Some(engine),
            )?;
            let value = eval_physical_scalar(expression, subqueries, &context)?;
            values.push(coerce_common_context_value(
                value,
                source_type.as_ref(),
                column_types[index].as_ref(),
            )?);
        }
        let row = uqa_execution::PhysicalRow::from_values(values);
        if let Some(consumer) = consumer {
            if matches!(
                consumer.consume(
                    engine,
                    uqa_execution::OwnedPhysicalRow::new(schema.clone(), row),
                )?,
                QueryConsumerControl::Stop
            ) {
                break;
            }
        } else if let Some(output) = output.as_mut() {
            output.push(row);
        }
    }
    if consumer.is_some() {
        return Ok(QueryOutput {
            columns,
            column_types,
            internal_columns: schema.columns().to_vec(),
            internal_types: schema.column_types().to_vec(),
            rows: QueryRows::Rows {
                named: Vec::new(),
                positional: None,
            },
        });
    }
    let scan: Box<dyn uqa_execution::PhysicalOperator + '_> = Box::new(
        uqa_execution::TableScan::from_physical_rows(schema, output.unwrap_or_default()),
    );
    collect_query_operator(engine, columns, scan, output_mode)
}

pub(in crate::sql) fn coerce_common_context_value(
    value: Value,
    source_type: Option<&ColumnType>,
    target_type: Option<&ColumnType>,
) -> Result<Value, SQLError> {
    let Some(target_type) = target_type else {
        return Ok(value);
    };
    if source_type == Some(target_type) {
        return Ok(value);
    }
    let cast_target = match target_type {
        ColumnType::Domain { base, .. } => base.as_ref(),
        target => target,
    };
    let source_name = source_type.map(ColumnType::sql_name);
    uqa_sql::expr::cast_value_from(&value, &cast_target.sql_name(), source_name.as_deref())
}

#[cfg(test)]
mod physical_failure_tests;