uqa-execution 0.4.9

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

//! Bind referenced and inherited ALTER targets before admitting the definition writer.

use super::{binding::TableAlterBindingContext, TableAlterContext};
use crate::row_locks::{
    binding::{bind_relation, lock_relation_identity, RelationBinding},
    RelationLockMode,
};
use std::collections::BTreeSet;
use uqa_sql::{
    ast::{AlterTableAction, PartitionBound},
    schema::constraint_changes::validation::{constraint_validation, ConstraintValidationKind},
    schema::relation_alteration::RelationAlterTarget,
    SQLError,
};

pub(super) fn prepare_table_alter_action<S: Clone + 'static>(
    binding: &TableAlterBindingContext<'_>,
    tables: &TableAlterContext<'_, S>,
    primary: &str,
    recurse: bool,
    action: &mut AlterTableAction,
    mode: RelationLockMode,
) -> Result<(), SQLError> {
    bind_secondary_relations(binding, tables, primary, action)?;
    lock_inherited_action(binding, tables, primary, recurse, action, mode)?;
    bind_key_index(tables, primary, action)
}

fn bind_key_index<S: Clone + 'static>(
    tables: &TableAlterContext<'_, S>,
    table: &str,
    action: &mut AlterTableAction,
) -> Result<(), SQLError> {
    let (name, mode) = match action {
        AlterTableAction::RenameConstraint { from, .. } => {
            (from, RelationLockMode::ShareUpdateExclusive)
        }
        AlterTableAction::DropConstraint { name, .. } => (name, RelationLockMode::AccessExclusive),
        _ => return Ok(()),
    };
    let (_, constraints) =
        crate::schema::constraints::table_constraint_state(&tables.constraints, table)?;
    let Some(owner) = constraints
        .key_constraints
        .iter()
        .find(|key| key.name.as_ref() == Some(name))
        .and_then(|key| key.catalog_identity)
    else {
        return Ok(());
    };
    let registry = &tables.constraints.publication.indexes;
    let catalog = registry.identities.catalog.current_catalog_snapshot();
    let mut identity = None;
    for row in catalog
        .catalog_indexes()
        .filter(|row| row.table_name == table)
    {
        let definition = crate::catalog::index::index_definition(row)
            .map_err(|error| super::ddl_storage_error("constraint index lock", error))?;
        if definition.relationships.owning_constraint == Some(owner.object_id) {
            identity = definition.catalog.map(|catalog| catalog.identity.object_id);
            break;
        }
    }
    let identity =
        identity.ok_or_else(|| SQLError::Internal("constraint has no owned index".into()))?;
    let current =
        crate::schema::indexes::registry::binding::index_identity(registry, identity, mode)
            .map_err(|error| super::ddl_storage_error("constraint index lock", error))?
            .ok_or_else(|| SQLError::Internal("constraint index disappeared".into()))?;
    *name = current.relation.name;
    Ok(())
}

