1use super::SessionExecutionView;
10use crate::Engine;
11use uqa_execution::catalog::{
12 context::CatalogContext,
13 services::{CatalogNamespace, CatalogSession, RelationCounts},
14 RelationNameResolution,
15};
16use uqa_sql::catalog::roles::RoleReference;
17use uqa_sql::catalog::session::{CursorMetadata, PreparedStatementMetadata};
18use uqa_sql::SQLError;
19
20impl SessionExecutionView<'_> {
21 fn relation_name_resolution_with_control(
22 &self,
23 control: &uqa_core::memory::ProductionControl<'_>,
24 ) -> Result<uqa_core::memory::Produced<RelationNameResolution>, SQLError> {
25 control.check()?;
26 let state = self.session.state.read();
27 let role = state.authorization.current();
28 RelationNameResolution::from_inputs_with_control(
29 state.search_path.iter().map(|name| {
30 if name == "$user" {
31 role.name.as_str()
32 } else {
33 name.as_str()
34 }
35 }),
36 control.format(format_args!("pg_temp_{}", self.session_id))?,
37 state.temporary_namespace.is_some(),
38 &RoleReference::Bound(role.clone()),
39 uqa_execution::catalog::RelationLookupMode::Dynamic,
40 control,
41 )
42 }
43}
44
45impl Engine {
46 pub(crate) fn catalog_identity_reservation_context(
47 &self,
48 ) -> uqa_execution::catalog::identity::CatalogIdentityReservationContext<'_> {
49 uqa_execution::catalog::identity::CatalogIdentityReservationContext {
50 catalog: self,
51 session: self,
52 locks: self,
53 }
54 }
55
56 pub(crate) fn catalog_execution(&self) -> CatalogContext<'_> {
57 CatalogContext {
58 catalog: self,
59 session: self,
60 namespaces: self,
61 routines: self,
62 expressions: self,
63 counts: self,
64 views: self,
65 cache: &self.runtime.regtype_output_cache,
66 }
67 }
68}
69impl CatalogSession for Engine {
70 fn current_role(&self) -> RoleReference {
71 self.session_execution_view().current_role()
72 }
73 fn temporary_schema_name(&self) -> String {
74 self.session_execution_view().temporary_schema_name()
75 }
76 fn relation_name_resolution(&self) -> RelationNameResolution {
77 self.session_execution_view().relation_name_resolution()
78 }
79
80 fn relation_name_resolution_with_control(
81 &self,
82 control: &uqa_core::memory::ProductionControl<'_>,
83 ) -> Result<uqa_core::memory::Produced<RelationNameResolution>, SQLError> {
84 self.session_execution_view()
85 .relation_name_resolution_with_control(control)
86 }
87
88 fn show_parameter(&self, name: &str) -> Result<(String, String), SQLError> {
89 self.session_execution_view().show_parameter(name)
90 }
91 fn parameter_name_with_control(
92 &self,
93 name: &str,
94 control: &uqa_core::memory::ProductionControl<'_>,
95 ) -> Result<uqa_core::memory::Produced<String>, SQLError> {
96 self.session_execution_view()
97 .parameter_name_with_control(name, control)
98 }
99 fn parameter_settings(&self) -> Vec<uqa_sql::semantics::parameters::setting::ParameterSetting> {
100 self.session_execution_view().parameter_settings()
101 }
102 fn explain_settings(
103 &self,
104 control: &uqa_core::memory::ProductionControl<'_>,
105 ) -> Result<
106 uqa_core::memory::Produced<uqa_sql::semantics::parameters::explain::ExplainSettings>,
107 SQLError,
108 > {
109 self.session_execution_view().explain_settings(control)
110 }
111 fn prepared_statements(&self) -> Vec<PreparedStatementMetadata> {
112 self.session_execution_view().prepared_statements()
113 }
114 fn cursors(&self) -> Vec<CursorMetadata> {
115 self.session_execution_view().cursors()
116 }
117}
118impl CatalogSession for SessionExecutionView<'_> {
119 fn current_role(&self) -> RoleReference {
120 SessionExecutionView::current_role(self)
121 }
122 fn temporary_schema_name(&self) -> String {
123 SessionExecutionView::temporary_schema_name(self)
124 }
125 fn relation_name_resolution(&self) -> RelationNameResolution {
126 SessionExecutionView::relation_name_resolution(self)
127 }
128
129 fn relation_name_resolution_with_control(
130 &self,
131 control: &uqa_core::memory::ProductionControl<'_>,
132 ) -> Result<uqa_core::memory::Produced<RelationNameResolution>, SQLError> {
133 SessionExecutionView::relation_name_resolution_with_control(self, control)
134 }
135
136 fn show_parameter(&self, name: &str) -> Result<(String, String), SQLError> {
137 SessionExecutionView::show_parameter(self, name)
138 }
139 fn parameter_name_with_control(
140 &self,
141 name: &str,
142 control: &uqa_core::memory::ProductionControl<'_>,
143 ) -> Result<uqa_core::memory::Produced<String>, SQLError> {
144 SessionExecutionView::parameter_name_with_control(self, name, control)
145 }
146 fn parameter_settings(&self) -> Vec<uqa_sql::semantics::parameters::setting::ParameterSetting> {
147 SessionExecutionView::parameter_settings(self)
148 }
149 fn explain_settings(
150 &self,
151 control: &uqa_core::memory::ProductionControl<'_>,
152 ) -> Result<
153 uqa_core::memory::Produced<uqa_sql::semantics::parameters::explain::ExplainSettings>,
154 SQLError,
155 > {
156 SessionExecutionView::explain_settings(self, control)
157 }
158 fn prepared_statements(&self) -> Vec<PreparedStatementMetadata> {
159 SessionExecutionView::prepared_statements(self)
160 }
161 fn cursors(&self) -> Vec<CursorMetadata> {
162 SessionExecutionView::cursors(self)
163 }
164}
165impl RelationCounts for Engine {
166 fn table_doc_count(&self, name: &str) -> Result<u64, SQLError> {
167 Engine::table_doc_count(self, name)
168 }
169}
170impl CatalogNamespace for Engine {
171 fn current_schema_names(&self, implicit: bool) -> Result<Vec<String>, SQLError> {
172 Engine::current_schema_names_in_execution(self, implicit)
173 .map_err(|error| SQLError::Internal(error.to_string()))
174 }
175 fn current_schema_names_with_catalog(
176 &self,
177 catalog: &uqa_execution::catalog::CatalogReadView,
178 implicit: bool,
179 ) -> Result<Vec<String>, SQLError> {
180 Ok(uqa_execution::catalog::namespaces::current_schema_names(
181 catalog,
182 &self.session_execution_view().relation_name_resolution(),
183 &self.current_role(),
184 implicit,
185 ))
186 }
187}
188
189impl uqa_execution::catalog::services::CatalogSnapshotSource for Engine {
190 fn bind_query_reads(
191 &self,
192 snapshot: uqa_execution::catalog::CatalogReadView,
193 ) -> Result<uqa_execution::catalog::CatalogReadView, SQLError> {
194 let map_error =
195 |error| uqa_execution::storage_errors::storage_error("bind catalog reads", &error);
196 let Some(context) = self.graph_read_context().map_err(map_error)? else {
197 return Ok(snapshot);
198 };
199 Ok(snapshot.with_graph_reads(
200 self.new_graph_store().map_err(map_error)?,
201 context,
202 &self.runtime.cancellation,
203 ))
204 }
205
206 fn retain_catalog_rows(
207 &self,
208 snapshot: uqa_execution::catalog::CatalogReadView,
209 ) -> Result<uqa_execution::catalog::CatalogReadView, SQLError> {
210 if !self.versioned_backend_transactions() || snapshot.has_physical_catalog() {
211 return Ok(snapshot);
212 }
213 let boundary = self
214 .session
215 .transactions
216 .lock()
217 .first()
218 .and_then(|frame| frame.fixed_catalog_records.clone());
219 let backend =
220 self.storage.backend.as_ref().ok_or_else(|| {
221 SQLError::Internal("versioned catalog has no storage backend".into())
222 })?;
223 let source = match boundary {
224 Some(boundary) => backend
225 .open_read_session_with_private_changes(&boundary, &self.runtime.cancellation),
226 None => backend.open_retained_read_session(&self.runtime.cancellation),
227 }
228 .map_err(|error| {
229 uqa_execution::storage_errors::storage_error("retain physical catalog rows", &error)
230 })?;
231 Ok(snapshot.with_physical_catalog(source.catalog))
232 }
233
234 fn refreshed_catalog_snapshot(
235 &self,
236 ) -> Result<uqa_execution::catalog::CatalogReadView, SQLError> {
237 self.refresh_catalog()?;
238 Ok(self.catalog_read_view())
239 }
240
241 fn refresh_catalog(&self) -> Result<(), SQLError> {
242 self.synchronize_table_catalog()
243 .map_err(|error| SQLError::Internal(format!("load table catalog: {error}")))?;
244 self.synchronize_catalog_registries()
245 .map_err(|error| SQLError::Internal(format!("load relation catalog: {error}")))?;
246 Ok(())
247 }
248
249 fn catalog_snapshot(&self) -> uqa_execution::catalog::CatalogReadView {
250 self.catalog_read_view()
251 }
252
253 fn builtin_routine_permissions(
254 &self,
255 current_role: RoleReference,
256 ) -> uqa_execution::catalog::security::builtin_routines::execution::BuiltinRoutinePermissions
257 {
258 use uqa_execution::catalog::security::builtin_routines::execution::BuiltinRoutinePermissions;
259
260 if let Some(snapshot) = &self.query_catalog_snapshot {
261 return BuiltinRoutinePermissions::new(snapshot.read_view.clone(), current_role);
262 }
263 BuiltinRoutinePermissions::try_unrestricted(
264 &self.durable.builtin_routine_security.snapshot(),
265 &self.durable.roles.snapshot(),
266 ¤t_role,
267 )
268 .unwrap_or_else(|| BuiltinRoutinePermissions::new(self.catalog_read_view(), current_role))
269 }
270
271 fn current_catalog_snapshot(&self) -> uqa_execution::catalog::CatalogReadView {
272 self.restored_catalog_read_view()
273 }
274
275 fn current_catalog_revision(&self) -> Option<u64> {
276 Some(self.runtime.regtype_output_cache.revision())
277 }
278}
279
280use uqa_core::Value;
281impl Engine {
282 pub(crate) fn clear_regtype_output_cache(&self) {
283 self.runtime.regtype_output_cache.clear();
284 }
285}
286
287use uqa_execution::catalog::services::{
288 CatalogExpressionEvaluation, ViewCatalogCapabilities, ViewCatalogMetadata,
289};
290use uqa_sql::ast::{Expr, TriggerEvent};
291impl CatalogExpressionEvaluation for Engine {
292 fn evaluate(&self, expression: &Expr) -> Result<Value, SQLError> {
293 crate::capabilities::query_expressions::eval_lowered_expression(self, expression, None, &[])
294 }
295}
296impl ViewCatalogCapabilities for Engine {
297 fn view_updatability_with_catalog(
298 &self,
299 name: &str,
300 catalog: &uqa_execution::catalog::CatalogReadView,
301 resolution: &RelationNameResolution,
302 ) -> Result<ViewCatalogMetadata, SQLError> {
303 let resources = self.query_retention_control()?;
304 let control = uqa_core::memory::ProductionControl::new(
305 resources.memory(),
306 resources.cancellation(),
307 self.query_runtime_view().cancellation,
308 );
309 let retained = uqa_execution::catalog::view::metadata::RetainedViewCatalog {
310 catalog,
311 resolution,
312 fallback: self,
313 replica: self.session_replication_role_is_replica(),
314 control: control.capture(),
315 };
316 let metadata = uqa_sql::semantics::view_rewrite::view_updatability(
317 uqa_sql::semantics::view_rewrite::context::ViewRewriteContext {
318 catalog: &retained,
319 ..self.view_rewrite_context()
320 },
321 name,
322 )?;
323 Ok(ViewCatalogMetadata {
324 catalog: metadata.catalog,
325 catalog_columns: metadata.catalog_columns,
326 check_option: metadata.check_option,
327 })
328 }
329 fn has_instead_of_trigger_with_catalog(
330 &self,
331 name: &str,
332 event: TriggerEvent,
333 catalog: &uqa_execution::catalog::CatalogReadView,
334 resolution: &RelationNameResolution,
335 ) -> Result<bool, SQLError> {
336 let resources = self.query_retention_control()?;
337 let control = uqa_core::memory::ProductionControl::new(
338 resources.memory(),
339 resources.cancellation(),
340 self.query_runtime_view().cancellation,
341 );
342 let retained = uqa_execution::catalog::view::metadata::RetainedViewCatalog {
343 catalog,
344 resolution,
345 fallback: self,
346 replica: self.session_replication_role_is_replica(),
347 control: control.capture(),
348 };
349 uqa_sql::semantics::view_rewrite::has_instead_of_trigger(
350 uqa_sql::semantics::view_rewrite::context::ViewRewriteContext {
351 catalog: &retained,
352 ..self.view_rewrite_context()
353 },
354 name,
355 event,
356 )
357 }
358 fn view_updatability(&self, name: &str) -> Result<ViewCatalogMetadata, SQLError> {
359 let metadata =
360 uqa_sql::semantics::view_rewrite::view_updatability(self.view_rewrite_context(), name)?;
361 Ok(ViewCatalogMetadata {
362 catalog: metadata.catalog,
363 catalog_columns: metadata.catalog_columns,
364 check_option: metadata.check_option,
365 })
366 }
367 fn has_instead_of_trigger(&self, name: &str, event: TriggerEvent) -> Result<bool, SQLError> {
368 uqa_sql::semantics::view_rewrite::has_instead_of_trigger(
369 self.view_rewrite_context(),
370 name,
371 event,
372 )
373 }
374}
375
376impl Engine {
377 pub(crate) fn publish_catalog_constraint_tuples(&self) -> Result<(), SQLError> {
378 let (Some(catalog), Some(backend)) = (&self.storage.catalog, &self.storage.backend) else {
379 return Ok(());
380 };
381 if !uqa_execution::catalog::tuples::publication::has_pending(catalog.as_ref()).map_err(
382 |error| {
383 uqa_execution::storage_errors::storage_error("inspect pending catalog rows", &error)
384 },
385 )? {
386 return Ok(());
387 }
388 let storage = uqa_storage::PersistentStorageSession::new(catalog.clone(), backend.clone());
389 uqa_execution::catalog::tuples::publication::publish_pending(
390 &self.catalog_execution(),
391 &self.restored_catalog_read_view(),
392 &self.session_execution_view().relation_name_resolution(),
393 &storage,
394 )
395 }
396}
397
398impl Engine {
399 pub(crate) fn initialize_catalog_constraint_tuples(
400 &self,
401 catalog: &std::sync::Arc<dyn uqa_storage::CatalogFacade>,
402 backend: &std::sync::Arc<dyn uqa_storage::PersistentStorageBackend>,
403 ) -> uqa_storage::StorageBackendResult<()> {
404 if !uqa_execution::catalog::tuples::publication::requires_initialization(catalog.as_ref())?
405 {
406 return self.publish_catalog_constraint_tuples().map_err(|error| {
407 uqa_storage::StorageBackendError::backend("finish restored physical catalog", error)
408 });
409 }
410 uqa_execution::catalog::tuples::publication::initialize(
411 &self.catalog_execution(),
412 &self.restored_catalog_read_view(),
413 &self.session_execution_view().relation_name_resolution(),
414 &uqa_storage::PersistentStorageSession::new(catalog.clone(), backend.clone()),
415 )
416 .map_err(|error| {
417 uqa_storage::StorageBackendError::backend("initialize physical catalog", error)
418 })
419 }
420}