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
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Execute the `ALTER COLUMN` identity actions as `PostgreSQL`'s `ATExecAddIdentity`, `ATExecSetIdentity` and `ATExecDropIdentity` do. A partitioned table's partitions share its identity sequence and follow each change; an inheritance child never takes identity.

use super::{ddl_storage_error, TableAlterContext};
use crate::schema::sequences::{
    alteration::SequenceDefinitionContext, dispatch::SequenceCommandCatalog,
    removal::SequenceRemovalInputs,
};
use uqa_core::RelationIdentity;
use uqa_sql::ast::{
    AlterSequence, AutoIncrement, AutoIncrementKind, ColumnDef, DeferredSQLError,
    IdentitySequenceDeclaration, SequenceBound, SequenceDeclaration, SequenceRestart,
};
use uqa_sql::SQLError;

/// The sequence catalog the identity actions change.
pub struct IdentityAlterContext<'a> {
    pub definitions: SequenceDefinitionContext<'a>,
    pub catalog: &'a dyn SequenceCommandCatalog,
    pub removal: &'a dyn SequenceRemovalInputs,
}

/// Where an action runs in a partition hierarchy.
#[derive(Clone, Copy)]
pub(super) struct IdentityTarget<'a> {
    pub table: &'a str,
    /// `ALTER TABLE` without `ONLY`.
    pub recurse: bool,
    /// A partition the action reached from its partitioned parent.
    pub recursing: bool,
}

/// The table's local name, which `PostgreSQL` diagnostics use.
fn local_name(table: &str) -> Result<String, SQLError> {
    RelationIdentity::from_legacy_name(table)
        .map(|relation| relation.name)
        .map_err(|error| SQLError::Internal(format!("resolve ALTER TABLE target: {error}")))
}

fn column_error(
    sqlstate: &str,
    table: &str,
    column: &str,
    detail: &str,
) -> Result<SQLError, SQLError> {
    Ok(SQLError::Routine {
        sqlstate: sqlstate.into(),
        message: format!(
            "column \"{column}\" of relation \"{}\" {detail}",
            local_name(table)?
        ),
    })
}

fn only_partitioned_error(message: &str) -> SQLError {
    SQLError::Diagnostic {
        sqlstate: "42P16".into(),
        message: message.into(),
        detail: None,
        hint: Some("Do not specify the ONLY keyword.".into()),
    }
}

fn partition_error(message: &str) -> SQLError {
    SQLError::Routine {
        sqlstate: "42P16".into(),
        message: message.into(),
    }
}

/// The column `name` of `table`, which `PostgreSQL` reports missing with `42703`.
fn column<S: Clone + 'static>(
    context: &TableAlterContext<'_, S>,
    table: &str,
    name: &str,
) -> Result<ColumnDef, SQLError> {
    context
        .hierarchy
        .catalog
        .try_describe_table(table)
        .map_err(|error| ddl_storage_error("ALTER COLUMN identity", error))?
        .unwrap_or_default()
        .into_iter()
        .find(|definition| definition.name == name)
        .map_or_else(
            || Err(column_error("42703", table, name, "does not exist")?),
            Ok,
        )
}

/// Whether a column draws its values as an identity column. A column an earlier version gave a table counter counts as one.
fn is_identity(column: &ColumnDef) -> bool {
    column
        .auto_increment
        .as_ref()
        .is_some_and(|provenance| provenance.is_identity() || provenance.is_legacy())
}

/// Whether `table` is partitioned, and whether it is a partition.
fn partitioning<S: Clone + 'static>(
    context: &TableAlterContext<'_, S>,
    table: &str,
) -> Result<(bool, bool), SQLError> {
    let hierarchy = context
        .hierarchy
        .partitions
        .catalog
        .try_table_hierarchy(table)
        .map_err(SQLError::Internal)?;
    Ok((
        hierarchy.partition_spec.is_some(),
        hierarchy.partition_bound.is_some(),
    ))
}

/// The partitions an action on the partitioned `table` reaches.
fn partitions<S: Clone + 'static>(
    context: &TableAlterContext<'_, S>,
    table: &str,
) -> Result<Vec<String>, SQLError> {
    context
        .hierarchy
        .partitions
        .catalog
        .direct_hierarchy_children(table)
}

/// `ADD GENERATED ... AS IDENTITY`: create the column's sequence as an identity declaration does, then check the column and make it an identity column, and its partitions' columns with it.
pub(super) fn add_identity<S: Clone + 'static>(
    context: &TableAlterContext<'_, S>,
    target: IdentityTarget<'_>,
    name: &str,
    kind: AutoIncrementKind,
    declaration: Option<Box<IdentitySequenceDeclaration>>,
) -> Result<(), SQLError> {
    let table = target.table;
    let mut definition = column(context, table, name)?;
    let persistence = context
        .addition
        .generated
        .keys
        .catalog
        .table_persistence(table)
        .map_err(|error| ddl_storage_error("ALTER COLUMN identity", error))?
        .unwrap_or_default();
    let existing = definition.auto_increment.take();
    definition.auto_increment = Some(AutoIncrement {
        kind,
        sequence: None,
        owner: None,
        declaration,
    });
    crate::schema::sequences::implicit::materialize_implicit_sequences(
        &context.addition.sequences,
        "ALTER TABLE",
        table,
        std::slice::from_mut(&mut definition),
        persistence,
    )?;
    let identity = definition.auto_increment.take();
    definition.auto_increment = existing;
    set_identity_provenance(context, target, &definition, identity)
}