fn bind_secondary_relations<S: Clone + 'static>(
    binding: &TableAlterBindingContext<'_>,
    tables: &TableAlterContext<'_, S>,
    primary: &str,
    action: &mut AlterTableAction,
) -> Result<(), SQLError> {
    match action {
        AlterTableAction::AddForeignKeyConstraint { constraint } => {
            constraint.ref_table = bind_secondary_table(
                binding,
                &constraint.ref_table,
                RelationLockMode::ShareRowExclusive,
                false,
            )?;
        }
        AlterTableAction::AddColumn { column, .. } => {
            let exists = tables
                .addition
                .state
                .has_column(primary, &column.name)
                .map_err(|error| super::ddl_storage_error("ALTER TABLE column locks", error))?;
            if let Some(reference) = column.references.as_mut().filter(|_| !exists) {
                reference.table = bind_secondary_table(
                    binding,
                    &reference.table,
                    RelationLockMode::ShareRowExclusive,
                    false,
                )?;
            }
        }
        AlterTableAction::AddInheritance { parent } => {
            *parent = bind_secondary_table(
                binding,
                parent,
                RelationLockMode::ShareUpdateExclusive,
                true,
            )?;
            lock_alter_children(binding, primary, RelationLockMode::AccessShare, |parent| {
                tables
                    .hierarchy
                    .partitions
                    .catalog
                    .direct_hierarchy_children(parent)
            })?;
        }
        AlterTableAction::DropInheritance { parent } => {
            *parent = bind_secondary_table(binding, parent, RelationLockMode::AccessShare, false)?;
        }
        AlterTableAction::AttachPartition { partition, .. } => {
            *partition =
                bind_secondary_table(binding, partition, RelationLockMode::AccessExclusive, true)?;
            lock_partition_subtree(binding, tables, partition)?;
            for child in tables
                .hierarchy
                .partitions
                .catalog
                .direct_hierarchy_children(primary)?
            {
                let hierarchy = tables
                    .hierarchy
                    .partitions
                    .catalog
                    .try_table_hierarchy(&child)
                    .map_err(SQLError::Internal)?;
                if matches!(hierarchy.partition_bound, Some(PartitionBound::Default)) {
                    lock_partition_subtree(binding, tables, &child)?;
                }
            }
        }
        AlterTableAction::DetachPartition { partition, .. } => {
            *partition =
                bind_secondary_table(binding, partition, RelationLockMode::AccessExclusive, false)?;
            lock_partition_subtree(binding, tables, partition)?;
        }
        AlterTableAction::ValidateConstraint { name } => {
            lock_validation_reference(binding, tables, primary, name)?;
        }
        AlterTableAction::AlterConstraint {
            name,
            enforceability: Some(enforced),
            ..
        } => {
            lock_enforceability_reference(binding, tables, primary, name, *enforced)?;
        }
        _ => {}
    }
    Ok(())
}

fn lock_validation_reference<S: Clone + 'static>(
    binding: &TableAlterBindingContext<'_>,
    tables: &TableAlterContext<'_, S>,
    primary: &str,
    name: &str,
) -> Result<(), SQLError> {
    let (columns, constraints) =
        crate::schema::constraints::table_constraint_state(&tables.constraints, primary)?;
    let target = constraint_validation(primary, name, &columns, &constraints)?;
    // A derived constraint validates the referencing rows against its referenced partition.
    let partition = match (target.validated, target.kind) {
        (false, ConstraintValidationKind::ReferencedPartition { partition }) => Some(
            binding
                .catalog
                .table_name(partition)
                .ok_or_else(|| SQLError::Internal("referenced partition disappeared".into()))?,
        ),
        _ => None,
    };
    let target = match (&partition, target.kind) {
        (Some(partition), _) => {
            uqa_sql::schema::constraint_changes::validation::ConstraintValidation {
                kind: ConstraintValidationKind::ForeignKey {
                    referenced_table: partition,
                },
                validated: false,
            }
        }
        _ => target,
    };
    if let (false, ConstraintValidationKind::ForeignKey { referenced_table }) =
        (target.validated, target.kind)
    {
        let identity = binding
            .catalog
            .relation_object_id(referenced_table)?
            .ok_or_else(|| SQLError::UnknownTable(referenced_table.to_string()))?;
        lock_relation_identity(
            binding.catalog,
            binding.locks,
            referenced_table.to_string(),
            identity,
            RelationLockMode::RowShare,
            false,
        )?
        .ok_or_else(|| SQLError::UnknownTable(referenced_table.to_string()))?;
    }
    Ok(())
}

