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