Skip to main content

uqa_sql/expr/casting/
mod.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! SQL cast dispatch and scalar, numeric, and range conversion.
8
9mod array;
10mod binary_oid;
11mod bit_string;
12mod legacy_vector;
13pub(crate) mod numeric;
14pub(crate) mod resolved;
15mod temporal;
16
17use super::conversion::value_to_string_with_control;
18use super::{out_of_range, ArrayValue, Result, SQLError, TemporalValue, Value};
19use crate::ast::RangeSubtype;
20use uqa_core::memory::{Produced, ProductionControl, ProductionString, ProductionVec};
21
22/// Cast a value to the named SQL type, mirroring `CAST(expr AS ty)`.
23/// Types outside the engine's coercion surface return
24/// [`SQLError::Unsupported`].
25pub fn cast_value(v: &Value, ty: &str) -> Result<Value> {
26    cast_value_from(v, ty, None)
27}
28
29/// Cast a value while preserving an explicitly declared source type when the runtime carrier erases it. `PostgreSQL` 18 integer-to-`bytea`/`oid` casts and `xid` cast rejection require the source's declared identity.
30pub fn cast_value_from(v: &Value, ty: &str, source_ty: Option<&str>) -> Result<Value> {
31    cast_value_from_with_control(v, ty, source_ty, &ProductionControl::uncontrolled())?
32        .into_uncontrolled()
33        .map_err(|_| SQLError::Internal("ordinary cast production owner".into()))
34}
35
36#[expect(
37    clippy::too_many_lines,
38    reason = "cast matrix preserves source-target and error precedence"
39)]
40pub fn cast_value_from_with_control(
41    v: &Value,
42    ty: &str,
43    source_ty: Option<&str>,
44    control: &ProductionControl<'_>,
45) -> Result<Produced<Value>> {
46    control.check()?;
47    if let Value::Datum(datum) = v {
48        return cast_value_from_with_control(
49            &*super::datums::read_with_control(datum, control)?,
50            ty,
51            source_ty,
52            control,
53        );
54    }
55    if let Some(element) = array_scalar_type_name(ty) {
56        let element = element.trim();
57        let element = element
58            .split_once('.')
59            .filter(|(schema, _)| schema.eq_ignore_ascii_case("pg_catalog"))
60            .map_or(element, |(_, name)| name);
61        if let Some(name) = ["void", "pg_node_tree"]
62            .into_iter()
63            .find(|name| element.eq_ignore_ascii_case(name))
64        {
65            return Err(SQLError::Routine {
66                sqlstate: "42704".into(),
67                message: format!("type \"{name}[]\" does not exist"),
68            });
69        }
70    }
71    if matches!(v, Value::Null) {
72        return Ok(control.finish(Value::Null, control.empty_reservation())?);
73    }
74    // Physical cast dispatch consumes the SQL owner's resolved builtin class, including quoted identifiers and catalog interval modifiers.
75    let canonical;
76    let ty = if ty.contains('"') || ty.starts_with("pg_catalog.") {
77        canonical = crate::ColumnType::from_sql_name_with_control(ty, control)?
78            .sql_name_with_control(control)?;
79        canonical.as_str()
80    } else {
81        ty
82    };
83    let canonical_source;
84    let source_ty = match source_ty {
85        Some(source) if source.contains('"') || source.starts_with("pg_catalog.") => {
86            canonical_source = crate::ColumnType::from_sql_name_with_control(source, control)?
87                .sql_name_with_control(control)?;
88            Some(canonical_source.as_str())
89        }
90        source => source,
91    };
92    let (base, modifier) = crate::ast::split_type_modifier_with_control(ty, control)?;
93    let target = base
94        .trim()
95        .strip_prefix("pg_catalog.")
96        .unwrap_or(base.trim());
97    if matches!(target, "bit" | "\"bit\"" | "varbit" | "bit varying") {
98        let target = crate::ColumnType::from_sql_name_with_control(ty, control)?;
99        return bit_string::cast(v, &target, source_ty, control);
100    }
101    if matches!(target, "vector" | "tensor") {
102        return match &*crate::ColumnType::from_sql_name_with_control(ty, control)? {
103            crate::ColumnType::Vector(dimensions) => {
104                crate::assignment::conversion::convert_vector_with_control(v, *dimensions, control)
105            }
106            crate::ColumnType::Tensor(dimensions) => {
107                crate::assignment::conversion::convert_tensor_with_control(v, *dimensions, control)
108            }
109            _ => Err(SQLError::Internal(
110                "resolved dense cast has no dimension".into(),
111            )),
112        };
113    }
114    if let Value::BitString(value) = v {
115        let integer_target = match target {
116            "integer" | "int" | "int4" => Some("integer"),
117            "bigint" | "int8" => Some("bigint"),
118            "smallint" | "int2" => Some("smallint"),
119            _ => None,
120        };
121        if let Some(target) = integer_target {
122            return Ok(control.finish(
123                bit_string::integer(value, target, source_ty, control)?,
124                control.empty_reservation(),
125            )?);
126        }
127    }
128    if matches!(v, Value::Void)
129        && !matches!(
130            target,
131            "void"
132                | "text"
133                | "name"
134                | "varchar"
135                | "character varying"
136                | "bpchar"
137                | "character"
138                | "char"
139        )
140    {
141        return Err(undefined_cast("void", postgres_type_display_name(target)));
142    }
143    if let Some(element_type) = array_scalar_type_name(ty) {
144        let source_element_type = source_ty.and_then(array_scalar_type_name).or(match v {
145            Value::LegacyVector(vector) => Some(match vector.kind() {
146                uqa_core::LegacyVectorKind::SmallInteger => "smallint",
147                uqa_core::LegacyVectorKind::Oid => "oid",
148            }),
149            _ => None,
150        });
151        let array = if let Value::Str(text) = v {
152            array::parse_pg_array_literal_with_input(text, control, |value| {
153                cast_value_from_with_control(&value, element_type, source_element_type, control)
154            })?
155        } else {
156            let array = match v {
157                Value::Array(array) => array,
158                Value::LegacyVector(vector) => vector.as_array(),
159                other => {
160                    return Err(SQLError::TypeMismatch(format!(
161                        "CAST AS {ty}: expected array, got {other:?}"
162                    )));
163                }
164            };
165            let elements = array::cast_array_elements(
166                array.elements(),
167                element_type,
168                source_element_type,
169                control,
170            )?;
171            let normalize_empty = array.elements().is_empty()
172                && !array::binary_compatible_elements(source_element_type, element_type, control)?;
173            let mut bounds = ProductionVec::new(*control);
174            bounds.reserve(array.lower_bounds().len())?;
175            if !normalize_empty {
176                for lower in array.lower_bounds() {
177                    bounds.push_copy(*lower)?;
178                }
179            }
180            ArrayValue::with_lower_bounds_with_control(elements, bounds.finish()?, control)?
181                .ok_or_else(|| {
182                    SQLError::TypeMismatch("array dimensions changed during cast".into())
183                })?
184        };
185        let (array, memory) = array.into_parts();
186        let element = crate::ColumnType::from_sql_name_with_control(element_type, control)?;
187        let oid = crate::catalog::type_metadata::pg_type_oid(&element) as u32;
188        return Ok(control.finish(Value::Array(array.with_element_type_oid(Some(oid))), memory)?);
189    }
190    let value = match &**base {
191        "void" | "pg_catalog.void" => {
192            let source = canonical_cast_source_with_control(source_ty, v, control)?;
193            if matches!(
194                source.as_str(),
195                "unknown" | "text" | "name" | "varchar" | "bpchar" | "void"
196            ) {
197                Ok(Value::Void)
198            } else {
199                Err(undefined_cast(postgres_type_display_name(&source), "void"))
200            }
201        }
202        "smallint" | "int2" | "pg_catalog.int2" => cast_integer(v, "smallint", control),
203        "integer" | "int" | "int4" | "serial" | "serial4" | "pg_catalog.int4" => {
204            binary_oid::cast_integer_from(v, source_ty, control)
205        }
206        "bigint" | "int8" | "bigserial" | "serial8" | "pg_catalog.int8" => {
207            cast_integer(v, "bigint", control)
208        }
209        "real" | "float4" | "pg_catalog.float4" => {
210            super::floating::to_float_with_control(v, super::FloatWidth::Real, control)
211                .map(Value::Float)
212        }
213        "float8" | "double" | "double precision" | "pg_catalog.float8" => {
214            super::floating::to_float_with_control(v, super::FloatWidth::DoublePrecision, control)
215                .map(Value::Float)
216        }
217        "numeric" | "decimal" => {
218            let value = super::conversion::to_decimal_with_control(v, control)?;
219            let modifier = if let Some(modifier) = modifier {
220                let mut parts = modifier.split(',').map(str::trim);
221                let precision: u32 = parts
222                    .next()
223                    .and_then(|p| p.parse().ok())
224                    .ok_or_else(|| SQLError::TypeMismatch("bad numeric precision".into()))?;
225                let scale: i32 = parts.next().and_then(|s| s.parse().ok()).unwrap_or(0);
226                Some((precision, scale))
227            } else {
228                None
229            };
230            return numeric::finish(value, modifier, control);
231        }
232        "regproc" | "regprocedure" | "regrole" | "regtype" if matches!(v, Value::Int(_)) => {
233            cast_oid(v, source_ty, control)
234        }
235        "pg_node_tree" => {
236            let source = canonical_cast_source_with_control(source_ty, v, control)?;
237            return match source.as_str() {
238                "pg_node_tree" => Ok(control.copy_value(v)?),
239                "unknown" | "text" | "varchar" | "bpchar" | "name" => Err(SQLError::Unsupported(
240                    "cannot accept a value of type pg_node_tree".into(),
241                )),
242                _ => Err(undefined_cast(
243                    postgres_type_display_name(&source),
244                    "pg_node_tree",
245                )),
246            };
247        }
248        "text"
249        | "refcursor"
250        | "pg_catalog.refcursor"
251        | "name"
252        | "regproc"
253        | "regprocedure"
254        | "regtype"
255        | "aclitem" => {
256            let source = source_ty
257                .map(str::trim)
258                .map(|source| source.strip_prefix("pg_catalog.").unwrap_or(source));
259            let text = match (source, v) {
260                (Some("int2vector" | "oidvector"), _) => {
261                    match super::conversion::vector_value_to_string_with_control(v, control)? {
262                        Some(text) => text,
263                        None => value_to_string_with_control(v, control)?,
264                    }
265                }
266                (
267                    Some(
268                        "regproc" | "regprocedure" | "regclass" | "regcollation" | "regnamespace"
269                        | "regrole" | "regtype",
270                    ),
271                    Value::Int(0),
272                ) => control.copy_text("-")?,
273                _ => cast_text(v, source_ty, control)?,
274            };
275            return text_value(text, false, control);
276        }
277        "int2vector" | "pg_catalog.int2vector" => {
278            return legacy_vector::cast_int2vector(v, source_ty, control);
279        }
280        "oidvector" | "pg_catalog.oidvector" => {
281            return legacy_vector::cast_oidvector(v, source_ty, control);
282        }
283        "oid" | "pg_catalog.oid" => cast_oid(v, source_ty, control),
284        "regclass"
285        | "pg_catalog.regclass"
286        | "regnamespace"
287        | "pg_catalog.regnamespace"
288        | "regcollation"
289        | "pg_catalog.regcollation"
290        | "regrole"
291        | "pg_catalog.regrole" => return cast_named_oid(v, target, source_ty, control),
292        "xid" | "pg_catalog.xid" => cast_xid(v, source_ty, control),
293        "\"char\"" => {
294            let source = canonical_cast_source_with_control(source_ty, v, control)?;
295            let byte = if source.as_str() == "\"char\"" {
296                super::internal_char::value_byte(v)
297                    .ok_or_else(|| SQLError::Internal("invalid internal char carrier".into()))?
298            } else if let ("int4", Value::Int(value)) = (source.as_str(), v) {
299                i8::try_from(*value).map_err(|_| out_of_range("\"char\""))? as u8
300            } else {
301                let text = value_to_string_with_control(v, control)?;
302                super::internal_char::input_byte(&text)
303            };
304            return Ok(super::internal_char::carrier_with_control(byte, control)?);
305        }
306        "uuid" => return cast_uuid(v, control),
307        // Every row is a record; `record_in` cannot read text without a composite type to read it as.
308        "record" => {
309            return match v {
310                Value::Row(_) | Value::Record(_) => Ok(control.copy_value(v)?),
311                Value::Str(_) | Value::FixedChar(_) => Err(SQLError::Routine {
312                    sqlstate: "0A000".into(),
313                    message: "input of anonymous composite types is not implemented".into(),
314                }),
315                _ => Err(undefined_cast(
316                    &canonical_cast_source_with_control(source_ty, v, control)?,
317                    "record",
318                )),
319            };
320        }
321        "varchar" | "character varying" => {
322            let text = cast_text(v, source_ty, control)?;
323            let Some(modifier) = modifier else {
324                return text_value(text, false, control);
325            };
326            let limit: usize = modifier
327                .trim()
328                .parse()
329                .map_err(|_| SQLError::TypeMismatch(format!("bad length modifier {modifier}")))?;
330            return character_value(text, limit, false, control);
331        }
332        "bpchar" if modifier.is_none() => {
333            let text = match v {
334                // A relabel to the same unlimited type keeps its padding;
335                // conversion through text would trim significant enum input.
336                Value::FixedChar(text) => control.copy_text(text)?,
337                _ => cast_text(v, source_ty, control)?,
338            };
339            return text_value(text, true, control);
340        }
341        "character" | "char" | "bpchar" => {
342            let text = cast_text(v, source_ty, control)?;
343            let limit: usize = match modifier {
344                Some(modifier) => modifier.trim().parse().map_err(|_| {
345                    SQLError::TypeMismatch(format!("bad length modifier {modifier}"))
346                })?,
347                None => 1,
348            };
349            if limit == 0 {
350                return Err(SQLError::TypeMismatch(
351                    "CHARACTER length must be greater than zero".into(),
352                ));
353            }
354            return character_value(text, limit, true, control);
355        }
356        "date" => cast_temporal(v, source_ty, TemporalCastTarget::Date, None, control),
357        "time" | "time without time zone" => {
358            cast_temporal(v, source_ty, TemporalCastTarget::Time, modifier, control)
359        }
360        "timetz" | "time with time zone" => {
361            cast_temporal(v, source_ty, TemporalCastTarget::TimeTz, modifier, control)
362        }
363        "timestamp" | "datetime" | "timestamp without time zone" => cast_temporal(
364            v,
365            source_ty,
366            TemporalCastTarget::Timestamp,
367            modifier,
368            control,
369        ),
370        "timestamptz" | "timestamp with time zone" => cast_temporal(
371            v,
372            source_ty,
373            TemporalCastTarget::TimestampTz,
374            modifier,
375            control,
376        ),
377        "interval" => temporal::cast_interval(v, source_ty, ty, control),
378        name if name.starts_with("interval ") => temporal::cast_interval(v, source_ty, ty, control),
379        "int4range" => return cast_range(v, source_ty, RangeSubtype::Integer, control),
380        "int8range" => return cast_range(v, source_ty, RangeSubtype::BigInteger, control),
381        "numrange" => return cast_range(v, source_ty, RangeSubtype::Numeric, control),
382        "daterange" => return cast_range(v, source_ty, RangeSubtype::Date, control),
383        "tsrange" => return cast_range(v, source_ty, RangeSubtype::Timestamp, control),
384        "tstzrange" => return cast_range(v, source_ty, RangeSubtype::TimestampTz, control),
385        "int4multirange" => return cast_multirange(v, source_ty, RangeSubtype::Integer, control),
386        "int8multirange" => {
387            return cast_multirange(v, source_ty, RangeSubtype::BigInteger, control);
388        }
389        "nummultirange" => return cast_multirange(v, source_ty, RangeSubtype::Numeric, control),
390        "datemultirange" => return cast_multirange(v, source_ty, RangeSubtype::Date, control),
391        "tsmultirange" => return cast_multirange(v, source_ty, RangeSubtype::Timestamp, control),
392        "tstzmultirange" => {
393            return cast_multirange(v, source_ty, RangeSubtype::TimestampTz, control);
394        }
395        "json" => return super::json::cast_json_value_with_control(v, false, control),
396        "xml" => {
397            return cast_xml(
398                v,
399                source_ty,
400                crate::xml::XmlOption::Content,
401                control,
402                |_| {},
403            )
404        }
405        "jsonb" => return super::json::cast_json_value_with_control(v, true, control),
406        "bytea" => return cast_bytea(v, source_ty, control),
407        "boolean" | "bool" => cast_boolean(v),
408        other => Err(SQLError::Unsupported(format!("CAST AS {other}"))),
409    }?;
410    Ok(control.finish(value, control.empty_reservation())?)
411}
412
413/// Repeated array brackets declare dimensions; every scalar leaf uses the same element input type.
414fn array_scalar_type_name(ty: &str) -> Option<&str> {
415    let mut element = ty.trim().strip_suffix("[]")?.trim_end();
416    while let Some(inner) = element.strip_suffix("[]") {
417        element = inner.trim_end();
418    }
419    Some(element)
420}
421
422pub(super) fn cast_xml(
423    value: &Value,
424    source: Option<&str>,
425    option: crate::xml::XmlOption,
426    control: &ProductionControl<'_>,
427    notice: impl FnMut(crate::SQLNotice),
428) -> Result<Produced<Value>> {
429    control.check()?;
430    if matches!(value, Value::Null) {
431        return Ok(control.copy_value(value)?);
432    }
433    let declared = source
434        .filter(|source| *source != "unknown")
435        .map(|source| crate::ColumnType::from_sql_name_with_control(source, control))
436        .transpose()?;
437    if declared.as_deref() == Some(&crate::ColumnType::Xml) {
438        return Ok(control.copy_value(value)?);
439    }
440    let source = declared
441        .as_deref()
442        .map(|ty| ty.sql_name_with_control(control))
443        .transpose()?;
444    let source =
445        canonical_cast_source_with_control(source.as_deref().map(String::as_str), value, control)?;
446    if !matches!(
447        source.as_str(),
448        "unknown" | "text" | "varchar" | "bpchar" | "name"
449    ) {
450        return Err(undefined_cast(postgres_type_display_name(&source), "xml"));
451    }
452    let text = cast_text(value, Some(&source), control)?;
453    crate::xml::validate_with_control(&text, option, control, notice)?;
454    text_value(text, false, control)
455}
456
457fn text_value(
458    text: Produced<String>,
459    fixed: bool,
460    control: &ProductionControl<'_>,
461) -> Result<Produced<Value>> {
462    let (text, memory) = text.into_parts();
463    Ok(control.finish(
464        if fixed {
465            Value::FixedChar(text)
466        } else {
467            Value::Str(text)
468        },
469        memory,
470    )?)
471}
472
473fn character_value(
474    text: Produced<String>,
475    limit: usize,
476    fixed: bool,
477    control: &ProductionControl<'_>,
478) -> Result<Produced<Value>> {
479    let mut count = 0;
480    let mut end = 0;
481    for (index, character) in text.char_indices().take(limit) {
482        control.check()?;
483        count += 1;
484        end = index + character.len_utf8();
485    }
486    let mut output = ProductionString::from_produced(text, *control)?;
487    output.truncate(end)?;
488    if fixed {
489        for _ in count..limit {
490            output.push(' ')?;
491        }
492    }
493    text_value(output.finish()?, fixed, control)
494}
495
496fn cast_range(
497    v: &Value,
498    source_ty: Option<&str>,
499    subtype: RangeSubtype,
500    control: &ProductionControl<'_>,
501) -> Result<Produced<Value>> {
502    let source = source_ty
503        .map(|source| canonical_type_name(source, control))
504        .transpose()?;
505    let source = source.as_ref().map(|source| source.as_str());
506    if source.is_some_and(|source| {
507        source != subtype.range_name() && !matches!(source, "unknown" | "cstring")
508    }) {
509        return Err(undefined_cast(
510            source.unwrap_or("unknown"),
511            subtype.range_name(),
512        ));
513    }
514    let (Value::Str(text) | Value::FixedChar(text)) = v else {
515        return Err(undefined_cast(
516            source.unwrap_or("unknown"),
517            subtype.range_name(),
518        ));
519    };
520    text_value(
521        super::range::canonical_range_text_with_control(text, subtype, control)?,
522        false,
523        control,
524    )
525}
526
527fn cast_multirange(
528    v: &Value,
529    source_ty: Option<&str>,
530    subtype: RangeSubtype,
531    control: &ProductionControl<'_>,
532) -> Result<Produced<Value>> {
533    let source = source_ty
534        .map(|source| canonical_type_name(source, control))
535        .transpose()?;
536    let source = source.as_ref().map(|source| source.as_str());
537    let (Value::Str(text) | Value::FixedChar(text)) = v else {
538        return Err(undefined_cast(
539            source.unwrap_or("unknown"),
540            subtype.multirange_name(),
541        ));
542    };
543    let text = match source {
544        Some(source) if source == subtype.range_name() => {
545            super::range::canonical_range_as_multirange_text_with_control(text, subtype, control)?
546        }
547        None | Some("unknown" | "cstring") => {
548            super::range::canonical_multirange_text_with_control(text, subtype, control)?
549        }
550        Some(source) if source == subtype.multirange_name() => {
551            super::range::canonical_multirange_text_with_control(text, subtype, control)?
552        }
553        Some(source) => return Err(undefined_cast(source, subtype.multirange_name())),
554    };
555    text_value(text, false, control)
556}
557
558fn canonical_type_name(
559    type_name: &str,
560    control: &ProductionControl<'_>,
561) -> Result<Produced<String>> {
562    let mut normalized = ProductionString::new(*control);
563    for character in type_name.trim().chars() {
564        normalized.push(character.to_ascii_lowercase())?;
565    }
566    Ok(control.copy_text(
567        normalized
568            .strip_prefix("pg_catalog.")
569            .unwrap_or(&normalized),
570    )?)
571}
572
573/// Apply `PostgreSQL` prefix `-` while retaining the operand's declared type.
574pub fn negate_value(value: &Value, source_ty: Option<&str>) -> Result<Value> {
575    negate_value_with_control(value, source_ty, &ProductionControl::uncontrolled())?
576        .into_uncontrolled()
577        .map_err(|_| SQLError::Internal("ordinary negation owner".into()))
578}
579
580pub fn negate_value_with_control(
581    value: &Value,
582    source_ty: Option<&str>,
583    control: &ProductionControl<'_>,
584) -> Result<Produced<Value>> {
585    control.check()?;
586    if matches!(value, Value::Null) {
587        return Ok(control.finish(Value::Null, control.empty_reservation())?);
588    }
589    let source = canonical_cast_source_with_control(source_ty, value, control)?;
590    let result = match (source.as_str(), value) {
591        ("int2", Value::Int(value)) => i16::try_from(*value)
592            .ok()
593            .and_then(i16::checked_neg)
594            .map(|value| Value::Int(i64::from(value)))
595            .ok_or_else(|| out_of_range("smallint")),
596        ("int4", Value::Int(value)) => i32::try_from(*value)
597            .ok()
598            .and_then(i32::checked_neg)
599            .map(|value| Value::Int(i64::from(value)))
600            .ok_or_else(|| out_of_range("integer")),
601        ("int8", Value::Int(value)) => value
602            .checked_neg()
603            .map(Value::Int)
604            .ok_or_else(|| out_of_range("bigint")),
605        ("float4" | "float8", Value::Float(value)) => Ok(Value::Float(-value)),
606        ("numeric", Value::Decimal(value)) => {
607            let (value, memory) = value.negated_with_control(control)?.into_parts();
608            return Ok(control.finish(Value::Decimal(value), memory)?);
609        }
610        ("interval", Value::Temporal(interval @ TemporalValue::Interval { .. })) => {
611            Ok(Value::Temporal(
612                super::IntervalFields::of(interval)
613                    .expect("interval operand")
614                    .negate()?
615                    .value(),
616            ))
617        }
618        _ => Err(crate::type_resolution::undefined_prefix_operator(
619            "-",
620            postgres_type_display_name(source.as_str()),
621        )),
622    }?;
623    Ok(control.finish(result, control.empty_reservation())?)
624}
625
626fn canonical_cast_source_with_control(
627    source_ty: Option<&str>,
628    value: &Value,
629    control: &ProductionControl<'_>,
630) -> Result<Produced<String>> {
631    let source = source_ty.unwrap_or(match value {
632        Value::Str(_) | Value::FixedChar(_) => "unknown",
633        Value::Int(_) => "integer",
634        Value::Bool(_) => "boolean",
635        Value::Float(_) => "double precision",
636        Value::Decimal(_) => "numeric",
637        Value::Bytes(_) => "bytea",
638        Value::BitString(_) => "bit",
639        Value::Temporal(TemporalValue::Date { .. }) => "date",
640        Value::Temporal(TemporalValue::Time { .. }) => "time without time zone",
641        Value::Temporal(TemporalValue::TimeTz { .. }) => "time with time zone",
642        Value::Temporal(TemporalValue::Timestamp { .. }) => "timestamp without time zone",
643        Value::Temporal(TemporalValue::TimestampTz { .. }) => "timestamp with time zone",
644        Value::Temporal(TemporalValue::Interval { .. }) => "interval",
645        Value::Json(_) => "json",
646        Value::JsonB(_) => "jsonb",
647        Value::Array(_) => "anyarray",
648        Value::Enum(_) => "anyenum",
649        Value::Datum(value) => super::datums::type_name(value),
650        Value::LegacyVector(vector) => vector.kind().type_name(),
651        Value::List(_) => "anyarray",
652        Value::Row(_) | Value::Record(_) => "record",
653        Value::Map(_) => "jsonb",
654        Value::Null => "unknown",
655        Value::Void => "void",
656    });
657    let declared;
658    let source = if source.contains('"') || source.starts_with("pg_catalog.") {
659        declared = crate::ColumnType::from_sql_name_with_control(source, control)?
660            .sql_name_with_control(control)?;
661        declared.as_str()
662    } else {
663        source
664    };
665    let (source, _) = crate::ast::split_type_modifier_with_control(source, control)?;
666    let mut normalized = ProductionString::new(*control);
667    for (index, word) in source.split_whitespace().enumerate() {
668        if index != 0 {
669            normalized.push(' ')?;
670        }
671        for character in word.chars() {
672            normalized.push(character.to_ascii_lowercase())?;
673        }
674    }
675    let source = normalized
676        .strip_prefix("pg_catalog.")
677        .unwrap_or(&normalized);
678    let canonical = match source {
679        "smallint" | "int2" => "int2",
680        "integer" | "int" | "int4" | "serial" | "serial4" => "int4",
681        "bigint" | "int8" | "bigserial" | "serial8" => "int8",
682        "character varying" | "varchar" => "varchar",
683        "character" | "char" | "bpchar" => "bpchar",
684        "\"bit\"" | "bit" => "bit",
685        "bit varying" | "varbit" => "varbit",
686        "boolean" | "bool" => "bool",
687        "double" | "double precision" | "float8" => "float8",
688        "real" | "float4" => "float4",
689        other => other,
690    };
691    Ok(control.copy_text(canonical)?)
692}
693
694fn undefined_cast(source: &str, target: &str) -> SQLError {
695    SQLError::Routine {
696        sqlstate: "42846".into(),
697        message: format!("cannot cast type {source} to {target}"),
698    }
699}
700
701fn postgres_type_display_name(name: &str) -> &str {
702    match name {
703        "int2" => "smallint",
704        "int4" => "integer",
705        "int8" => "bigint",
706        "float4" => "real",
707        "float8" => "double precision",
708        "bool" => "boolean",
709        "varchar" => "character varying",
710        "bpchar" => "character",
711        other => other,
712    }
713}
714
715fn cast_text(
716    value: &Value,
717    source: Option<&str>,
718    control: &ProductionControl<'_>,
719) -> Result<Produced<String>> {
720    if source == Some("\"char\"") {
721        return cast_text_from_type(value, Some(&crate::ColumnType::InternalChar), control);
722    }
723    if let (Value::Float(_) | Value::Array(_), Some(source)) = (value, source) {
724        let source = crate::ast::ColumnType::from_sql_name_with_control(source, control);
725        match source {
726            Ok(source) => return cast_text_from_type(value, Some(&source), control),
727            Err(error) if matches!(error.sqlstate(), Some("53200" | "57014")) => return Err(error),
728            _ => {}
729        }
730    }
731    cast_text_from_type(value, None, control)
732}
733
734fn cast_text_from_type(
735    value: &Value,
736    source: Option<&crate::ColumnType>,
737    control: &ProductionControl<'_>,
738) -> Result<Produced<String>> {
739    if matches!(source, Some(crate::ColumnType::InternalChar)) {
740        let byte = super::internal_char::value_byte(value)
741            .ok_or_else(|| SQLError::Internal("invalid internal char carrier".into()))?;
742        return Ok(super::internal_char::output_with_control(byte, control)?);
743    }
744    if let (Value::Float(value), Some(crate::ColumnType::Real)) = (value, source) {
745        return super::floating::format_real_with_control(*value as f32, control);
746    }
747    if let (Value::Array(_), Some(source @ crate::ColumnType::Array(_))) = (value, source) {
748        return crate::result::format_postgres_text_with_control(value, source, None, control);
749    }
750    value_to_string_with_control(value, control)
751}
752
753fn cast_uuid(value: &Value, control: &ProductionControl<'_>) -> Result<Produced<Value>> {
754    let text = match value {
755        Value::Str(text) | Value::FixedChar(text) => text,
756        other => {
757            return Err(SQLError::TypeMismatch(format!(
758                "cannot cast {other:?} to uuid"
759            )));
760        }
761    };
762    text_value(
763        super::uuid::canonicalize_uuid_with_control(text, control)?,
764        false,
765        control,
766    )
767}
768
769/// CAST to the integer family with `PostgreSQL` conversion rules:
770/// float8 rounds half-to-even, numeric rounds half-away-from-zero,
771/// strings must be integral text, and the result must fit the target
772/// width.
773pub(super) fn cast_integer(
774    v: &Value,
775    target: &str,
776    control: &ProductionControl<'_>,
777) -> Result<Value> {
778    control.check()?;
779    let n: i64 = match v {
780        Value::Int(n) => *n,
781        Value::Bool(b) => i64::from(*b),
782        Value::Float(f) => {
783            if !f.is_finite() {
784                return Err(out_of_range(target));
785            }
786            let rounded = f.round_ties_even();
787            // `i64::MAX as f64` rounds up to 2^63.  Comparing with `>` would
788            // therefore admit 2^63 and Rust's float-to-int cast would silently
789            // saturate it to `i64::MAX`.
790            if rounded < i64::MIN as f64 || rounded >= 9_223_372_036_854_775_808.0 {
791                return Err(out_of_range(target));
792            }
793            rounded as i64
794        }
795        Value::Decimal(d) => d
796            .round_to_scale_with_control(0, control)?
797            .ok_or_else(|| out_of_range(target))?
798            .to_i64_trunc_with_control(control)?
799            .ok_or_else(|| out_of_range(target))?,
800        Value::Str(s) | Value::FixedChar(s) => return integer_from_text(s, target),
801        Value::Bytes(bytes) => bytea_to_integer(bytes, target)?,
802        other => {
803            return Err(SQLError::TypeMismatch(format!(
804                "cannot cast {other:?} to {target}"
805            )));
806        }
807    };
808    let in_range = match target {
809        "smallint" => i16::try_from(n).is_ok(),
810        "integer" => i32::try_from(n).is_ok(),
811        _ => true,
812    };
813    if !in_range {
814        return Err(out_of_range(target));
815    }
816    Ok(Value::Int(n))
817}
818
819/// `boolin`: `PostgreSQL`'s `parse_bool` over trimmed text, accepting case-insensitive prefixes of `true`, `false`, `yes` and `no`, `on`, at least two letters of `off`, and `1` and `0`.
820#[must_use]
821pub fn parse_boolean_input(text: &str) -> Option<bool> {
822    let text = text.trim();
823    let matches_prefix = |word: &str| {
824        !text.is_empty()
825            && word
826                .get(..text.len())
827                .is_some_and(|prefix| prefix.eq_ignore_ascii_case(text))
828    };
829    if matches_prefix("true") || matches_prefix("yes") || text == "1" {
830        Some(true)
831    } else if matches_prefix("false") || matches_prefix("no") || text == "0" {
832        Some(false)
833    } else if text.eq_ignore_ascii_case("on") {
834        Some(true)
835    } else if matches_prefix("off") && text.len() >= 2 {
836        Some(false)
837    } else {
838        None
839    }
840}
841
842/// The error `boolin` reports for text that is not a boolean.
843#[must_use]
844pub fn invalid_boolean_input(text: &str) -> SQLError {
845    SQLError::Routine {
846        sqlstate: "22P02".into(),
847        message: format!("invalid input syntax for type boolean: \"{text}\""),
848    }
849}
850
851/// Text read as `PostgreSQL`'s `int2in`, `int4in` and `int8in` read it, whose out-of-range error names the text and the type.
852fn integer_from_text(text: &str, target: &str) -> Result<Value> {
853    use crate::expr::integer_input::{parse_int8, IntegerInputError};
854    let out_of_range = || SQLError::Routine {
855        sqlstate: "22003".into(),
856        message: format!("value \"{text}\" is out of range for type {target}"),
857    };
858    let value = parse_int8(text).map_err(|error| match error {
859        IntegerInputError::OutOfRange => out_of_range(),
860        IntegerInputError::InvalidSyntax => SQLError::Routine {
861            sqlstate: "22P02".into(),
862            message: format!("invalid input syntax for type {target}: \"{text}\""),
863        },
864    })?;
865    let in_range = match target {
866        "smallint" => i16::try_from(value).is_ok(),
867        "integer" => i32::try_from(value).is_ok(),
868        _ => true,
869    };
870    if in_range {
871        Ok(Value::Int(value))
872    } else {
873        Err(out_of_range())
874    }
875}
876
877/// CAST to boolean: strings follow `PostgreSQL`'s `parse_bool`
878/// (prefixes of true/false/yes/no, on/off, 1/0); numbers are non-zero
879/// tests.
880pub(super) fn cast_boolean(v: &Value) -> Result<Value> {
881    match v {
882        Value::Bool(b) => Ok(Value::Bool(*b)),
883        Value::Int(n) => Ok(Value::Bool(*n != 0)),
884        Value::Float(f) => Ok(Value::Bool(*f != 0.0)),
885        Value::Decimal(d) => Ok(Value::Bool(!d.is_zero())),
886        Value::Str(s) | Value::FixedChar(s) => parse_boolean_input(s)
887            .map(Value::Bool)
888            .ok_or_else(|| invalid_boolean_input(s)),
889        other => Err(SQLError::TypeMismatch(format!(
890            "cannot cast {other:?} to boolean"
891        ))),
892    }
893}
894
895pub(in crate::expr) use array::parse_pg_array_literal_with_input;
896pub use array::{array_dimensions, parse_pg_array_literal, parse_pg_array_literal_with_control};
897use binary_oid::{bytea_to_integer, cast_bytea, cast_named_oid, cast_oid, cast_xid};
898pub(crate) use temporal::text_input_is_session_independent;
899use temporal::{cast_temporal, TemporalCastTarget};
900
901#[cfg(test)]
902mod production_tests;
903#[cfg(test)]
904mod tests;