/// A foreign key whose enforceability changes creates or drops the triggers of the table it references and of that table's partitions, which `PostgreSQL` locks `ShareRowExclusive` to create them and `AccessExclusive` to drop them.
fn lock_enforceability_reference<S: Clone + 'static>(
    binding: &TableAlterBindingContext<'_>,
    tables: &TableAlterContext<'_, S>,
    primary: &str,
    name: &str,
    enforced: bool,
) -> Result<(), SQLError> {
    let (columns, constraints) =
        crate::schema::constraints::table_constraint_state(&tables.constraints, primary)?;
    let Some(location) =
        uqa_sql::schema::constraint_changes::find_constraint(&columns, &constraints, name)
    else {
        return Ok(());
    };
    let (referenced_table, current) = match location {
        uqa_sql::schema::constraint_changes::ConstraintLocation::ColumnForeignKey(index) => {
            let Some(reference) = columns[index].references.as_ref() else {
                return Ok(());
            };
            (reference.table.clone(), reference.enforced)
        }
        uqa_sql::schema::constraint_changes::ConstraintLocation::TableForeignKey(index) => (
            constraints.foreign_keys[index].ref_table.clone(),
            constraints.foreign_keys[index].enforced,
        ),
        _ => return Ok(()),
    };
    if current == enforced {
        return Ok(());
    }
    let mode = if enforced {
        RelationLockMode::ShareRowExclusive
    } else {
        RelationLockMode::AccessExclusive
    };
    let referenced = bind_secondary_table(binding, &referenced_table, mode, false)?;
    let partitioned = tables
        .hierarchy
        .partitions
        .catalog
        .try_table_hierarchy(&referenced)
        .map_err(SQLError::Internal)?
        .partition_spec
        .is_some();
    if partitioned {
        lock_alter_children(binding, &referenced, mode, |parent| {
            tables
                .hierarchy
                .partitions
                .catalog
                .direct_hierarchy_children(parent)
        })?;
    }
    Ok(())
}

fn bind_secondary_table(
    context: &TableAlterBindingContext<'_>,
    requested: &str,
    mode: RelationLockMode,
    require_owner: bool,
) -> Result<String, SQLError> {
    let binding = bind_relation(
        context.locks,
        mode,
        false,
        || {
            let target = RelationAlterTarget::resolve(
                context.names.resolve_relation_kind(requested)?,
                requested,
                false,
                &mut |_| {},
            )?
            .ok_or_else(|| SQLError::Internal("required ALTER relation has no target".into()))?;
            Ok(Some(RelationBinding {
                object_id: context.catalog.relation_object_id(&target.canonical)?,
                name: target.canonical.clone(),
                value: target,
            }))
        },
        |binding| {
            let target = &binding.value;
            if require_owner {
                crate::schema::relation_alteration::validate_relation_alter_authority(
                    &context.authority,
                    &context.creation,
                    &target.relation,
                    target.kind,
                    false,
                )?;
            }
            target.require_kind("table")
        },
    )?
    .ok_or_else(|| SQLError::Internal("required ALTER relation disappeared".into()))?;
    Ok(binding.name)
}

fn lock_partition_subtree<S: Clone + 'static>(
    context: &TableAlterBindingContext<'_>,
    tables: &TableAlterContext<'_, S>,
    root: &str,
) -> Result<(), SQLError> {
    let Some(identity) = context.catalog.relation_object_id(root)? else {
        return Ok(());
    };
    let Some(current) = lock_relation_identity(
        context.catalog,
        context.locks,
        root.to_string(),
        identity,
        RelationLockMode::AccessExclusive,
        false,
    )?
    else {
        return Ok(());
    };
    lock_alter_children(
        context,
        &current,
        RelationLockMode::AccessExclusive,
        |parent| {
            tables
                .hierarchy
                .partitions
                .catalog
                .direct_hierarchy_children(parent)
        },
    )
}

fn lock_inherited_action<S: Clone + 'static>(
    context: &TableAlterBindingContext<'_>,
    tables: &TableAlterContext<'_, S>,
    root: &str,
    recurse: bool,
    action: &AlterTableAction,
    mode: RelationLockMode,
) -> Result<(), SQLError> {
    let all_descendants = locks_all_descendants(tables, root, recurse, action)?;
    if !all_descendants && !recurse {
        return Ok(());
    }
    lock_alter_children(context, root, mode, |parent| {
        if all_descendants {
            tables
                .hierarchy
                .partitions
                .catalog
                .direct_hierarchy_children(parent)
        } else if matches!(
            action,
            AlterTableAction::AddColumn { .. } | AlterTableAction::SetNotNull { .. }
        ) {
            super::recursion::recursive_alter_children(tables, parent, recurse, action)
        } else {
            Ok(Vec::new())
        }
    })
}

