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