uqa-execution 0.6.3

Volcano physical operators with row-batch pipelines
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
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Prepare named relational inputs once, before any statement input produces rows.

use super::{ColumnPrune, CteScope, RowSchema, SourceContext};
use uqa_core::memory::ProductionVec;
use uqa_sql::binding::production::{BindingMap, BindingNameSet};
use uqa_sql::{
    binding::SourceScope,
    plan::{OwnedQueryPlan, QueryPlan, RelationalPlan, SourcePlan},
    SQLError, SQLParam,
};

mod inspection;

pub(crate) enum PreparedQuery<'a> {
    Borrowed(&'a QueryPlan),
    Owned(OwnedQueryPlan),
}

impl AsRef<QueryPlan> for PreparedQuery<'_> {
    fn as_ref(&self) -> &QueryPlan {
        self
    }
}

impl std::ops::Deref for PreparedQuery<'_> {
    type Target = QueryPlan;
    fn deref(&self) -> &QueryPlan {
        match self {
            Self::Borrowed(query) => query,
            Self::Owned(query) => query,
        }
    }
}

pub(crate) fn prepare<'a, S: Clone + Send + Sync + 'static>(
    context: &SourceContext<'_, S>,
    query: &'a QueryPlan,
    params: &[SQLParam],
    scope: &CteScope<S>,
) -> Result<PreparedQuery<'a>, SQLError> {
    let retained = context.ctes.queries.read_control()?;
    let control = uqa_core::memory::ProductionControl::new(
        retained.memory(),
        retained.cancellation(),
        context.ctes.runtime.cancellation,
    );
    if !inspection::needed(query, scope, control)? {
        return Ok(PreparedQuery::Borrowed(query));
    }
    let query = OwnedQueryPlan::from_produced(query.clone_with_control(&control)?, &control)?;
    prepare_owned(
        context,
        query,
        params,
        scope,
        scope.row_lock_outer_row().map(|row| &row.schema),
    )
    .map(PreparedQuery::Owned)
}

/// Private preparation keeps the input and every newly attached executable's leases together. It only fills source attachments and shared analysis descriptors; existing scalar and source storage is not removed.
pub(crate) fn prepare_in_place<S: Clone + Send + Sync + 'static>(
    context: &SourceContext<'_, S>,
    query: OwnedQueryPlan,
    params: &[SQLParam],
    scope: &CteScope<S>,
) -> Result<OwnedQueryPlan, SQLError> {
    let retained = context.ctes.queries.read_control()?;
    let control = uqa_core::memory::ProductionControl::new(
        retained.memory(),
        retained.cancellation(),
        context.ctes.runtime.cancellation,
    );
    if !inspection::needed(&query, scope, control)? {
        return Ok(query);
    }
    prepare_owned(
        context,
        query,
        params,
        scope,
        scope.row_lock_outer_row().map(|row| &row.schema),
    )
}

fn prepare_owned<S: Clone + Send + Sync + 'static>(
    context: &SourceContext<'_, S>,
    query: OwnedQueryPlan,
    params: &[SQLParam],
    scope: &CteScope<S>,
    outer: Option<&RowSchema>,
) -> Result<OwnedQueryPlan, SQLError> {
    struct Preparation {
        query: Box<QueryPlan>,
        memory: uqa_sql::plan::ExecutableMemory,
    }
    let (query, memory) = query.into_parts();
    let mut preparation = Preparation { query, memory };
    prepare_query(
        context,
        &mut preparation.query,
        params,
        scope,
        outer,
        &mut preparation.memory,
    )?;
    Ok(OwnedQueryPlan::from_parts(
        preparation.query,
        preparation.memory,
    ))
}

