uqa_execution/catalog/projection/routine_definitions/
cache.rs1use super::{BuiltinRoutineCatalogEntry, CatalogReadView, SQLError, SQLUserFunction};
10use crate::catalog::cache::OrderedOidLookup;
11use std::{
12 collections::BTreeMap,
13 sync::{Arc, OnceLock},
14};
15
16#[derive(Default)]
17pub(in crate::catalog) struct RoutineDefinitions {
18 by_oid: OnceLock<OrderedOidLookup<(String, usize)>>,
19}
20
21impl CatalogReadView {
22 pub fn sql_function_by_oid(&self, oid: u32) -> Result<Option<&Arc<SQLUserFunction>>, SQLError> {
24 user_routine_by_oid(self, i64::from(oid))
25 }
26}
27
28pub(super) fn user_routine_by_oid(
29 catalog: &CatalogReadView,
30 oid: i64,
31) -> Result<Option<&Arc<SQLUserFunction>>, SQLError> {
32 let lookup = catalog.routine_definitions.by_oid.get_or_init(|| {
33 OrderedOidLookup::build(
34 catalog
35 .snapshot()
36 .definitions
37 .sql_user_functions
38 .iter()
39 .flat_map(|(name, overloads)| {
40 overloads
41 .iter()
42 .enumerate()
43 .map(move |(position, function)| {
44 #[cfg(test)]
45 ROUTINE_ADDRESSES.set(ROUTINE_ADDRESSES.get() + 1);
46 super::super::pg_proc::user_routine_catalog_oid(function)
47 .map(|oid| (oid, (name.clone(), position)))
48 })
49 }),
50 )
51 });
52 Ok(lookup.get(oid)?.map(|(name, position)| {
53 &catalog.snapshot().definitions.sql_user_functions[name][*position]
54 }))
55}
56
57pub(super) fn builtin_routine_by_oid(oid: i64) -> Option<BuiltinRoutineCatalogEntry> {
58 static BUILTINS: OnceLock<BTreeMap<i64, BuiltinRoutineCatalogEntry>> = OnceLock::new();
59 BUILTINS
60 .get_or_init(|| {
61 let mut by_oid = BTreeMap::new();
62 for entry in super::super::builtin_routines::PG18_BUILTIN_ROUTINE_GROUPS
63 .iter()
64 .flat_map(|group| group.iter())
65 .copied()
66 .chain(super::super::builtin_routines::native_foreign_handlers())
67 {
68 by_oid.entry(entry.oid).or_insert(entry);
69 }
70 by_oid
71 })
72 .get(&oid)
73 .copied()
74}
75
76#[cfg(test)]
77thread_local! {
78 static ROUTINE_ADDRESSES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
79}
80
81#[cfg(test)]
82mod tests;