1pub mod foreign_key_target;
9pub mod inheritance;
10pub mod names;
11pub mod not_null_removal;
12pub mod renaming;
13pub mod validation;
14
15#[cfg(test)]
16mod tests;
17
18use crate::schema::foreign_keys::column_foreign_key;
19use crate::{
20 ast::{ColumnType, ForeignKey, TableCheck},
21 SQLError,
22};
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum ConstraintLocation {
25 NotNull(usize),
26 ColumnCheck(usize),
27 ColumnForeignKey(usize),
28 TableCheck(usize),
29 TableForeignKey(usize),
30 Key(usize),
31 ReferencedPartition(ForeignKeyLocation, usize),
33}
34
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub enum ForeignKeyLocation {
38 Column(usize),
39 Table(usize),
40}
41
42impl ForeignKeyLocation {
43 pub const fn constraint(self) -> ConstraintLocation {
44 match self {
45 Self::Column(index) => ConstraintLocation::ColumnForeignKey(index),
46 Self::Table(index) => ConstraintLocation::TableForeignKey(index),
47 }
48 }
49
50 pub fn derived<'a>(
52 self,
53 columns: &'a [crate::ast::ColumnDef],
54 constraints: &'a crate::ast::TableConstraintSet,
55 ) -> Option<(&'a str, &'a [crate::ast::ReferencedPartitionConstraint])> {
56 match self {
57 Self::Column(index) => columns
58 .get(index)?
59 .references
60 .as_ref()
61 .and_then(|reference| {
62 Some((
63 reference.name.as_deref()?,
64 reference.referenced_partitions.as_slice(),
65 ))
66 }),
67 Self::Table(index) => constraints.foreign_keys.get(index).and_then(|foreign_key| {
68 Some((
69 foreign_key.name.as_deref()?,
70 foreign_key.referenced_partitions.as_slice(),
71 ))
72 }),
73 }
74 }
75
76 pub fn derived_mut<'a>(
78 self,
79 columns: &'a mut [crate::ast::ColumnDef],
80 constraints: &'a mut crate::ast::TableConstraintSet,
81 ) -> Option<&'a mut Vec<crate::ast::ReferencedPartitionConstraint>> {
82 match self {
83 Self::Column(index) => columns
84 .get_mut(index)?
85 .references
86 .as_mut()
87 .map(|reference| &mut reference.referenced_partitions),
88 Self::Table(index) => constraints
89 .foreign_keys
90 .get_mut(index)
91 .map(|foreign_key| &mut foreign_key.referenced_partitions),
92 }
93 }
94}
95
96pub fn constraint_error(sqlstate: &str, message: impl Into<String>) -> SQLError {
97 SQLError::Routine {
98 sqlstate: sqlstate.into(),
99 message: message.into(),
100 }
101}
102
103pub fn find_constraint(
104 columns: &[crate::ast::ColumnDef],
105 constraints: &crate::ast::TableConstraintSet,
106 name: &str,
107) -> Option<ConstraintLocation> {
108 names::ConstraintNames::from_definition(columns, constraints)
109 .entries()
110 .find(|constraint| constraint.name == name)
111 .map(|constraint| constraint.location)
112}
113
114pub fn ensure_constraint_name_available(
115 columns: &[crate::ast::ColumnDef],
116 constraints: &crate::ast::TableConstraintSet,
117 name: Option<&str>,
118 table: &str,
119) -> Result<(), SQLError> {
120 if let Some(name) = name.filter(|name| find_constraint(columns, constraints, name).is_some()) {
121 return Err(constraint_error(
122 "42710",
123 format!("constraint \"{name}\" for relation \"{table}\" already exists"),
124 ));
125 }
126 Ok(())
127}
128
129pub fn ensure_not_null_inheritable(
130 table: &str,
131 column: &crate::ast::ColumnDef,
132 sqlstate: &str,
133) -> Result<(), SQLError> {
134 if column.not_null_no_inherit {
135 return Err(constraint_error(
136 sqlstate,
137 not_null_inheritance_message(table, column)?,
138 ));
139 }
140 Ok(())
141}
142
143pub fn validate_inherited_not_null_addition(
145 table: &str,
146 column: &crate::ast::ColumnDef,
147 validated: bool,
148) -> Result<(), SQLError> {
149 let (message, hint) = if column.not_null_no_inherit {
150 (
151 not_null_inheritance_message(table, column)?,
152 "You might need to make the existing constraint inheritable using ALTER TABLE ... ALTER CONSTRAINT ... INHERIT.",
153 )
154 } else if validated && !column.not_null_validated {
155 let relation =
156 uqa_core::RelationIdentity::from_legacy_name(table).map_err(SQLError::Internal)?;
157 let name = column.not_null_name.as_deref().unwrap_or("<unnamed>");
158 (
159 format!(
160 "incompatible NOT VALID constraint \"{name}\" on relation \"{}\"",
161 relation.name
162 ),
163 "You might need to validate it using ALTER TABLE ... VALIDATE CONSTRAINT.",
164 )
165 } else {
166 return Ok(());
167 };
168 Err(SQLError::Diagnostic {
169 sqlstate: "55000".into(),
170 message,
171 detail: None,
172 hint: Some(hint.into()),
173 })
174}
175
176fn not_null_inheritance_message(
177 table: &str,
178 column: &crate::ast::ColumnDef,
179) -> Result<String, SQLError> {
180 let relation = uqa_core::RelationIdentity::from_legacy_name(table)
181 .map_err(|error| SQLError::Internal(format!("resolve NOT NULL relation: {error}")))?;
182 let name = column.not_null_name.as_deref().unwrap_or("<unnamed>");
183 Ok(format!(
184 "cannot change NO INHERIT status of NOT NULL constraint \"{name}\" on relation \"{}\"",
185 relation.name
186 ))
187}
188
189pub fn take_column_check(column: &mut crate::ast::ColumnDef) -> Option<TableCheck> {
190 let check = TableCheck {
191 expr: column.check.take()?,
192 catalog_oid: column.check_catalog_oid.take(),
193 name: column.check_name.take(),
194 object_id: column.check_object_id.take(),
195 is_local: column.check_is_local,
196 enforced: column.check_enforced,
197 validated: column.check_validated,
198 no_inherit: column.check_no_inherit,
199 partition_constraint: None,
200 };
201 column.check_is_local = true;
202 column.check_enforced = true;
203 column.check_validated = true;
204 column.check_no_inherit = false;
205 Some(check)
206}
207
208pub fn restore_column_check(column: &mut crate::ast::ColumnDef, check: TableCheck) {
210 column.check = Some(check.expr);
211 column.check_catalog_oid = check.catalog_oid;
212 column.check_name = check.name;
213 column.check_object_id = check.object_id;
214 column.check_is_local = check.is_local;
215 column.check_enforced = check.enforced;
216 column.check_validated = check.validated;
217 column.check_no_inherit = check.no_inherit;
218}
219
220pub fn foreign_key_object_id(
221 columns: &[crate::ast::ColumnDef],
222 constraints: &crate::ast::TableConstraintSet,
223 location: ConstraintLocation,
224) -> Option<[u8; 16]> {
225 match location {
226 ConstraintLocation::ColumnForeignKey(index) => columns[index]
227 .references
228 .as_ref()
229 .and_then(|reference| reference.object_id),
230 ConstraintLocation::TableForeignKey(index) => constraints.foreign_keys[index].object_id,
231 _ => None,
232 }
233}
234
235pub trait ConstraintTypeReferrers {
236 fn try_referrers_to(
237 &self,
238 table: &str,
239 ) -> Result<Vec<(String, ForeignKey)>, crate::assignment::columns::ColumnCatalogError>;
240}
241pub struct ConstraintTypeContext<'a> {
242 pub foreign_keys: crate::schema::foreign_keys::ForeignKeyDefinitionContext<'a>,
243 pub referrers: &'a dyn ConstraintTypeReferrers,
244}
245fn ddl_storage_error(
246 action: &str,
247 error: crate::assignment::columns::ColumnCatalogError,
248) -> SQLError {
249 crate::catalog::errors::storage_error(action, error.as_ref())
250}
251pub fn validate_altered_constraint_column_types(
252 context: &ConstraintTypeContext<'_>,
253 table: &str,
254 candidate_columns: &[crate::ast::ColumnDef],
255 key_constraints: &[crate::ast::TableKeyConstraint],
256 foreign_keys: &[ForeignKey],
257) -> Result<(), SQLError> {
258 for constraint in key_constraints
259 .iter()
260 .filter(|constraint| constraint.without_overlaps)
261 {
262 let Some(period_column) = constraint.columns.last() else {
263 return Err(SQLError::Internal(
264 "WITHOUT OVERLAPS constraint has no period column".into(),
265 ));
266 };
267 let period_type = candidate_columns
268 .iter()
269 .find(|column| column.name == *period_column)
270 .map(|column| &column.ty)
271 .ok_or_else(|| SQLError::UnknownColumn(format!("{table}.{period_column}")))?;
272 if !matches!(
273 period_type,
274 ColumnType::Range(_) | ColumnType::Multirange(_)
275 ) {
276 return Err(SQLError::Routine {
277 sqlstate: "42804".into(),
278 message: format!(
279 "column \"{period_column}\" in WITHOUT OVERLAPS is not a range or multirange type"
280 ),
281 });
282 }
283 }
284
285 for foreign_key in foreign_keys.iter().filter(|foreign_key| foreign_key.period) {
286 let (parent_name, parent_columns, parent_keys) =
287 crate::schema::foreign_keys::resolve_foreign_key_parent(
288 &context.foreign_keys,
289 &foreign_key.ref_table,
290 )?;
291 let parent_columns = if parent_name == table {
292 candidate_columns
293 } else {
294 parent_columns.as_slice()
295 };
296 crate::schema::constraints::validate_foreign_key_definition(
297 table,
298 candidate_columns,
299 &parent_name,
300 parent_columns,
301 &parent_keys,
302 foreign_key,
303 )?;
304 }
305
306 for (child_table, foreign_key) in context
307 .referrers
308 .try_referrers_to(table)
309 .map_err(|error| ddl_storage_error("ALTER COLUMN TYPE", error))?
310 .into_iter()
311 .filter(|(_, foreign_key)| foreign_key.period)
312 {
313 let child_columns = if child_table == table {
314 candidate_columns.to_vec()
315 } else {
316 context
317 .foreign_keys
318 .columns
319 .try_describe_table(&child_table)
320 .map_err(|error| ddl_storage_error("ALTER COLUMN TYPE", error))?
321 .ok_or_else(|| SQLError::UnknownTable(child_table.clone()))?
322 };
323 crate::schema::constraints::validate_foreign_key_definition(
324 &child_table,
325 &child_columns,
326 table,
327 candidate_columns,
328 key_constraints,
329 &foreign_key,
330 )?;
331 }
332 Ok(())
333}
334
335pub struct ConstraintAlterOptions {
336 pub enforceability: Option<bool>,
337 pub deferrability: Option<(bool, bool)>,
338 pub no_inherit: Option<bool>,
339 pub ancestor: Option<ConstraintAncestor>,
341}
342
343#[derive(Debug, Clone, PartialEq, Eq)]
345pub struct ConstraintAncestor {
346 pub name: String,
347 pub table: String,
348}
349
350pub fn derived_constraint_alteration(
352 table: &str,
353 name: &str,
354 ancestor: &ConstraintAncestor,
355) -> SQLError {
356 let local = |table: &str| match uqa_core::RelationIdentity::from_legacy_name(table) {
357 Ok(relation) => Ok(relation.name),
358 Err(error) => Err(SQLError::Internal(error)),
359 };
360 let (relation, ancestor_relation) = match (local(table), local(&ancestor.table)) {
361 (Ok(relation), Ok(ancestor_relation)) => (relation, ancestor_relation),
362 (Err(error), _) | (_, Err(error)) => return error,
363 };
364 SQLError::Diagnostic {
365 sqlstate: "55000".into(),
366 message: format!("cannot alter constraint \"{name}\" on relation \"{relation}\""),
367 detail: Some(format!(
368 "Constraint \"{name}\" is derived from constraint \"{}\" of relation \"{ancestor_relation}\".",
369 ancestor.name
370 )),
371 hint: Some("You may alter the constraint it derives from instead.".into()),
372 }
373}
374pub struct ConstraintAlterEffects {
375 pub recreated_foreign_key: Option<ForeignKey>,
376 pub validate_after_publish: bool,
377 pub changed: bool,
379}
380fn ensure_alteration_applies(
382 location: ConstraintLocation,
383 relation: &str,
384 name: &str,
385 enforceability: bool,
386 deferrability: bool,
387 no_inherit: bool,
388) -> Result<(), SQLError> {
389 let is_foreign_key = matches!(
390 location,
391 ConstraintLocation::ColumnForeignKey(_)
392 | ConstraintLocation::TableForeignKey(_)
393 | ConstraintLocation::ReferencedPartition(..)
394 );
395 if enforceability && !is_foreign_key {
396 return Err(constraint_error(
397 "42809",
398 format!(
399 "cannot alter enforceability of constraint \"{name}\" of relation \"{relation}\""
400 ),
401 ));
402 }
403 if deferrability && !is_foreign_key {
404 return Err(constraint_error(
405 "42809",
406 format!(
407 "constraint \"{name}\" of relation \"{relation}\" is not a foreign key constraint"
408 ),
409 ));
410 }
411 if no_inherit && !matches!(location, ConstraintLocation::NotNull(_)) {
412 return Err(constraint_error(
413 "42809",
414 format!(
415 "constraint \"{name}\" of relation \"{relation}\" is not a not-null constraint"
416 ),
417 ));
418 }
419 Ok(())
420}
421
422pub fn apply_constraint_alteration(
423 table: &str,
424 name: &str,
425 columns: &mut [crate::ast::ColumnDef],
426 constraints: &mut crate::ast::TableConstraintSet,
427 options: ConstraintAlterOptions,
428) -> Result<ConstraintAlterEffects, SQLError> {
429 let ConstraintAlterOptions {
430 enforceability,
431 deferrability,
432 no_inherit,
433 ancestor,
434 } = options;
435 let relation = uqa_core::RelationIdentity::from_legacy_name(table)
437 .map_err(SQLError::Internal)?
438 .name;
439 let location = find_constraint(columns, constraints, name).ok_or_else(|| {
440 constraint_error(
441 "42704",
442 format!("constraint \"{name}\" of relation \"{relation}\" does not exist"),
443 )
444 })?;
445 ensure_alteration_applies(
446 location,
447 &relation,
448 name,
449 enforceability.is_some(),
450 deferrability.is_some(),
451 no_inherit.is_some(),
452 )?;
453 let ancestor = match location {
455 ConstraintLocation::ReferencedPartition(foreign_key, _) => foreign_key
456 .derived(columns, constraints)
457 .map(|(foreign_key, _)| ConstraintAncestor {
458 name: foreign_key.to_string(),
459 table: table.to_string(),
460 }),
461 _ => ancestor,
462 };
463 if let Some(ancestor) = &ancestor {
464 return Err(derived_constraint_alteration(table, name, ancestor));
465 }
466 let recreated_foreign_key = if enforceability == Some(true) {
467 match location {
468 ConstraintLocation::ColumnForeignKey(index) => columns[index]
469 .references
470 .as_ref()
471 .filter(|foreign_key| !foreign_key.enforced)
472 .map(|foreign_key| column_foreign_key(&columns[index], foreign_key)),
473 ConstraintLocation::TableForeignKey(index) => constraints
474 .foreign_keys
475 .get(index)
476 .filter(|foreign_key| !foreign_key.enforced)
477 .cloned(),
478 ConstraintLocation::NotNull(_)
479 | ConstraintLocation::ColumnCheck(_)
480 | ConstraintLocation::TableCheck(_)
481 | ConstraintLocation::Key(_)
482 | ConstraintLocation::ReferencedPartition(..) => None,
483 }
484 } else {
485 None
486 };
487 let mut validate_after_publish = false;
488 let mut changed = false;
489 match location {
490 ConstraintLocation::NotNull(index) => {
491 if let Some(no_inherit) = no_inherit {
492 changed = columns[index].not_null_no_inherit != no_inherit;
493 columns[index].not_null_no_inherit = no_inherit;
494 }
495 }
496 ConstraintLocation::ColumnForeignKey(index) => {
497 let effects =
498 crate::schema::inheritance::foreign_keys::DeclaredForeignKey::Column(index)
499 .alter_with_effects(columns, constraints, enforceability, deferrability);
500 changed = effects.changed;
501 validate_after_publish = effects.became_enforced;
502 }
503 ConstraintLocation::TableForeignKey(index) => {
504 let effects =
505 crate::schema::inheritance::foreign_keys::DeclaredForeignKey::Table(index)
506 .alter_with_effects(columns, constraints, enforceability, deferrability);
507 changed = effects.changed;
508 validate_after_publish = effects.became_enforced;
509 }
510 ConstraintLocation::ColumnCheck(_)
511 | ConstraintLocation::TableCheck(_)
512 | ConstraintLocation::Key(_)
513 | ConstraintLocation::ReferencedPartition(..) => {}
514 }
515 Ok(ConstraintAlterEffects {
516 recreated_foreign_key,
517 validate_after_publish,
518 changed,
519 })
520}