Skip to main content

uqa_sql/type_resolution/
mod.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Static SQL type propagation and PostgreSQL-compatible common-type rules.
8
9use crate::ast::{ColumnType, FunctionBinding};
10use crate::{SQLError, SQLParam};
11
12use crate::schema::ScalarTypeSchema;
13use crate::{RowSchema, ScalarExpr};
14use uqa_core::Value;
15
16mod array_transform;
17pub(crate) mod between;
18pub(crate) mod boolean;
19pub(crate) use array_transform::resolve_array_transform_call;
20mod call;
21mod cast_compatibility;
22mod checksum;
23mod common;
24pub(crate) mod concatenation;
25pub(crate) use common::literal_input_type_with_control;
26pub(crate) use common::select_common_input_type_in_with_control;
27pub(crate) use common::value_type;
28pub(crate) use common::value_type_with_control;
29pub(crate) use common::{array_element_type, base_type};
30mod containment;
31pub(crate) mod enums;
32mod equality;
33pub(crate) mod field_selection;
34mod fixed_builtin;
35pub(crate) use fixed_builtin::overloads as fixed_builtin_overloads;
36mod function_inputs;
37mod functions;
38pub(crate) use function_inputs::{call_type_from_observations, CallInputTypes};
39mod gamma;
40mod inference;
41use inference::scalar_type_inner_with_control;
42mod introspection;
43pub(crate) mod json_path;
44mod json_strip;
45mod length;
46mod md5;
47pub(crate) mod membership;
48mod operator_errors;
49pub(crate) mod row_comparison;
50pub(crate) mod row_distinct;
51pub use operator_errors::{
52    ambiguous_binary_operator, ambiguous_prefix_operator, undefined_binary_operator,
53    undefined_binary_operator_named, undefined_prefix_operator,
54};
55mod operators;
56pub(crate) use operators::comparison::ComparisonSupport;
57pub use operators::comparison::{
58    comparison_key_is_constant, equality_types_share_hash_key, type_supports_hashing,
59    type_supports_ordering, ComparisonKeySupport,
60};
61mod overload_resolution;
62pub(crate) use overload_resolution::resolve_local_builtin_call_with_control;
63mod qualified_column;
64mod range;
65mod range_offsets;
66pub use range_offsets::range_frame_offset_type;
67mod reverse;
68mod routine_signature;
69mod scalar_input;
70mod stored_constants;
71pub use scalar_input::{
72    scalar_array_element_oid_with_control, scalar_cast_source_type_name_with_control,
73    scalar_integer_operation_width, scalar_integer_operation_width_with_control,
74    scalar_operand_type_name, scalar_operand_type_name_with_control,
75    scalar_operand_type_with_engine_and_control, scalar_record_field_type_with_control,
76};
77pub(crate) use stored_constants::store_syntax_operand_coercions;
78pub use stored_constants::{
79    contains_unknown_literal, fold_stored_enum_constants, store_operand_coercions,
80    stored_enum_constant,
81};
82pub(crate) mod pattern;
83mod string_binary;
84
85pub use cast_compatibility::{
86    assignment_type_compatible, cast_catalog_entry, cast_volatility, explicit_type_compatible,
87    immutable_cast_type, pg_catalog_builtin_type, CastCatalogEntry, CastMethod,
88};
89pub(crate) use cast_compatibility::{cast_catalog_entry_with_control, preserves_record_identity};
90#[doc(hidden)]
91pub use checksum::{resolve_checksum_overload, ResolvedChecksumOverload};
92pub use common::{
93    common_context_expression_type, common_type, common_type_in, effective_overload_argument_type,
94    effective_overload_argument_type_with_params, function_call_argument_signature,
95    select_common_input_type, values_column_types, CommonTypeContext,
96    FunctionCallArgumentSignature,
97};
98pub use equality::{
99    equality_operand_type, equality_operand_type_with_control, foreign_key_operand_type,
100};
101#[doc(hidden)]
102pub use fixed_builtin::{
103    fixed_builtin_return_type, fixed_builtin_return_type_with_control,
104    is_function as is_fixed_builtin, resolve_fixed_builtin_call, selected_builtin_dispatch,
105    ResolvedFixedBuiltinCall,
106};
107pub use functions::{
108    builtin_function_argument_targets, builtin_function_type, builtin_function_type_with_resolver,
109};
110#[doc(hidden)]
111pub use gamma::{resolve_gamma_overload, ResolvedGammaOverload};
112pub use introspection::{
113    bind_type_introspection, bind_type_introspection_with_control,
114    bind_type_introspection_with_resolver, validate_catalog_literals,
115};
116#[doc(hidden)]
117pub use json_strip::{resolve_json_strip_overload, ResolvedJsonStripOverload};
118#[doc(hidden)]
119pub use length::{resolve_length_overload, ResolvedLengthOverload};
120#[doc(hidden)]
121pub use md5::{resolve_md5_overload, ResolvedMd5Overload};
122#[doc(hidden)]
123pub use operators::{
124    binary_operator_by_oid, binary_operator_catalog_entry, binary_operator_types,
125    binary_operator_types_with_control, binary_operator_volatility, binary_result_type,
126    binary_result_type_with_control, numeric_operator_types, numeric_operator_types_with_control,
127    require_equality_operator, require_ordering_operator, unary_minus_catalog_entry,
128    unary_operator_by_oid, BinaryOperatorCatalogEntry, NumericOperatorTypes,
129    UnaryOperatorCatalogEntry,
130};
131pub(crate) use operators::{named_binary_operator_catalog_entry, named_binary_operator_types};
132#[doc(hidden)]
133pub use overload_resolution::{
134    builtin_binding_matches, builtin_name_matches, canonical_column_type_name,
135    canonical_routine_type_name, function_resolution_error, match_builtin_function_call,
136    match_builtin_function_overload, match_function_signature, parse_enum_type_identity,
137    rank_function_matches, resolve_local_builtin_overload, routine_type_accepts_implicit_cast,
138    routine_type_category, routine_type_is_preferred, FunctionParameterDescriptor,
139    MatchedBuiltinFunction, MatchedFunctionSignature, RankedFunctionMatch,
140};
141#[doc(hidden)]
142pub use reverse::{resolve_reverse_overload, ResolvedReverseOverload};
143#[doc(hidden)]
144pub(crate) use routine_signature::match_routine_candidate;
145pub use routine_signature::{
146    match_routine_signature, routine_polymorphic_type, MatchedRoutineSignature,
147    RoutineCallDescriptor, RoutineCoercionTarget, RoutineParameterDescriptor,
148    RoutinePolymorphicFamily, RoutinePolymorphicType, RoutineSignatureMatchError,
149    RoutineTypeSubstitutions, RoutineVariadicMode, RoutineVariadicPlan,
150};
151#[doc(hidden)]
152pub use string_binary::{ResolvedStringBinaryOverload, ResolvedTextByteaOverload};
153
154pub trait FunctionTypeResolver: Send + Sync {
155    /// Format a selected type using the binding catalog's namespace visibility.
156    fn format_type_name(&self, ty: &ColumnType) -> Result<String, SQLError> {
157        Ok(ty.sql_name())
158    }
159
160    /// Return whether an external runtime callback claims this unbound function
161    /// name without exposing a declared SQL return type. Such callbacks must
162    /// retain dispatch precedence instead of being rebound to a same-named
163    /// built-in overload.
164    fn has_untyped_function(&self, _name: &str) -> bool {
165        false
166    }
167
168    /// Resolve a catalog-owned SQL type name that is not represented by the
169    /// built-in [`ColumnType::from_sql_name`] mapping, such as a domain.
170    fn resolve_type_name(&self, _name: &str) -> Result<Option<ColumnType>, SQLError> {
171        Ok(None)
172    }
173
174    /// Resolve an explicit collation name with the binding catalog's namespace visibility and privileges.
175    fn resolve_collation_name(&self, _name: &str) -> Result<Option<u32>, SQLError> {
176        Ok(None)
177    }
178
179    /// Enum labels of the binding catalog. Binding converts `unknown` literals coerced to an enum type with them, as `PostgreSQL` parse analysis calls the type's input function.
180    fn enum_labels(&self) -> Option<&dyn crate::expr::enums::EnumLabelCatalog> {
181        None
182    }
183
184    /// Input functions whose catalog constraints must run when an unknown literal is analyzed. Callers retain the returned constant; metadata-only inference does not invoke this capability.
185    fn catalog_input_functions(&self) -> Option<&dyn crate::expr::CatalogInputFunctions> {
186        None
187    }
188
189    /// Composite type attributes of the binding catalog, which type field selections and row coercions.
190    fn composite_types(&self) -> Option<&dyn crate::expr::composites::CompositeTypeCatalog> {
191        None
192    }
193
194    /// Require the current user's `USAGE` privilege on a type that a relation column, domain or routine declares, as `object_aclcheck(TypeRelationId, ..., ACL_USAGE)` and `aclcheck_error_type` require it; see [`crate::catalog::security::type_inquiry::usage_governing_type`]. A resolver without roles and type privileges has nothing to deny.
195    fn require_type_usage(&self, _ty: &ColumnType) -> Result<(), SQLError> {
196        Ok(())
197    }
198
199    fn resolve_function_type(
200        &self,
201        name: &str,
202        binding: Option<&FunctionBinding>,
203        argument_names: &[Option<String>],
204        argument_types: &[Option<ColumnType>],
205        explicit_variadic: bool,
206    ) -> Result<Option<ColumnType>, SQLError>;
207
208    /// Resolve a catalog-backed overload together with the stable binding needed to execute it after built-in and user-defined candidates have been ranked.
209    fn resolve_function_overload(
210        &self,
211        _name: &str,
212        _binding: Option<&FunctionBinding>,
213        _argument_names: &[Option<String>],
214        _argument_types: &[Option<ColumnType>],
215        _explicit_variadic: bool,
216    ) -> Result<Option<ResolvedFunctionOverload>, SQLError> {
217        Ok(None)
218    }
219
220    /// Return whether an exact catalog-selected binding can execute in a scalar expression. The conservative default prevents aggregate, procedure, and set-returning routines from being attached to [`ScalarExpr::Func`].
221    fn is_scalar_function_binding(&self, _binding: &FunctionBinding) -> Result<bool, SQLError> {
222        Ok(false)
223    }
224
225    /// Resolve catalog-backed routines and the supplied built-in overloads as
226    /// one `PostgreSQL` candidate set. Implementations with catalog visibility
227    /// should override this so search-path shadowing and unknown-category
228    /// selection happen before a winner is chosen.
229    fn resolve_function_overload_with_builtins(
230        &self,
231        name: &str,
232        binding: Option<&FunctionBinding>,
233        argument_names: &[Option<String>],
234        argument_types: &[Option<ColumnType>],
235        explicit_variadic: bool,
236        _builtins: &[BuiltinFunctionOverload],
237    ) -> Result<Option<ResolvedFunctionOverload>, SQLError> {
238        self.resolve_function_overload(
239            name,
240            binding,
241            argument_names,
242            argument_types,
243            explicit_variadic,
244        )
245    }
246
247    /// Resolve the declared first-column type of a physical scalar-subquery slot when the owning execution context carries its plan arena.
248    fn resolve_scalar_subquery_type(
249        &self,
250        _subquery: crate::SubqueryId,
251        _outer_schema: &RowSchema,
252        _params: &[SQLParam],
253    ) -> Result<Option<ColumnType>, SQLError> {
254        Ok(None)
255    }
256}
257
258#[derive(Debug, Clone, PartialEq, Eq)]
259pub struct BuiltinFunctionOverload {
260    /// The final declared array parameter accepts expanded elements or an explicit VARIADIC array.
261    pub variadic: bool,
262    pub name: String,
263    pub argument_names: Vec<Option<String>>,
264    pub argument_types: Vec<ColumnType>,
265    pub default_arguments: usize,
266    pub return_type: ColumnType,
267}
268
269#[derive(Debug, Clone, PartialEq, Eq)]
270pub struct ResolvedFunctionOverload {
271    pub binding: FunctionBinding,
272    pub return_type: ColumnType,
273    pub exact_matches: usize,
274    pub known_arguments: usize,
275    pub preferred_matches: usize,
276    pub precedes_pg_catalog: bool,
277}
278
279impl ResolvedFunctionOverload {
280    #[must_use]
281    pub fn is_exact_for_known_arguments(&self) -> bool {
282        self.known_arguments > 0 && self.exact_matches == self.known_arguments
283    }
284}
285
286pub fn scalar_type(
287    expression: &ScalarExpr,
288    schema: &dyn ScalarTypeSchema,
289    params: &[SQLParam],
290) -> Result<Option<ColumnType>, SQLError> {
291    scalar_type_inner(expression, schema, params, None)
292}
293
294/// Infer a scalar type from borrowed schema and parameter metadata while retaining every constructed type and temporary buffer under the supplied allowance.
295pub fn scalar_type_with_control(
296    expression: &ScalarExpr,
297    schema: &dyn ScalarTypeSchema,
298    params: &[SQLParam],
299    control: &uqa_core::memory::ProductionControl<'_>,
300) -> Result<Option<uqa_core::memory::Produced<ColumnType>>, SQLError> {
301    scalar_type_inner_with_control(expression, schema, params, None, control)
302}
303
304/// Preserve unknown-literal and domain rules when selecting an operator's common type without a catalog callback.
305pub fn common_context_type_with_control(
306    expression: &ScalarExpr,
307    schema: &dyn ScalarTypeSchema,
308    params: &[SQLParam],
309    control: &uqa_core::memory::ProductionControl<'_>,
310) -> Result<Option<uqa_core::memory::Produced<ColumnType>>, SQLError> {
311    common::common_context_expression_type_with_control(expression, schema, params, None, control)
312}
313
314pub fn scalar_type_with_resolver(
315    expression: &ScalarExpr,
316    schema: &dyn ScalarTypeSchema,
317    params: &[SQLParam],
318    resolver: &dyn FunctionTypeResolver,
319) -> Result<Option<ColumnType>, SQLError> {
320    scalar_type_inner(expression, schema, params, Some(resolver))
321}
322
323/// A bare string or NULL literal, which `PostgreSQL` types as `unknown` until its context resolves it.
324pub fn is_unknown_literal(expression: &ScalarExpr) -> bool {
325    matches!(expression, ScalarExpr::Literal(Value::Str(_) | Value::Null))
326}
327
328/// Whether a type's input function consults the catalog: the OID alias types and `aclitem` look names up, and an enum, a composite type, a record or a type known by name is read through its catalog definition. Analysis without the catalog leaves such a literal in the cast form that binding or evaluation reads, and reads every other literal with the type's input function.
329pub fn catalog_input_type(ty: &ColumnType) -> bool {
330    match ty {
331        ColumnType::Regproc
332        | ColumnType::Regprocedure
333        | ColumnType::Regclass
334        | ColumnType::Regcollation
335        | ColumnType::Regnamespace
336        | ColumnType::Regrole
337        | ColumnType::Regtype
338        | ColumnType::AclItem
339        | ColumnType::PgNodeTree
340        | ColumnType::Named(_)
341        | ColumnType::Enum(_)
342        | ColumnType::Composite(_)
343        | ColumnType::Record
344        | ColumnType::AnyArray
345        | ColumnType::Vector(_)
346        | ColumnType::Tensor(_) => true,
347        ColumnType::Array(inner) | ColumnType::Domain { base: inner, .. } => {
348            catalog_input_type(inner)
349        }
350        _ => false,
351    }
352}
353
354/// Whether value operations can require live catalog metadata: enum identities, record fields and their array/domain containers cannot be evaluated by a catalog-free scalar implementation. OID aliases have already decoded their names and operate on ordinary integer values.
355#[must_use]
356pub fn catalog_value_type(ty: &ColumnType) -> bool {
357    match ty {
358        ColumnType::Named(_)
359        | ColumnType::Enum(_)
360        | ColumnType::Composite(_)
361        | ColumnType::Record
362        | ColumnType::AnyArray => true,
363        ColumnType::Array(inner) | ColumnType::Domain { base: inner, .. } => {
364            catalog_value_type(inner)
365        }
366        _ => false,
367    }
368}
369
370/// The type of an assignment's source before coercion to its destination. A bare string or NULL literal has none: `transformAssignedExpr` and `transformAssignmentIndirection` convert it with the destination type's input function instead of checking a source type, so `'7'` assigns to an integer array element and `'abc'` fails as integer input.
371pub fn assignment_source_type(
372    expression: &ScalarExpr,
373    schema: &dyn ScalarTypeSchema,
374    params: &[SQLParam],
375    resolver: &dyn FunctionTypeResolver,
376) -> Result<Option<ColumnType>, SQLError> {
377    if is_unknown_literal(expression) {
378        return Ok(None);
379    }
380    scalar_type_with_resolver(expression, schema, params, resolver)
381}
382
383pub(super) fn scalar_type_inner(
384    expression: &ScalarExpr,
385    schema: &dyn ScalarTypeSchema,
386    params: &[SQLParam],
387    resolver: Option<&dyn FunctionTypeResolver>,
388) -> Result<Option<ColumnType>, SQLError> {
389    scalar_type_inner_with_control(
390        expression,
391        schema,
392        params,
393        resolver,
394        &uqa_core::memory::ProductionControl::uncontrolled(),
395    )
396    .map(|ty| {
397        ty.map(|ty| {
398            ty.into_uncontrolled()
399                .expect("ordinary scalar inference has no reservation")
400        })
401    })
402}
403
404#[cfg(test)]
405mod tests;
406
407mod declaration;
408pub use declaration::{resolve_alter_column_type, resolve_declared_column_type};
409
410mod coercion;
411pub mod composite_rows;
412pub use coercion::coerce_common_context_value;