Skip to main content

uqa_execution/catalog/
read.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Immutable statement catalog snapshots and relation-name resolution.
8
9mod indexes;
10mod privileges;
11
12#[cfg(test)]
13mod tests;
14
15use std::{
16    collections::{BTreeMap, BTreeSet},
17    sync::Arc,
18};
19use uqa_sql::catalog::roles::identity::RoleSubject;
20use uqa_sql::catalog::roles::RoleReference;
21
22use uqa_sql::SQLError;
23
24use super::{
25    CatalogReadView, CatalogSequenceSnapshot, CatalogTableSnapshot, RelationNameResolution,
26    RelationResolution,
27};
28
29impl CatalogReadView {
30    fn relation_names(&self) -> super::relation_names::RelationNameCatalog<'_> {
31        super::relation_names::RelationNameCatalog::new(
32            &self.snapshot.tables,
33            &self.snapshot.definitions,
34        )
35    }
36
37    fn relation_lookup_candidates(
38        &self,
39        resolution: &RelationNameResolution,
40        name: &str,
41    ) -> Result<Vec<uqa_core::RelationIdentity>, SQLError> {
42        self.relation_names()
43            .relation_lookup_candidates(resolution, name)
44    }
45
46    fn relation_exists(&self, relation: &uqa_core::RelationIdentity) -> bool {
47        uqa_sql::catalog::SystemRelation::at(&relation.schema, &relation.name).is_some()
48            || self.snapshot.tables.contains_key(relation)
49            || self.snapshot.definitions.views.contains_key(relation)
50            || self.snapshot.definitions.sequences.contains_key(relation)
51            || self
52                .snapshot
53                .definitions
54                .foreign_tables
55                .contains_key(relation)
56            || self
57                .snapshot
58                .definitions
59                .catalog_indexes
60                .contains_key(relation)
61            || self.has_constraint_index(relation)
62    }
63
64    pub fn relation_kind_resolution(
65        &self,
66        resolution: &RelationNameResolution,
67        name: &str,
68    ) -> Result<RelationResolution, SQLError> {
69        self.relation_names()
70            .relation_kind_resolution(resolution, name)
71    }
72
73    pub fn virtual_relation_resolved(
74        &self,
75        resolution: &RelationNameResolution,
76        name: &str,
77    ) -> Result<Option<uqa_sql::catalog::VirtualRelation>, SQLError> {
78        for relation in self.relation_lookup_candidates(resolution, name)? {
79            if let Some(relation) =
80                uqa_sql::catalog::VirtualRelation::at(&relation.schema, &relation.name)
81            {
82                return Ok(Some(relation));
83            }
84            if self.relation_exists(&relation) {
85                return Ok(None);
86            }
87        }
88        Ok(None)
89    }
90
91    pub fn all_schema_names(&self) -> Vec<String> {
92        let mut schemas = vec![
93            "pg_catalog".to_string(),
94            "information_schema".to_string(),
95            "ag_catalog".to_string(),
96        ];
97        schemas.extend(self.snapshot.definitions.schemas.keys().cloned());
98        schemas.extend(self.snapshot.definitions.graphs.keys().cloned());
99        if let Some(temporary) = &self.snapshot.temporary_namespace {
100            schemas.push(temporary.schema.clone());
101            schemas.push(temporary.toast_schema());
102        }
103        schemas.sort();
104        schemas.dedup();
105        schemas
106    }
107
108    pub fn schema_security(
109        &self,
110        name: &str,
111    ) -> Option<&crate::catalog::security::BoundSchemaSecurity> {
112        self.snapshot.definitions.schemas.get(name)
113    }
114
115    pub fn schema_security_names(
116        &self,
117        name: &str,
118    ) -> Result<Option<crate::catalog::security::SchemaSecurity>, SQLError> {
119        self.schema_security(name)
120            .map(|security| {
121                security
122                    .resolve(&self.snapshot.definitions.roles)
123                    .map_err(SQLError::Internal)
124            })
125            .transpose()
126    }
127
128    pub fn database_security(&self) -> &crate::catalog::security::BoundDatabaseSecurity {
129        &self.snapshot.definitions.database_security
130    }
131
132    pub fn database_security_names(
133        &self,
134    ) -> Result<crate::catalog::security::DatabaseSecurity, SQLError> {
135        self.database_security()
136            .resolve(&self.snapshot.definitions.roles)
137            .map_err(SQLError::Internal)
138    }
139
140    pub fn has_schema(&self, name: &str) -> bool {
141        self.snapshot.definitions.schemas.contains_key(name)
142    }
143
144    pub fn table_names(&self) -> Vec<String> {
145        self.snapshot
146            .tables
147            .keys()
148            .map(uqa_core::RelationIdentity::qualified_name)
149            .collect()
150    }
151
152    pub fn roles(&self) -> impl Iterator<Item = &uqa_sql::catalog::roles::RoleDefinition> {
153        self.snapshot.definitions.roles.values()
154    }
155
156    pub fn relation_security_names(
157        &self,
158        security: &crate::catalog::security::BoundTableSecurity,
159    ) -> Result<crate::catalog::security::TableSecurity, SQLError> {
160        security
161            .resolve(&self.snapshot.definitions.roles)
162            .map_err(SQLError::Internal)
163    }
164
165    pub fn view_owner(
166        &self,
167        view: &crate::catalog::view::StoredView,
168    ) -> Result<RoleReference, SQLError> {
169        view.security
170            .owner_reference(&self.snapshot.definitions.roles)
171    }
172
173    pub fn bind_role(&self, name: &str) -> Result<RoleReference, SQLError> {
174        RoleReference::from(name)
175            .bind(&self.snapshot.definitions.roles)
176            .map(|role| RoleReference::Bound(Arc::new(role)))
177    }
178
179    pub fn role_oid(&self, name: &str) -> Result<i64, SQLError> {
180        self.snapshot
181            .definitions
182            .roles
183            .get(name)
184            .map(|role| role.oid)
185            .ok_or_else(|| SQLError::Internal(format!("catalog references missing role `{name}`")))
186    }
187
188    pub fn role_memberships(
189        &self,
190    ) -> impl Iterator<Item = &uqa_sql::catalog::roles::RoleMembership> {
191        self.snapshot.definitions.role_memberships.values()
192    }
193
194    /// The OIDs the graph recorded when it and its labels were created; `None` for a graph created before OIDs were recorded.
195    pub fn graph_catalog_oids(
196        &self,
197        graph: &str,
198    ) -> Option<&uqa_sql::catalog::graph_oids::GraphCatalogOids> {
199        self.snapshot.definitions.graph_catalog_oids.get(graph)
200    }
201
202    /// The `pg_class` OID of the sequence with the object identity.
203    pub fn sequence_catalog_oid(&self, object_id: &[u8; 16]) -> i64 {
204        super::sequence::catalog_oids::sequence_catalog_oid(
205            &self.snapshot.definitions.sequence_catalog_oids,
206            object_id,
207        )
208    }
209
210    pub fn sequences(&self) -> Result<Vec<super::CatalogSequenceMetadata>, SQLError> {
211        self.snapshot
212            .definitions
213            .sequences
214            .keys()
215            .map(|identity| {
216                Ok((
217                    identity.qualified_name(),
218                    self.snapshot
219                        .definitions
220                        .sequence_persistence
221                        .get(identity)
222                        .copied()
223                        .unwrap_or_default(),
224                    self.snapshot
225                        .definitions
226                        .sequence_object_ids
227                        .get(identity)
228                        .copied()
229                        .unwrap_or_default(),
230                    self.sequence_security(identity)?,
231                ))
232            })
233            .collect()
234    }
235
236    /// Sequence definitions with their persistence and security, for readers that show no value state.
237    pub fn sequence_definitions(
238        &self,
239    ) -> Result<
240        Vec<(
241            uqa_core::RelationIdentity,
242            crate::catalog::sequence::SequenceState,
243            uqa_sql::ast::RelationPersistence,
244            crate::catalog::security::SequenceSecurity,
245        )>,
246        SQLError,
247    > {
248        self.snapshot
249            .definitions
250            .sequences
251            .iter()
252            .map(|(identity, state)| {
253                Ok((
254                    identity.clone(),
255                    *state,
256                    self.snapshot
257                        .definitions
258                        .sequence_persistence
259                        .get(identity)
260                        .copied()
261                        .unwrap_or_default(),
262                    self.sequence_security(identity)?,
263                ))
264            })
265            .collect()
266    }
267
268    /// Sequence definitions with their persistence and security, each with the value state its latest committed value record holds, at the exact position a shared position records.
269    pub fn sequence_states(
270        &self,
271    ) -> Result<
272        Vec<(
273            uqa_core::RelationIdentity,
274            crate::catalog::sequence::SequenceState,
275            uqa_sql::ast::RelationPersistence,
276            crate::catalog::security::SequenceSecurity,
277        )>,
278        SQLError,
279    > {
280        let positions = match self.sequence_positions.as_ref() {
281            Some(positions) => positions.sequence_positions()?,
282            None => std::collections::HashMap::new(),
283        };
284        let records = self.latest_sequence_records()?;
285        let object_ids = &self.snapshot.definitions.sequence_object_ids;
286        Ok(self
287            .sequence_definitions()?
288            .into_iter()
289            .map(|(identity, state, persistence, security)| {
290                let key = object_ids
291                    .get(&identity)
292                    .map(|object_id| state.position_key(*object_id));
293                let state = state
294                    .with_record(key.and_then(|key| records.get(&key)))
295                    .at_position(key.and_then(|key| positions.get(&key)).copied());
296                (identity, state, persistence, security)
297            })
298            .collect())
299    }
300
301    /// The state of one sequence with the value state of its latest committed value record, at the exact position a shared position records.
302    fn sequence_state_at_position(
303        &self,
304        relation: &uqa_core::RelationIdentity,
305        state: crate::catalog::sequence::SequenceState,
306    ) -> Result<crate::catalog::sequence::SequenceState, SQLError> {
307        let Some(object_id) = self.snapshot.definitions.sequence_object_ids.get(relation) else {
308            return Ok(state);
309        };
310        let key = state.position_key(*object_id);
311        let state = state.with_record(self.latest_sequence_records()?.get(&key));
312        let Some(positions) = self.sequence_positions.as_ref() else {
313            return Ok(state);
314        };
315        Ok(state.at_position(positions.sequence_position(key)?))
316    }
317
318    /// The committed value records of sequences, which a session's catalog cache does not follow. A sequence this transaction created, and a temporary one, has none, and keeps the state the cache holds.
319    fn latest_sequence_records(
320        &self,
321    ) -> Result<
322        std::collections::HashMap<
323            crate::row_locks::SequencePositionKey,
324            uqa_storage::SequenceValuePosition,
325        >,
326        SQLError,
327    > {
328        self.latest_sequence_values.as_ref().map_or_else(
329            || Ok(std::collections::HashMap::new()),
330            |values| {
331                values.latest_sequence_values().map_err(|error| {
332                    uqa_sql::catalog::errors::storage_error("read sequence values", &error)
333                })
334            },
335        )
336    }
337
338    fn sequence_security(
339        &self,
340        relation: &uqa_core::RelationIdentity,
341    ) -> Result<crate::catalog::security::SequenceSecurity, SQLError> {
342        self.snapshot
343            .definitions
344            .sequence_security
345            .get(relation)
346            .ok_or_else(|| {
347                SQLError::Internal(format!(
348                    "sequence `{}` has no security metadata",
349                    relation.qualified_name()
350                ))
351            })?
352            .resolve(&self.snapshot.definitions.roles)
353            .map_err(SQLError::Internal)
354    }
355
356    pub fn sequence_is_visible_to(
357        &self,
358        security: &crate::catalog::security::SequenceSecurity,
359        role: &(impl RoleSubject + ?Sized),
360    ) -> bool {
361        crate::catalog::security::sequence::role_can_view_sequence(
362            security,
363            role,
364            &self.snapshot.definitions.roles,
365            &self.snapshot.definitions.role_memberships,
366        )
367    }
368
369    pub fn sequence_is_selectable_to(
370        &self,
371        security: &crate::catalog::security::SequenceSecurity,
372        role: &(impl RoleSubject + ?Sized),
373    ) -> bool {
374        crate::catalog::security::sequence::role_can_select_sequence(
375            security,
376            role,
377            &self.snapshot.definitions.roles,
378            &self.snapshot.definitions.role_memberships,
379        )
380    }
381
382    pub fn sequence_value_is_readable_to(
383        &self,
384        security: &crate::catalog::security::SequenceSecurity,
385        role: &(impl RoleSubject + ?Sized),
386    ) -> bool {
387        crate::catalog::security::sequence::role_can_read_sequence_value(
388            security,
389            role,
390            &self.snapshot.definitions.roles,
391            &self.snapshot.definitions.role_memberships,
392        )
393    }
394
395    pub fn sequence_resolved(
396        &self,
397        resolution: &RelationNameResolution,
398        name: &str,
399    ) -> Result<Option<CatalogSequenceSnapshot>, SQLError> {
400        for relation in self.relation_lookup_candidates(resolution, name)? {
401            if let Some(state) = self.snapshot.definitions.sequences.get(&relation) {
402                return Ok(Some(CatalogSequenceSnapshot {
403                    state: self.sequence_state_at_position(&relation, *state)?,
404                    security: self.sequence_security(&relation)?,
405                    relation,
406                }));
407            }
408            if self.relation_exists(&relation) {
409                return Ok(None);
410            }
411        }
412        Ok(None)
413    }
414
415    pub fn schema_has_privilege_to(
416        &self,
417        schema: &str,
418        role: &(impl RoleSubject + ?Sized),
419        privilege: crate::catalog::security::schema::SchemaAclPrivilege,
420    ) -> bool {
421        let toast_security;
422        let security = match self.snapshot.definitions.schemas.get(schema) {
423            Some(security) => security,
424            None => match self.snapshot.temporary_namespace.as_ref() {
425                // `InitTempTableNamespace` creates the TOAST namespace for the bootstrap superuser with no ACL, so only its privileges reach it.
426                Some(temporary) if schema == temporary.toast_schema() => {
427                    toast_security =
428                        crate::catalog::security::BoundSchemaSecurity::bootstrap_with_oid(
429                            schema,
430                            temporary.oids.toast_namespace,
431                        );
432                    &toast_security
433                }
434                _ => return true,
435            },
436        };
437        security
438            .resolve(&self.snapshot.definitions.roles)
439            .is_ok_and(|security| {
440                crate::catalog::security::schema::role_has_schema_privilege(
441                    &security,
442                    role,
443                    privilege,
444                    &self.snapshot.definitions.roles,
445                    &self.snapshot.definitions.role_memberships,
446                )
447            })
448    }
449
450    pub fn views_of_kind(
451        &self,
452        kind: crate::catalog::view::StoredViewKind,
453    ) -> Vec<(String, crate::catalog::view::StoredView)> {
454        self.snapshot
455            .definitions
456            .views
457            .iter()
458            .filter(|(_, view)| view.kind == kind)
459            .map(|(identity, view)| (identity.qualified_name(), view.clone()))
460            .collect()
461    }
462
463    pub fn foreign_table_names(&self) -> Vec<String> {
464        self.snapshot
465            .definitions
466            .foreign_tables
467            .keys()
468            .map(uqa_core::RelationIdentity::qualified_name)
469            .collect()
470    }
471
472    pub fn foreign_tables(&self) -> Vec<(String, crate::catalog::foreign::StoredForeignTable)> {
473        self.snapshot
474            .definitions
475            .foreign_tables
476            .iter()
477            .map(|(identity, table)| (identity.qualified_name(), table.clone()))
478            .collect()
479    }
480
481    pub fn foreign_table_security(
482        &self,
483        name: &str,
484    ) -> Result<crate::catalog::security::TableSecurity, SQLError> {
485        let relation = uqa_core::RelationIdentity::from_legacy_name(name).map_err(|error| {
486            SQLError::Internal(format!("resolve catalog foreign table `{name}`: {error}"))
487        })?;
488        self.snapshot
489            .definitions
490            .foreign_table_security
491            .get(&relation)
492            .ok_or_else(|| {
493                SQLError::Internal(format!(
494                    "catalog foreign table `{name}` has no security metadata"
495                ))
496            })?
497            .resolve(&self.snapshot.definitions.roles)
498            .map_err(SQLError::Internal)
499    }
500
501    pub fn catalog_indexes(&self) -> impl Iterator<Item = &uqa_storage::CatalogIndexRow> {
502        self.snapshot.definitions.catalog_indexes.values()
503    }
504
505    pub fn triggers(&self) -> Vec<uqa_sql::catalog::events::StoredTrigger> {
506        self.snapshot
507            .definitions
508            .triggers
509            .values()
510            .flat_map(|triggers| triggers.values().cloned())
511            .collect()
512    }
513
514    pub fn rules(&self) -> Vec<uqa_sql::catalog::events::StoredRule> {
515        self.snapshot
516            .definitions
517            .rules
518            .values()
519            .flat_map(|rules| rules.values().cloned())
520            .collect()
521    }
522
523    /// Share the captured domain allocation with static signature analysis.
524    pub fn domain_snapshot(&self) -> Arc<BTreeMap<String, uqa_sql::catalog::domain::StoredDomain>> {
525        self.snapshot.definitions.domains.clone()
526    }
527
528    pub fn domains(&self) -> impl Iterator<Item = &uqa_sql::catalog::domain::StoredDomain> {
529        self.snapshot.definitions.domains.values()
530    }
531
532    pub fn enums(&self) -> impl Iterator<Item = &uqa_sql::catalog::enum_type::StoredEnum> {
533        self.snapshot.definitions.enums.values()
534    }
535
536    pub fn composites(
537        &self,
538    ) -> impl Iterator<Item = &uqa_sql::catalog::composite_type::StoredComposite> {
539        self.snapshot.definitions.composites.values()
540    }
541
542    /// Resolve a standalone composite type by its type OID or by the OID of its generated array type.
543    pub fn composite_by_type_oid(
544        &self,
545        oid: u32,
546    ) -> Option<&uqa_sql::catalog::composite_type::StoredComposite> {
547        self.composites()
548            .find(|definition| definition.oid == oid || definition.array_oid == oid)
549    }
550
551    /// Resolve an enum by its type OID or by the OID of its generated array type.
552    pub fn enum_by_type_oid(&self, oid: u32) -> Option<&uqa_sql::catalog::enum_type::StoredEnum> {
553        self.enums()
554            .find(|definition| definition.oid == oid || definition.array_oid == oid)
555    }
556
557    pub fn sql_functions(
558        &self,
559        resolution: &RelationNameResolution,
560        name: &str,
561    ) -> Result<Option<Vec<std::sync::Arc<uqa_sql::routines::SQLUserFunction>>>, SQLError> {
562        let (schema, local_name) =
563            uqa_core::RelationIdentity::parse_reference(name).map_err(|error| {
564                SQLError::Routine {
565                    sqlstate: "42602".into(),
566                    message: format!("invalid routine name `{name}`: {error}"),
567                }
568            })?;
569        let keys = schema.map_or_else(
570            || {
571                resolution
572                    .search_path
573                    .iter()
574                    .map(|schema| {
575                        uqa_core::RelationIdentity::new(schema, &local_name).qualified_name()
576                    })
577                    .collect::<Vec<_>>()
578            },
579            |schema| vec![uqa_core::RelationIdentity::new(schema, &local_name).qualified_name()],
580        );
581        let mut visible = Vec::new();
582        let mut seen = BTreeSet::new();
583        for key in keys {
584            let Some(overloads) = self.snapshot.definitions.sql_user_functions.get(&key) else {
585                continue;
586            };
587            for function in overloads {
588                let identity = (
589                    uqa_sql::routines::routine_signature_types(&function.def),
590                    function.def.is_procedure,
591                );
592                if seen.insert(identity) {
593                    visible.push(function.clone());
594                }
595            }
596        }
597        Ok((!visible.is_empty()).then_some(visible))
598    }
599
600    pub fn all_sql_functions(&self) -> Vec<std::sync::Arc<uqa_sql::routines::SQLUserFunction>> {
601        self.snapshot
602            .definitions
603            .sql_user_functions
604            .values()
605            .flat_map(|functions| functions.iter().cloned())
606            .collect()
607    }
608
609    pub fn table(
610        &self,
611        resolution: &RelationNameResolution,
612        name: &str,
613    ) -> Result<Option<&CatalogTableSnapshot>, SQLError> {
614        self.table_resolved(resolution, name)
615    }
616
617    pub fn table_resolved(
618        &self,
619        resolution: &RelationNameResolution,
620        name: &str,
621    ) -> Result<Option<&CatalogTableSnapshot>, SQLError> {
622        for relation in self.relation_lookup_candidates(resolution, name)? {
623            if let Some(table) = self.snapshot.tables.get(&relation) {
624                return Ok(Some(table));
625            }
626            if self.relation_exists(&relation) {
627                return Ok(None);
628            }
629        }
630        Ok(None)
631    }
632
633    pub fn table_name(
634        &self,
635        resolution: &RelationNameResolution,
636        name: &str,
637    ) -> Result<Option<String>, SQLError> {
638        self.table_name_resolved(resolution, name)
639    }
640
641    pub fn table_name_resolved(
642        &self,
643        resolution: &RelationNameResolution,
644        name: &str,
645    ) -> Result<Option<String>, SQLError> {
646        for relation in self.relation_lookup_candidates(resolution, name)? {
647            if self.snapshot.tables.contains_key(&relation) {
648                return Ok(Some(relation.qualified_name()));
649            }
650            if self.relation_exists(&relation) {
651                return Ok(None);
652            }
653        }
654        Ok(None)
655    }
656
657    pub fn hierarchy_scan_tables(
658        &self,
659        resolution: &RelationNameResolution,
660        name: &str,
661        include_descendants: bool,
662    ) -> Result<Vec<String>, SQLError> {
663        let root = self
664            .relation_lookup_candidates(resolution, name)?
665            .into_iter()
666            .find(|relation| self.snapshot.tables.contains_key(relation))
667            .ok_or_else(|| SQLError::UnknownTable(name.to_string()))?;
668        if !include_descendants {
669            return Ok(vec![root.qualified_name()]);
670        }
671        let mut output = Vec::new();
672        let mut visiting = BTreeSet::new();
673        let mut visited = BTreeSet::new();
674        self.collect_hierarchy_descendants(&root, &mut visiting, &mut visited, &mut output)?;
675        Ok(output)
676    }
677
678    pub fn direct_hierarchy_children(
679        &self,
680        resolution: &RelationNameResolution,
681        name: &str,
682    ) -> Result<Vec<String>, SQLError> {
683        let parent = self
684            .table_name(resolution, name)?
685            .ok_or_else(|| SQLError::UnknownTable(name.to_string()))?;
686        Ok(self
687            .snapshot
688            .tables
689            .iter()
690            .filter(|(_, table)| table.hierarchy.parents.iter().any(|item| item == &parent))
691            .map(|(identity, _)| identity.qualified_name())
692            .collect())
693    }
694
695    pub fn table_has_rules(
696        &self,
697        resolution: &RelationNameResolution,
698        name: &str,
699    ) -> Result<bool, SQLError> {
700        let relation = self
701            .relation_lookup_candidates(resolution, name)?
702            .into_iter()
703            .find(|relation| self.snapshot.tables.contains_key(relation))
704            .ok_or_else(|| SQLError::UnknownTable(name.to_string()))?;
705        Ok(self
706            .snapshot
707            .definitions
708            .rules
709            .get(&relation)
710            .is_some_and(|rules| !rules.is_empty()))
711    }
712
713    pub fn relation_has_triggers(
714        &self,
715        resolution: &RelationNameResolution,
716        name: &str,
717    ) -> Result<bool, SQLError> {
718        let relation = self
719            .relation_lookup_candidates(resolution, name)?
720            .into_iter()
721            .find(|relation| {
722                self.snapshot.tables.contains_key(relation)
723                    || self.snapshot.definitions.views.contains_key(relation)
724                    || self
725                        .snapshot
726                        .definitions
727                        .foreign_tables
728                        .contains_key(relation)
729            })
730            .ok_or_else(|| SQLError::UnknownTable(name.to_string()))?;
731        if !self.snapshot.tables.contains_key(&relation) {
732            return Ok(self
733                .snapshot
734                .definitions
735                .triggers
736                .get(&relation)
737                .is_some_and(|triggers| !triggers.is_empty()));
738        }
739        let sources = self.partition_trigger_sources(resolution, &relation.qualified_name())?;
740        Ok(sources.iter().enumerate().any(|(index, source)| {
741            self.snapshot
742                .definitions
743                .triggers
744                .get(source)
745                .is_some_and(|entries| {
746                    entries
747                        .values()
748                        .any(|trigger| index == 0 || trigger.definition.row)
749                })
750        }))
751    }
752
753    pub fn partition_trigger_sources(
754        &self,
755        resolution: &RelationNameResolution,
756        name: &str,
757    ) -> Result<Vec<uqa_core::RelationIdentity>, SQLError> {
758        let mut current = self
759            .relation_lookup_candidates(resolution, name)?
760            .into_iter()
761            .find(|relation| self.snapshot.tables.contains_key(relation))
762            .ok_or_else(|| SQLError::UnknownTable(name.to_string()))?;
763        let mut sources = Vec::new();
764        let mut visited = BTreeSet::new();
765        loop {
766            if !visited.insert(current.clone()) {
767                return Err(SQLError::Internal(format!(
768                    "trigger partition hierarchy contains a cycle at `{}`",
769                    current.qualified_name()
770                )));
771            }
772            sources.push(current.clone());
773            let hierarchy = &self
774                .snapshot
775                .tables
776                .get(&current)
777                .ok_or_else(|| SQLError::UnknownTable(current.qualified_name()))?
778                .hierarchy;
779            if hierarchy.partition_bound.is_none() {
780                break;
781            }
782            let Some(parent) = hierarchy.parents.first() else {
783                return Err(SQLError::Internal(format!(
784                    "partition `{}` has no parent",
785                    current.qualified_name()
786                )));
787            };
788            current = uqa_core::RelationIdentity::from_legacy_name(parent).map_err(|error| {
789                SQLError::Internal(format!(
790                    "decode query trigger partition parent `{parent}`: {error}"
791                ))
792            })?;
793        }
794        Ok(sources)
795    }
796
797    pub fn view_resolved(
798        &self,
799        resolution: &RelationNameResolution,
800        name: &str,
801    ) -> Result<Option<&crate::catalog::view::StoredView>, SQLError> {
802        for relation in self.relation_lookup_candidates(resolution, name)? {
803            if let Some(view) = self.snapshot.definitions.views.get(&relation) {
804                return Ok(Some(view));
805            }
806            if self.relation_exists(&relation) {
807                return Ok(None);
808            }
809        }
810        Ok(None)
811    }
812
813    pub fn view_name_resolved(
814        &self,
815        resolution: &RelationNameResolution,
816        name: &str,
817    ) -> Result<Option<String>, SQLError> {
818        for relation in self.relation_lookup_candidates(resolution, name)? {
819            if self.snapshot.definitions.views.contains_key(&relation) {
820                return Ok(Some(relation.qualified_name()));
821            }
822            if self.relation_exists(&relation) {
823                return Ok(None);
824            }
825        }
826        Ok(None)
827    }
828
829    pub fn foreign_table_resolved(
830        &self,
831        resolution: &RelationNameResolution,
832        name: &str,
833    ) -> Result<Option<&crate::catalog::foreign::StoredForeignTable>, SQLError> {
834        for relation in self.relation_lookup_candidates(resolution, name)? {
835            if let Some(table) = self.snapshot.definitions.foreign_tables.get(&relation) {
836                return Ok(Some(table));
837            }
838            if self.relation_exists(&relation) {
839                return Ok(None);
840            }
841        }
842        Ok(None)
843    }
844
845    pub fn foreign_table_entry_resolved(
846        &self,
847        resolution: &RelationNameResolution,
848        name: &str,
849    ) -> Result<Option<(String, crate::catalog::foreign::StoredForeignTable)>, SQLError> {
850        for relation in self.relation_lookup_candidates(resolution, name)? {
851            if let Some(table) = self.snapshot.definitions.foreign_tables.get(&relation) {
852                return Ok(Some((relation.qualified_name(), table.clone())));
853            }
854            if self.relation_exists(&relation) {
855                return Ok(None);
856            }
857        }
858        Ok(None)
859    }
860
861    fn collect_hierarchy_descendants(
862        &self,
863        parent: &uqa_core::RelationIdentity,
864        visiting: &mut BTreeSet<uqa_core::RelationIdentity>,
865        visited: &mut BTreeSet<uqa_core::RelationIdentity>,
866        output: &mut Vec<String>,
867    ) -> Result<(), SQLError> {
868        if visiting.contains(parent) {
869            return Err(SQLError::Internal(format!(
870                "table inheritance cycle reaches `{}`",
871                parent.qualified_name()
872            )));
873        }
874        if !visited.insert(parent.clone()) {
875            return Ok(());
876        }
877        visiting.insert(parent.clone());
878        output.push(parent.qualified_name());
879        let parent_name = parent.qualified_name();
880        let children = self
881            .snapshot
882            .tables
883            .iter()
884            .filter(|(_, table)| {
885                table
886                    .hierarchy
887                    .parents
888                    .iter()
889                    .any(|candidate| candidate == &parent_name)
890            })
891            .map(|(identity, _)| identity.clone())
892            .collect::<Vec<_>>();
893        for child in children {
894            self.collect_hierarchy_descendants(&child, visiting, visited, output)?;
895        }
896        visiting.remove(parent);
897        Ok(())
898    }
899}
900
901mod lineage;