1use crate::ast::ColumnType;
8use crate::{SQLError, SQLParam};
9use uqa_core::{
10 memory::{Produced, ProductionControl},
11 Value,
12};
13
14use crate::schema::ScalarTypeSchema;
15use crate::{RowSchema, ScalarExpr};
16
17use super::FunctionTypeResolver;
18
19mod inputs;
20mod signature;
21pub use inputs::select_common_input_type;
22pub(crate) use inputs::select_common_input_type_in_with_control;
23pub(crate) use inputs::select_common_input_type_with_control;
24pub(super) use inputs::CommonInputType;
25pub use signature::function_call_argument_signature_with_control;
26
27pub(super) fn unknown_input(mut expression: &ScalarExpr) -> bool {
29 while let Ok(Some(clause)) = crate::catalog::collations::expression::scalar_clause(expression) {
30 expression = clause.argument;
31 }
32 matches!(
33 expression,
34 ScalarExpr::Literal(Value::Null | Value::Str(_)) | ScalarExpr::Param(_)
35 )
36}
37
38pub(crate) fn function_arguments_have_runtime_types_with_control(
40 arguments: &[ScalarExpr],
41 types: &[Option<ColumnType>],
42 control: &uqa_core::memory::ProductionControl<'_>,
43) -> Result<bool, SQLError> {
44 let arguments = crate::ir::scalar_call_arguments_with_control(arguments, control)?;
45 assert_eq!(arguments.len(), types.len());
46 Ok(arguments
47 .iter()
48 .zip(types)
49 .any(|(argument, ty)| runtime_input(argument.value, ty.as_ref())))
50}
51
52pub(crate) fn runtime_input(expression: &ScalarExpr, ty: Option<&ColumnType>) -> bool {
53 ty.is_none() && !unknown_input(expression)
54}
55
56#[doc(hidden)]
58pub type FunctionCallArgumentSignature = (Vec<Option<String>>, Vec<Option<ColumnType>>, bool);
59
60#[doc(hidden)]
62pub fn function_call_argument_signature(
63 arguments: &[ScalarExpr],
64 schema: &dyn ScalarTypeSchema,
65 params: &[SQLParam],
66 resolver: Option<&dyn FunctionTypeResolver>,
67) -> Result<FunctionCallArgumentSignature, SQLError> {
68 Ok(function_call_argument_signature_with_control(
69 arguments,
70 schema,
71 params,
72 resolver,
73 &ProductionControl::uncontrolled(),
74 )?
75 .into_uncontrolled()
76 .expect("ordinary call signature"))
77}
78
79pub(super) fn local_routine_name(name: &str) -> String {
80 let lower = name.to_ascii_lowercase();
81 lower
82 .strip_prefix("pg_catalog.")
83 .unwrap_or(&lower)
84 .to_string()
85}
86
87pub(super) fn numeric_type() -> ColumnType {
88 ColumnType::Numeric {
89 precision: None,
90 scale: None,
91 }
92}
93
94pub(crate) fn base_type(mut ty: &ColumnType) -> &ColumnType {
95 while let ColumnType::Domain { base, .. } = ty {
96 ty = base;
97 }
98 ty.without_temporal_modifiers()
99}
100
101pub(crate) fn literal_input_type_with_control(
103 mut ty: &ColumnType,
104 control: &ProductionControl<'_>,
105) -> Result<Produced<ColumnType>, SQLError> {
106 fn input_type(
107 ty: &ColumnType,
108 control: &ProductionControl<'_>,
109 ) -> Result<Produced<ColumnType>, SQLError> {
110 Ok(match ty {
111 ColumnType::IntervalWithFields { .. } | ColumnType::Domain { .. } => {
112 ty.clone_with_control(control)?
113 }
114 ColumnType::Array(element) => {
115 ColumnType::array_with_control(input_type(element, control)?, control)?
116 }
117 _ => ty.without_type_modifiers_with_control(control)?,
118 })
119 }
120 while let ColumnType::Domain { base, .. } = ty {
121 ty = base;
122 }
123 input_type(ty, control)
124}
125
126pub(crate) fn array_element_type(ty: &ColumnType) -> Option<&ColumnType> {
127 match base_type(ty) {
128 ColumnType::Array(element) => {
129 let mut element = element.as_ref();
130 while let ColumnType::Array(inner) = element {
131 element = inner;
132 }
133 Some(element)
134 }
135 ColumnType::Int2Vector => Some(&ColumnType::SmallInteger),
136 ColumnType::OidVector => Some(&ColumnType::Oid),
137 _ => None,
138 }
139}
140
141pub fn values_column_types(
142 rows: &[Vec<ScalarExpr>],
143 params: &[SQLParam],
144) -> Result<Vec<Option<ColumnType>>, SQLError> {
145 let width = rows.first().map_or(0, Vec::len);
146 let empty = RowSchema::default();
147 let control = ProductionControl::uncontrolled();
148 let mut types = (0..width)
149 .map(|_| CommonInputType::new())
150 .collect::<Vec<_>>();
151 for row in rows {
152 if row.len() != width {
153 return Err(SQLError::TypeMismatch(
154 "VALUES lists must all be the same length".into(),
155 ));
156 }
157 for (position, expression) in row.iter().enumerate() {
158 let ty = common_context_expression_type_with_control(
159 expression, &empty, params, None, &control,
160 )?;
161 if ty.is_some() || unknown_input(expression) {
162 types[position].include_owned(CommonTypeContext::Values, ty, &control)?;
163 }
164 }
165 }
166 types
167 .into_iter()
168 .map(|ty| {
169 ty.finish(&control).map(|ty| {
170 Some(
171 ty.into_uncontrolled()
172 .expect("ordinary VALUES type has no reservation"),
173 )
174 })
175 })
176 .collect()
177}
178
179pub fn common_context_expression_type(
181 expression: &ScalarExpr,
182 schema: &dyn ScalarTypeSchema,
183 params: &[SQLParam],
184 resolver: Option<&dyn FunctionTypeResolver>,
185) -> Result<Option<ColumnType>, SQLError> {
186 common_context_expression_type_with_control(
187 expression,
188 schema,
189 params,
190 resolver,
191 &ProductionControl::uncontrolled(),
192 )
193 .map(|ty| {
194 ty.map(|ty| {
195 ty.into_uncontrolled()
196 .expect("ordinary common-context inference has no reservation")
197 })
198 })
199}
200
201pub(crate) fn common_context_expression_type_with_control(
202 expression: &ScalarExpr,
203 schema: &dyn ScalarTypeSchema,
204 params: &[SQLParam],
205 resolver: Option<&dyn FunctionTypeResolver>,
206 control: &ProductionControl<'_>,
207) -> Result<Option<Produced<ColumnType>>, SQLError> {
208 control.check()?;
209 if let Some(ty) = schema.observed_expression_type(expression) {
210 return super::inference::copy_type(ty, control);
211 }
212 if let Some(clause) = crate::catalog::collations::expression::scalar_clause(expression)? {
213 let ty = common_context_expression_type_with_control(
214 clause.argument,
215 schema,
216 params,
217 resolver,
218 control,
219 )?;
220 crate::catalog::collations::expression::select_with_control(
221 clause.name,
222 clause.oid,
223 ty.as_deref(),
224 resolver,
225 control,
226 )?;
227 return Ok(ty);
228 }
229 if matches!(expression, ScalarExpr::Literal(Value::Str(_) | Value::Null)) {
230 return Ok(None);
231 }
232 super::scalar_type_inner_with_control(expression, schema, params, resolver, control)
233}
234
235#[doc(hidden)]
237pub fn effective_overload_argument_type(
238 expression: &ScalarExpr,
239 resolved: Option<ColumnType>,
240) -> Option<ColumnType> {
241 if effective_overload_argument_type_ref_with_params(expression, resolved.as_ref(), &[])
242 .is_some()
243 {
244 resolved
245 } else {
246 None
247 }
248}
249
250#[doc(hidden)]
252pub fn effective_overload_argument_type_with_params(
253 expression: &ScalarExpr,
254 resolved: Option<ColumnType>,
255 params: &[SQLParam],
256) -> Option<ColumnType> {
257 if effective_overload_argument_type_ref_with_params(expression, resolved.as_ref(), params)
258 .is_some()
259 {
260 resolved
261 } else {
262 None
263 }
264}
265
266pub(crate) fn effective_overload_argument_type_ref_with_params<'a>(
268 expression: &ScalarExpr,
269 resolved: Option<&'a ColumnType>,
270 params: &[SQLParam],
271) -> Option<&'a ColumnType> {
272 if let ScalarExpr::Param(index) = expression {
273 if index
274 .checked_sub(1)
275 .and_then(|index| params.get(index))
276 .is_some_and(|parameter| parameter.declared_scalar_type().is_some())
277 {
278 return resolved;
279 }
280 }
281 if matches!(expression, ScalarExpr::Literal(Value::Str(_) | Value::Null))
282 || matches!(expression, ScalarExpr::Param(_)) && matches!(resolved, Some(ColumnType::Text))
283 {
284 None
285 } else {
286 resolved
287 }
288}
289
290mod runtime;
291use runtime::RuntimeType;
292pub(crate) use runtime::{parameter_type_matches, parameter_type_with_control};
293
294pub(crate) fn value_type(value: &Value) -> Option<ColumnType> {
295 value_type_with_control(value, &ProductionControl::uncontrolled())
296 .expect("ordinary value type inference cannot be cancelled or limited")
297 .map(|value| {
298 value
299 .into_uncontrolled()
300 .expect("ordinary value type has no reservation")
301 })
302}
303
304pub fn runtime_value_type_with_control(
308 value: &Value,
309 catalog: Option<&dyn crate::expr::SQLValueCatalog>,
310 control: &ProductionControl<'_>,
311) -> Result<Option<Produced<ColumnType>>, SQLError> {
312 control.check()?;
313 if let Value::Datum(datum) = value {
314 if let Some(ty) = crate::catalog::type_metadata::builtin_scalar_type(datum.type_oid()) {
315 return Ok(Some(ty.clone_with_control(control)?));
316 }
317 let ty = catalog
318 .map(|catalog| catalog.value_type_by_oid(datum.type_oid()))
319 .transpose()?
320 .flatten();
321 control.check()?;
322 return Ok(ty
323 .map(|ty| ty.retain_external_with_control(control))
324 .transpose()?);
325 }
326 value_type_with_control(value, control)
327}
328
329pub(crate) fn value_type_with_control(
330 value: &Value,
331 control: &ProductionControl<'_>,
332) -> Result<Option<Produced<ColumnType>>, SQLError> {
333 RuntimeType::infer(value, control)?
334 .map(|ty| ty.into_produced(control))
335 .transpose()
336}
337
338pub(super) fn merge_value_types(
339 left: Option<Produced<ColumnType>>,
340 right: Option<Produced<ColumnType>>,
341 control: &ProductionControl<'_>,
342) -> Result<Option<Produced<ColumnType>>, SQLError> {
343 control.check()?;
344 match (left, right) {
345 (None, other) | (other, None) => Ok(other),
346 (Some(left), Some(right)) if *left == *right => Ok(Some(left)),
347 (Some(left), Some(right)) => common_type_with_control(&left, &right, control).map(Some),
348 }
349}
350
351pub(super) fn read_unknown_literals<'a>(
353 expressions: impl IntoIterator<Item = &'a ScalarExpr>,
354 target: &ColumnType,
355) -> Result<(), SQLError> {
356 read_unknown_literals_with_control(expressions, target, &ProductionControl::uncontrolled())
357}
358
359pub(super) fn read_unknown_literals_with_control<'a>(
360 expressions: impl IntoIterator<Item = &'a ScalarExpr>,
361 target: &ColumnType,
362 control: &ProductionControl<'_>,
363) -> Result<(), SQLError> {
364 control.check()?;
365 if super::catalog_input_type(target) {
366 return Ok(());
367 }
368 let target = base_type(target).without_type_modifiers_with_control(control)?;
369 let name = target.catalog_name_with_control(control)?;
370 for expression in expressions {
371 control.check()?;
372 if let ScalarExpr::Literal(Value::Str(text)) = expression {
373 let (text, memory) = control.copy_text(text)?.into_parts();
374 let input = control.finish(Value::Str(text), memory)?;
375 crate::expr::cast_value_from_with_control(&input, &name, None, control)?;
376 }
377 }
378 Ok(())
379}
380
381pub fn common_type(left: &ColumnType, right: &ColumnType) -> Result<ColumnType, SQLError> {
382 common_type_with_control(left, right, &ProductionControl::uncontrolled()).map(|value| {
383 value
384 .into_uncontrolled()
385 .expect("ordinary common type has no reservation")
386 })
387}
388
389pub fn common_type_in(
391 context: CommonTypeContext,
392 left: &ColumnType,
393 right: &ColumnType,
394) -> Result<ColumnType, SQLError> {
395 common_type_in_with_control(context, left, right, &ProductionControl::uncontrolled()).map(
396 |value| {
397 value
398 .into_uncontrolled()
399 .expect("ordinary common type has no reservation")
400 },
401 )
402}
403
404pub fn common_type_in_with_control(
406 context: CommonTypeContext,
407 left: &ColumnType,
408 right: &ColumnType,
409 control: &ProductionControl<'_>,
410) -> Result<Produced<ColumnType>, SQLError> {
411 select_pair_with_control(left, right, control).map_err(|failure| failure.in_context(context))
412}
413
414#[derive(Clone, Copy, Debug, PartialEq, Eq)]
416pub enum CommonTypeContext {
417 Union,
418 Intersect,
419 Except,
420 Values,
421 Case,
422 Coalesce,
423 Array,
424 Greatest,
425 Least,
426 In,
427 JoinUsing,
428 Cycle,
429}
430
431impl CommonTypeContext {
432 pub const fn label(self) -> &'static str {
433 match self {
434 Self::Union => "UNION",
435 Self::Intersect => "INTERSECT",
436 Self::Except => "EXCEPT",
437 Self::Values => "VALUES",
438 Self::Case => "CASE",
439 Self::Coalesce => "COALESCE",
440 Self::Array => "ARRAY",
441 Self::Greatest => "GREATEST",
442 Self::Least => "LEAST",
443 Self::In => "IN",
444 Self::JoinUsing => "JOIN/USING",
445 Self::Cycle => "CYCLE",
446 }
447 }
448
449 pub const fn coercion_label(self) -> &'static str {
451 match self {
452 Self::Case => "CASE/WHEN",
453 other => other.label(),
454 }
455 }
456
457 pub const fn set_operation(kind: crate::ast::SetOpKind) -> Self {
458 match kind {
459 crate::ast::SetOpKind::Union => Self::Union,
460 crate::ast::SetOpKind::Intersect => Self::Intersect,
461 crate::ast::SetOpKind::Except => Self::Except,
462 }
463 }
464
465 pub fn function(name: &str) -> Option<Self> {
467 match local_routine_name(name).as_str() {
468 "coalesce" => Some(Self::Coalesce),
469 "greatest" => Some(Self::Greatest),
470 "least" => Some(Self::Least),
471 _ => None,
472 }
473 }
474}
475
476#[derive(Debug)]
478pub(super) enum CommonTypeFailure {
479 Unmatched(Box<(ColumnType, ColumnType)>),
481 Inconvertible(Box<(ColumnType, ColumnType)>),
483 Failed(Box<SQLError>),
484}
485
486impl CommonTypeFailure {
487 fn failed(error: impl Into<SQLError>) -> Self {
488 Self::Failed(Box::new(error.into()))
489 }
490
491 fn in_context(self, context: CommonTypeContext) -> SQLError {
493 match self {
494 Self::Unmatched(types) => SQLError::Routine {
495 sqlstate: "42804".into(),
496 message: format!(
497 "{} types {} and {} cannot be matched",
498 context.label(),
499 types.0.sql_name(),
500 types.1.sql_name()
501 ),
502 },
503 Self::Inconvertible(types) => SQLError::Routine {
504 sqlstate: "42846".into(),
505 message: format!(
506 "{} could not convert type {} to {}",
507 context.coercion_label(),
508 types.0.sql_name(),
509 types.1.sql_name()
510 ),
511 },
512 Self::Failed(error) => *error,
513 }
514 }
515
516 fn without_context(self, left: &ColumnType, right: &ColumnType) -> SQLError {
518 match self {
519 Self::Failed(error) => *error,
520 Self::Unmatched(_) | Self::Inconvertible(_) => SQLError::TypeMismatch(format!(
521 "types {} and {} cannot be matched",
522 left.sql_name(),
523 right.sql_name()
524 )),
525 }
526 }
527}
528
529pub(super) fn common_type_with_control(
531 left: &ColumnType,
532 right: &ColumnType,
533 control: &ProductionControl<'_>,
534) -> Result<Produced<ColumnType>, SQLError> {
535 select_pair_with_control(left, right, control)
536 .map_err(|failure| failure.without_context(left, right))
537}
538
539fn select_pair_with_control(
541 left: &ColumnType,
542 right: &ColumnType,
543 control: &ProductionControl<'_>,
544) -> Result<Produced<ColumnType>, CommonTypeFailure> {
545 control.check().map_err(CommonTypeFailure::failed)?;
546 if left == right {
547 return left
548 .clone_with_control(control)
549 .map_err(CommonTypeFailure::failed);
550 }
551 if left != left.without_temporal_modifiers() || right != right.without_temporal_modifiers() {
552 return select_pair_with_control(
553 left.without_temporal_modifiers(),
554 right.without_temporal_modifiers(),
555 control,
556 );
557 }
558 if matches!(left, ColumnType::Domain { .. }) || matches!(right, ColumnType::Domain { .. }) {
559 return select_pair_with_control(base_type(left), base_type(right), control);
560 }
561 if let (ColumnType::Array(_), ColumnType::Array(_)) = (left, right) {
562 let element = select_pair_with_control(
564 innermost_array_element(left),
565 innermost_array_element(right),
566 control,
567 )?;
568 return ColumnType::array_with_control(element, control).map_err(CommonTypeFailure::failed);
569 }
570 let scalar = match common_scalar_type(left, right) {
571 Some(scalar) => scalar,
572 None => same_category_common_type(left, right)?,
573 };
574 control
575 .finish(scalar, control.empty_reservation())
576 .map_err(CommonTypeFailure::failed)
577}
578
579fn common_scalar_type(left: &ColumnType, right: &ColumnType) -> Option<ColumnType> {
581 if let Some(numeric) = common_numeric_type(left, right) {
582 return Some(numeric);
583 }
584 if matches!(left, ColumnType::Oid) && is_integral_type(right)
585 || matches!(right, ColumnType::Oid) && is_integral_type(left)
586 {
587 return Some(ColumnType::Oid);
588 }
589 if left.is_character_string() && right.is_character_string() {
590 return Some(match left {
591 ColumnType::Bpchar | ColumnType::Character(_) => ColumnType::Bpchar,
592 ColumnType::Varchar(_) => ColumnType::Varchar(None),
593 ColumnType::Name => ColumnType::Name,
594 _ => ColumnType::Text,
595 });
596 }
597 match (left, right) {
598 (ColumnType::Date, ColumnType::Timestamp) | (ColumnType::Timestamp, ColumnType::Date) => {
599 Some(ColumnType::Timestamp)
600 }
601 (ColumnType::Date | ColumnType::Timestamp, ColumnType::TimestampTz)
602 | (ColumnType::TimestampTz, ColumnType::Date | ColumnType::Timestamp) => {
603 Some(ColumnType::TimestampTz)
604 }
605 _ => None,
606 }
607}
608
609fn same_category_common_type(
611 left: &ColumnType,
612 right: &ColumnType,
613) -> Result<ColumnType, CommonTypeFailure> {
614 let left_name = super::canonical_column_type_name(left);
615 let right_name = super::canonical_column_type_name(right);
616 match category_choice(&left_name, &right_name) {
617 CategoryChoice::Left => Ok(left.clone()),
618 CategoryChoice::Right => Ok(right.clone()),
619 CategoryChoice::Unmatched => Err(CommonTypeFailure::Unmatched(Box::new((
620 left.clone(),
621 right.clone(),
622 )))),
623 CategoryChoice::Inconvertible => Err(CommonTypeFailure::Inconvertible(Box::new((
624 right.clone(),
625 left.clone(),
626 )))),
627 }
628}
629
630enum CategoryChoice {
631 Left,
632 Right,
633 Unmatched,
634 Inconvertible,
635}
636
637fn category_choice(left: &str, right: &str) -> CategoryChoice {
639 use super::overload_resolution::{
640 canonical_type_category, canonical_type_is_preferred,
641 routine_type_accepts_implicit_cast as implicit,
642 };
643 if canonical_type_category(left) != canonical_type_category(right) {
644 return CategoryChoice::Unmatched;
645 }
646 if !canonical_type_is_preferred(left) && implicit(left, right) && !implicit(right, left) {
647 return CategoryChoice::Right;
648 }
649 if implicit(right, left) {
650 CategoryChoice::Left
651 } else {
652 CategoryChoice::Inconvertible
653 }
654}
655
656pub(super) mod case;
657
658fn innermost_array_element(mut ty: &ColumnType) -> &ColumnType {
660 while let ColumnType::Array(element) = ty {
661 ty = element;
662 }
663 ty
664}
665
666fn is_integral_type(ty: &ColumnType) -> bool {
667 matches!(
668 base_type(ty),
669 ColumnType::SmallInteger | ColumnType::Integer | ColumnType::BigInteger
670 )
671}
672
673pub(super) fn common_numeric_type(left: &ColumnType, right: &ColumnType) -> Option<ColumnType> {
674 let rank = numeric_rank(left)?.max(numeric_rank(right)?);
675 Some(match rank {
676 0 => ColumnType::SmallInteger,
677 1 => ColumnType::Integer,
678 2 => ColumnType::BigInteger,
679 3 => numeric_type(),
680 4 => ColumnType::Real,
681 _ => ColumnType::DoublePrecision,
682 })
683}
684
685pub(super) fn numeric_rank(ty: &ColumnType) -> Option<u8> {
686 match ty {
687 ColumnType::SmallInteger => Some(0),
688 ColumnType::Integer => Some(1),
689 ColumnType::BigInteger => Some(2),
690 ColumnType::Numeric { .. } => Some(3),
691 ColumnType::Real => Some(4),
692 ColumnType::DoublePrecision => Some(5),
693 _ => None,
694 }
695}
696
697pub(super) fn same_operator_type_with_control(
699 left: &ColumnType,
700 right: &ColumnType,
701 control: &ProductionControl<'_>,
702) -> Result<bool, uqa_core::ValueRetentionError> {
703 fn element(mut ty: &ColumnType) -> &ColumnType {
704 while let ColumnType::Array(inner) = ty {
705 ty = inner;
706 }
707 ty
708 }
709 let left = base_type(left);
710 let right = base_type(right);
711 let (left, right) = match (left, right) {
712 (ColumnType::Array(left), ColumnType::Array(right)) => (element(left), element(right)),
713 _ => (left, right),
714 };
715 let left = left.without_type_modifiers_with_control(control)?;
716 let right = right.without_type_modifiers_with_control(control)?;
717 Ok(*left == *right)
718}
719
720#[cfg(test)]
721mod production_tests;