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