Skip to main content

uqa_sql/schema/
keys.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Declaration and identity rules for newly added PRIMARY KEY and UNIQUE constraints.
8use crate::{
9    ast::{ColumnDef, TableKeyConstraint, TableKeyConstraintKind},
10    SQLError,
11};
12/// The relation that ALTER TABLE adds a key to.
13pub struct AddedKeyRelation<'a> {
14    pub table: &'a str,
15    pub columns: &'a [ColumnDef],
16    pub keys: &'a [TableKeyConstraint],
17    /// The relation's own partition key, when it is partitioned.
18    pub partition: Option<&'a crate::ast::PartitionSpec>,
19}
20
21mod not_null;
22pub use not_null::{
23    validate_primary_key_not_null_child, validate_primary_key_not_null_constraint,
24    validate_primary_key_not_null_constraints, validate_primary_key_not_null_target,
25};
26
27/// Validate a key that ALTER TABLE adds, before its index is named: its declaration as `transformIndexConstraint` checks it, a primary key's columns as the NOT NULL constraints that `ATPrepAddPrimaryKey` adds before the index, and then the checks of `DefineIndex`, which resolves the key's columns.
28pub fn validate_added_key(
29    relation: &AddedKeyRelation<'_>,
30    key: &TableKeyConstraint,
31) -> Result<(), SQLError> {
32    validate_added_key_declaration(relation.columns, key)?;
33    if key.kind == TableKeyConstraintKind::PrimaryKey {
34        for name in &key.columns {
35            validate_primary_key_not_null_target(relation.table, relation.columns, name)?;
36        }
37    }
38    definition::validate_added_key_definition(
39        &definition::KeyRelation {
40            table: relation.table,
41            columns: relation.columns,
42            partition: relation.partition,
43            has_primary_key: relation
44                .keys
45                .iter()
46                .any(|existing| existing.kind == TableKeyConstraintKind::PrimaryKey),
47        },
48        key,
49    )
50}
51
52/// Validate the key declaration before executing its generated NOT NULL constraints.
53pub fn validate_added_key_declaration(
54    columns: &[ColumnDef],
55    key: &TableKeyConstraint,
56) -> Result<(), SQLError> {
57    if let Some(column) = key
58        .columns
59        .iter()
60        .enumerate()
61        .find_map(|(position, column)| key.columns[..position].contains(column).then_some(column))
62    {
63        return Err(definition::repeated_key_column(key.kind, column));
64    }
65    let column = |name: &str| columns.iter().find(|column| column.name == name);
66    let system = definition::is_system_column;
67    if key.without_overlaps {
68        if let Some(period) = key.columns.last() {
69            if let Some(found) = column(period) {
70                definition::validate_overlaps_column(period, Some(&found.ty))?;
71            } else if system(period) {
72                definition::validate_overlaps_column(period, None)?;
73            }
74        }
75    }
76    definition::validate_overlaps_key_length(key)?;
77    Ok(())
78}
79
80/// The keys that ALTER TABLE ADD COLUMN declares on the new column, transformed as `transformIndexConstraints` transforms the statement: a second primary key fails with the relation's name as written, and a key repeating an earlier key's index is dropped.
81pub fn transform_column_keys(
82    relation: &str,
83    keys: &[TableKeyConstraint],
84) -> Result<Vec<TableKeyConstraint>, SQLError> {
85    if keys
86        .iter()
87        .filter(|key| key.kind == TableKeyConstraintKind::PrimaryKey)
88        .count()
89        > 1
90    {
91        return Err(definition::multiple_primary_keys(relation));
92    }
93    Ok(definition::index_order(keys.to_vec()))
94}
95
96/// Apply the NOT NULL requirement of a primary key to the stored column candidate.
97pub fn apply_primary_key_columns(
98    table: &str,
99    constraint: &TableKeyConstraint,
100    columns: &mut [ColumnDef],
101) -> Result<(), String> {
102    if constraint.kind == TableKeyConstraintKind::PrimaryKey {
103        for key_column in &constraint.columns {
104            let column = columns
105                .iter_mut()
106                .find(|column| column.name == *key_column)
107                .ok_or_else(|| {
108                    format!("column `{key_column}` does not exist on table `{table}`")
109                })?;
110            column.not_null = true;
111        }
112    }
113    Ok(())
114}
115
116pub mod definition;
117
118#[cfg(test)]
119mod tests;