/// The checks `PostgreSQL` makes before it gives a column identity, then the change itself, here and in each partition.
fn set_identity_provenance<S: Clone + 'static>(
    context: &TableAlterContext<'_, S>,
    target: IdentityTarget<'_>,
    definition: &ColumnDef,
    identity: Option<AutoIncrement>,
) -> Result<(), SQLError> {
    let table = target.table;
    let name = definition.name.as_str();
    let (partitioned, partition) = partitioning(context, table)?;
    if partitioned && !target.recurse {
        return Err(only_partitioned_error(
            "cannot add identity to a column of only the partitioned table",
        ));
    }
    if partition && !target.recursing {
        return Err(partition_error(
            "cannot add identity to a column of a partition",
        ));
    }
    if !(definition.not_null || definition.primary_key) {
        return Err(column_error(
            "55000",
            table,
            name,
            "must be declared NOT NULL before identity can be added",
        )?);
    }
    if is_identity(definition) {
        return Err(column_error(
            "55000",
            table,
            name,
            "is already an identity column",
        )?);
    }
    if definition.default.is_some() || definition.generated.is_some() {
        return Err(column_error(
            "55000",
            table,
            name,
            "already has a default value",
        )?);
    }
    crate::schema::columns::alteration::set_auto_increment(
        &context.columns,
        table,
        name,
        identity.clone(),
    )?;
    if !target.recursing {
        crate::schema::sequences::ownership::attach_table_owners(
            &context.addition.ownership,
            table,
        )
        .map_err(|error| ddl_storage_error("ALTER COLUMN identity ownership", error))?;
    }
    if partitioned {
        for partition in partitions(context, table)? {
            let child = column(context, &partition, name)?;
            set_identity_provenance(
                context,
                IdentityTarget {
                    table: &partition,
                    recurse: true,
                    recursing: true,
                },
                &child,
                identity.clone(),
            )?;
        }
    }
    Ok(())
}

/// The sequence an identity column draws from, which a partition shares with its partitioned parent.
fn identity_sequence(column: &ColumnDef) -> Option<&str> {
    column
        .auto_increment
        .as_ref()
        .filter(|provenance| provenance.is_identity())
        .and_then(|provenance| provenance.sequence.as_deref())
}

/// `SET GENERATED`, `RESTART` and `SET sequence_option`: change an identity column's sequence as `ALTER SEQUENCE` would, then its generation, here and in each partition.
pub(super) fn set_identity<S: Clone + 'static>(
    context: &TableAlterContext<'_, S>,
    target: IdentityTarget<'_>,
    name: &str,
    kind: Option<AutoIncrementKind>,
    repeated_kind: bool,
    sequence: &SequenceDeclaration,
    error: Option<&DeferredSQLError>,
) -> Result<(), SQLError> {
    let table = target.table;
    let definition = column(context, table, name)?;
    if !target.recursing {
        if let Some(sequence_name) = identity_sequence(&definition) {
            if error.is_some() || *sequence != SequenceDeclaration::default() {
                alter_identity_sequence(&context.identities, sequence_name, sequence, error)?;
            }
        }
    }
    if repeated_kind {
        return Err(SQLError::Routine {
            sqlstate: "42601".into(),
            message: "conflicting or redundant options".into(),
        });
    }
    let (partitioned, partition) = partitioning(context, table)?;
    if partitioned && !target.recurse {
        return Err(only_partitioned_error(
            "cannot change identity column of only the partitioned table",
        ));
    }
    if partition && !target.recursing {
        return Err(partition_error(
            "cannot change identity column of a partition",
        ));
    }
    if !is_identity(&definition) {
        return Err(column_error(
            "55000",
            table,
            name,
            "is not an identity column",
        )?);
    }
    let Some(kind) = kind else {
        return Ok(());
    };
    let mut provenance = definition
        .auto_increment
        .clone()
        .expect("an identity column has its provenance");
    provenance.kind = kind;
    crate::schema::columns::alteration::set_auto_increment(
        &context.columns,
        table,
        name,
        Some(provenance),
    )?;
    if partitioned {
        for partition in partitions(context, table)? {
            set_identity(
                context,
                IdentityTarget {
                    table: &partition,
                    recurse: true,
                    recursing: true,
                },
                name,
                Some(kind),
                false,
                &SequenceDeclaration::default(),
                None,
            )?;
        }
    }
    Ok(())
}

