Skip to main content

uqa_execution/schema/
table_creation.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Execute table creation with the original namespace, sequence, and schema write boundaries.
8use super::{
9    publication::{self, SchemaWriteTransaction},
10    sequences::{
11        implicit::{self, ImplicitSequenceContext},
12        ownership::{self, ImplicitOwnershipContext},
13    },
14};
15use crate::catalog::identity::{allocate_catalog_object_id, CatalogIdentityReservationContext};
16use uqa_sql::ast::{
17    ColumnType, CreateTable, DeferredCreateTable, OnCommitAction, RelationPersistence,
18    TableConstraintSet, TableHierarchy,
19};
20use uqa_sql::catalog::relation_oids::{RelationCatalogOids, RelationOidKind};
21use uqa_sql::schema::constraint_metadata::CatalogIdentityAllocator;
22use uqa_sql::schema::table_creation::declaration::{self, CreateTableAnalysisContext};
23use uqa_sql::schema::table_creation::{checks, not_nulls};
24use uqa_sql::{SQLError, SQLResult};
25use uqa_storage::{StorageBackendError, StorageBackendResult};
26
27pub mod entry;
28
29pub trait TableCreationNamespace {
30    fn prepare_writer(&self) -> Result<bool, SQLError>;
31    fn relation_exists(&self, name: &str) -> Result<bool, SQLError>;
32}
33pub trait TableCreationPublication {
34    /// Create the relation under the OIDs `CREATE TABLE` allocated for it where `heap_create_with_catalog` allocates them.
35    fn create_table(
36        &self,
37        name: &str,
38        persistence: RelationPersistence,
39        on_commit: OnCommitAction,
40        owner: &crate::catalog::security::roles::locking::RoleBinding,
41        catalog_oids: RelationCatalogOids,
42    ) -> StorageBackendResult<()>;
43    fn create_vector_field(
44        &self,
45        table: &str,
46        field: String,
47        dimensions: u32,
48    ) -> StorageBackendResult<bool>;
49    fn install_hierarchy(&self, table: &str, hierarchy: TableHierarchy)
50        -> StorageBackendResult<()>;
51    fn persist_schema(&self, table: &str) -> StorageBackendResult<bool>;
52    fn refresh_value_indexes(&self, table: &str) -> StorageBackendResult<()>;
53    /// Reject a new partition whose bound accepts a row already stored in the parent's default partition.
54    fn validate_default_partition_rows(
55        &self,
56        parent: &str,
57        bound: &uqa_sql::ast::PartitionBound,
58    ) -> Result<(), SQLError>;
59}
60pub struct CreateTableContext<'a> {
61    pub creation: crate::schema::namespaces::relations::RelationCreationContext<'a>,
62    pub namespace: &'a dyn TableCreationNamespace,
63    pub analysis: CreateTableAnalysisContext<'a>,
64    pub sequences: ImplicitSequenceContext<'a>,
65    pub ownership: ImplicitOwnershipContext<'a>,
66    pub schema_transactions: &'a dyn SchemaWriteTransaction,
67    pub publication: &'a dyn TableCreationPublication,
68    /// The database's OID counter and catalog, from which the statement draws the OIDs of the relation and of each object it defines.
69    pub identities: CatalogIdentityReservationContext<'a>,
70    pub notices: &'a crate::query::NoticeQueue,
71}
72fn storage_error(action: &str, error: StorageBackendError) -> SQLError {
73    uqa_sql::catalog::errors::storage_error(action, &error)
74}
75
76pub fn run_create_table(
77    context: &CreateTableContext<'_>,
78    mut table: CreateTable,
79) -> Result<SQLResult, SQLError> {
80    let owner = context.creation.bind_owner()?;
81    let Some((name, persistence)) = preflight(
82        context,
83        &table.name,
84        table.persistence,
85        table.if_not_exists,
86        ExistingRelation::Deferred,
87    )?
88    else {
89        return Ok(SQLResult::empty());
90    };
91    table.name = name;
92    table.persistence = persistence;
93    declaration::transform_create_table(&context.analysis, &mut table)?;
94    create_after_preflight(context, table, &owner)
95}
96pub fn run_create_table_if_not_exists(
97    context: &CreateTableContext<'_>,
98    deferred: DeferredCreateTable,
99) -> Result<SQLResult, SQLError> {
100    let owner = context.creation.bind_owner()?;
101    let Some((name, persistence)) = preflight(
102        context,
103        &deferred.name,
104        deferred.persistence,
105        true,
106        ExistingRelation::Deferred,
107    )?
108    else {
109        return Ok(SQLResult::empty());
110    };
111    let mut table = uqa_sql::resolve_deferred_create_table(&deferred)?;
112    table.name = name;
113    table.persistence = persistence;
114    declaration::transform_create_table(&context.analysis, &mut table)?;
115    create_after_preflight(context, table, &owner)
116}
117
118/// When a relation that already has the name is an error. `transformCreateStmt` skips `IF NOT EXISTS` before it analyzes the declaration, but `heap_create_with_catalog` reports the collision only after `MergeAttributes`, `BuildDescForRelation` and `CheckAttributeNamesTypes` accepted the row type.
119#[derive(Clone, Copy, PartialEq, Eq)]
120enum ExistingRelation {
121    Deferred,
122    Reported,
123}
124/// Resolve the new table's name and persistence as `RangeVarGetAndCheckCreationNamespace` does, before `transformCreateStmt` looks for a relation that already has the name.
125fn preflight(
126    context: &CreateTableContext<'_>,
127    name: &str,
128    persistence: RelationPersistence,
129    if_not_exists: bool,
130    existing: ExistingRelation,
131) -> Result<Option<(String, RelationPersistence)>, SQLError> {
132    if !context
133        .creation
134        .targets_temporary_namespace(name, persistence)?
135    {
136        context.namespace.prepare_writer()?;
137    }
138    let (name, persistence) = context.creation.relation_target(name, persistence)?;
139    if context.namespace.relation_exists(&name)? {
140        let local = uqa_core::RelationIdentity::from_legacy_name(&name)
141            .map_err(SQLError::Internal)?
142            .name;
143        if if_not_exists {
144            context.notices.push(
145                uqa_sql::SQLNotice::notice(format!(
146                    "relation \"{local}\" already exists, skipping"
147                ))
148                .with_sqlstate("42P07"),
149            );
150            return Ok(None);
151        }
152        if existing == ExistingRelation::Reported {
153            return Err(SQLError::Routine {
154                sqlstate: "42P07".into(),
155                message: format!("relation \"{local}\" already exists"),
156            });
157        }
158    }
159    Ok(Some((name, persistence)))
160}
161/// Create the table in `DefineRelation`'s order, after the sequences of its columns: `MergeAttributes` and the relation's name, then the relation and row type under the OIDs `heap_create_with_catalog` allocates, followed by its expressions and constraints, each taking its OIDs as it is defined. A statement that fails after the relation's OIDs has used them, as the counter advances outside the transaction.
162fn create_after_preflight(
163    context: &CreateTableContext<'_>,
164    mut table: CreateTable,
165    owner: &crate::catalog::security::roles::locking::RoleBinding,
166) -> Result<SQLResult, SQLError> {
167    implicit::materialize_implicit_sequences(
168        &context.sequences,
169        "CREATE TABLE",
170        &table.name,
171        &mut table.columns,
172        table.persistence,
173    )?;
174    let mut notices = Vec::new();
175    let inherited =
176        declaration::prepare_create_table_declaration(&context.analysis, &mut table, &mut notices);
177    // A notice reaches the client before the error that ends the statement.
178    for notice in notices {
179        context.notices.push(notice);
180    }
181    let inherited = inherited?;
182    context.creation.retain_owner(owner)?;
183    if preflight(
184        context,
185        &table.name,
186        table.persistence,
187        table.if_not_exists,
188        ExistingRelation::Reported,
189    )?
190    .is_none()
191    {
192        return Ok(SQLResult::empty());
193    }
194    // `heap_create_with_catalog` checks the row type's name, allocates the relation's OIDs and stores the inherited expressions before `DefineRelation` analyzes the statement's own.
195    context.creation.reserve_row_type_name(&table.name)?;
196    let relation =
197        uqa_core::RelationIdentity::from_legacy_name(&table.name).map_err(SQLError::Internal)?;
198    let mut allocator = context.identities.allocator(allocate_catalog_object_id);
199    let catalog_oids = allocator.allocate_relation_oids(RelationOidKind::Table, &relation)?;
200    create_declared_relation(context, &mut table, owner, catalog_oids, &mut allocator)?;
201    define_expressions_and_constraints(
202        context,
203        &mut table,
204        &inherited,
205        catalog_oids.relation,
206        &mut allocator,
207    )?;
208    let mut vector_fields = Vec::new();
209    for column in &table.columns {
210        match &column.ty {
211            ColumnType::Vector(dim) | ColumnType::Tensor(dim) => {
212                vector_fields.push((column.name.clone(), *dim));
213            }
214            _ => {}
215        }
216    }
217    for (field, dimensions) in vector_fields {
218        context
219            .publication
220            .create_vector_field(&table.name, field, dimensions)
221            .map_err(|error| storage_error("CREATE TABLE vector field", error))?;
222    }
223    uqa_sql::schema::table_creation::foreign_keys::define_foreign_keys(
224        &context.analysis,
225        &mut table,
226        inherited.foreign_keys,
227        &mut allocator,
228    )?;
229    publish_catalog_state(context, &table, table.columns.clone())?;
230    Ok(SQLResult::empty())
231}
232
233fn create_declared_relation(
234    context: &CreateTableContext<'_>,
235    table: &mut CreateTable,
236    owner: &crate::catalog::security::roles::locking::RoleBinding,
237    catalog_oids: RelationCatalogOids,
238    allocate: &mut CatalogIdentityAllocator<'_>,
239) -> Result<(), SQLError> {
240    let columns = declaration::declared_row_columns(&mut table.columns, allocate)?;
241    context
242        .publication
243        .create_table(
244            &table.name,
245            table.persistence,
246            table.on_commit,
247            owner,
248            catalog_oids,
249        )
250        .map_err(|error| storage_error("CREATE TABLE", error))?;
251    context
252        .schema_transactions
253        .with_schema_write(Box::new(|schema| {
254            publication::declare_row_columns(schema, &table.name, columns)
255        }))
256        .map_err(|error| storage_error("CREATE TABLE row type", error))
257}
258
259/// Publish the created relation's columns and constraints, the ownership of its sequences and its hierarchy, then persist its schema and refresh its indexes.
260fn publish_catalog_state(
261    context: &CreateTableContext<'_>,
262    table: &CreateTable,
263    registered_columns: Vec<uqa_sql::ast::ColumnDef>,
264) -> Result<(), SQLError> {
265    let constraints = TableConstraintSet {
266        columns_declared: Some(true),
267        persistence: table.persistence,
268        on_commit: table.on_commit,
269        checks: table.checks.clone(),
270        foreign_keys: table.foreign_keys.clone(),
271        key_constraints: table.key_constraints.clone(),
272        hierarchy: table.hierarchy.clone(),
273        // The created relation's state carries its OIDs; publication records them.
274        catalog_oids: None,
275        row_type_array_name: None,
276        dropped_attributes: Vec::new(),
277    };
278    context
279        .schema_transactions
280        .with_schema_write(Box::new(|schema| {
281            publication::replace_constraint_state(
282                schema,
283                &table.name,
284                registered_columns,
285                constraints,
286            )
287        }))
288        .map_err(|error| storage_error("CREATE TABLE constraints", error))?;
289    ownership::attach_table_owners(&context.ownership, &table.name)?;
290    context
291        .publication
292        .install_hierarchy(&table.name, table.hierarchy.clone())
293        .map_err(|error| storage_error("CREATE TABLE hierarchy", error))?;
294    republish_ancestor_references(context, table)?;
295    context
296        .publication
297        .persist_schema(&table.name)
298        .map_err(|error| storage_error("CREATE TABLE", error))?;
299    context
300        .publication
301        .refresh_value_indexes(&table.name)
302        .map_err(|error| storage_error("CREATE TABLE btree indexes", error))
303}
304
305/// The inherited expressions, the defaults and generation expressions in column order, the partition bound and key, the keys a partition clones, the CHECK constraints in written order, the NOT NULL constraints as `AddRelationNotNullConstraints` creates them, and then the declared keys, in the order `DefineRelation` and the commands it queues define them; each defined object takes its OIDs from `allocate` as it is defined. `relation_oid` is the relation's OID, which a constraint name violation reports.
306fn define_expressions_and_constraints(
307    context: &CreateTableContext<'_>,
308    table: &mut CreateTable,
309    inherited: &declaration::InheritedDefinitions,
310    relation_oid: u32,
311    allocate: &mut CatalogIdentityAllocator<'_>,
312) -> Result<(), SQLError> {
313    declaration::define_inherited_expressions(table, inherited, allocate)?;
314    declaration::define_create_table_defaults(&context.analysis, table, allocate)?;
315    bind_partitioning(context, table)?;
316    let indexes =
317        declaration::clone_create_table_parent_keys(&context.analysis, table, inherited, allocate)?;
318    let cloned = declaration::cloned_constraint_names(table, inherited);
319    let mut notices = Vec::new();
320    let checks = checks::define_create_table_checks(
321        &context.analysis,
322        table,
323        &cloned,
324        &mut notices,
325        allocate,
326    );
327    // A notice reaches the client before the error that ends the statement.
328    for notice in notices {
329        context.notices.push(notice);
330    }
331    checks?;
332    not_nulls::define_not_null_constraints(
333        &context.analysis,
334        table,
335        inherited,
336        relation_oid,
337        allocate,
338    )?;
339    declaration::define_create_table_constraints(table, indexes, inherited, allocate)
340}
341
342/// `DefineRelation` binds a new partition's bound and the table's partition key once the relation exists, and `check_default_partition_contents` rejects a bound that accepts a row the parent's default partition holds.
343fn bind_partitioning(
344    context: &CreateTableContext<'_>,
345    table: &mut CreateTable,
346) -> Result<(), SQLError> {
347    declaration::bind_create_table_partitioning(&context.analysis, table)?;
348    if let (Some(parent), Some(bound)) = (
349        table.hierarchy.parents.first(),
350        table.hierarchy.partition_bound.as_ref(),
351    ) {
352        context
353            .publication
354            .validate_default_partition_rows(parent, bound)?;
355    }
356    Ok(())
357}
358
359/// The foreign keys referencing a new partition's ancestors derive constraints on it.
360fn republish_ancestor_references(
361    context: &CreateTableContext<'_>,
362    table: &CreateTable,
363) -> Result<(), SQLError> {
364    let Some(parent) = table
365        .hierarchy
366        .parents
367        .first()
368        .filter(|_| table.hierarchy.is_partition())
369    else {
370        return Ok(());
371    };
372    let parent = parent.clone();
373    context
374        .schema_transactions
375        .with_schema_write(Box::new(move |schema| {
376            publication::referenced_partitions::republish_referencing_tables(
377                schema,
378                &parent,
379                crate::row_locks::RelationLockMode::ShareRowExclusive,
380            )
381            .map_err(|error| {
382                StorageBackendError::backend("CREATE TABLE derived constraints", error)
383            })
384        }))
385        .map_err(|error| storage_error("CREATE TABLE derived constraints", error))
386}