1mod 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 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 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 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 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 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 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 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 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 shells(&self) -> impl Iterator<Item = &uqa_sql::catalog::shell_type::StoredShellType> {
537 self.snapshot.definitions.shells.values()
538 }
539
540 pub fn ranges(&self) -> impl Iterator<Item = &uqa_sql::catalog::range_type::StoredRange> {
541 self.snapshot.definitions.ranges.values()
542 }
543
544 pub fn composites(
545 &self,
546 ) -> impl Iterator<Item = &uqa_sql::catalog::composite_type::StoredComposite> {
547 self.snapshot.definitions.composites.values()
548 }
549
550 pub fn composite_by_type_oid(
552 &self,
553 oid: u32,
554 ) -> Option<&uqa_sql::catalog::composite_type::StoredComposite> {
555 self.composites()
556 .find(|definition| definition.oid == oid || definition.array_oid == oid)
557 }
558
559 pub fn enum_by_type_oid(&self, oid: u32) -> Option<&uqa_sql::catalog::enum_type::StoredEnum> {
561 self.enums()
562 .find(|definition| definition.oid == oid || definition.array_oid == oid)
563 }
564
565 pub fn sql_functions(
566 &self,
567 resolution: &RelationNameResolution,
568 name: &str,
569 ) -> Result<Option<Vec<std::sync::Arc<uqa_sql::routines::SQLUserFunction>>>, SQLError> {
570 let (schema, local_name) =
571 uqa_core::RelationIdentity::parse_reference(name).map_err(|error| {
572 SQLError::Routine {
573 sqlstate: "42602".into(),
574 message: format!("invalid routine name `{name}`: {error}"),
575 }
576 })?;
577 let keys = schema.map_or_else(
578 || {
579 resolution
580 .search_path
581 .iter()
582 .map(|schema| {
583 uqa_core::RelationIdentity::new(schema, &local_name).qualified_name()
584 })
585 .collect::<Vec<_>>()
586 },
587 |schema| vec![uqa_core::RelationIdentity::new(schema, &local_name).qualified_name()],
588 );
589 let mut visible = Vec::new();
590 let mut seen = BTreeSet::new();
591 for key in keys {
592 let Some(overloads) = self.snapshot.definitions.sql_user_functions.get(&key) else {
593 continue;
594 };
595 for function in overloads {
596 let identity = (
597 uqa_sql::routines::routine_signature_types(&function.def),
598 function.def.is_procedure,
599 );
600 if seen.insert(identity) {
601 visible.push(function.clone());
602 }
603 }
604 }
605 Ok((!visible.is_empty()).then_some(visible))
606 }
607
608 pub fn all_sql_functions(&self) -> Vec<std::sync::Arc<uqa_sql::routines::SQLUserFunction>> {
609 self.snapshot
610 .definitions
611 .sql_user_functions
612 .values()
613 .flat_map(|functions| functions.iter().cloned())
614 .collect()
615 }
616
617 pub fn table(
618 &self,
619 resolution: &RelationNameResolution,
620 name: &str,
621 ) -> Result<Option<&CatalogTableSnapshot>, SQLError> {
622 self.table_resolved(resolution, name)
623 }
624
625 pub fn table_resolved(
626 &self,
627 resolution: &RelationNameResolution,
628 name: &str,
629 ) -> Result<Option<&CatalogTableSnapshot>, SQLError> {
630 for relation in self.relation_lookup_candidates(resolution, name)? {
631 if let Some(table) = self.snapshot.tables.get(&relation) {
632 return Ok(Some(table));
633 }
634 if self.relation_exists(&relation) {
635 return Ok(None);
636 }
637 }
638 Ok(None)
639 }
640
641 pub fn table_name(
642 &self,
643 resolution: &RelationNameResolution,
644 name: &str,
645 ) -> Result<Option<String>, SQLError> {
646 self.table_name_resolved(resolution, name)
647 }
648
649 pub fn table_name_resolved(
650 &self,
651 resolution: &RelationNameResolution,
652 name: &str,
653 ) -> Result<Option<String>, SQLError> {
654 for relation in self.relation_lookup_candidates(resolution, name)? {
655 if self.snapshot.tables.contains_key(&relation) {
656 return Ok(Some(relation.qualified_name()));
657 }
658 if self.relation_exists(&relation) {
659 return Ok(None);
660 }
661 }
662 Ok(None)
663 }
664
665 pub fn hierarchy_scan_tables(
666 &self,
667 resolution: &RelationNameResolution,
668 name: &str,
669 include_descendants: bool,
670 ) -> Result<Vec<String>, SQLError> {
671 let root = self
672 .relation_lookup_candidates(resolution, name)?
673 .into_iter()
674 .find(|relation| self.snapshot.tables.contains_key(relation))
675 .ok_or_else(|| SQLError::UnknownTable(name.to_string()))?;
676 if !include_descendants {
677 return Ok(vec![root.qualified_name()]);
678 }
679 let mut output = Vec::new();
680 let mut visiting = BTreeSet::new();
681 let mut visited = BTreeSet::new();
682 self.collect_hierarchy_descendants(&root, &mut visiting, &mut visited, &mut output)?;
683 Ok(output)
684 }
685
686 pub fn direct_hierarchy_children(
687 &self,
688 resolution: &RelationNameResolution,
689 name: &str,
690 ) -> Result<Vec<String>, SQLError> {
691 let parent = self
692 .table_name(resolution, name)?
693 .ok_or_else(|| SQLError::UnknownTable(name.to_string()))?;
694 Ok(self
695 .snapshot
696 .tables
697 .iter()
698 .filter(|(_, table)| table.hierarchy.parents.iter().any(|item| item == &parent))
699 .map(|(identity, _)| identity.qualified_name())
700 .collect())
701 }
702
703 pub fn table_has_rules(
704 &self,
705 resolution: &RelationNameResolution,
706 name: &str,
707 ) -> Result<bool, SQLError> {
708 let relation = self
709 .relation_lookup_candidates(resolution, name)?
710 .into_iter()
711 .find(|relation| self.snapshot.tables.contains_key(relation))
712 .ok_or_else(|| SQLError::UnknownTable(name.to_string()))?;
713 Ok(self
714 .snapshot
715 .definitions
716 .rules
717 .get(&relation)
718 .is_some_and(|rules| !rules.is_empty()))
719 }
720
721 pub fn relation_has_triggers(
722 &self,
723 resolution: &RelationNameResolution,
724 name: &str,
725 ) -> Result<bool, SQLError> {
726 let relation = self
727 .relation_lookup_candidates(resolution, name)?
728 .into_iter()
729 .find(|relation| {
730 self.snapshot.tables.contains_key(relation)
731 || self.snapshot.definitions.views.contains_key(relation)
732 || self
733 .snapshot
734 .definitions
735 .foreign_tables
736 .contains_key(relation)
737 })
738 .ok_or_else(|| SQLError::UnknownTable(name.to_string()))?;
739 if !self.snapshot.tables.contains_key(&relation) {
740 return Ok(self
741 .snapshot
742 .definitions
743 .triggers
744 .get(&relation)
745 .is_some_and(|triggers| !triggers.is_empty()));
746 }
747 let sources = self.partition_trigger_sources(resolution, &relation.qualified_name())?;
748 Ok(sources.iter().enumerate().any(|(index, source)| {
749 self.snapshot
750 .definitions
751 .triggers
752 .get(source)
753 .is_some_and(|entries| {
754 entries
755 .values()
756 .any(|trigger| index == 0 || trigger.definition.row)
757 })
758 }))
759 }
760
761 pub fn partition_trigger_sources(
762 &self,
763 resolution: &RelationNameResolution,
764 name: &str,
765 ) -> Result<Vec<uqa_core::RelationIdentity>, SQLError> {
766 let mut current = self
767 .relation_lookup_candidates(resolution, name)?
768 .into_iter()
769 .find(|relation| self.snapshot.tables.contains_key(relation))
770 .ok_or_else(|| SQLError::UnknownTable(name.to_string()))?;
771 let mut sources = Vec::new();
772 let mut visited = BTreeSet::new();
773 loop {
774 if !visited.insert(current.clone()) {
775 return Err(SQLError::Internal(format!(
776 "trigger partition hierarchy contains a cycle at `{}`",
777 current.qualified_name()
778 )));
779 }
780 sources.push(current.clone());
781 let hierarchy = &self
782 .snapshot
783 .tables
784 .get(¤t)
785 .ok_or_else(|| SQLError::UnknownTable(current.qualified_name()))?
786 .hierarchy;
787 if hierarchy.partition_bound.is_none() {
788 break;
789 }
790 let Some(parent) = hierarchy.parents.first() else {
791 return Err(SQLError::Internal(format!(
792 "partition `{}` has no parent",
793 current.qualified_name()
794 )));
795 };
796 current = uqa_core::RelationIdentity::from_legacy_name(parent).map_err(|error| {
797 SQLError::Internal(format!(
798 "decode query trigger partition parent `{parent}`: {error}"
799 ))
800 })?;
801 }
802 Ok(sources)
803 }
804
805 pub fn view_resolved(
806 &self,
807 resolution: &RelationNameResolution,
808 name: &str,
809 ) -> Result<Option<&crate::catalog::view::StoredView>, SQLError> {
810 for relation in self.relation_lookup_candidates(resolution, name)? {
811 if let Some(view) = self.snapshot.definitions.views.get(&relation) {
812 return Ok(Some(view));
813 }
814 if self.relation_exists(&relation) {
815 return Ok(None);
816 }
817 }
818 Ok(None)
819 }
820
821 pub fn view_name_resolved(
822 &self,
823 resolution: &RelationNameResolution,
824 name: &str,
825 ) -> Result<Option<String>, SQLError> {
826 for relation in self.relation_lookup_candidates(resolution, name)? {
827 if self.snapshot.definitions.views.contains_key(&relation) {
828 return Ok(Some(relation.qualified_name()));
829 }
830 if self.relation_exists(&relation) {
831 return Ok(None);
832 }
833 }
834 Ok(None)
835 }
836
837 pub fn foreign_table_resolved(
838 &self,
839 resolution: &RelationNameResolution,
840 name: &str,
841 ) -> Result<Option<&crate::catalog::foreign::StoredForeignTable>, SQLError> {
842 for relation in self.relation_lookup_candidates(resolution, name)? {
843 if let Some(table) = self.snapshot.definitions.foreign_tables.get(&relation) {
844 return Ok(Some(table));
845 }
846 if self.relation_exists(&relation) {
847 return Ok(None);
848 }
849 }
850 Ok(None)
851 }
852
853 pub fn foreign_table_entry_resolved(
854 &self,
855 resolution: &RelationNameResolution,
856 name: &str,
857 ) -> Result<Option<(String, crate::catalog::foreign::StoredForeignTable)>, SQLError> {
858 for relation in self.relation_lookup_candidates(resolution, name)? {
859 if let Some(table) = self.snapshot.definitions.foreign_tables.get(&relation) {
860 return Ok(Some((relation.qualified_name(), table.clone())));
861 }
862 if self.relation_exists(&relation) {
863 return Ok(None);
864 }
865 }
866 Ok(None)
867 }
868
869 fn collect_hierarchy_descendants(
870 &self,
871 parent: &uqa_core::RelationIdentity,
872 visiting: &mut BTreeSet<uqa_core::RelationIdentity>,
873 visited: &mut BTreeSet<uqa_core::RelationIdentity>,
874 output: &mut Vec<String>,
875 ) -> Result<(), SQLError> {
876 if visiting.contains(parent) {
877 return Err(SQLError::Internal(format!(
878 "table inheritance cycle reaches `{}`",
879 parent.qualified_name()
880 )));
881 }
882 if !visited.insert(parent.clone()) {
883 return Ok(());
884 }
885 visiting.insert(parent.clone());
886 output.push(parent.qualified_name());
887 let parent_name = parent.qualified_name();
888 let children = self
889 .snapshot
890 .tables
891 .iter()
892 .filter(|(_, table)| {
893 table
894 .hierarchy
895 .parents
896 .iter()
897 .any(|candidate| candidate == &parent_name)
898 })
899 .map(|(identity, _)| identity.clone())
900 .collect::<Vec<_>>();
901 for child in children {
902 self.collect_hierarchy_descendants(&child, visiting, visited, output)?;
903 }
904 visiting.remove(parent);
905 Ok(())
906 }
907}
908
909mod lineage;