uqa-sql 0.6.3

PostgreSQL-compatible SQL compiler built on libpg_query
Documentation
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
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Static relational row-type binding.
//!
//! This module derives source and query output schemas from plans, catalog
//! declarations, and already-bound CTE schemas. It never executes a query or
//! samples a result row, so empty, spilled, and correlated relations retain
//! the same declared `PostgreSQL` type identities as non-empty relations.

mod analysis;
pub mod catalog_sources;
mod command_scopes;
mod commands;
pub mod composite_dependencies;
mod composite_inputs;
pub mod composite_rename;
mod cte_controls;
mod ctes;
mod dependencies;
mod execution;
pub mod legacy_collations;
pub mod legacy_patterns;
mod merge_scopes;
mod ordered_calls;
mod preparation;
pub mod production;
pub use production::{
    analyze_query_plan_schema_with_control, analyze_source_plan_schema_with_control,
    bind_query_plan_schema_with_control,
};
mod projection;
mod record_fields;
mod routine_binding;
mod routine_parameters;
mod scope;
pub mod scoped_references;
mod source_schemas;
mod sources;
pub use sources::bind_source_plan_schema_in_scope;
pub mod statements;
mod type_resolution;
mod variable_sites;

pub use commands::{analyze_prepared_command_schema, analyze_prepared_command_schema_with_control};
pub use execution::{
    bind_query_block_for_execution, bind_query_block_for_execution_with_control,
    bind_query_block_with_sources, bind_query_block_with_sources_with_control, BoundExecutionBlock,
    ControlledExecutionBlock, ExecutionBindingOptions, ExecutionQueryBlock,
    ExecutionSourceBindings, SharedExecutionSourceBindings,
};
pub use preparation::bind_expression_plan_routines_for_storage_owned;
pub use preparation::{
    analyze_column_type_transform, assign_stored_query_input_collations,
    bind_routine_parameter_references_owned, infer_prepared_parameter_types,
    parameter_input_types_with_control, prepare_routine_body_inputs_owned,
    read_prepared_inputs_owned, read_procedural_inputs_owned, read_procedure_inputs_owned,
    restore_query_layouts, restore_query_layouts_owned, retain_prepared_input_metadata_owned,
    PreparedOwnedInputs, PreparedOwnedRoutineBody, ProceduralOwnedInputs,
};
pub(crate) use preparation::{
    analyze_default_inputs, analyze_routine_body_argument, analyze_routine_body_inputs,
    prepare_routine_body_inputs, read_procedure_inputs,
};
pub(crate) use preparation::{
    analyze_domain_check, analyze_stored_expression_inputs, analyze_table_check,
    assign_stored_input_collations, read_prepared_inputs, retain_prepared_input_metadata,
};

#[cfg(test)]
mod tests;

pub use cte_controls::{analyze_recursive_control_step, extend_cte_generated_schema};
pub use preparation::resolve_variable_sites_owned;
pub use projection::{
    analyze_projection_output_schema, analyze_projection_output_schema_with_control,
    bind_projection_output_schema, bind_projection_output_schema_with_control,
    validate_query_block_expression_types, validate_query_block_expression_types_with_control,
    validate_query_block_references, validate_query_block_references_with_control,
    ProjectionSchemas,
};
pub use routine_binding::{
    bind_expression_plan_routines_for_storage, bind_query_plan_routines_for_storage,
    bind_syntax_query_plan_routines,
};
pub use routine_parameters::{bind_routine_parameter_references, RoutineParameterScope};
pub use scope::SourceScope;
pub use scope::{
    analyze_expression_plan_type, analyze_query_plan_schema,
    analyze_query_plan_schema_with_catalog, bind_expression_plan_type, bind_query_plan_schema,
};
pub use scope::{
    overlay_outer_schema, overlay_outer_schema_with_control, values_schema_in_scope,
    values_types_in_scope,
};
pub use sources::{
    analyze_source_plan_schema, bind_source_input_schema, bind_source_plan_for_execution_owned,
    bind_source_plan_schema, bind_source_plan_schema_for_execution,
    with_query_table_pseudo_columns, with_query_table_pseudo_columns_with_control,
    SourceBindingInput,
};
pub use variable_sites::{resolve_variable_sites, VariableSiteResolution};