fn lock_alter_children(
    context: &TableAlterBindingContext<'_>,
    root: &str,
    mode: RelationLockMode,
    mut children: impl FnMut(&str) -> Result<Vec<String>, SQLError>,
) -> Result<(), SQLError> {
    let mut pending = vec![root.to_string()];
    let mut retained = BTreeSet::new();
    while let Some(parent) = pending.pop() {
        // Enumerate below each locked parent after refreshing: a wait may have admitted a new child before this lock was acquired.
        let targets = children(&parent)?
            .into_iter()
            .map(|name| {
                context
                    .catalog
                    .relation_object_id(&name)
                    .map(|id| id.map(|id| (name, id)))
            })
            .collect::<Result<Vec<_>, _>>()?;
        for (name, identity) in targets.into_iter().flatten() {
            if !retained.insert(identity) {
                continue;
            }
            if let Some(current) =
                lock_relation_identity(context.catalog, context.locks, name, identity, mode, false)?
            {
                pending.push(current);
            }
        }
    }
    Ok(())
}

fn locks_all_descendants<S: Clone + 'static>(
    context: &TableAlterContext<'_, S>,
    parent: &str,
    recurse: bool,
    action: &AlterTableAction,
) -> Result<bool, SQLError> {
    if matches!(
        action,
        AlterTableAction::AddKeyConstraint { .. }
            | AlterTableAction::DropConstraint { .. }
            | AlterTableAction::RenameColumn { .. }
            | AlterTableAction::DropColumn { .. }
    ) && context
        .hierarchy
        .partitions
        .catalog
        .try_table_hierarchy(parent)
        .map_err(|error| SQLError::Internal(error.to_string()))?
        .partition_spec
        .is_some()
    {
        return Ok(true);
    }
    // ALTER CONSTRAINT of a partitioned table alters the copies on every partition; ONLY fails before reaching them.
    if matches!(action, AlterTableAction::AlterConstraint { .. }) {
        return Ok(recurse
            && context
                .hierarchy
                .partitions
                .catalog
                .try_table_hierarchy(parent)
                .map_err(|error| SQLError::Internal(error.to_string()))?
                .partition_spec
                .is_some());
    }
    // PostgreSQL prepares ADD CONSTRAINT by locking every inheritor before execution can merge a constraint or stop its propagation with NO INHERIT.
    if matches!(
        action,
        AlterTableAction::AddCheckConstraint { .. }
            | AlterTableAction::AddNotNullConstraint { .. }
            | AlterTableAction::AddForeignKeyConstraint { .. }
    ) {
        return Ok(recurse);
    }
    if let AlterTableAction::ValidateConstraint { name } = action {
        let (columns, constraints) =
            crate::schema::constraints::table_constraint_state(&context.constraints, parent)?;
        let validation = constraint_validation(parent, name, &columns, &constraints)?;
        // An unvalidated foreign key of a partitioned table validates the copies on its partitions, as `QueueFKConstraintValidation` opens each of them.
        let partition_foreign_key = !validation.validated
            && matches!(validation.kind, ConstraintValidationKind::ForeignKey { .. })
            && context
                .hierarchy
                .partitions
                .catalog
                .try_table_hierarchy(parent)
                .map_err(|error| SQLError::Internal(error.to_string()))?
                .partition_spec
                .is_some();
        return Ok(validation.requires_descendants() || partition_foreign_key);
    }
    if let AlterTableAction::RenameConstraint { from: name, .. } = action {
        let (columns, constraints) =
            crate::schema::constraints::table_constraint_state(&context.constraints, parent)?;
        return Ok(
            uqa_sql::schema::constraint_changes::inheritance::InheritedConstraint::find(
                &columns,
                &constraints,
                name,
            )
            .is_some_and(|constraint| !constraint.no_inherit && recurse),
        );
    }
    Ok(false)
}