Skip to main content

uqa_sql/type_resolution/
common.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7use 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
24/// Inputs whose absent type means `PostgreSQL` `unknown`, rather than an unresolved UQA runtime value.
25pub(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/// A column or callback whose type is unavailable remains a runtime carrier; it cannot participate in overload selection as an unknown string or NULL literal.
36pub(crate) fn function_arguments_have_runtime_types(
37    arguments: &[ScalarExpr],
38    types: &[Option<ColumnType>],
39) -> Result<bool, SQLError> {
40    let arguments = scalar_call_arguments(arguments)?;
41    assert_eq!(arguments.len(), types.len());
42    Ok(arguments
43        .iter()
44        .zip(types)
45        .any(|(argument, ty)| runtime_input(argument.value, ty.as_ref())))
46}
47
48pub(crate) fn runtime_input(expression: &ScalarExpr, ty: Option<&ColumnType>) -> bool {
49    ty.is_none() && !unknown_input(expression)
50}
51
52/// Decoded function-call argument names, effective overload types, and whether the call used explicit `VARIADIC` syntax.
53#[doc(hidden)]
54pub type FunctionCallArgumentSignature = (Vec<Option<String>>, Vec<Option<ColumnType>>, bool);
55
56/// Build the PostgreSQL-compatible overload signature for one physical function call using the shared common-context typing rule.
57#[doc(hidden)]
58pub fn function_call_argument_signature(
59    arguments: &[ScalarExpr],
60    schema: &dyn ScalarTypeSchema,
61    params: &[SQLParam],
62    resolver: Option<&dyn FunctionTypeResolver>,
63) -> Result<FunctionCallArgumentSignature, SQLError> {
64    let call_arguments = scalar_call_arguments(arguments)?;
65    let explicit_variadic = call_arguments
66        .iter()
67        .any(|argument| argument.explicit_variadic);
68    let mut argument_names = Vec::with_capacity(call_arguments.len());
69    let mut argument_types = Vec::with_capacity(call_arguments.len());
70    for argument in call_arguments {
71        argument_names.push(argument.name.map(str::to_string));
72        let argument_type =
73            common_context_expression_type(argument.value, schema, params, resolver)?;
74        argument_types.push(effective_overload_argument_type_with_params(
75            argument.value,
76            argument_type,
77            params,
78        ));
79    }
80    Ok((argument_names, argument_types, explicit_variadic))
81}
82
83pub(super) fn local_routine_name(name: &str) -> String {
84    let lower = name.to_ascii_lowercase();
85    lower
86        .strip_prefix("pg_catalog.")
87        .unwrap_or(&lower)
88        .to_string()
89}
90
91pub(super) fn numeric_type() -> ColumnType {
92    ColumnType::Numeric {
93        precision: None,
94        scale: None,
95    }
96}
97
98pub(crate) fn base_type(mut ty: &ColumnType) -> &ColumnType {
99    while let ColumnType::Domain { base, .. } = ty {
100        ty = base;
101    }
102    ty.without_temporal_modifiers()
103}
104
105/// `coerce_type` reads a scalar domain through its base input, but array input keeps each element's domain checks. Input functions receive interval modifiers; other modifiers remain on the outer coercion.
106pub(crate) fn literal_input_type_with_control(
107    mut ty: &ColumnType,
108    control: &ProductionControl<'_>,
109) -> Result<Produced<ColumnType>, SQLError> {
110    fn input_type(
111        ty: &ColumnType,
112        control: &ProductionControl<'_>,
113    ) -> Result<Produced<ColumnType>, SQLError> {
114        Ok(match ty {
115            ColumnType::IntervalWithFields { .. } | ColumnType::Domain { .. } => {
116                ty.clone_with_control(control)?
117            }
118            ColumnType::Array(element) => {
119                ColumnType::array_with_control(input_type(element, control)?, control)?
120            }
121            _ => ty.without_type_modifiers_with_control(control)?,
122        })
123    }
124    while let ColumnType::Domain { base, .. } = ty {
125        ty = base;
126    }
127    input_type(ty, control)
128}
129
130pub(crate) fn array_element_type(ty: &ColumnType) -> Option<&ColumnType> {
131    match base_type(ty) {
132        ColumnType::Array(element) => {
133            let mut element = element.as_ref();
134            while let ColumnType::Array(inner) = element {
135                element = inner;
136            }
137            Some(element)
138        }
139        ColumnType::Int2Vector => Some(&ColumnType::SmallInteger),
140        ColumnType::OidVector => Some(&ColumnType::Oid),
141        _ => None,
142    }
143}
144
145pub fn values_column_types(
146    rows: &[Vec<ScalarExpr>],
147    params: &[SQLParam],
148) -> Result<Vec<Option<ColumnType>>, SQLError> {
149    let width = rows.first().map_or(0, Vec::len);
150    let empty = RowSchema::default();
151    let control = ProductionControl::uncontrolled();
152    let mut types = (0..width)
153        .map(|_| CommonInputType::new())
154        .collect::<Vec<_>>();
155    for row in rows {
156        if row.len() != width {
157            return Err(SQLError::TypeMismatch(
158                "VALUES lists must all be the same length".into(),
159            ));
160        }
161        for (position, expression) in row.iter().enumerate() {
162            let ty = common_context_expression_type_with_control(
163                expression, &empty, params, None, &control,
164            )?;
165            if ty.is_some() || unknown_input(expression) {
166                types[position].include_owned(CommonTypeContext::Values, ty, &control)?;
167            }
168        }
169    }
170    types
171        .into_iter()
172        .map(|ty| {
173            ty.finish(&control).map(|ty| {
174                Some(
175                    ty.into_uncontrolled()
176                        .expect("ordinary VALUES type has no reservation"),
177                )
178            })
179        })
180        .collect()
181}
182
183/// Resolve an expression participating in `PostgreSQL`'s common-type selection. Bare string and NULL literals retain the parser's `unknown` type until the surrounding VALUES, set operation, CASE, or array context selects a concrete type.
184pub fn common_context_expression_type(
185    expression: &ScalarExpr,
186    schema: &dyn ScalarTypeSchema,
187    params: &[SQLParam],
188    resolver: Option<&dyn FunctionTypeResolver>,
189) -> Result<Option<ColumnType>, SQLError> {
190    common_context_expression_type_with_control(
191        expression,
192        schema,
193        params,
194        resolver,
195        &ProductionControl::uncontrolled(),
196    )
197    .map(|ty| {
198        ty.map(|ty| {
199            ty.into_uncontrolled()
200                .expect("ordinary common-context inference has no reservation")
201        })
202    })
203}
204
205pub(super) fn common_context_expression_type_with_control(
206    expression: &ScalarExpr,
207    schema: &dyn ScalarTypeSchema,
208    params: &[SQLParam],
209    resolver: Option<&dyn FunctionTypeResolver>,
210    control: &ProductionControl<'_>,
211) -> Result<Option<Produced<ColumnType>>, SQLError> {
212    control.check()?;
213    if let Some(ty) = schema.observed_expression_type(expression) {
214        return super::inference::copy_type(ty, control);
215    }
216    if let Some(clause) = crate::catalog::collations::expression::scalar_clause(expression)? {
217        let ty = common_context_expression_type_with_control(
218            clause.argument,
219            schema,
220            params,
221            resolver,
222            control,
223        )?;
224        crate::catalog::collations::expression::select_with_control(
225            clause.name,
226            clause.oid,
227            ty.as_deref(),
228            resolver,
229            control,
230        )?;
231        return Ok(ty);
232    }
233    if matches!(expression, ScalarExpr::Literal(Value::Str(_) | Value::Null)) {
234        return Ok(None);
235    }
236    super::scalar_type_inner_with_control(expression, schema, params, resolver, control)
237}
238
239/// Preserve parser-level `unknown` identity for fixed built-in overload selection.
240#[doc(hidden)]
241pub fn effective_overload_argument_type(
242    expression: &ScalarExpr,
243    resolved: Option<ColumnType>,
244) -> Option<ColumnType> {
245    if effective_overload_argument_type_ref_with_params(expression, resolved.as_ref(), &[])
246        .is_some()
247    {
248        resolved
249    } else {
250        None
251    }
252}
253
254/// Preserve an explicitly typed scalar parameter while retaining the legacy `unknown` treatment of untyped text-valued [`SQLParam::Scalar`] parameters.
255#[doc(hidden)]
256pub fn effective_overload_argument_type_with_params(
257    expression: &ScalarExpr,
258    resolved: Option<ColumnType>,
259    params: &[SQLParam],
260) -> Option<ColumnType> {
261    if effective_overload_argument_type_ref_with_params(expression, resolved.as_ref(), params)
262        .is_some()
263    {
264        resolved
265    } else {
266        None
267    }
268}
269
270/// Borrow the same effective argument type before a controlled caller decides whether a payload copy is needed.
271pub(super) fn effective_overload_argument_type_ref_with_params<'a>(
272    expression: &ScalarExpr,
273    resolved: Option<&'a ColumnType>,
274    params: &[SQLParam],
275) -> Option<&'a ColumnType> {
276    if let ScalarExpr::Param(index) = expression {
277        if index
278            .checked_sub(1)
279            .and_then(|index| params.get(index))
280            .is_some_and(|parameter| parameter.declared_scalar_type().is_some())
281        {
282            return resolved;
283        }
284    }
285    if matches!(expression, ScalarExpr::Literal(Value::Str(_) | Value::Null))
286        || matches!(expression, ScalarExpr::Param(_)) && matches!(resolved, Some(ColumnType::Text))
287    {
288        None
289    } else {
290        resolved
291    }
292}
293
294pub(super) fn parameter_type_with_control(
295    parameter: &SQLParam,
296    control: &ProductionControl<'_>,
297) -> Result<Option<Produced<ColumnType>>, SQLError> {
298    control.check()?;
299    let scalar = match parameter {
300        SQLParam::Scalar(value) => return value_type_with_control(value, control),
301        SQLParam::TypedScalar { ty, .. } | SQLParam::DeferredError { ty, .. } => {
302            return Ok(Some(ty.clone_with_control(control)?))
303        }
304        SQLParam::Vector(values) => u32::try_from(values.len()).ok().map(ColumnType::Vector),
305        SQLParam::TypedTensor(value) => Some(ColumnType::Tensor(value.dimensions())),
306        SQLParam::Tensor(values) => values
307            .first()
308            .and_then(|values| u32::try_from(values.len()).ok())
309            .map(ColumnType::Tensor),
310    };
311    scalar
312        .map(|ty| {
313            control
314                .finish(ty, control.empty_reservation())
315                .map_err(Into::into)
316        })
317        .transpose()
318}
319
320pub(crate) fn value_type(value: &Value) -> Option<ColumnType> {
321    value_type_with_control(value, &ProductionControl::uncontrolled())
322        .expect("ordinary value type inference cannot be cancelled or limited")
323        .map(|value| {
324            value
325                .into_uncontrolled()
326                .expect("ordinary value type has no reservation")
327        })
328}
329
330/// Observe an untyped host argument using its physical OID or SQL's runtime
331/// carrier rules. This never reads physical payload bytes or reconstructs an
332/// expression's lost declaration/modifiers. Unknown carriers return None.
333pub fn runtime_value_type_with_control(
334    value: &Value,
335    catalog: Option<&dyn crate::expr::SQLValueCatalog>,
336    control: &ProductionControl<'_>,
337) -> Result<Option<Produced<ColumnType>>, SQLError> {
338    control.check()?;
339    if let Value::Datum(datum) = value {
340        if let Some(ty) = crate::catalog::type_metadata::builtin_scalar_type(datum.type_oid()) {
341            return Ok(Some(ty.clone_with_control(control)?));
342        }
343        let ty = catalog
344            .map(|catalog| catalog.value_type_by_oid(datum.type_oid()))
345            .transpose()?
346            .flatten();
347        control.check()?;
348        return Ok(ty
349            .map(|ty| ty.retain_external_with_control(control))
350            .transpose()?);
351    }
352    value_type_with_control(value, control)
353}
354
355pub(crate) fn value_type_with_control(
356    value: &Value,
357    control: &ProductionControl<'_>,
358) -> Result<Option<Produced<ColumnType>>, SQLError> {
359    control.check()?;
360    let scalar = match value {
361        // A runtime enum carrier knows only its type OID; declared expression types supply the enum's identity.
362        Value::Null | Value::Map(_) | Value::Enum(_) | Value::Datum(_) => None,
363        Value::Void => Some(ColumnType::Void),
364        Value::Row(_) | Value::Record(_) => Some(ColumnType::Record),
365        Value::Bool(_) => Some(ColumnType::Boolean),
366        Value::Int(value) if i32::try_from(*value).is_ok() => Some(ColumnType::Integer),
367        Value::Int(_) => Some(ColumnType::BigInteger),
368        Value::Float(_) => Some(ColumnType::DoublePrecision),
369        Value::Decimal(_) => Some(numeric_type()),
370        Value::Str(_) => Some(ColumnType::Text),
371        Value::FixedChar(value) => {
372            let mut count = 0_usize;
373            for _ in value.chars() {
374                control.check()?;
375                count += 1;
376            }
377            u32::try_from(count).ok().map(ColumnType::Character)
378        }
379        Value::Bytes(_) => Some(ColumnType::Bytea),
380        Value::BitString(_) => Some(ColumnType::Bit(None)),
381        Value::Temporal(value) => Some(match value {
382            uqa_core::TemporalValue::Date { .. } => ColumnType::Date,
383            uqa_core::TemporalValue::Time { .. } => ColumnType::Time,
384            uqa_core::TemporalValue::TimeTz { .. } => ColumnType::TimeTz,
385            uqa_core::TemporalValue::Timestamp { .. } => ColumnType::Timestamp,
386            uqa_core::TemporalValue::TimestampTz { .. } => ColumnType::TimestampTz,
387            uqa_core::TemporalValue::Interval { .. } => ColumnType::Interval,
388        }),
389        Value::Json(_) => Some(ColumnType::Json),
390        Value::JsonB(_) => Some(ColumnType::JsonB),
391        Value::LegacyVector(vector) => Some(match vector.kind() {
392            uqa_core::LegacyVectorKind::SmallInteger => ColumnType::Int2Vector,
393            uqa_core::LegacyVectorKind::Oid => ColumnType::OidVector,
394        }),
395        Value::Array(array) => {
396            let mut element = None;
397            if !merge_array_element_types(array.elements(), &mut element, control)? {
398                return Ok(None);
399            }
400            return element
401                .map(|element| ColumnType::array_with_control(element, control).map_err(Into::into))
402                .transpose();
403        }
404        Value::List(values) => {
405            let mut element = None;
406            for value in values {
407                let next = value_type_with_control(value, control)?;
408                match merge_value_types(element, next, control) {
409                    Ok(merged) => element = merged,
410                    Err(error) if matches!(error.sqlstate(), Some("53200" | "57014")) => {
411                        return Err(error)
412                    }
413                    Err(_) => return Ok(None),
414                }
415            }
416            return element
417                .map(|element| ColumnType::array_with_control(element, control).map_err(Into::into))
418                .transpose();
419        }
420    };
421    scalar
422        .map(|ty| {
423            control
424                .finish(ty, control.empty_reservation())
425                .map_err(Into::into)
426        })
427        .transpose()
428}
429
430fn merge_array_element_types(
431    values: &[Value],
432    element: &mut Option<Produced<ColumnType>>,
433    control: &ProductionControl<'_>,
434) -> Result<bool, SQLError> {
435    for value in values {
436        control.check()?;
437        if let Value::List(nested) = value {
438            if !merge_array_element_types(nested, element, control)? {
439                return Ok(false);
440            }
441        } else {
442            match merge_value_types(
443                element.take(),
444                value_type_with_control(value, control)?,
445                control,
446            ) {
447                Ok(merged) => *element = merged,
448                Err(error) if matches!(error.sqlstate(), Some("53200" | "57014")) => {
449                    return Err(error)
450                }
451                Err(_) => return Ok(false),
452            }
453        }
454    }
455    Ok(true)
456}
457
458pub(super) fn merge_value_types(
459    left: Option<Produced<ColumnType>>,
460    right: Option<Produced<ColumnType>>,
461    control: &ProductionControl<'_>,
462) -> Result<Option<Produced<ColumnType>>, SQLError> {
463    control.check()?;
464    match (left, right) {
465        (None, other) | (other, None) => Ok(other),
466        (Some(left), Some(right)) if *left == *right => Ok(Some(left)),
467        (Some(left), Some(right)) => common_type_with_control(&left, &right, control).map(Some),
468    }
469}
470
471/// `coerce_to_common_type` reads an `unknown` string constant with the selected type's input function, which reports what the type rejects, before the statement runs. A type whose input function consults the catalog is read when the expression is bound to it.
472pub(super) fn read_unknown_literals<'a>(
473    expressions: impl IntoIterator<Item = &'a ScalarExpr>,
474    target: &ColumnType,
475) -> Result<(), SQLError> {
476    if super::catalog_input_type(target) {
477        return Ok(());
478    }
479    // `coerce_type` hands the literal to the target type's input function, so the diagnostic is the input function's.
480    let target = base_type(target).without_type_modifiers().catalog_name();
481    for expression in expressions {
482        if let ScalarExpr::Literal(Value::Str(text)) = expression {
483            crate::expr::cast_value_from(&Value::Str(text.clone()), &target, None)?;
484        }
485    }
486    Ok(())
487}
488
489pub fn common_type(left: &ColumnType, right: &ColumnType) -> Result<ColumnType, SQLError> {
490    common_type_with_control(left, right, &ProductionControl::uncontrolled()).map(|value| {
491        value
492            .into_uncontrolled()
493            .expect("ordinary common type has no reservation")
494    })
495}
496
497/// The common type of `left` and `right` for the construct `context`, which reports a conflict as `select_common_type` and `coerce_to_common_type` report it: `42804` when the types are of different categories and `42846` when the other type has no implicit cast to the selected one.
498pub fn common_type_in(
499    context: CommonTypeContext,
500    left: &ColumnType,
501    right: &ColumnType,
502) -> Result<ColumnType, SQLError> {
503    select_pair_with_control(left, right, &ProductionControl::uncontrolled())
504        .map(|value| {
505            value
506                .into_uncontrolled()
507                .expect("ordinary common type has no reservation")
508        })
509        .map_err(|failure| failure.in_context(context))
510}
511
512/// The construct selecting a common type, as `select_common_type` and `coerce_to_common_type` name it in their diagnostics.
513#[derive(Clone, Copy, Debug, PartialEq, Eq)]
514pub enum CommonTypeContext {
515    Union,
516    Intersect,
517    Except,
518    Values,
519    Case,
520    Coalesce,
521    Array,
522    Greatest,
523    Least,
524    In,
525    JoinUsing,
526    Cycle,
527}
528
529impl CommonTypeContext {
530    pub const fn label(self) -> &'static str {
531        match self {
532            Self::Union => "UNION",
533            Self::Intersect => "INTERSECT",
534            Self::Except => "EXCEPT",
535            Self::Values => "VALUES",
536            Self::Case => "CASE",
537            Self::Coalesce => "COALESCE",
538            Self::Array => "ARRAY",
539            Self::Greatest => "GREATEST",
540            Self::Least => "LEAST",
541            Self::In => "IN",
542            Self::JoinUsing => "JOIN/USING",
543            Self::Cycle => "CYCLE",
544        }
545    }
546
547    /// The name `coerce_to_common_type` reports: `transformCaseExpr` coerces the results in a `CASE/WHEN` context.
548    pub const fn coercion_label(self) -> &'static str {
549        match self {
550            Self::Case => "CASE/WHEN",
551            other => other.label(),
552        }
553    }
554
555    pub const fn set_operation(kind: crate::ast::SetOpKind) -> Self {
556        match kind {
557            crate::ast::SetOpKind::Union => Self::Union,
558            crate::ast::SetOpKind::Intersect => Self::Intersect,
559            crate::ast::SetOpKind::Except => Self::Except,
560        }
561    }
562
563    /// The context of a function whose arguments share a common type.
564    pub fn function(name: &str) -> Option<Self> {
565        match local_routine_name(name).as_str() {
566            "coalesce" => Some(Self::Coalesce),
567            "greatest" => Some(Self::Greatest),
568            "least" => Some(Self::Least),
569            _ => None,
570        }
571    }
572}
573
574/// Why two types have no common type: `select_common_type` finds them in different categories, or `coerce_to_common_type` finds no implicit cast from the other type to the selected one. `Failed` carries an error the selection itself met.
575#[derive(Debug)]
576pub(super) enum CommonTypeFailure {
577    /// The two types, in the order they met.
578    Unmatched(Box<(ColumnType, ColumnType)>),
579    /// The type without an implicit cast, and the selected type it would convert to.
580    Inconvertible(Box<(ColumnType, ColumnType)>),
581    Failed(Box<SQLError>),
582}
583
584impl CommonTypeFailure {
585    fn failed(error: impl Into<SQLError>) -> Self {
586        Self::Failed(Box::new(error.into()))
587    }
588
589    /// The diagnostic the construct `context` reports.
590    fn in_context(self, context: CommonTypeContext) -> SQLError {
591        match self {
592            Self::Unmatched(types) => SQLError::Routine {
593                sqlstate: "42804".into(),
594                message: format!(
595                    "{} types {} and {} cannot be matched",
596                    context.label(),
597                    types.0.sql_name(),
598                    types.1.sql_name()
599                ),
600            },
601            Self::Inconvertible(types) => SQLError::Routine {
602                sqlstate: "42846".into(),
603                message: format!(
604                    "{} could not convert type {} to {}",
605                    context.coercion_label(),
606                    types.0.sql_name(),
607                    types.1.sql_name()
608                ),
609            },
610            Self::Failed(error) => *error,
611        }
612    }
613
614    /// The diagnostic of a selection without a construct: a type mismatch naming the two types.
615    fn without_context(self, left: &ColumnType, right: &ColumnType) -> SQLError {
616        match self {
617            Self::Failed(error) => *error,
618            Self::Unmatched(_) | Self::Inconvertible(_) => SQLError::TypeMismatch(format!(
619                "types {} and {} cannot be matched",
620                left.sql_name(),
621                right.sql_name()
622            )),
623        }
624    }
625}
626
627/// Preserve the existing common-type rules while the selected type owns its copied names and array boxes; a conflict is a type mismatch naming the two types.
628pub(super) fn common_type_with_control(
629    left: &ColumnType,
630    right: &ColumnType,
631    control: &ProductionControl<'_>,
632) -> Result<Produced<ColumnType>, SQLError> {
633    select_pair_with_control(left, right, control)
634        .map_err(|failure| failure.without_context(left, right))
635}
636
637/// `select_common_type` over two types: equal types, temporal modifiers and domains reduce first, then the numeric, OID, character, temporal and array rules, and then the category rule.
638fn select_pair_with_control(
639    left: &ColumnType,
640    right: &ColumnType,
641    control: &ProductionControl<'_>,
642) -> Result<Produced<ColumnType>, CommonTypeFailure> {
643    control.check().map_err(CommonTypeFailure::failed)?;
644    if left == right {
645        return left
646            .clone_with_control(control)
647            .map_err(CommonTypeFailure::failed);
648    }
649    if left != left.without_temporal_modifiers() || right != right.without_temporal_modifiers() {
650        return select_pair_with_control(
651            left.without_temporal_modifiers(),
652            right.without_temporal_modifiers(),
653            control,
654        );
655    }
656    if matches!(left, ColumnType::Domain { .. }) || matches!(right, ColumnType::Domain { .. }) {
657        return select_pair_with_control(base_type(left), base_type(right), control);
658    }
659    let scalar = if let Some(numeric) = common_numeric_type(left, right) {
660        numeric
661    } else if matches!(left, ColumnType::Oid) && is_integral_type(right)
662        || matches!(right, ColumnType::Oid) && is_integral_type(left)
663    {
664        ColumnType::Oid
665    } else if left.is_character_string() && right.is_character_string() {
666        match left {
667            ColumnType::Bpchar | ColumnType::Character(_) => ColumnType::Bpchar,
668            ColumnType::Varchar(_) => ColumnType::Varchar(None),
669            ColumnType::Name => ColumnType::Name,
670            _ => ColumnType::Text,
671        }
672    } else {
673        match (left, right) {
674            (ColumnType::Date, ColumnType::Timestamp)
675            | (ColumnType::Timestamp, ColumnType::Date) => ColumnType::Timestamp,
676            (ColumnType::Date | ColumnType::Timestamp, ColumnType::TimestampTz)
677            | (ColumnType::TimestampTz, ColumnType::Date | ColumnType::Timestamp) => {
678                ColumnType::TimestampTz
679            }
680            (ColumnType::Array(_), ColumnType::Array(_)) => {
681                // An array type does not fix its number of dimensions: `integer[][]` is `integer[]`, so arrays meet at their element types, and each value keeps its own dimensions.
682                let element = select_pair_with_control(
683                    innermost_array_element(left),
684                    innermost_array_element(right),
685                    control,
686                )?;
687                return ColumnType::array_with_control(element, control)
688                    .map_err(CommonTypeFailure::failed);
689            }
690            _ => same_category_common_type(left, right)?,
691        }
692    };
693    control
694        .finish(scalar, control.empty_reservation())
695        .map_err(CommonTypeFailure::failed)
696}
697
698/// `select_common_type` for two types of one category that the rules above do not cover: the first type stays unless it is not its category's preferred type and coerces implicitly to the second, which does not coerce back to it. The other type must then coerce implicitly to the selected one, as `coerce_to_common_type` requires.
699fn same_category_common_type(
700    left: &ColumnType,
701    right: &ColumnType,
702) -> Result<ColumnType, CommonTypeFailure> {
703    use super::overload_resolution::{
704        routine_type_accepts_implicit_cast as implicit, routine_type_category,
705        routine_type_is_preferred,
706    };
707    let left_name = super::canonical_column_type_name(left);
708    let right_name = super::canonical_column_type_name(right);
709    if routine_type_category(&left_name) != routine_type_category(&right_name) {
710        return Err(CommonTypeFailure::Unmatched(Box::new((
711            left.clone(),
712            right.clone(),
713        ))));
714    }
715    let switch = !routine_type_is_preferred(&left_name)
716        && implicit(&left_name, &right_name)
717        && !implicit(&right_name, &left_name);
718    let (selected, other, selected_name, other_name) = if switch {
719        (right, left, &right_name, &left_name)
720    } else {
721        (left, right, &left_name, &right_name)
722    };
723    if implicit(other_name, selected_name) {
724        Ok(selected.clone())
725    } else {
726        Err(CommonTypeFailure::Inconvertible(Box::new((
727            other.clone(),
728            selected.clone(),
729        ))))
730    }
731}
732
733pub(super) mod case;
734
735/// The element type below every array level of `ty`.
736fn innermost_array_element(mut ty: &ColumnType) -> &ColumnType {
737    while let ColumnType::Array(element) = ty {
738        ty = element;
739    }
740    ty
741}
742
743fn is_integral_type(ty: &ColumnType) -> bool {
744    matches!(
745        base_type(ty),
746        ColumnType::SmallInteger | ColumnType::Integer | ColumnType::BigInteger
747    )
748}
749
750pub(super) fn common_numeric_type(left: &ColumnType, right: &ColumnType) -> Option<ColumnType> {
751    let rank = numeric_rank(left)?.max(numeric_rank(right)?);
752    Some(match rank {
753        0 => ColumnType::SmallInteger,
754        1 => ColumnType::Integer,
755        2 => ColumnType::BigInteger,
756        3 => numeric_type(),
757        4 => ColumnType::Real,
758        _ => ColumnType::DoublePrecision,
759    })
760}
761
762pub(super) fn numeric_rank(ty: &ColumnType) -> Option<u8> {
763    match ty {
764        ColumnType::SmallInteger => Some(0),
765        ColumnType::Integer => Some(1),
766        ColumnType::BigInteger => Some(2),
767        ColumnType::Numeric { .. } => Some(3),
768        ColumnType::Real => Some(4),
769        ColumnType::DoublePrecision => Some(5),
770        _ => None,
771    }
772}
773
774/// Array dimensions belong to values; `PostgreSQL` operator signatures identify an array by its scalar element type, including an element domain's identity.
775pub(super) fn same_operator_type_with_control(
776    left: &ColumnType,
777    right: &ColumnType,
778    control: &ProductionControl<'_>,
779) -> Result<bool, uqa_core::ValueRetentionError> {
780    fn element(mut ty: &ColumnType) -> &ColumnType {
781        while let ColumnType::Array(inner) = ty {
782            ty = inner;
783        }
784        ty
785    }
786    let left = base_type(left);
787    let right = base_type(right);
788    let (left, right) = match (left, right) {
789        (ColumnType::Array(left), ColumnType::Array(right)) => (element(left), element(right)),
790        _ => (left, right),
791    };
792    let left = left.without_type_modifiers_with_control(control)?;
793    let right = right.without_type_modifiers_with_control(control)?;
794    Ok(*left == *right)
795}
796
797#[cfg(test)]
798mod production_tests;