fn declare_ctes<S: Clone + Send + Sync + 'static>(
    context: &SourceContext<'_, S>,
    query: &mut QueryPlan,
    params: &[SQLParam],
    scope: &mut CteScope<S>,
    folded: &BindingNameSet,
    outer: Option<&RowSchema>,
) -> Result<(), SQLError> {
    let mut restored_outputs = BindingMap::new();
    let retained = context.ctes.queries.read_control()?;
    let control = uqa_core::memory::ProductionControl::new(
        retained.memory(),
        retained.cancellation(),
        context.ctes.runtime.cancellation,
    );
    let ordered = uqa_sql::semantics::order_cte_plans_with_control(&query.ctes, control)?;
    for cte in ordered.iter().copied() {
        let (mut definition, definition_memory) = cte.clone_with_control(&control)?.into_parts();
        if !uqa_sql::semantics::cte_references_own_name_with_control(cte, control)? {
            if let Some(body) = definition
                .body
                .query_mut()
                .filter(|body| body.analyzed_output.is_none())
            {
                // Stored syntax omits transient layouts. Describe each definition before a later declaration replaces any of its inputs.
                let schema = crate::query::binding::bind_query_plan_schema(
                    context.ctes.routines,
                    body,
                    params,
                    scope,
                    outer,
                )?;
                body.analyzed_output = Some(schema.clone());
                restored_outputs.insert_with_control(&cte.name, schema, &control)?;
            }
        }
        scope.insert_preparation_cte_with_control(
            uqa_sql::plan::RetainedCtePlan::from_produced(
                control.finish(definition, definition_memory)?,
                &control,
            )?,
            folded.contains(&cte.name),
            &control,
        )?;
    }
    drop(ordered);
    for cte in &mut query.ctes {
        if let Some(schema) = restored_outputs.remove(&cte.name) {
            cte.body
                .query_mut()
                .expect("query output restored")
                .analyzed_output = Some(schema);
        }
    }
    Ok(())
}

fn prepare_query<S: Clone + Send + Sync + 'static>(
    context: &SourceContext<'_, S>,
    query: &mut QueryPlan,
    params: &[SQLParam],
    parent: &CteScope<S>,
    outer: Option<&RowSchema>,
    memory: &mut uqa_sql::plan::ExecutableMemory,
) -> Result<(), SQLError> {
    let resources = context.ctes.production_resources()?;
    let control = resources.control();
    let mut scope = parent.copy_with_control(&control)?;
    let mut lookup = scope.enter_query_plan_scope_with_control(query, &resources.control())?;
    let scheduled =
        crate::query::cte::strategy::schedule_plan_ctes(context.ctes, context.volatility, query)?;
    let mut folded = BindingNameSet::new();
    let mut materialized = BindingNameSet::new();
    for cte in scheduled.iter() {
        let names = if cte.deferred {
            &mut folded
        } else {
            &mut materialized
        };
        names.insert_with_control(&cte.plan.name, &control)?;
    }
    drop(scheduled);
    declare_ctes(context, query, params, &mut lookup, &folded, outer)?;
    let mut names = ProductionVec::new(control);
    for cte in &query.ctes {
        names.push_produced(control.copy_text(&cte.name)?)?;
    }
    let names = names.finish()?;
    let mut scope =
        lookup.enter_visible_ctes_with_control(names.iter().map(String::as_str), &control)?;
    for cte in &mut query.ctes {
        // Folded inputs are prepared at each selected reference; unused inputs never execute.
        if !materialized.contains(&cte.name) {
            continue;
        }
        let definition_scope = scope
            .definition_scope_for_name_with_control(&cte.name, &control)?
            .expect("declared CTE scope");
        if let Some(body) = cte.body.query_mut() {
            prepare_query(context, body, params, &definition_scope, outer, memory)?;
        }
    }
    match &mut query.root {
        RelationalPlan::QueryBlock(block) => {
            let arena_resources = context.ctes.production_resources()?;
            scope.scalar_subqueries = uqa_sql::plan::RetainedQueryArena::capture(
                &block.subqueries,
                &arena_resources.control(),
            )?;
            let mut source_schema = RowSchema::default();
            if let Some(from) = &block.from {
                source_schema = crate::query::binding::bind_source_plan_schema(
                    context.ctes.routines,
                    from,
                    params,
                    &scope,
                    outer,
                    &control,
                )?;
                let prune =
                    context
                        .planning
                        .column_prune(block, from, &scope, Some(&source_schema))?;
                prepare_source(
                    context,
                    block.from.as_mut().expect("source checked"),
                    params,
                    &scope,
                    prune.as_ref(),
                    SourceScope::new(outer),
                    memory,
                )?;
            }
            let expression_schema = uqa_sql::binding::overlay_outer_schema_with_control(
                &source_schema,
                outer,
                &control,
            )?;
            prepare_subqueries(
                context,
                &mut block.subqueries,
                params,
                &scope,
                Some(&expression_schema),
                memory,
            )?;
        }
        RelationalPlan::SetOp {
            left,
            right,
            subqueries,
            ..
        } => {
            prepare_query(context, left, params, &scope, outer, memory)?;
            prepare_query(context, right, params, &scope, outer, memory)?;
            prepare_subqueries(context, subqueries, params, &scope, outer, memory)?;
        }
        RelationalPlan::Values { subqueries, .. } => {
            prepare_subqueries(context, subqueries, params, &scope, outer, memory)?;
        }
    }
    Ok(())
}

