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