use catalog_sources::operator_join_relation_schemas;
use cte_controls::extend_recursive_cte_binding_schema;
pub use cte_controls::hide_recursive_generated_schema;
use projection::rename_schema;
use sources::{alias_table_schema, JoinSchemaBinding};
use type_resolution::QueryFunctionTypeResolver;

use crate::plan::{QueryBlockPlan, QueryPlan, RelationalPlan, SourcePlan};
use crate::semantics::{cte_references_own_name, projection_columns};
use crate::{SQLError, SQLParam, ScalarExpr};
pub use context::BindingContext;

pub mod context;
mod rule_inputs;
use crate::ast::ColumnType;
use crate::catalog::analysis::CatalogReadView;
use crate::catalog::resolution::RelationNameResolution;
use crate::routines::RoutineResolution;
use crate::RowSchema;

#[cfg(test)]
thread_local! {
    static SOURCE_BINDINGS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

#[derive(Clone, Copy)]
enum ScalarBindingMode {
    References,
    Stored,
    CompositeInputs,
}

struct SchemaScope {
    execution_sources: Option<execution::CapturedSources>,
    collations: preparation::PendingCollations,
    catalog: CatalogReadView,
    resolution: production::BindingResolution,
    ctes: production::BindingMap<RowSchema>,
    deferred_ctes: production::BindingMap<crate::plan::RetainedCtePlan>,
    non_returning_ctes: production::BindingNameSet,
    production: uqa_core::memory::OwnedProductionControl,
    visiting_views: production::BindingNameSet,
    validate_references: bool,
    stored_expression_outer: Option<RowSchema>,
    rule_condition_event: Option<crate::ast::RuleEvent>,
    /// Native MERGE action syntax is legal in a RETURNING expression and its descendant queries.
    merge_returning: bool,
    /// The kind of expression under analysis at this query level, which decides where a set-returning call may appear, as `PostgreSQL`'s `p_expr_kind` does.
    set_placement: crate::semantics::sets::placement::SetPlacement,
    /// The set-returning calls analyzed so far at this query level. Two readings differ exactly when an expression analyzed between them contains one, as `PostgreSQL` compares `p_last_srf`.
    set_calls: usize,
    stored_whole_rows: [Option<crate::plan::OwnedScalarExpr>; 2],
    /// The parameters of the SQL routine whose body is bound, as the outermost scope: a reference that resolves into them, because no column of any query level takes its name, becomes the positional parameter it names.
    routine_parameters: Option<RoutineParameterScope>,
    /// Select reference resolution, complete stored binding, or prepared composite identity retention.
    scalar_binding: ScalarBindingMode,
    /// The names of a `PL/pgSQL` statement that the function's variables take, checked against what the statement can see.
    variable_sites: Option<variable_sites::VariableSites>,
    /// Keep `*` projections and `GROUP BY` output-name references as written, so a bound copy of stored syntax still corresponds to that syntax node for node.
    preserve_syntax_shape: bool,
    prepared_dependencies: Option<crate::prepared::dependencies::PreparedAnalysisDependencies>,
    composite_dependencies: Option<Vec<crate::catalog::dependencies::ObjectAddress>>,
}

fn non_returning_cte_error(name: &str) -> SQLError {
    SQLError::Unsupported(format!(
        "WITH query \"{name}\" does not have a RETURNING clause"
    ))
}

impl SchemaScope {
    fn from_context(ctes: &BindingContext) -> Result<Self, SQLError> {
        let control = uqa_core::memory::ProductionControl::uncontrolled();
        Self::from_context_with_control(ctes.copy_with_control(&control)?, &control)
    }

    fn for_analysis(ctes: &BindingContext) -> Result<Self, SQLError> {
        let control = uqa_core::memory::ProductionControl::uncontrolled();
        Self::for_analysis_with_control(ctes.copy_with_control(&control)?, &control)
    }

    fn for_catalog_analysis(catalog: CatalogReadView, resolution: RelationNameResolution) -> Self {
        let control = uqa_core::memory::ProductionControl::uncontrolled();
        Self::for_analysis_with_control(
            production::ControlledBindingContext {
                catalog,
                resolution: resolution.into(),
                ctes: production::BindingMap::new(),
                deferred_ctes: production::BindingMap::new(),
                non_returning_ctes: production::BindingNameSet::new(),
                scalar_subqueries: &[],
            },
            &control,
        )
        .expect("ordinary catalog scope construction")
    }

    fn bind_query(
        &mut self,
        routines: &dyn RoutineResolution,
        plan: &QueryPlan,
        params: &[SQLParam],
        outer: Option<&RowSchema>,
    ) -> Result<RowSchema, SQLError> {
        let lookup_mode = if plan.relations_bound {
            crate::catalog::resolution::RelationLookupMode::Bound
        } else {
            crate::catalog::resolution::RelationLookupMode::Dynamic
        };
        let previous = self.resolution.set_lookup_mode(lookup_mode);
        let result = self.bind_query_inner(routines, plan, params, outer);
        self.resolution.set_lookup_mode(previous);
        result
    }

    fn bind_query_inner(
        &mut self,
        routines: &dyn RoutineResolution,
        plan: &QueryPlan,
        params: &[SQLParam],
        outer: Option<&RowSchema>,
    ) -> Result<RowSchema, SQLError> {
        let previous = self.bind_cte_schemas(routines, &plan.ctes, params, outer)?;

        let result = self.bind_root(routines, &plan.root, params, outer);
        self.restore_cte_schemas(previous);
        let output = result?;
        self.collations.validate_query(plan)?;
        Ok(output)
    }

    fn bind_recursive_seed(
        &mut self,
        routines: &dyn RoutineResolution,
        plan: &QueryPlan,
        params: &[SQLParam],
        outer: Option<&RowSchema>,
    ) -> Result<RowSchema, SQLError> {
        match &plan.root {
            RelationalPlan::SetOp { left, .. } => self.bind_query(routines, left, params, outer),
            _ => self.bind_root(routines, &plan.root, params, outer),
        }
    }

    fn bind_root(
        &mut self,
        routines: &dyn RoutineResolution,
        root: &RelationalPlan,
        params: &[SQLParam],
        outer: Option<&RowSchema>,
    ) -> Result<RowSchema, SQLError> {
        match root {
            RelationalPlan::QueryBlock(block) => {
                self.bind_query_block(routines, block, params, outer)
            }
            RelationalPlan::SetOp { .. } => {
                preparation::set_metadata(self, routines, root, outer, params)
            }
            RelationalPlan::Values { rows, subqueries } => {
                self.bind_values_schema(routines, rows, subqueries, outer, params)
            }
        }
    }

    fn bind_query_block(
        &mut self,
        routines: &dyn RoutineResolution,
        block: &QueryBlockPlan,
        params: &[SQLParam],
        outer: Option<&RowSchema>,
    ) -> Result<RowSchema, SQLError> {
        let production = self.production.clone();
        let control = production.control();
        let captured_outer = outer
            .map(|schema| {
                crate::semantics::view_rewrite::bind_outer_rewrite_scope_with_control(
                    block, schema, &control,
                )
            })
            .transpose()?;
        let outer = captured_outer.as_deref();
        let source_rewrites = if block.deferred_outer_rewrites.is_empty() || block.from.is_none() {
            None
        } else {
            Some(crate::semantics::view_rewrite::resolve_outer_sources_owned(
                block.copy_for_rewrite(&control)?,
                outer,
                &mut |source, subqueries, scope| {
                    self.bind_source_input(routines, source, subqueries, params, scope)
                },
                &control,
            )?)
        };
        let block = match &source_rewrites {
            Some(query) => {
                let RelationalPlan::QueryBlock(block) = &query.root else {
                    unreachable!("retained query block")
                };
                block.as_ref()
            }
            None => block,
        };
        let source = match block.from.as_ref() {
            Some(source) => self.bind_source(routines, source, &block.subqueries, params, outer)?,
            None => RowSchema::new_with_control(
                control.finish(Vec::new(), control.empty_reservation())?,
                &control,
            )?,
        };
        if let Some(sources) = &mut self.execution_sources {
            sources.record(block, &source, outer);
        }
        // Query-owned metadata types belong to both analysis and metadata-only binding.
        let source = analysis::with_query_source_columns_with_control(&source, block, &control)?;
        let rewritten = if block.deferred_outer_rewrites.is_empty() {
            None
        } else {
            Some(
                crate::semantics::view_rewrite::resolve_outer_rewrites_owned(
                    block.copy_for_rewrite(&control)?,
                    &source,
                    &control,
                )?,
            )
        };
        let block = match &rewritten {
            Some(query) => {
                let RelationalPlan::QueryBlock(block) = &query.root else {
                    unreachable!("retained query block")
                };
                block.as_ref()
            }
            None => block,
        };
        let expression_schema = overlay_outer_schema_with_control(&source, outer, &control)?;
        let output = preparation::block_metadata(self, routines, block, &source, outer, params)?;
        let output = analysis::with_projected_open_columns_with_control(
            &output,
            &block.projections,
            &source,
            &control,
        )?;
        if self.validate_references {
            self.validate_query_block_clauses(
                routines,
                block,
                &expression_schema,
                &output,
                params,
                outer,
            )?;
        }
        Ok(output)
    }

    fn bind_expression_type(
        &mut self,
        routines: &dyn RoutineResolution,
        expression: &ScalarExpr,
        schema: &RowSchema,
        subqueries: &[QueryPlan],
        params: &[SQLParam],
    ) -> Result<Option<ColumnType>, SQLError> {
        if let ScalarExpr::ScalarSubquery(index) = expression {
            let plan = subqueries.get(*index).ok_or_else(|| {
                SQLError::Internal(format!("scalar subquery slot {index} is out of bounds"))
            })?;
            // Result typing and validation share the complete lexical row scope.
            let subquery_outer = Some(schema);
            let output = self.bind_query(routines, plan, params, subquery_outer)?;
            return Ok(output.column_type(0).cloned());
        }
        let schema = self.with_stored_outer_internal_aliases(schema)?;
        let schema = &schema;
        let resolver =
            self.query_function_type_resolver(routines, expression, schema, subqueries, params)?;
        if self.validate_references {
            Self::validate_expression_references_with_resolver(
                self.rule_condition_event,
                routines,
                expression,
                schema,
                None,
                params,
                &resolver,
            )?;
        }
        crate::type_resolution::validate_catalog_literals(expression, schema, params, &resolver)?;
        crate::scalar_type_with_resolver(expression, schema, params, &resolver)
    }

    fn bind_projection_metadata(
        &mut self,
        routines: &dyn RoutineResolution,
        expression: &ScalarExpr,
        schema: &RowSchema,
        subqueries: &[QueryPlan],
        params: &[SQLParam],
    ) -> Result<projection::ProjectionMetadata, SQLError> {
        let schema = self.with_stored_outer_internal_aliases(schema)?;
        preparation::projection_metadata(self, routines, expression, &schema, subqueries, params)
    }

    #[expect(
        clippy::too_many_lines,
        reason = "preserves SELECT schema and row identity"
    )]
    fn bind_source_inner(
        &mut self,
        routines: &dyn RoutineResolution,
        source: &SourcePlan,
        subqueries: &[QueryPlan],
        params: &[SQLParam],
        scope: SourceScope<'_>,
    ) -> Result<RowSchema, SQLError> {
        #[cfg(test)]
        SOURCE_BINDINGS.with(|count| count.set(count.get() + 1));
        let input = (!matches!(source, SourcePlan::Join { .. }))
            .then(|| scope.input_with_control(source, &self.control()))
            .transpose()?
            .flatten();
        let outer = input.as_ref();
        match source {
            SourcePlan::Table { .. } => self.bind_relation_source(routines, source, params, outer),
            SourcePlan::Values {
                rows,
                alias,
                column_aliases,
                internal_relation,
                internal_column_types,
                ..
            } => {
                if internal_relation.is_some()
                    && internal_column_types.iter().any(Option::is_none)
                    && !rows.is_empty()
                {
                    let inferred =
                        self.bind_values_schema(routines, rows, subqueries, outer, params)?;
                    if let Some(schema) = source
                        .internal_values_schema_with_control(Some(&inferred), &self.control())?
                    {
                        return Ok(schema);
                    }
                }
                if let Some(schema) =
                    source.internal_values_schema_with_control(None, &self.control())?
                {
                    return Ok(schema);
                }
                let schema = self.bind_values_schema(routines, rows, subqueries, outer, params)?;
                projection::rename_schema_with_control(
                    &schema,
                    column_aliases,
                    alias.as_deref(),
                    &self.control(),
                )
            }
            SourcePlan::RetainedRows(source) => Ok(source.schema().clone()),
            SourcePlan::Function { .. } => {
                self.bind_function_source(routines, source, subqueries, params, outer)
            }
            SourcePlan::FunctionGroup { .. } => {
                self.bind_function_group_source(routines, source, subqueries, params, outer)
            }
            SourcePlan::Subquery {
                body,
                alias,
                column_aliases,
                ..
            } => {
                let schema = self.bind_query(routines, body, params, outer)?;
                Ok(match source {
                    SourcePlan::Subquery {
                        captured_output: Some(relation),
                        ..
                    } => {
                        RowSchema::capture_output_with_control(&schema, *relation, &self.control())?
                    }
                    _ => match alias {
                        Some(alias) if !schema.columns_are_open(None) => {
                            alias_table_schema(&schema, alias, column_aliases, &self.control())?
                        }
                        alias => projection::rename_schema_with_control(
                            &schema,
                            column_aliases,
                            alias.as_deref(),
                            &self.control(),
                        )?,
                    },
                })
            }
            SourcePlan::Join {
                left,
                right,
                kind,
                on,
                using,
                natural,
                alias,
                column_aliases,
                lateral,
                ..
            } => {
                let left_schema = self.bind_source_in_scope(
                    routines,
                    left,
                    subqueries,
                    params,
                    scope.with_names(),
                )?;
                let preceding = scope.right_namespace_with_control(
                    left,
                    &left_schema,
                    *kind,
                    &self.control(),
                )?;
                let right_schema = self.bind_source_in_scope(
                    routines,
                    right,
                    subqueries,
                    params,
                    SourceScope {
                        outer: scope.outer,
                        preceding: Some(&preceding),
                        inherited_lateral: *lateral,
                        retain_names: true,
                    },
                )?;
                let condition = scope.condition_with_control(&self.control())?;
                self.bind_join_output_schema(JoinSchemaBinding {
                    routines,
                    kind: *kind,
                    on: on.as_ref(),
                    using: using.as_ref(),
                    natural: *natural,
                    alias: alias.as_deref(),
                    column_aliases,
                    left: &left_schema,
                    right: &right_schema,
                    subqueries,
                    params,
                    outer: condition.as_ref(),
                })
            }
        }
    }
}

#[cfg(test)]
pub(crate) mod fixture;

pub mod correlation;

pub mod stored_columns;
pub mod stored_relations;
pub mod stored_routines;
pub mod stored_types;
pub mod syntax_sites;

pub mod scoped_types;
pub mod snapshot;

pub mod view_dependencies;

pub mod portals;