Skip to main content

uqa_engine/
catalog_indexes.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7use super::{
8    CatalogIndexRow, Engine, RelationIdentity, SQLError, StorageBackendError, StorageBackendResult,
9};
10
11mod definition;
12pub(crate) use definition::{index_definition, IndexDefinition};
13
14/// The catalog row of an index with its keys, options and definition serialized as the registry stores them.
15fn catalog_index_row(
16    relation: &RelationIdentity,
17    index_type: &str,
18    table: &str,
19    columns: &[uqa_sql::ast::IndexKey],
20    options: &[(String, String)],
21    definition: &IndexDefinition,
22) -> StorageBackendResult<CatalogIndexRow> {
23    let options: std::collections::BTreeMap<String, String> = options.iter().cloned().collect();
24    Ok(CatalogIndexRow {
25        relation: relation.clone(),
26        index_type: index_type.to_string(),
27        table_name: table.to_string(),
28        columns_json: serde_json::to_string(columns).map_err(StorageBackendError::from)?,
29        parameters_json: serde_json::to_string(&options).map_err(StorageBackendError::from)?,
30        definition_json: Some(serde_json::to_string(definition)?),
31    })
32}
33
34impl Engine {
35    pub fn register_catalog_index(
36        &self,
37        name: &str,
38        index_type: &str,
39        table: &str,
40        columns: &[String],
41        options: &[(String, String)],
42    ) -> StorageBackendResult<()> {
43        self.try_register_catalog_index(name, index_type, table, columns, options)
44    }
45
46    pub(crate) fn try_register_catalog_index(
47        &self,
48        name: &str,
49        index_type: &str,
50        table: &str,
51        columns: &[String],
52        options: &[(String, String)],
53    ) -> StorageBackendResult<()> {
54        self.register_catalog_index_definition(
55            name,
56            index_type,
57            table,
58            &columns
59                .iter()
60                .cloned()
61                .map(uqa_sql::ast::IndexKey::Column)
62                .collect::<Vec<_>>(),
63            options,
64            &IndexDefinition::default(),
65        )
66    }
67
68    pub(crate) fn register_catalog_index_definition(
69        &self,
70        name: &str,
71        index_type: &str,
72        table: &str,
73        columns: &[uqa_sql::ast::IndexKey],
74        options: &[(String, String)],
75        definition: &IndexDefinition,
76    ) -> StorageBackendResult<()> {
77        self.with_implicit_storage_definition_transaction(|engine| {
78            engine.try_register_catalog_index_inner(
79                name, index_type, table, columns, options, definition,
80            )
81        })
82    }
83
84    fn try_register_catalog_index_inner(
85        &self,
86        name: &str,
87        index_type: &str,
88        table: &str,
89        columns: &[uqa_sql::ast::IndexKey],
90        options: &[(String, String)],
91        definition: &IndexDefinition,
92    ) -> StorageBackendResult<()> {
93        self.synchronize_catalog_registries()?;
94        let (relation, table_relation) =
95            uqa_execution::schema::indexes::registry::binding::registration(
96                &self.index_registry_context(),
97                name,
98                table,
99            )?;
100        let table = table_relation.qualified_name();
101        if let crate::capabilities::RelationResolution::Found(_, kind) = self
102            .resolve_bound_relation_kind(&relation.qualified_name())
103            .map_err(|error| StorageBackendError::Other(error.to_string()))?
104        {
105            if kind != "index" {
106                return Err(StorageBackendError::Other(format!(
107                    "relation `{}` already exists as a {kind}",
108                    relation.qualified_name()
109                )));
110            }
111        }
112        let definition = uqa_execution::schema::indexes::registration::prepare(
113            self.catalog_identity_reservation_context(),
114            &relation,
115            &table_relation,
116            definition,
117        )
118        .map_err(|error| StorageBackendError::backend("index catalog identity", error))?;
119        uqa_execution::schema::indexes::registry::lifecycle::register(
120            &self.index_registry_context(),
121            catalog_index_row(&relation, index_type, &table, columns, options, &definition)?,
122        )
123    }
124
125    /// The indexes that registering this index would create on the partitions below `table`, as partition and index name.
126    pub(crate) fn planned_catalog_partition_indexes(
127        &self,
128        name: &str,
129        index_type: &str,
130        table: &str,
131        columns: &[uqa_sql::ast::IndexKey],
132        options: &[(String, String)],
133        definition: &IndexDefinition,
134    ) -> StorageBackendResult<std::collections::BTreeMap<String, String>> {
135        self.synchronize_catalog_registries()?;
136        let relation =
137            RelationIdentity::from_legacy_name(name).map_err(StorageBackendError::Other)?;
138        uqa_execution::schema::indexes::registry::lifecycle::planned_partition_indexes(
139            &self.index_registry_context(),
140            catalog_index_row(&relation, index_type, table, columns, options, definition)?,
141        )
142    }
143
144    pub fn drop_catalog_index(&self, name: &str) -> StorageBackendResult<Option<CatalogIndexRow>> {
145        self.try_drop_catalog_index(name)
146    }
147
148    pub(crate) fn try_drop_catalog_index(
149        &self,
150        name: &str,
151    ) -> StorageBackendResult<Option<CatalogIndexRow>> {
152        self.with_implicit_storage_definition_transaction(|engine| {
153            let Some(relation) = engine.try_resolve_catalog_index_relation(name)? else {
154                return Ok(None);
155            };
156            uqa_execution::schema::indexes::registry::binding::removal(
157                &engine.index_registry_context(),
158                &relation,
159            )?;
160            engine.try_drop_catalog_index_inner(&relation, false)
161        })
162    }
163
164    pub(crate) fn try_drop_catalog_index_relation(
165        &self,
166        relation: &RelationIdentity,
167    ) -> StorageBackendResult<Option<CatalogIndexRow>> {
168        self.with_implicit_storage_definition_transaction(|engine| {
169            engine.try_drop_catalog_index_inner(relation, true)
170        })
171    }
172
173    fn try_drop_catalog_index_inner(
174        &self,
175        relation: &RelationIdentity,
176        cascade: bool,
177    ) -> StorageBackendResult<Option<CatalogIndexRow>> {
178        self.synchronize_catalog_registries()?;
179        uqa_execution::schema::indexes::registry::lifecycle::remove(
180            &self.index_registry_context(),
181            relation,
182            cascade,
183        )
184    }
185
186    pub fn catalog_index(&self, name: &str) -> StorageBackendResult<Option<CatalogIndexRow>> {
187        self.with_catalog_read_snapshot(|engine| engine.catalog_index_in_execution(name))
188    }
189
190    pub(crate) fn catalog_index_in_execution(
191        &self,
192        name: &str,
193    ) -> StorageBackendResult<Option<CatalogIndexRow>> {
194        let Some(relation) = self.try_resolve_catalog_index_relation(name)? else {
195            return Ok(None);
196        };
197        self.bound_catalog_index(&relation.qualified_name())
198    }
199
200    pub fn has_catalog_index(&self, name: &str) -> StorageBackendResult<bool> {
201        self.with_catalog_read_snapshot(|engine| {
202            Ok(engine.try_resolve_catalog_index_relation(name)?.is_some())
203        })
204    }
205
206    pub(crate) fn try_resolve_catalog_index_relation(
207        &self,
208        name: &str,
209    ) -> StorageBackendResult<Option<RelationIdentity>> {
210        self.synchronize_catalog_registries()?;
211        let candidates = self.relation_lookup_candidates(name)?;
212        let indexes = self.durable.catalog_indexes.read();
213        Ok(candidates.into_iter().find(|candidate| {
214            indexes.contains_key(candidate)
215                || self
216                    .query_catalog_snapshot
217                    .as_ref()
218                    .is_some_and(|snapshot| snapshot.read_view.has_constraint_index(candidate))
219        }))
220    }
221
222    pub(crate) fn bound_catalog_index(
223        &self,
224        canonical_name: &str,
225    ) -> StorageBackendResult<Option<CatalogIndexRow>> {
226        self.synchronize_catalog_registries()?;
227        let (schema, name) = RelationIdentity::parse_reference(canonical_name)
228            .map_err(StorageBackendError::Other)?;
229        let schema = schema.ok_or_else(|| {
230            StorageBackendError::Other(format!(
231                "bound index identity `{canonical_name}` is not schema-qualified"
232            ))
233        })?;
234        let relation = RelationIdentity::new(schema, name);
235        if let Some(index) = self.durable.catalog_indexes.read().get(&relation).cloned() {
236            return Ok(Some(index));
237        }
238        // Current constraint indexes already belong to the registry above; only a retained query can have an earlier row absent from it.
239        self.query_catalog_snapshot
240            .as_ref()
241            .map_or(Ok(None), |snapshot| {
242                snapshot
243                    .read_view
244                    .constraint_index(&relation)
245                    .map_err(|error| StorageBackendError::Other(error.to_string()))
246            })
247    }
248
249    /// An index has no independent owner: `PostgreSQL` derives its owner from the indexed table and additionally permits the containing schema's owner to drop it.
250    pub(crate) fn require_index_drop_authority(
251        &self,
252        index: &CatalogIndexRow,
253    ) -> Result<(), SQLError> {
254        let table = RelationIdentity::from_legacy_name(&index.table_name)
255            .map_err(|error| SQLError::Internal(format!("resolve indexed table: {error}")))?;
256        let table_owner = self
257            .storage
258            .tables
259            .read()
260            .get(&table)
261            .cloned()
262            .ok_or_else(|| {
263                SQLError::Internal(format!(
264                    "index `{}` references missing table `{}`",
265                    index.relation.qualified_name(),
266                    index.table_name
267                ))
268            })?
269            .role_owner();
270        if self.current_user_has_role_privileges(&table_owner)
271            || self
272                .schema_security_for_privilege(&index.relation.schema)
273                .is_some_and(|schema| self.current_user_has_role_privileges(&schema.role_owner))
274        {
275            return Ok(());
276        }
277        Err(SQLError::Routine {
278            sqlstate: "42501".into(),
279            message: format!("must be owner of index {}", index.relation.name),
280        })
281    }
282}