1use super::{RegisteredSQLFunction, SQLAggregateFactory, SQLScalarFunction, SQLTableFunction};
10use crate::{state::StatementGate, SQLError, SessionContext};
11use parking_lot::{Mutex, RwLock};
12use std::sync::atomic::{AtomicU64, Ordering};
13use std::{
14 collections::BTreeMap,
15 sync::{Arc, Weak},
16};
17
18#[derive(Debug, thiserror::Error)]
19pub enum SQLFunctionRegistrationError {
20 #[error("SQL function registry has active execution or retained function resources")]
21 Busy,
22 #[error(transparent)]
23 Invalid(#[from] SQLError),
24}
25
26impl From<SQLFunctionRegistrationError> for SQLError {
27 fn from(error: SQLFunctionRegistrationError) -> Self {
28 match error {
29 SQLFunctionRegistrationError::Busy => Self::Routine {
30 sqlstate: "55006".into(),
31 message: error.to_string(),
32 },
33 SQLFunctionRegistrationError::Invalid(error) => error,
34 }
35 }
36}
37
38type Result<T> = std::result::Result<T, SQLFunctionRegistrationError>;
39type Map<F> = RwLock<BTreeMap<String, RegisteredSQLFunction<F>>>;
40
41enum Function {
42 Scalar(Arc<dyn SQLScalarFunction>),
43 Table(Arc<dyn SQLTableFunction>),
44 Aggregate(Arc<dyn SQLAggregateFactory>),
45}
46
47enum WeakFunction {
48 Scalar(Weak<dyn SQLScalarFunction>),
49 Table(Weak<dyn SQLTableFunction>),
50 Aggregate(Weak<dyn SQLAggregateFactory>),
51}
52
53impl WeakFunction {
54 fn upgrade(&self) -> Option<Function> {
55 match self {
56 Self::Scalar(function) => function.upgrade().map(Function::Scalar),
57 Self::Table(function) => function.upgrade().map(Function::Table),
58 Self::Aggregate(function) => function.upgrade().map(Function::Aggregate),
59 }
60 }
61}
62
63struct Session {
64 context: Weak<SessionContext>,
65 gate: Weak<StatementGate>,
66}
67
68#[derive(Default)]
69struct Members {
70 sessions: Vec<Session>,
71 functions: Vec<WeakFunction>,
72}
73
74pub(crate) struct Registry {
75 pub(crate) scalar: Map<dyn SQLScalarFunction>,
76 pub(crate) table: Map<dyn SQLTableFunction>,
77 pub(crate) aggregate: Map<dyn SQLAggregateFactory>,
78 members: Mutex<Members>,
79 revision: AtomicU64,
80}
81
82impl Registry {
83 pub(crate) fn new(session: &Arc<SessionContext>, gate: &Arc<StatementGate>) -> Self {
84 let registry = Self {
85 scalar: RwLock::default(),
86 table: RwLock::default(),
87 aggregate: RwLock::default(),
88 members: Mutex::default(),
89 revision: AtomicU64::new(0),
90 };
91 registry.attach(session, gate);
92 registry
93 }
94
95 pub(crate) fn revision(&self) -> u64 {
96 self.revision.load(Ordering::Acquire)
97 }
98
99 pub(crate) fn attach(&self, session: &Arc<SessionContext>, gate: &Arc<StatementGate>) {
100 let mut members = self.members.lock();
101 members
102 .sessions
103 .retain(|entry| entry.context.strong_count() != 0 && entry.gate.strong_count() != 0);
104 members.sessions.push(Session {
105 context: Arc::downgrade(session),
106 gate: Arc::downgrade(gate),
107 });
108 }
109
110 fn change<T>(&self, change: impl FnOnce(&mut Members) -> Result<T>) -> Result<T> {
114 let mut retained = Vec::new();
117 let mut members = self
118 .members
119 .try_lock()
120 .ok_or(SQLFunctionRegistrationError::Busy)?;
121 let sessions: Vec<_> = members
122 .sessions
123 .iter()
124 .filter_map(|member| Some((member.context.upgrade()?, member.gate.upgrade()?)))
125 .collect();
126 let _gates: Vec<_> = sessions
127 .iter()
128 .map(|(_, gate)| {
129 gate.try_lock_idle()
130 .ok_or(SQLFunctionRegistrationError::Busy)
131 })
132 .collect::<Result<_>>()?;
133 members.functions.retain(|function| {
134 if let Some(function) = function.upgrade() {
135 retained.push(function);
136 true
137 } else {
138 false
139 }
140 });
141 let next_revision = self
142 .revision()
143 .checked_add(1)
144 .ok_or_else(|| SQLError::Routine {
145 sqlstate: "54000".into(),
146 message: "SQL function registry revision space exhausted".into(),
147 })?;
148 for (session, _) in &sessions {
149 session.state.write().sql_statement_cache.clear();
150 uqa_execution::statement::prepared::invalidation::PreparedCatalogChange::GlobalCatalog
151 .invalidate_with_routines(
152 session.prepared.write().values_mut(),
153 &session.routine_bodies,
154 );
155 }
156 let result = change(&mut members);
157 if result.is_ok() {
158 self.revision.store(next_revision, Ordering::Release);
159 }
160 result
161 }
162}
163
164pub struct SQLFunctionRegistration {
168 active: Option<Registration>,
169}
170
171struct Registration {
172 registry: Arc<Registry>,
173 name: String,
174 function: Function,
175}
176
177macro_rules! registration {
178 ($method:ident, $field:ident, $kind:ident, $trait:ident) => {
179 impl Registry {
180 pub(super) fn $method(
181 self: &Arc<Self>,
182 name: String,
183 function: Arc<dyn $trait>,
184 options: crate::SQLFunctionOptions,
185 ) -> Result<SQLFunctionRegistration> {
186 let previous = self.change(|members| {
187 members
188 .functions
189 .push(WeakFunction::$kind(Arc::downgrade(&function)));
190 Ok(self.$field.write().insert(
191 name.clone(),
192 RegisteredSQLFunction::new(Arc::clone(&function), options),
193 ))
194 })?;
195 drop(previous);
196 Ok(SQLFunctionRegistration {
197 active: Some(Registration {
198 registry: Arc::clone(self),
199 name,
200 function: Function::$kind(function),
201 }),
202 })
203 }
204 }
205 };
206}
207registration!(register_scalar, scalar, Scalar, SQLScalarFunction);
208registration!(register_table, table, Table, SQLTableFunction);
209registration!(
210 register_aggregate,
211 aggregate,
212 Aggregate,
213 SQLAggregateFactory
214);
215
216impl SQLFunctionRegistration {
217 pub fn unregister(&mut self) -> Result<()> {
222 let Some(active) = &self.active else {
223 return Ok(());
224 };
225 active.registry.change(|_| match &active.function {
226 Function::Scalar(function) => retire(&active.registry.scalar, &active.name, function),
227 Function::Table(function) => retire(&active.registry.table, &active.name, function),
228 Function::Aggregate(function) => {
229 retire(&active.registry.aggregate, &active.name, function)
230 }
231 })?;
232 self.active.take();
233 Ok(())
234 }
235}
236
237fn retire<F: ?Sized>(map: &Map<F>, name: &str, function: &Arc<F>) -> Result<()> {
238 let mut map = map.write();
239 let current = map
240 .get(name)
241 .is_some_and(|entry| Arc::ptr_eq(&entry.function, function));
242 if Arc::strong_count(function) != 2 + usize::from(current) {
244 return Err(SQLFunctionRegistrationError::Busy);
245 }
246 if current {
247 map.remove(name);
248 }
249 Ok(())
250}