/// Change an identity sequence as `ALTER SEQUENCE` would: read the options in `PostgreSQL`'s order against its current definition and value, then apply them.
fn alter_identity_sequence(
    context: &IdentityAlterContext<'_>,
    name: &str,
    sequence: &SequenceDeclaration,
    error: Option<&DeferredSQLError>,
) -> Result<(), SQLError> {
    if let Some(error) = error {
        return Err(error.clone().into());
    }
    let relation = RelationIdentity::from_legacy_name(name)
        .map_err(|error| SQLError::Internal(format!("resolve sequence `{name}`: {error}")))?;
    let state = context
        .definitions
        .catalog
        .state(&relation)?
        .ok_or_else(|| SQLError::Internal(format!("identity sequence `{name}` disappeared")))?;
    let altered = uqa_sql::schema::sequences::declaration::alter_declared_sequence(
        sequence,
        &state.definition(),
        state.current,
        true,
    )?;
    let changed = altered.definition;
    let bound = |declared: bool, value: i64| {
        if declared {
            SequenceBound::Value(value)
        } else {
            SequenceBound::Unchanged
        }
    };
    let alter = AlterSequence {
        name: name.to_owned(),
        restart: sequence
            .restart
            .as_ref()
            .map_or(SequenceRestart::Unchanged, |_| {
                SequenceRestart::With(altered.current)
            }),
        increment: sequence.increment.as_ref().map(|_| changed.increment),
        start: sequence.start.as_ref().map(|_| changed.start),
        data_type: sequence.data_type.as_ref().map(|_| changed.data_type),
        min_value: bound(sequence.min_value.is_some(), changed.min_value),
        max_value: bound(sequence.max_value.is_some(), changed.max_value),
        cycle: sequence.cycle,
        cache_size: sequence.cache.as_ref().map(|_| changed.cache_size),
        ..AlterSequence::default()
    };
    crate::schema::sequences::alteration::alter_sequence_definition(
        &context.definitions,
        name,
        &relation,
        context.catalog.sequence_persistence(&relation),
        &alter,
    )?;
    Ok(())
}

/// Change the type of an identity column's sequence with the column's own type change, as `PostgreSQL` issues `ALTER SEQUENCE ... AS` for it first. A partition's column draws from its parent's sequence, which the parent's change already retyped.
pub(super) fn retype_identity_sequence<S: Clone + 'static>(
    context: &TableAlterContext<'_, S>,
    table: &str,
    name: &str,
    ty: &uqa_sql::ast::ColumnType,
) -> Result<(), SQLError> {
    let (_, partition) = partitioning(context, table)?;
    if partition {
        return Ok(());
    }
    let definition = column(context, table, name)?;
    let Some(sequence_name) = identity_sequence(&definition) else {
        return Ok(());
    };
    alter_identity_sequence(
        &context.identities,
        sequence_name,
        &SequenceDeclaration {
            data_type: Some(ty.clone()),
            ..SequenceDeclaration::default()
        },
        None,
    )
}

/// `DROP IDENTITY [ IF EXISTS ]`: stop the column, and its partitions' columns, from drawing identity values, and drop the sequence. The column keeps its `NOT NULL`.
pub(super) fn drop_identity<S: Clone + 'static>(
    context: &TableAlterContext<'_, S>,
    target: IdentityTarget<'_>,
    name: &str,
    if_exists: bool,
) -> Result<(), SQLError> {
    let table = target.table;
    let (partitioned, partition) = partitioning(context, table)?;
    if partitioned && !target.recurse {
        return Err(only_partitioned_error(
            "cannot drop identity from a column of only the partitioned table",
        ));
    }
    if partition && !target.recursing {
        return Err(partition_error(
            "cannot drop identity from a column of a partition",
        ));
    }
    let definition = column(context, table, name)?;
    if !is_identity(&definition) {
        if if_exists {
            context
                .constraints
                .notices
                .lock()
                .push(uqa_sql::SQLNotice::notice(format!(
                    "column \"{name}\" of relation \"{}\" is not an identity column, skipping",
                    local_name(table)?
                )));
            return Ok(());
        }
        return Err(column_error(
            "55000",
            table,
            name,
            "is not an identity column",
        )?);
    }
    let sequence = identity_sequence(&definition).map(str::to_owned);
    crate::schema::columns::alteration::set_auto_increment(&context.columns, table, name, None)?;
    if partitioned {
        for partition in partitions(context, table)? {
            drop_identity(
                context,
                IdentityTarget {
                    table: &partition,
                    recurse: true,
                    recursing: true,
                },
                name,
                false,
            )?;
        }
    }
    if let (false, Some(sequence)) = (target.recursing, sequence) {
        context
            .identities
            .removal
            .sequence_removal_context()
            .drop_owned_sequence(&sequence, false)
            .map_err(|error| ddl_storage_error("ALTER COLUMN DROP IDENTITY", error))?;
    }
    Ok(())
}