fn prepare_subqueries<S: Clone + Send + Sync + 'static>(
    context: &SourceContext<'_, S>,
    queries: &mut [QueryPlan],
    params: &[SQLParam],
    scope: &CteScope<S>,
    outer: Option<&RowSchema>,
    memory: &mut uqa_sql::plan::ExecutableMemory,
) -> Result<(), SQLError> {
    for query in queries {
        prepare_query(context, query, params, scope, outer, memory)?;
    }
    Ok(())
}

fn prepare_source<S: Clone + Send + Sync + 'static>(
    context: &SourceContext<'_, S>,
    source: &mut SourcePlan,
    params: &[SQLParam],
    parent: &CteScope<S>,
    prune: Option<&ColumnPrune>,
    names: SourceScope<'_>,
    memory: &mut uqa_sql::plan::ExecutableMemory,
) -> Result<(), SQLError> {
    let resources = context.ctes.production_resources()?;
    let control = resources.control();
    let input = (!matches!(source, SourcePlan::Join { .. }))
        .then(|| names.input_with_control(source, &control))
        .transpose()?
        .flatten();
    let outer = input.as_ref();
    match source {
        SourcePlan::Table { .. } => {
            prepare_named_source(context, source, params, parent, prune, outer, memory)?;
        }
        SourcePlan::Join {
            left,
            right,
            lateral,
            kind,
            ..
        } => {
            prepare_source(
                context,
                left,
                params,
                parent,
                prune,
                names.with_names(),
                memory,
            )?;
            let left_schema =
                uqa_sql::binding::production::bind_source_plan_schema_in_scope_with_control(
                    context.ctes.routines,
                    left,
                    params,
                    crate::query::binding::binding_context_with_control(parent, &control)?,
                    names.with_names(),
                    &control,
                )?;
            let preceding =
                names.right_namespace_with_control(left, &left_schema, *kind, &control)?;
            prepare_source(
                context,
                right,
                params,
                parent,
                prune,
                SourceScope {
                    outer: names.outer,
                    preceding: Some(&preceding),
                    inherited_lateral: *lateral,
                    retain_names: true,
                },
                memory,
            )?;
        }
        SourcePlan::Subquery { body, .. } => {
            prepare_query(context, body, params, parent, outer, memory)?;
        }
        _ => {}
    }
    Ok(())
}

