1use crate::ast::{
10 ColumnDef, ColumnType, GeneratedColumnKind, PartitionSpec, TableKeyConstraint,
11 TableKeyConstraintKind,
12};
13use crate::catalog::index::operator_classes::{
14 missing_operator_class, require_default_btree_operator_class,
15};
16use crate::schema::columns::POSTGRES_SYSTEM_COLUMNS;
17use crate::SQLError;
18
19pub fn missing_key_column(column: &str) -> SQLError {
21 SQLError::Routine {
22 sqlstate: "42703".into(),
23 message: format!("column \"{column}\" named in key does not exist"),
24 }
25}
26
27pub fn repeated_key_column(kind: TableKeyConstraintKind, column: &str) -> SQLError {
29 let constraint = match kind {
30 TableKeyConstraintKind::PrimaryKey => "primary key",
31 TableKeyConstraintKind::Unique => "unique",
32 };
33 SQLError::Routine {
34 sqlstate: "42701".into(),
35 message: format!("column \"{column}\" appears twice in {constraint} constraint"),
36 }
37}
38
39pub fn multiple_primary_keys(table: &str) -> SQLError {
41 SQLError::Routine {
42 sqlstate: "42P16".into(),
43 message: format!("multiple primary keys for table \"{table}\" are not allowed"),
44 }
45}
46
47pub fn validate_overlaps_column(column: &str, ty: Option<&ColumnType>) -> Result<(), SQLError> {
49 if matches!(ty, Some(ColumnType::Range(_) | ColumnType::Multirange(_))) {
50 return Ok(());
51 }
52 Err(SQLError::Routine {
53 sqlstate: "42804".into(),
54 message: format!(
55 "column \"{column}\" in WITHOUT OVERLAPS is not a range or multirange type"
56 ),
57 })
58}
59
60pub fn validate_overlaps_key_length(key: &TableKeyConstraint) -> Result<(), SQLError> {
62 if !key.without_overlaps || key.columns.len() >= 2 {
63 return Ok(());
64 }
65 Err(SQLError::Routine {
66 sqlstate: "42601".into(),
67 message: "constraint using WITHOUT OVERLAPS needs at least two columns".into(),
68 })
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum IndexOwner {
74 Key(TableKeyConstraintKind),
75 Index,
76}
77
78pub fn is_system_column(name: &str) -> bool {
80 POSTGRES_SYSTEM_COLUMNS.contains(&name)
81}
82
83pub fn resolve_system_key_attribute(name: &str, access_method: &str) -> Result<(), SQLError> {
85 let type_name = match name {
86 "xmin" | "xmax" => "xid",
87 "cmin" | "cmax" => "cid",
88 "ctid" => "tid",
89 _ => return Ok(()),
90 };
91 let ordered = match access_method {
92 "hash" => true,
93 "" | "btree" => type_name == "tid",
94 _ => false,
95 };
96 if ordered {
97 Ok(())
98 } else {
99 Err(missing_operator_class(
100 type_name,
101 if access_method.is_empty() {
102 "btree"
103 } else {
104 access_method
105 },
106 ))
107 }
108}
109
110pub fn validate_index_attribute(
112 columns: &[ColumnDef],
113 name: &str,
114 owner: IndexOwner,
115) -> Result<(), SQLError> {
116 let Some(column) = columns.iter().find(|column| column.name == name) else {
117 if is_system_column(name) {
118 return Err(system_column_index());
119 }
120 return Err(SQLError::Internal(format!(
121 "index attribute `{name}` is not a column"
122 )));
123 };
124 if column
125 .generated
126 .as_ref()
127 .is_some_and(|generated| generated.kind == GeneratedColumnKind::Virtual)
128 {
129 let message = match owner {
130 IndexOwner::Key(TableKeyConstraintKind::PrimaryKey) => {
131 "primary keys on virtual generated columns are not supported"
132 }
133 IndexOwner::Key(TableKeyConstraintKind::Unique) => {
134 "unique constraints on virtual generated columns are not supported"
135 }
136 IndexOwner::Index => "indexes on virtual generated columns are not supported",
137 };
138 return Err(SQLError::Routine {
139 sqlstate: "0A000".into(),
140 message: message.into(),
141 });
142 }
143 Ok(())
144}
145
146pub fn system_column_index() -> SQLError {
148 SQLError::Routine {
149 sqlstate: "0A000".into(),
150 message: "index creation on system columns is not supported".into(),
151 }
152}
153
154pub struct KeyRelation<'a> {
156 pub table: &'a str,
158 pub columns: &'a [ColumnDef],
159 pub partition: Option<&'a PartitionSpec>,
161 pub has_primary_key: bool,
163}
164
165pub fn validate_key_definition(
167 relation: &KeyRelation<'_>,
168 key: &TableKeyConstraint,
169) -> Result<(), SQLError> {
170 validate_definition(relation, key, false)
171}
172
173pub fn validate_added_key_definition(
175 relation: &KeyRelation<'_>,
176 key: &TableKeyConstraint,
177) -> Result<(), SQLError> {
178 validate_definition(relation, key, true)
179}
180
181fn validate_definition(
182 relation: &KeyRelation<'_>,
183 key: &TableKeyConstraint,
184 require_not_null: bool,
185) -> Result<(), SQLError> {
186 let declared = |name: &str| relation.columns.iter().any(|column| column.name == name);
187 let access_method = if key.without_overlaps {
188 "gist"
189 } else {
190 "btree"
191 };
192 for name in &key.columns {
193 if let Some(column) = relation.columns.iter().find(|column| column.name == *name) {
194 if access_method == "btree" {
195 require_default_btree_operator_class(&column.ty)?;
196 }
197 continue;
198 }
199 if !is_system_column(name) {
200 return Err(missing_key_column(name));
201 }
202 resolve_system_key_attribute(name, access_method)?;
203 }
204 if let Some(name) = key
205 .included_columns
206 .iter()
207 .find(|name| !declared(name) && !is_system_column(name))
208 {
209 return Err(missing_key_column(name));
210 }
211 if key.kind == TableKeyConstraintKind::PrimaryKey && relation.has_primary_key {
212 let local = uqa_core::RelationIdentity::from_legacy_name(relation.table)
213 .map_err(SQLError::Internal)?;
214 return Err(multiple_primary_keys(&local.name));
215 }
216 if require_not_null && key.kind == TableKeyConstraintKind::PrimaryKey {
217 for name in &key.columns {
218 if relation
219 .columns
220 .iter()
221 .any(|column| column.name == *name && !column.not_null)
222 {
223 return Err(SQLError::Routine {
224 sqlstate: "42P16".into(),
225 message: format!("primary key column \"{name}\" is not marked NOT NULL"),
226 });
227 }
228 }
229 }
230 if let Some(partition) = relation.partition {
231 crate::schema::indexes::unique::validate_partitioned_key_constraint(
232 relation.table,
233 key,
234 partition,
235 )?;
236 }
237 for name in key.columns.iter().chain(&key.included_columns) {
238 validate_index_attribute(relation.columns, name, IndexOwner::Key(key.kind))?;
239 }
240 Ok(())
241}
242
243pub struct KeyPartition<'a> {
245 pub table: &'a str,
246 pub partition: Option<&'a PartitionSpec>,
248 pub keys: &'a [TableKeyConstraint],
250}
251
252#[derive(Debug, Clone, Copy, PartialEq, Eq)]
254pub enum PartitionKeyIndex {
255 Adopted,
257 Created,
259}
260
261pub fn define_partition_key(
263 partition: &KeyPartition<'_>,
264 key: &TableKeyConstraint,
265) -> Result<PartitionKeyIndex, SQLError> {
266 if partition
267 .keys
268 .iter()
269 .any(|existing| crate::schema::inheritance::alter::key_equivalent(existing, key))
270 {
271 return Ok(PartitionKeyIndex::Adopted);
272 }
273 if key.kind == TableKeyConstraintKind::PrimaryKey
274 && partition
275 .keys
276 .iter()
277 .any(|existing| existing.kind == TableKeyConstraintKind::PrimaryKey)
278 {
279 let local = uqa_core::RelationIdentity::from_legacy_name(partition.table)
280 .map_err(SQLError::Internal)?;
281 return Err(multiple_primary_keys(&local.name));
282 }
283 if let Some(spec) = partition.partition {
284 crate::schema::indexes::unique::validate_partitioned_key_constraint(
285 partition.table,
286 key,
287 spec,
288 )?;
289 }
290 Ok(PartitionKeyIndex::Created)
291}
292
293pub fn index_order(mut keys: Vec<TableKeyConstraint>) -> Vec<TableKeyConstraint> {
295 let mut ordered = Vec::with_capacity(keys.len());
296 if let Some(position) = keys
297 .iter()
298 .position(|key| key.kind == TableKeyConstraintKind::PrimaryKey)
299 {
300 ordered.push(keys.remove(position));
301 }
302 for key in keys {
303 match ordered
304 .iter_mut()
305 .find(|prior: &&mut TableKeyConstraint| same_index(prior, &key))
306 {
307 Some(prior) => {
308 if prior.name.is_none() {
309 prior.name = key.name;
310 }
311 }
312 None => ordered.push(key),
313 }
314 }
315 ordered
316}
317
318fn same_index(left: &TableKeyConstraint, right: &TableKeyConstraint) -> bool {
320 left.columns == right.columns
321 && left.included_columns == right.included_columns
322 && left.nulls_not_distinct == right.nulls_not_distinct
323 && left.without_overlaps == right.without_overlaps
324}