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, type_supports_hashing, type_supports_ordering, ComparisonKeySupport,
59};
60mod overload_resolution;
61pub(crate) use overload_resolution::resolve_local_builtin_call_with_control;
62mod qualified_column;
63mod range;
64mod range_offsets;
65pub use range_offsets::range_frame_offset_type;
66mod reverse;
67mod routine_signature;
68mod scalar_input;
69mod stored_constants;
70pub use scalar_input::{
71    scalar_array_element_oid_with_control, scalar_cast_source_type_name_with_control,
72    scalar_integer_operation_width, scalar_integer_operation_width_with_control,
73    scalar_operand_type_name, scalar_operand_type_name_with_control,
74    scalar_record_field_type_with_control,
75};
76pub(crate) use stored_constants::store_syntax_operand_coercions;
77pub use stored_constants::{
78    contains_unknown_literal, fold_stored_enum_constants, store_operand_coercions,
79    stored_enum_constant,
80};
81pub(crate) mod pattern;
82mod string_binary;
83
84pub use cast_compatibility::{
85    assignment_type_compatible, cast_catalog_entry, cast_volatility, explicit_type_compatible,
86    CastCatalogEntry, CastMethod,
87};
88pub(crate) use cast_compatibility::{cast_catalog_entry_with_control, preserves_record_identity};
89#[doc(hidden)]
90pub use checksum::{resolve_checksum_overload, ResolvedChecksumOverload};
91pub use common::{
92    common_context_expression_type, common_type, common_type_in, effective_overload_argument_type,
93    effective_overload_argument_type_with_params, function_call_argument_signature,
94    select_common_input_type, values_column_types, CommonTypeContext,
95    FunctionCallArgumentSignature,
96};
97pub use equality::{
98    equality_operand_type, equality_operand_type_with_control, foreign_key_operand_type,
99};
100#[doc(hidden)]
101pub use fixed_builtin::{
102    fixed_builtin_return_type, fixed_builtin_return_type_with_control,
103    is_function as is_fixed_builtin, resolve_fixed_builtin_call, selected_builtin_dispatch,
104    ResolvedFixedBuiltinCall,
105};
106pub use functions::{
107    builtin_function_argument_targets, builtin_function_type, builtin_function_type_with_resolver,
108};
109#[doc(hidden)]
110pub use gamma::{resolve_gamma_overload, ResolvedGammaOverload};
111pub use introspection::{
112    bind_type_introspection, bind_type_introspection_with_control,
113    bind_type_introspection_with_resolver, validate_catalog_literals,
114};
115#[doc(hidden)]
116pub use json_strip::{resolve_json_strip_overload, ResolvedJsonStripOverload};
117#[doc(hidden)]
118pub use length::{resolve_length_overload, ResolvedLengthOverload};
119#[doc(hidden)]
120pub use md5::{resolve_md5_overload, ResolvedMd5Overload};
121#[doc(hidden)]
122pub use operators::{
123    binary_operator_by_oid, binary_operator_catalog_entry, binary_operator_types,
124    binary_operator_types_with_control, binary_operator_volatility, binary_result_type,
125    binary_result_type_with_control, numeric_operator_types, numeric_operator_types_with_control,
126    require_equality_operator, require_ordering_operator, unary_minus_catalog_entry,
127    unary_operator_by_oid, BinaryOperatorCatalogEntry, NumericOperatorTypes,
128    UnaryOperatorCatalogEntry,
129};
130pub(crate) use operators::{named_binary_operator_catalog_entry, named_binary_operator_types};
131#[doc(hidden)]
132pub use overload_resolution::{
133    builtin_binding_matches, builtin_name_matches, canonical_column_type_name,
134    canonical_routine_type_name, function_resolution_error, match_builtin_function_call,
135    match_builtin_function_overload, match_function_signature, parse_enum_type_identity,
136    rank_function_matches, resolve_local_builtin_overload, routine_type_accepts_implicit_cast,
137    routine_type_category, routine_type_is_preferred, FunctionParameterDescriptor,
138    MatchedBuiltinFunction, MatchedFunctionSignature, RankedFunctionMatch,
139};
140#[doc(hidden)]
141pub use reverse::{resolve_reverse_overload, ResolvedReverseOverload};
142#[doc(hidden)]
143pub(crate) use routine_signature::match_routine_candidate;
144pub use routine_signature::{
145    match_routine_signature, routine_polymorphic_type, MatchedRoutineSignature,
146    RoutineCallDescriptor, RoutineCoercionTarget, RoutineParameterDescriptor,
147    RoutinePolymorphicFamily, RoutinePolymorphicType, RoutineSignatureMatchError,
148    RoutineTypeSubstitutions, RoutineVariadicMode, RoutineVariadicPlan,
149};
150#[doc(hidden)]
151pub use string_binary::{ResolvedStringBinaryOverload, ResolvedTextByteaOverload};
152
153pub trait FunctionTypeResolver: Send + Sync {
154    /// Format a selected type using the binding catalog's namespace visibility.
155    fn format_type_name(&self, ty: &ColumnType) -> Result<String, SQLError> {
156        Ok(ty.sql_name())
157    }
158
159    /// Return whether an external runtime callback claims this unbound function
160    /// name without exposing a declared SQL return type. Such callbacks must
161    /// retain dispatch precedence instead of being rebound to a same-named
162    /// built-in overload.
163    fn has_untyped_function(&self, _name: &str) -> bool {
164        false
165    }
166
167    /// Resolve a catalog-owned SQL type name that is not represented by the
168    /// built-in [`ColumnType::from_sql_name`] mapping, such as a domain.
169    fn resolve_type_name(&self, _name: &str) -> Result<Option<ColumnType>, SQLError> {
170        Ok(None)
171    }
172
173    /// Resolve an explicit collation name with the binding catalog's namespace visibility and privileges.
174    fn resolve_collation_name(&self, _name: &str) -> Result<Option<u32>, SQLError> {
175        Ok(None)
176    }
177
178    /// 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.
179    fn enum_labels(&self) -> Option<&dyn crate::expr::enums::EnumLabelCatalog> {
180        None
181    }
182
183    /// 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.
184    fn catalog_input_functions(&self) -> Option<&dyn crate::expr::CatalogInputFunctions> {
185        None
186    }
187
188    /// Composite type attributes of the binding catalog, which type field selections and row coercions.
189    fn composite_types(&self) -> Option<&dyn crate::expr::composites::CompositeTypeCatalog> {
190        None
191    }
192
193    /// 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.
194    fn require_type_usage(&self, _ty: &ColumnType) -> Result<(), SQLError> {
195        Ok(())
196    }
197
198    fn resolve_function_type(
199        &self,
200        name: &str,
201        binding: Option<&FunctionBinding>,
202        argument_names: &[Option<String>],
203        argument_types: &[Option<ColumnType>],
204        explicit_variadic: bool,
205    ) -> Result<Option<ColumnType>, SQLError>;
206
207    /// Resolve a catalog-backed overload together with the stable binding needed to execute it after built-in and user-defined candidates have been ranked.
208    fn resolve_function_overload(
209        &self,
210        _name: &str,
211        _binding: Option<&FunctionBinding>,
212        _argument_names: &[Option<String>],
213        _argument_types: &[Option<ColumnType>],
214        _explicit_variadic: bool,
215    ) -> Result<Option<ResolvedFunctionOverload>, SQLError> {
216        Ok(None)
217    }
218
219    /// 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`].
220    fn is_scalar_function_binding(&self, _binding: &FunctionBinding) -> Result<bool, SQLError> {
221        Ok(false)
222    }
223
224    /// Resolve catalog-backed routines and the supplied built-in overloads as
225    /// one `PostgreSQL` candidate set. Implementations with catalog visibility
226    /// should override this so search-path shadowing and unknown-category
227    /// selection happen before a winner is chosen.
228    fn resolve_function_overload_with_builtins(
229        &self,
230        name: &str,
231        binding: Option<&FunctionBinding>,
232        argument_names: &[Option<String>],
233        argument_types: &[Option<ColumnType>],
234        explicit_variadic: bool,
235        _builtins: &[BuiltinFunctionOverload],
236    ) -> Result<Option<ResolvedFunctionOverload>, SQLError> {
237        self.resolve_function_overload(
238            name,
239            binding,
240            argument_names,
241            argument_types,
242            explicit_variadic,
243        )
244    }
245
246    /// Resolve the declared first-column type of a physical scalar-subquery slot when the owning execution context carries its plan arena.
247    fn resolve_scalar_subquery_type(
248        &self,
249        _subquery: crate::SubqueryId,
250        _outer_schema: &RowSchema,
251        _params: &[SQLParam],
252    ) -> Result<Option<ColumnType>, SQLError> {
253        Ok(None)
254    }
255}
256
257#[derive(Debug, Clone, PartialEq, Eq)]
258pub struct BuiltinFunctionOverload {
259    /// The final declared array parameter accepts expanded elements or an explicit VARIADIC array.
260    pub variadic: bool,
261    pub name: String,
262    pub argument_names: Vec<Option<String>>,
263    pub argument_types: Vec<ColumnType>,
264    pub default_arguments: usize,
265    pub return_type: ColumnType,
266}
267
268#[derive(Debug, Clone, PartialEq, Eq)]
269pub struct ResolvedFunctionOverload {
270    pub binding: FunctionBinding,
271    pub return_type: ColumnType,
272    pub exact_matches: usize,
273    pub known_arguments: usize,
274    pub preferred_matches: usize,
275    pub precedes_pg_catalog: bool,
276}
277
278impl ResolvedFunctionOverload {
279    #[must_use]
280    pub fn is_exact_for_known_arguments(&self) -> bool {
281        self.known_arguments > 0 && self.exact_matches == self.known_arguments
282    }
283}
284
285pub fn scalar_type(
286    expression: &ScalarExpr,
287    schema: &dyn ScalarTypeSchema,
288    params: &[SQLParam],
289) -> Result<Option<ColumnType>, SQLError> {
290    scalar_type_inner(expression, schema, params, None)
291}
292
293/// Infer a scalar type from borrowed schema and parameter metadata while retaining every constructed type and temporary buffer under the supplied allowance.
294pub fn scalar_type_with_control(
295    expression: &ScalarExpr,
296    schema: &dyn ScalarTypeSchema,
297    params: &[SQLParam],
298    control: &uqa_core::memory::ProductionControl<'_>,
299) -> Result<Option<uqa_core::memory::Produced<ColumnType>>, SQLError> {
300    scalar_type_inner_with_control(expression, schema, params, None, control)
301}
302
303/// Preserve unknown-literal and domain rules when selecting an operator's common type without a catalog callback.
304pub fn common_context_type_with_control(
305    expression: &ScalarExpr,
306    schema: &dyn ScalarTypeSchema,
307    params: &[SQLParam],
308    control: &uqa_core::memory::ProductionControl<'_>,
309) -> Result<Option<uqa_core::memory::Produced<ColumnType>>, SQLError> {
310    common::common_context_expression_type_with_control(expression, schema, params, None, control)
311}
312
313pub fn scalar_type_with_resolver(
314    expression: &ScalarExpr,
315    schema: &dyn ScalarTypeSchema,
316    params: &[SQLParam],
317    resolver: &dyn FunctionTypeResolver,
318) -> Result<Option<ColumnType>, SQLError> {
319    scalar_type_inner(expression, schema, params, Some(resolver))
320}
321
322/// A bare string or NULL literal, which `PostgreSQL` types as `unknown` until its context resolves it.
323pub fn is_unknown_literal(expression: &ScalarExpr) -> bool {
324    matches!(expression, ScalarExpr::Literal(Value::Str(_) | Value::Null))
325}
326
327/// 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.
328pub fn catalog_input_type(ty: &ColumnType) -> bool {
329    match ty {
330        ColumnType::Regproc
331        | ColumnType::Regprocedure
332        | ColumnType::Regclass
333        | ColumnType::Regcollation
334        | ColumnType::Regnamespace
335        | ColumnType::Regrole
336        | ColumnType::Regtype
337        | ColumnType::AclItem
338        | ColumnType::PgNodeTree
339        | ColumnType::Named(_)
340        | ColumnType::Enum(_)
341        | ColumnType::Composite(_)
342        | ColumnType::Record
343        | ColumnType::AnyArray
344        | ColumnType::Vector(_)
345        | ColumnType::Tensor(_) => true,
346        ColumnType::Array(inner) | ColumnType::Domain { base: inner, .. } => {
347            catalog_input_type(inner)
348        }
349        _ => false,
350    }
351}
352
353/// 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.
354#[must_use]
355pub fn catalog_value_type(ty: &ColumnType) -> bool {
356    match ty {
357        ColumnType::Named(_)
358        | ColumnType::Enum(_)
359        | ColumnType::Composite(_)
360        | ColumnType::Record
361        | ColumnType::AnyArray => true,
362        ColumnType::Array(inner) | ColumnType::Domain { base: inner, .. } => {
363            catalog_value_type(inner)
364        }
365        _ => false,
366    }
367}
368
369/// 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.
370pub fn assignment_source_type(
371    expression: &ScalarExpr,
372    schema: &dyn ScalarTypeSchema,
373    params: &[SQLParam],
374    resolver: &dyn FunctionTypeResolver,
375) -> Result<Option<ColumnType>, SQLError> {
376    if is_unknown_literal(expression) {
377        return Ok(None);
378    }
379    scalar_type_with_resolver(expression, schema, params, resolver)
380}
381
382pub(super) fn scalar_type_inner(
383    expression: &ScalarExpr,
384    schema: &dyn ScalarTypeSchema,
385    params: &[SQLParam],
386    resolver: Option<&dyn FunctionTypeResolver>,
387) -> Result<Option<ColumnType>, SQLError> {
388    scalar_type_inner_with_control(
389        expression,
390        schema,
391        params,
392        resolver,
393        &uqa_core::memory::ProductionControl::uncontrolled(),
394    )
395    .map(|ty| {
396        ty.map(|ty| {
397            ty.into_uncontrolled()
398                .expect("ordinary scalar inference has no reservation")
399        })
400    })
401}
402
403#[cfg(test)]
404mod tests;
405
406mod declaration;
407pub use declaration::{resolve_alter_column_type, resolve_declared_column_type};
408
409mod coercion;
410pub mod composite_rows;
411pub use coercion::coerce_common_context_value;