1use uqa_core::{
10 memory::{Produced, ProductionControl},
11 Value,
12};
13
14use crate::ast::{ColumnType, InternalColumnRef};
15use crate::error::{Result, SQLError};
16use crate::params::SQLParam;
17use crate::result::ResultRow;
18
19mod casting;
20mod regtype;
21pub(crate) use casting::evaluate_selected_cast;
22pub use casting::{
23 cast_value_with_numeric_resolution_with_control, cast_value_with_resolution_with_control,
24 cast_value_with_scoped_resolution, cast_value_with_type_resolution,
25 cast_value_with_type_resolution_with_control, coercion_type_name, read_catalog_array_input,
26 read_catalog_input, CatalogCastScope, CatalogInputFunctions, RetainedCatalogCast,
27 ScopedCastResult,
28};
29pub(crate) use casting::{requires_catalog_constant_input, requires_domain_array_input};
30pub(crate) use regtype::format_regtype_value_with_catalog_and_control;
31pub use regtype::{
32 format_regtype_elements_with_control, format_regtype_value, format_regtype_value_with_control,
33};
34
35pub trait EngineHook {
40 fn sql_notice(&self, _notice: crate::SQLNotice) {}
42
43 fn require_builtin_execute(&self, _binding: &crate::ast::FunctionBinding) -> Result<()> {
45 Ok(())
46 }
47
48 fn transaction_timestamp_micros(&self) -> Option<i64> {
50 None
51 }
52
53 fn statement_timestamp_micros(&self) -> Option<i64> {
55 None
56 }
57
58 fn nextval(&self, name: &str) -> Result<i64>;
59 fn currval(&self, name: &str) -> Result<i64>;
60 fn lastval(&self) -> Result<i64> {
61 Err(SQLError::Unsupported(
62 "lastval requires an engine hook implementation".into(),
63 ))
64 }
65 fn setval(&self, name: &str, value: i64, is_called: bool) -> Result<i64>;
66
67 fn call_scalar_function(&self, _name: &str, _args: &[Value]) -> Option<Result<Value>> {
68 None
69 }
70
71 fn call_bound_builtin_function(
76 &self,
77 _binding: &crate::ast::FunctionBinding,
78 _args: &[(Option<String>, Value)],
79 ) -> Option<Result<Value>> {
80 None
81 }
82
83 fn has_scalar_functions(&self) -> bool {
84 true
85 }
86
87 fn enum_labels(&self) -> Option<&dyn super::enums::EnumLabelCatalog> {
89 None
90 }
91
92 fn composite_types(&self) -> Option<&dyn super::composites::CompositeTypeCatalog> {
94 None
95 }
96
97 fn read_range_input(
99 &self,
100 oid: u32,
101 _text: &str,
102 _control: &ProductionControl<'_>,
103 ) -> Result<Produced<Value>> {
104 Err(SQLError::Internal(format!(
105 "cache lookup failed for range type {oid}"
106 )))
107 }
108
109 fn construct_range(
111 &self,
112 oid: u32,
113 _bounds: super::RangeBoundsInput,
114 _control: &ProductionControl<'_>,
115 ) -> Result<Produced<Value>> {
116 Err(SQLError::Internal(format!(
117 "cache lookup failed for range type {oid}"
118 )))
119 }
120
121 fn construct_multirange(
123 &self,
124 oid: u32,
125 _members: &[Value],
126 _control: &ProductionControl<'_>,
127 ) -> Result<Produced<Value>> {
128 Err(SQLError::Internal(format!(
129 "cache lookup failed for range type {oid}"
130 )))
131 }
132
133 fn catalog_cast_scope(&self) -> Option<&CatalogCastScope> {
135 None
136 }
137
138 fn resolve_type_name(&self, _name: &str) -> std::result::Result<Option<ColumnType>, String> {
140 Ok(None)
141 }
142
143 fn resolve_type_oid(&self, _oid: u32) -> std::result::Result<Option<ColumnType>, String> {
145 Ok(None)
146 }
147
148 fn type_oid_exists(&self, oid: u32) -> std::result::Result<bool, String> {
150 self.resolve_type_oid(oid).map(|ty| ty.is_some())
151 }
152
153 fn cast_domain(
155 &self,
156 _value: &Value,
157 _source: Option<&str>,
158 _target: &ColumnType,
159 ) -> Result<Option<Value>> {
160 Ok(None)
161 }
162
163 fn cast_domain_with_control(
165 &self,
166 value: &Value,
167 source: Option<&str>,
168 target: &ColumnType,
169 control: &ProductionControl<'_>,
170 ) -> Result<Option<Produced<Value>>> {
171 control.check()?;
172 self.cast_domain(value, source, target)?
173 .map(|value| control.retain_external_value(value).map_err(SQLError::from))
174 .transpose()
175 }
176
177 fn resolve_regtype_input(&self, _name: &str) -> Result<Option<i64>> {
179 Ok(None)
180 }
181
182 fn resolve_regclass(&self, _name: &str) -> std::result::Result<Option<i64>, String> {
184 Ok(None)
185 }
186
187 fn resolve_regclass_input(&self, name: &str) -> Result<Option<i64>> {
189 self.resolve_regclass(name).map_err(SQLError::Internal)
190 }
191
192 fn resolve_regproc(&self, _name: &str) -> Result<Option<i64>> {
194 Ok(None)
195 }
196
197 fn resolve_regprocedure(&self, _name: &str) -> std::result::Result<Option<i64>, String> {
199 Ok(None)
200 }
201
202 fn resolve_regprocedure_input(&self, name: &str) -> Result<Option<i64>> {
204 self.resolve_regprocedure(name).map_err(SQLError::Internal)
205 }
206
207 fn resolve_regrole(&self, _name: &str) -> Result<Option<i64>> {
209 Ok(None)
210 }
211
212 fn resolve_regnamespace(&self, name: &str) -> Result<Option<i64>> {
214 self.resolve_regobject(&ColumnType::Regnamespace, name)
215 }
216
217 fn resolve_regcollation(&self, name: &str) -> Result<Option<i64>> {
219 self.resolve_regobject(&ColumnType::Regcollation, name)
220 }
221
222 fn resolve_regobject(&self, ty: &ColumnType, name: &str) -> Result<Option<i64>> {
224 match ty {
225 ColumnType::Regclass => self.resolve_regclass_input(name),
226 ColumnType::Regprocedure => self.resolve_regprocedure(name).map_err(SQLError::Internal),
227 ColumnType::Regrole => self.resolve_regrole(name),
228 ColumnType::Regproc
229 | ColumnType::Regcollation
230 | ColumnType::Regnamespace
231 | ColumnType::Regtype => Ok(None),
232 _ => Err(SQLError::Internal(format!(
233 "unsupported regobject lookup type `{}`",
234 ty.sql_name()
235 ))),
236 }
237 }
238
239 fn resolve_regtype_output(
241 &self,
242 _ty: &ColumnType,
243 _oid: i64,
244 ) -> std::result::Result<Option<String>, String> {
245 Ok(None)
246 }
247
248 fn current_schema(&self) -> std::result::Result<Option<String>, String> {
250 Ok(Some("public".into()))
251 }
252
253 fn current_user(&self) -> std::result::Result<Option<String>, crate::SQLError> {
254 Ok(None)
255 }
256
257 fn session_user(&self) -> std::result::Result<Option<String>, crate::SQLError> {
258 Ok(None)
259 }
260
261 fn runtime_parameter(&self, _name: &str) -> Result<Option<String>> {
263 Err(SQLError::Unsupported(
264 "engine hook does not provide session settings".into(),
265 ))
266 }
267
268 fn temporal_interval_style(&self) -> Result<Option<uqa_core::TemporalIntervalStyle>> {
270 Ok(None)
271 }
272
273 fn temporal_time_zone(&self) -> Result<Option<uqa_core::TemporalTimeZone>> {
275 Ok(None)
276 }
277
278 fn sleep(&self, _duration: std::time::Duration) -> Result<()> {
280 Err(SQLError::Unsupported(
281 "engine hook does not provide session sleeps".into(),
282 ))
283 }
284
285 fn set_runtime_parameter(
287 &self,
288 _name: &str,
289 _value: Option<&str>,
290 _local: bool,
291 ) -> Result<String> {
292 Err(SQLError::Unsupported(
293 "engine hook does not provide session settings".into(),
294 ))
295 }
296
297 fn current_schemas(
299 &self,
300 _include_implicit: bool,
301 ) -> std::result::Result<Option<Vec<String>>, String> {
302 Ok(None)
303 }
304
305 fn random_value(&self) -> std::result::Result<Option<f64>, String> {
308 Ok(None)
309 }
310
311 fn random_u64(&self) -> std::result::Result<Option<u64>, String> {
315 Ok(None)
316 }
317
318 fn set_random_seed(&self, _seed: f64) -> std::result::Result<bool, String> {
321 Ok(false)
322 }
323
324 fn call_user_function(
329 &self,
330 _name: &str,
331 _args: &[(Option<String>, Value)],
332 ) -> Option<Result<Value>> {
333 None
334 }
335
336 fn call_bound_user_function(
337 &self,
338 _binding: &crate::ast::FunctionBinding,
339 _args: &[(Option<String>, Value)],
340 ) -> Option<Result<Value>> {
341 None
342 }
343
344 fn routine_description_scope(
349 &self,
350 ) -> Option<crate::routines::invocation::descriptions::RoutineDescriptionScope> {
351 None
352 }
353
354 fn call_bound_user_function_with_descriptions(
356 &self,
357 binding: &crate::ast::FunctionBinding,
358 args: &[(Option<String>, Value)],
359 _descriptions: &crate::routines::invocation::descriptions::RoutineCallDescriptions,
360 _control: &uqa_core::memory::ProductionControl<'_>,
361 ) -> Option<Result<Value>> {
362 self.call_bound_user_function(binding, args)
363 }
364}
365
366#[derive(Debug, Clone, Copy, PartialEq, Eq)]
371pub enum RowKeySpace {
372 PhysicalSlot,
374 LogicalPosition,
376}
377
378pub trait RowLookup {
379 fn column(&self, name: &str) -> Option<&Value>;
380
381 fn column_is_ambiguous(&self, _name: &str) -> bool {
385 false
386 }
387
388 fn qualified_column(&self, qualifier: &str, column: &str) -> Option<&Value>;
389
390 fn qualified_column_is_ambiguous(&self, _qualifier: &str, _column: &str) -> bool {
392 false
393 }
394
395 fn positional_column(&self, _index: usize) -> Option<&Value> {
400 None
401 }
402
403 fn resolution_schema(&self) -> Option<&crate::RowSchema> {
405 None
406 }
407
408 fn key_space(&self) -> RowKeySpace {
410 RowKeySpace::PhysicalSlot
411 }
412
413 fn column_key(&self, _name: &str) -> Option<usize> {
415 None
416 }
417
418 fn qualified_column_key(&self, _qualifier: &str, _column: &str) -> Option<usize> {
420 None
421 }
422
423 fn keyed_value(&self, _key: usize) -> Option<&Value> {
425 None
426 }
427
428 fn internal_column(&self, _column: InternalColumnRef) -> Option<&Value> {
431 None
432 }
433
434 fn score_source(&self, _qualifier: Option<&str>) -> Option<&Value> {
436 None
437 }
438
439 fn score_source_is_ambiguous(&self, _qualifier: Option<&str>) -> bool {
441 false
442 }
443
444 fn visit_columns(&self, _visitor: &mut dyn FnMut(&str, &Value)) {}
449}
450
451impl RowLookup for ResultRow {
452 fn column(&self, name: &str) -> Option<&Value> {
453 self.get(name)
454 }
455
456 fn qualified_column(&self, _qualifier: &str, _column: &str) -> Option<&Value> {
457 None
458 }
459
460 fn visit_columns(&self, visitor: &mut dyn FnMut(&str, &Value)) {
461 for (column, value) in self {
462 visitor(column, value);
463 }
464 }
465}
466
467pub struct EvalContext<'a> {
468 pub row: Option<&'a ResultRow>,
469 row_lookup: Option<&'a dyn RowLookup>,
470 pub params: &'a [SQLParam],
471 pub engine: Option<&'a dyn EngineHook>,
472 enum_comparison_states: [Option<&'a super::enums::EnumComparisonState>; 4],
473}
474
475impl<'a> EvalContext<'a> {
476 pub fn new(row: Option<&'a ResultRow>, params: &'a [SQLParam]) -> Self {
477 Self {
478 row,
479 row_lookup: row.map(|row| row as &dyn RowLookup),
480 params,
481 engine: None,
482 enum_comparison_states: [None; 4],
483 }
484 }
485
486 pub fn from_row_lookup(row: &'a dyn RowLookup, params: &'a [SQLParam]) -> Self {
487 Self {
488 row: None,
492 row_lookup: Some(row),
493 params,
494 engine: None,
495 enum_comparison_states: [None; 4],
496 }
497 }
498
499 pub fn with_engine(mut self, engine: &'a dyn EngineHook) -> Self {
500 self.engine = Some(engine);
501 self
502 }
503
504 pub fn with_enum_comparison_state(
506 mut self,
507 state: Option<&'a super::enums::EnumComparisonState>,
508 ) -> Self {
509 self.enum_comparison_states[0] = state;
510 self
511 }
512
513 pub fn with_enum_comparison_states(
516 mut self,
517 states: [Option<&'a super::enums::EnumComparisonState>; 4],
518 ) -> Self {
519 self.enum_comparison_states = states;
520 self
521 }
522
523 pub(super) fn enum_comparison_state(&self) -> Option<&super::enums::EnumComparisonState> {
524 self.enum_comparison_states[0]
525 }
526
527 pub(super) fn enum_comparison_state_at(
528 &self,
529 slot: usize,
530 ) -> Option<&super::enums::EnumComparisonState> {
531 self.enum_comparison_states[slot]
532 }
533
534 pub(super) fn row_lookup(&self) -> Result<&'a dyn RowLookup> {
535 self.row_lookup
536 .ok_or_else(|| SQLError::Internal("column reference without row context".into()))
537 }
538
539 pub fn column_value(&self, name: &str) -> Result<Value> {
543 self.column_value_with_control(name, &ProductionControl::uncontrolled())
544 .map(|value| value.into_uncontrolled().expect("ordinary column value"))
545 }
546
547 pub fn column_value_with_control(
549 &self,
550 name: &str,
551 control: &ProductionControl<'_>,
552 ) -> Result<Produced<Value>> {
553 control.check()?;
554 let row = self.row_lookup()?;
555 if row.column_is_ambiguous(name) {
556 return Err(SQLError::AmbiguousColumn(name.to_string()));
557 }
558 Ok(control.copy_value(row.column(name).unwrap_or(&Value::Null))?)
559 }
560
561 pub fn qualified_column_value(&self, qualifier: &str, column: &str) -> Result<Value> {
563 self.qualified_column_value_with_control(
564 qualifier,
565 column,
566 &ProductionControl::uncontrolled(),
567 )
568 .map(|value| {
569 value
570 .into_uncontrolled()
571 .expect("ordinary qualified column value")
572 })
573 }
574
575 pub fn qualified_column_value_with_control(
577 &self,
578 qualifier: &str,
579 column: &str,
580 control: &ProductionControl<'_>,
581 ) -> Result<Produced<Value>> {
582 control.check()?;
583 let row = self.row_lookup()?;
584 if row.qualified_column_is_ambiguous(qualifier, column) {
585 return Err(SQLError::AmbiguousColumn(format!("{qualifier}.{column}")));
586 }
587 Ok(control.copy_value(
588 row.qualified_column(qualifier, column)
589 .unwrap_or(&Value::Null),
590 )?)
591 }
592}
593
594#[cfg(test)]
595mod production_tests;