fn prepare_named_source<S: Clone + Send + Sync + 'static>(
    context: &SourceContext<'_, S>,
    source: &mut SourcePlan,
    params: &[SQLParam],
    parent: &CteScope<S>,
    prune: Option<&ColumnPrune>,
    outer: Option<&RowSchema>,
    memory: &mut uqa_sql::plan::ExecutableMemory,
) -> Result<(), SQLError> {
    let SourcePlan::Table {
        name,
        qualifier,
        alias,
        column_aliases,
        executable_query,
        ..
    } = source
    else {
        unreachable!("named source checked by the traversal");
    };
    if executable_query.is_some() {
        return Ok(());
    }
    let retained = context.ctes.queries.read_control()?;
    let control = uqa_core::memory::ProductionControl::new(
        retained.memory(),
        retained.cancellation(),
        context.ctes.runtime.cancellation,
    );
    let qualifier = alias.as_deref().unwrap_or(qualifier);
    let mut scope = parent.copy_with_control(&control)?;
    let (mut query, aliases, optimize) = if let Some(cte) = parent.deferred_reference(name) {
        if !scope.cte_is_folded(name) {
            return Ok(());
        }
        let Some(query) = cte.body.query() else {
            return Ok(());
        };
        let query = query.copy_for_rewrite(&control)?;
        let aliases = super::table_source::production::output_aliases(
            &cte.columns,
            column_aliases,
            &control,
        )?;
        scope = parent
            .definition_scope_with_control(name, &control)?
            .expect("declared CTE scope");
        (query, aliases, false)
    } else {
        if scope.is_visible_cte(name) {
            return Ok(());
        }
        let catalog = scope.catalog_read_view()?;
        let resolution = scope.relation_name_resolution_with_control(&control)?;
        let Some(view) = catalog.view_resolved_with_control(&resolution, name, &control)? else {
            return Ok(());
        };
        if view.kind == uqa_sql::catalog::view::StoredViewKind::Materialized {
            return Ok(());
        }
        let subject = if view.security_invoker() {
            scope.invoking_role()?.clone_with_control(&control)?
        } else {
            control.finish(
                catalog.view_owner_with_control(view.security.role_owner, &control)?,
                control.empty_reservation(),
            )?
        };
        scope = {
            let scoped = scope.enter_privilege_subject_with_control(subject, &control)?;
            scoped.copy_with_control(&control)?
        };
        (
            view.query.copy_for_rewrite(&control)?,
            super::table_source::production::output_aliases(
                view.output_columns.as_deref().unwrap_or_default(),
                column_aliases,
                &control,
            )?,
            true,
        )
    };
    let _stored = optimize
        .then(uqa_sql::semantics::sets::placement_scope::SetPlacementScope::stored_definition);
    if optimize {
        query = super::table_source::production::restore_layouts(
            context, query, params, &scope, outer, &control,
        )?;
    }
    if let Some(projection) = prune.and_then(|prune| prune.get(qualifier)) {
        query = super::table_source::production::prune_outputs(
            context,
            query,
            &aliases,
            projection,
            super::table_source::production::QueryBinding {
                params,
                scope: &scope,
                outer,
            },
            &control,
        )?;
    }
    let query = finish_named_source(context, query, optimize, params, &scope, outer, &control)?;
    let (query, attached) = query.into_parts();
    *executable_query = Some(query);
    memory.absorb(attached);
    Ok(())
}

fn finish_named_source<S: Clone + Send + Sync + 'static>(
    context: &SourceContext<'_, S>,
    query: uqa_sql::plan::MutableQueryPlan,
    optimize: bool,
    params: &[SQLParam],
    scope: &CteScope<S>,
    outer: Option<&RowSchema>,
    control: &uqa_core::memory::ProductionControl<'_>,
) -> Result<OwnedQueryPlan, SQLError> {
    let query = if optimize {
        context
            .ctes
            .rewrites
            .optimize_retained_query(query, control)?
    } else {
        OwnedQueryPlan::from_produced(query.finish(control)?, control)?
    };
    prepare_owned(context, query, params, scope, outer)
}