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