Skip to main content

sql_values/postgres/
cast.rs

1//! PostgreSQL 18's explicit casts, of a literal, `'…'::type` or `1.5::type`, and of a typed
2//! value, each the input function or the cast function `pg_cast` names followed by the length
3//! coercion of the target's modifier, and the typing of a numeric constant.
4
5use alloc::string::{String, ToString};
6use core::fmt;
7
8use super::{
9    BuiltinType,
10    bpchar::PgBpchar,
11    datetime::{
12        DateTimeError, InputContext, PgDate, PgTime, PgTimeTz, PgTimestamp, PgTimestampTz,
13        USECS_PER_DAY,
14    },
15    integer::IntegerType,
16    interval::{IntervalError, PgInterval, parse_interval, parse_interval_typmod},
17    jsonb::{JsonbError, JsonbKind, PgJsonb},
18    numeric::{NumericError, NumericTypmod, PgNumeric},
19    uuid::{PgUuid, UuidError},
20};
21
22/// A literal as written before `::`, its quotes and escapes already decoded.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
24pub enum Literal<'a> {
25    /// A string constant, `'…'`, `E'…'` or `$$…$$`, whose type PostgreSQL leaves unknown until
26    /// the cast reads it with the target's input function.
27    Quoted(&'a str),
28    /// A numeric constant as PostgreSQL 18's lexer reads it, `42`, `0x2A`, `1_000`, `2.5`, `.5`
29    /// or `1e2`, with a leading `-` for a negation the parser folds into the constant, as in
30    /// `(-2.5)::int`.
31    Number(&'a str),
32}
33
34/// The length of a `varchar(n)` or `char(n)` type, in characters.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36pub struct CharLength(usize);
37
38/// `MaxAttrSize`, the longest length a character type takes.
39const MAX_CHAR_LENGTH: usize = 10_485_760;
40
41impl CharLength {
42    /// The character count encoded by this modifier.
43    #[must_use]
44    pub const fn get(self) -> usize {
45        self.0
46    }
47    /// The length PostgreSQL accepts in `varchar(n)` and `char(n)`, from 1 to 10485760.
48    ///
49    /// ```
50    /// use sql_values::postgres::CharLength;
51    ///
52    /// assert!(CharLength::new(1).is_some());
53    /// assert!(CharLength::new(0).is_none());
54    /// assert!(CharLength::new(10_485_761).is_none());
55    /// ```
56    #[must_use]
57    pub fn new(length: usize) -> Option<Self> {
58        (1..=MAX_CHAR_LENGTH)
59            .contains(&length)
60            .then_some(Self(length))
61    }
62}
63
64/// The value a cast produces or takes, printed by [`Display`](fmt::Display) as the type's output
65/// function prints it under the default `DateStyle` of `ISO`.
66#[derive(Debug, Clone, PartialEq, Eq, Hash)]
67pub enum CastValue {
68    /// A `boolean`, printed `t` or `f`.
69    Boolean(bool),
70    /// A `smallint`.
71    Smallint(i16),
72    /// An `integer`.
73    Integer(i32),
74    /// A `bigint`.
75    Bigint(i64),
76    /// A `numeric`.
77    Numeric(PgNumeric),
78    /// A `text` or `varchar`.
79    Text(String),
80    /// A `char(n)`, blank-padded to its length as PostgreSQL holds it, equal to another as
81    /// PostgreSQL finds it, ignoring trailing blanks.
82    Bpchar(PgBpchar<'static>),
83    /// A `date`.
84    Date(PgDate),
85    /// A `timestamp`.
86    Timestamp(PgTimestamp),
87    /// A `timestamptz`, printed as under `TimeZone` `UTC`.
88    TimestampTz(PgTimestampTz),
89    /// A `time`.
90    Time(PgTime),
91    /// A `timetz`, printed with the offset it holds.
92    TimeTz(PgTimeTz),
93    /// A `jsonb`.
94    Jsonb(PgJsonb),
95    /// A `uuid`.
96    Uuid(PgUuid),
97    /// An `interval`, printed under the default `IntervalStyle` of `postgres`, equal to another
98    /// as PostgreSQL finds it, with a month as 30 days and a day as 24 hours.
99    Interval(PgInterval),
100}
101
102/// Why PostgreSQL refuses a cast, one variant per message it raises, or why this crate declines
103/// to answer for it.
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
105#[non_exhaustive]
106pub enum CastError {
107    /// Text the target's input function cannot read.
108    #[error("invalid input syntax for type {}", .0.input_name())]
109    InvalidInputSyntax(BuiltinType),
110    /// Text the integer input function reads as a number beyond the type.
111    #[error("value is out of range for type {}", .0.diagnostic_name())]
112    ValueOutOfRange(BuiltinType),
113    /// A value the cast to an integer type finds beyond the type.
114    #[error("{} out of range", .0.diagnostic_name())]
115    OutOfRange(BuiltinType),
116    /// A `NaN` cast to an integer type.
117    #[error("cannot convert NaN to {}", .0.diagnostic_name())]
118    CannotConvertNaN(BuiltinType),
119    /// An infinite `numeric` cast to an integer type.
120    #[error("cannot convert infinity to {}", .0.diagnostic_name())]
121    CannotConvertInfinity(BuiltinType),
122    /// A value beyond the precision of `numeric(p, s)` after rounding to its scale, or an
123    /// infinity cast to it.
124    #[error("numeric field overflow")]
125    NumericFieldOverflow,
126    /// A `numeric` beyond the weight or display scale PostgreSQL stores.
127    #[error("value overflows numeric format")]
128    NumericFormatOverflow,
129    /// A year, month or day no calendar has.
130    #[error("date/time field value out of range")]
131    DateTimeFieldOutOfRange,
132    /// A date before 4714-11-24 BC.
133    #[error("date out of range")]
134    DateOutOfRange,
135    /// A timestamp before 4714-11-24 BC.
136    #[error("timestamp out of range")]
137    TimestampOutOfRange,
138    /// A date from 294277-01-01 cast to `timestamp`.
139    #[error("date out of range for timestamp")]
140    DateOutOfRangeForTimestamp,
141    /// An offset of 16 hours or more, or with minutes or seconds of 60 or more.
142    #[error("time zone displacement out of range")]
143    TimeZoneDisplacementOutOfRange,
144    /// A number of an interval's text beyond the integer its field accumulates in.
145    #[error("interval field value out of range")]
146    IntervalFieldValueOutOfRange,
147    /// An interval beyond the type, read or rounded to a precision.
148    #[error("interval out of range")]
149    IntervalOutOfRange,
150    /// An infinite `interval` cast to `time`.
151    #[error("cannot convert infinite interval to time")]
152    CannotConvertInfiniteIntervalToTime,
153    /// A value of a type with no cast to the target.
154    #[error("cannot cast type {} to {}", .from.diagnostic_name(), .to.diagnostic_name())]
155    CannotCast {
156        /// The value's type.
157        from: BuiltinType,
158        /// The target's type.
159        to: BuiltinType,
160    },
161    /// A `jsonb` of a kind the cast to a scalar type cannot take, a `null` aside, which casts
162    /// to `NULL`.
163    #[error("cannot cast jsonb {from} to type {}", .to.diagnostic_name())]
164    CannotCastJsonb {
165        /// The kind of the `jsonb`.
166        from: JsonbKind,
167        /// The target's type.
168        to: BuiltinType,
169    },
170    /// Text `jsonb_in` cannot read, any number in it aside, whose refusal is `numeric_in`'s.
171    #[error(transparent)]
172    Jsonb(JsonbError),
173    /// An array literal `array_in` cannot read.
174    #[error("malformed array literal")]
175    MalformedArrayLiteral,
176    /// An array of more than 6 dimensions.
177    #[error("number of array dimensions exceeds the maximum allowed (6)")]
178    ArrayDimensionsExceeded,
179    /// A specified dimension whose upper bound is less than its lower bound.
180    #[error("upper bound cannot be less than lower bound")]
181    UpperBoundLessThanLower,
182    /// A specified dimension whose upper bound is `2147483647`.
183    #[error("array upper bound is too large: {0}")]
184    ArrayUpperBoundTooLarge(i32),
185    /// An array whose size overflows `int32` arithmetic.
186    #[error("array size exceeds the maximum allowed (134217727)")]
187    ArraySizeExceeded,
188    /// A dimension bound `i32` cannot hold.
189    #[error("array bound is out of integer range")]
190    ArrayBoundOutOfRange,
191    /// A literal or cast this crate does not model. A date, timestamp or time is read only in
192    /// the spellings [`PgDate::parse`], [`PgTimestamp::parse`] and [`PgTime::parse`] read, and a
193    /// `timestamptz` or `timetz` only with its offset, since without one the session's
194    /// `TimeZone` decides it. For the same reason no cast from `timestamptz` to `date`,
195    /// `timestamp`, `time`, `timetz` or a character type, from `time` to `timetz`, or from
196    /// `date` or `timestamp` to `timestamptz` is modelled.
197    #[error("cast not modelled")]
198    Unsupported,
199}
200
201/// The value PostgreSQL 18's explicit cast `literal::target` produces, or the error it raises,
202/// with a database encoding of UTF-8.
203///
204/// A string constant is read by the target's input function, an interval type's with the fields
205/// and precision of the target, which `coerce_type` gives `interval_in` alone. So
206/// `'1.75'::interval minute` reads `1.75` as minutes, where a `text` value reads as seconds.
207///
208/// # Errors
209///
210/// The [`CastError`] PostgreSQL raises, or [`CastError::Unsupported`] for a literal or cast this
211/// crate does not model.
212///
213/// ```
214/// use sql_values::postgres::{
215///     CastError, BuiltinType, CharLength, IntervalFields, IntervalTypmod, Literal, NumericTypmod,
216///     cast_literal,
217/// };
218///
219/// let cast = |literal, target| cast_literal(literal, target).map(|value| value.to_string());
220/// let length = |n| CharLength::new(n);
221///
222/// assert_eq!(cast(Literal::Number("2.5"), BuiltinType::Integer).unwrap(), "3");
223/// assert_eq!(cast(Literal::Number("-2.5"), BuiltinType::Integer).unwrap(), "-3");
224/// assert_eq!(cast(Literal::Number("1e2"), BuiltinType::Integer).unwrap(), "100");
225/// assert_eq!(cast(Literal::Number("2.5"), BuiltinType::Smallint).unwrap(), "3");
226/// assert_eq!(
227///     cast(Literal::Number("32768"), BuiltinType::Smallint),
228///     Err(CastError::OutOfRange(BuiltinType::Smallint)),
229/// );
230/// assert_eq!(
231///     cast(Literal::Quoted("2.5"), BuiltinType::Integer),
232///     Err(CastError::InvalidInputSyntax(BuiltinType::Integer)),
233/// );
234///
235/// assert_eq!(cast(Literal::Quoted("abc"), BuiltinType::Bpchar(length(2))).unwrap(), "ab");
236/// assert_eq!(cast(Literal::Quoted("ab"), BuiltinType::Bpchar(length(4))).unwrap(), "ab  ");
237/// assert_eq!(cast(Literal::Quoted("ab"), BuiltinType::Varchar(length(1))).unwrap(), "a");
238/// assert_eq!(cast(Literal::Quoted("abc  "), BuiltinType::Varchar(length(3))).unwrap(), "abc");
239///
240/// let numeric_4_1 = BuiltinType::Numeric(NumericTypmod::new(4, 1));
241/// assert_eq!(cast(Literal::Quoted("12.345"), numeric_4_1).unwrap(), "12.3");
242/// assert_eq!(cast(Literal::Number("12.345"), numeric_4_1).unwrap(), "12.3");
243///
244/// assert_eq!(cast(Literal::Quoted("yes"), BuiltinType::Boolean).unwrap(), "t");
245///
246/// assert_eq!(cast(Literal::Quoted("2026-01-01 23:00"), BuiltinType::Date).unwrap(), "2026-01-01");
247/// assert_eq!(
248///     cast(Literal::Quoted("2026-01-01T23:00:00+05"), BuiltinType::Date).unwrap(),
249///     "2026-01-01",
250/// );
251/// assert_eq!(
252///     cast(Literal::Quoted("2026-01-01 23:00:00.6"), BuiltinType::Timestamp(Some(sql_values::postgres::TimePrecision::new(0)))).unwrap(),
253///     "2026-01-01 23:00:01",
254/// );
255/// assert_eq!(cast(Literal::Quoted("today"), BuiltinType::Date), Err(CastError::Unsupported));
256///
257/// let instant = BuiltinType::TimestampTz(None);
258/// assert_eq!(
259///     cast(Literal::Quoted("2030-01-01 00:00:00+02"), instant).unwrap(),
260///     "2029-12-31 22:00:00+00",
261/// );
262/// assert_eq!(
263///     cast(Literal::Quoted("2030-01-01 00:00:00"), instant),
264///     Err(CastError::Unsupported),
265/// );
266///
267/// assert_eq!(
268///     cast(Literal::Quoted(r#"{"b": 1, "a": 2.50}"#), BuiltinType::Jsonb).unwrap(),
269///     r#"{"a": 2.50, "b": 1}"#,
270/// );
271/// assert_eq!(cast(Literal::Number("1"), BuiltinType::Jsonb), Err(CastError::CannotCast {
272///     from: BuiltinType::Integer,
273///     to: BuiltinType::Jsonb,
274/// }));
275///
276/// assert_eq!(
277///     cast(Literal::Quoted("{A0EEBC999C0B4EF8BB6D6BB9BD380A11}"), BuiltinType::Uuid).unwrap(),
278///     "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11",
279/// );
280///
281/// let minute = IntervalTypmod::new(Some(IntervalFields::Minute), None).unwrap();
282/// assert_eq!(cast(Literal::Quoted("1.75"), BuiltinType::Interval(minute)).unwrap(), "00:01:00");
283/// assert_eq!(
284///     cast(Literal::Quoted("178956971 years"), BuiltinType::Interval(minute)),
285///     Err(CastError::IntervalOutOfRange),
286/// );
287/// ```
288pub fn cast_literal(literal: Literal<'_>, target: BuiltinType) -> Result<CastValue, CastError> {
289    match literal {
290        Literal::Quoted(text) => cast_quoted(text, target),
291        Literal::Number(_) if !target.supports_cast() => Err(CastError::Unsupported),
292        Literal::Number(text) => cast_non_null(number_constant(text)?, target),
293    }
294}
295
296/// The value PostgreSQL 18 makes of a numeric constant, written as [`Literal::Number`] takes it,
297/// as its lexer and `make_const` type it. An integer is an `integer` when it fits, else a
298/// `bigint` when it fits, else a `numeric`, and a constant with a point or an exponent is a
299/// `numeric`.
300///
301/// # Errors
302///
303/// [`CastError::Unsupported`] for text that is not one numeric constant, and the error
304/// `numeric_in` raises for a `numeric` PostgreSQL cannot store.
305///
306/// ```
307/// use sql_values::postgres::{CastValue, number_constant};
308///
309/// assert_eq!(number_constant("2147483647"), Ok(CastValue::Integer(i32::MAX)));
310/// assert_eq!(number_constant("2147483648"), Ok(CastValue::Bigint(2_147_483_648)));
311/// assert_eq!(number_constant("-0x8000_0000"), Ok(CastValue::Integer(i32::MIN)));
312/// let big = number_constant("9223372036854775808").unwrap();
313/// assert!(matches!(big, CastValue::Numeric(_)));
314/// assert_eq!(number_constant("1.50").unwrap().to_string(), "1.50");
315/// ```
316pub fn number_constant(text: &str) -> Result<CastValue, CastError> {
317    let unsigned = text.strip_prefix('-').unwrap_or(text);
318    match scan_number(unsigned.as_bytes()) {
319        None => Err(CastError::Unsupported),
320        Some(NumberToken::Integer) => [IntegerType::Integer, IntegerType::Bigint]
321            .into_iter()
322            .find_map(|integer| int_input(text, integer).ok())
323            .map_or_else(|| numeric_input(text).map(CastValue::Numeric), Ok),
324        Some(NumberToken::Decimal) => numeric_input(text).map(CastValue::Numeric),
325    }
326}
327
328/// The value PostgreSQL 18's explicit cast `value::target` produces, `None` for `NULL`, or the
329/// error it raises.
330///
331/// A value of a character type is read by the target's input function, as `pg_cast`'s I/O
332/// coercion does, and a value cast to a character type is printed by its type's output function,
333/// `boolean` as `true` or `false`. Between the other types the cast is the function `pg_cast`
334/// names, `int4_bool`, `bool_int4`, the integer narrowings, `int*_numeric`, `numeric_int*`,
335/// `date_timestamp`, `timestamp_date`, `timestamp_time`, `timetz_time`, `time_interval`,
336/// `interval_time`, `jsonb_bool`, `jsonb_numeric` and `jsonb_int*`, the last three followed by
337/// `numeric_int*`. A `jsonb` `null` cast to `boolean`, `numeric` or an integer type and an
338/// infinite `timestamp` cast to `time` are `NULL`, the only casts giving `NULL`. The length
339/// coercion of the target's modifier follows, which for an interval type is `interval_scale`,
340/// and a pair `pg_cast` has no cast for raises [`CastError::CannotCast`].
341///
342/// # Errors
343///
344/// The [`CastError`] PostgreSQL raises, or [`CastError::Unsupported`] for a cast whose answer
345/// the session's `TimeZone` decides, or a text the target's input function is not modelled for.
346///
347/// ```
348/// use sql_values::postgres::{
349///     CastError, BuiltinType, CastValue, IntervalFields, IntervalTypmod, JsonbKind, PgInterval,
350///     PgJsonb, PgNumeric, PgTime, PgTimestamp, cast_value, parse_interval,
351/// };
352///
353/// let cast = |value, target| {
354///     cast_value(value, target).map(|value| value.map(|value| value.to_string()))
355/// };
356/// let some = |text: &str| Ok(Some(text.to_owned()));
357///
358/// assert_eq!(cast(CastValue::Integer(1), BuiltinType::Boolean), some("t"));
359/// assert_eq!(
360///     cast(CastValue::Bigint(1), BuiltinType::Boolean),
361///     Err(CastError::CannotCast { from: BuiltinType::Bigint, to: BuiltinType::Boolean }),
362/// );
363/// assert_eq!(cast(CastValue::Boolean(true), BuiltinType::Text), some("true"));
364/// let half = PgNumeric::parse("-2.5").unwrap();
365/// assert_eq!(cast(CastValue::Numeric(half), BuiltinType::Smallint), some("-3"));
366/// assert_eq!(
367///     cast(CastValue::Numeric(PgNumeric::NAN), BuiltinType::Integer),
368///     Err(CastError::CannotConvertNaN(BuiltinType::Integer)),
369/// );
370/// assert_eq!(
371///     cast(CastValue::Integer(40_000), BuiltinType::Smallint),
372///     Err(CastError::OutOfRange(BuiltinType::Smallint)),
373/// );
374/// assert_eq!(
375///     cast(CastValue::Text("x".into()), BuiltinType::Boolean),
376///     Err(CastError::InvalidInputSyntax(BuiltinType::Boolean)),
377/// );
378///
379/// let jsonb = |text| CastValue::Jsonb(PgJsonb::parse(text).unwrap());
380/// assert_eq!(cast(jsonb("1.5"), BuiltinType::Integer), some("2"));
381/// assert_eq!(cast(jsonb("null"), BuiltinType::Integer), Ok(None));
382/// assert_eq!(
383///     cast(jsonb("[1]"), BuiltinType::Numeric(None)),
384///     Err(CastError::CannotCastJsonb { from: JsonbKind::Array, to: BuiltinType::Numeric(None) }),
385/// );
386///
387/// let late = PgTime::from_hms_micro(23, 59, 59, 990_000).unwrap();
388/// assert_eq!(cast(CastValue::Time(late), BuiltinType::Time(Some(sql_values::postgres::TimePrecision::new(1)))), some("24:00:00"));
389/// let endless = CastValue::Timestamp(PgTimestamp::INFINITY);
390/// assert_eq!(cast(endless, BuiltinType::Time(None)), Ok(None));
391///
392/// let hour = BuiltinType::Interval(IntervalTypmod::new(Some(IntervalFields::Hour), None).unwrap());
393/// let span = CastValue::Interval(parse_interval("90 minutes").unwrap());
394/// assert_eq!(cast(span, hour), some("01:00:00"));
395/// let minute = IntervalTypmod::new(Some(IntervalFields::Minute), None).unwrap();
396/// let seconds = cast_value(CastValue::Text("1.75".into()), BuiltinType::Interval(minute));
397/// assert_eq!(seconds.unwrap().unwrap().to_string(), "00:00:00");
398/// let span = CastValue::Interval(parse_interval("-1 days -01:00:00").unwrap());
399/// assert_eq!(cast(span, BuiltinType::Time(None)), some("23:00:00"));
400/// assert_eq!(
401///     cast(CastValue::Interval(PgInterval::INFINITY), BuiltinType::Time(None)),
402///     Err(CastError::CannotConvertInfiniteIntervalToTime),
403/// );
404/// ```
405pub fn cast_value(value: CastValue, target: BuiltinType) -> Result<Option<CastValue>, CastError> {
406    match (value, target) {
407        (CastValue::Jsonb(value), _) => cast_jsonb(value, target),
408        // `timestamp_time`, which gives `NULL` for an infinity.
409        (CastValue::Timestamp(at), BuiltinType::Time(precision)) => Ok(at.time().map(|time| {
410            CastValue::Time(time.adjust_for_typmod(precision.map(super::TimePrecision::get)))
411        })),
412        (value, _) => cast_non_null(value, target).map(Some),
413    }
414}
415
416/// The cast of a `jsonb`, by `jsonb_bool`, `jsonb_numeric`, `jsonb_int*` or its output function.
417fn cast_jsonb(value: PgJsonb, target: BuiltinType) -> Result<Option<CastValue>, CastError> {
418    let to = target.pg_type();
419    let cannot_cast = |from| CastError::CannotCastJsonb { from, to };
420    match target {
421        BuiltinType::Boolean => Ok(value
422            .to_bool()
423            .map_err(cannot_cast)?
424            .map(CastValue::Boolean)),
425        BuiltinType::Smallint
426        | BuiltinType::Integer
427        | BuiltinType::Bigint
428        | BuiltinType::Numeric(_) => value
429            .into_numeric()
430            .map_err(cannot_cast)?
431            .map(|number| cast_non_null(CastValue::Numeric(number), target))
432            .transpose(),
433        BuiltinType::Text | BuiltinType::Varchar(_) | BuiltinType::Bpchar(_) => {
434            Ok(Some(character(&value.to_string(), target)))
435        }
436        BuiltinType::Jsonb => Ok(Some(CastValue::Jsonb(value))),
437        _ => cast_non_null(CastValue::Jsonb(value), target).map(Some),
438    }
439}
440
441/// The cast of a value other than a `jsonb`, and other than a `timestamp` cast to `time`, which
442/// never gives `NULL`.
443fn cast_non_null(value: CastValue, target: BuiltinType) -> Result<CastValue, CastError> {
444    if !target.supports_cast() {
445        return Err(CastError::Unsupported);
446    }
447    let cannot_cast = CastError::CannotCast {
448        from: value.pg_type(),
449        to: target.pg_type(),
450    };
451    match (value, target) {
452        (CastValue::Text(text), _) => cast_text(&text, target),
453        // `rtrim1`, dropping the blanks `char(n)` pads with.
454        (CastValue::Bpchar(value), BuiltinType::Text | BuiltinType::Varchar(_)) => {
455            Ok(character(value.as_text(), target))
456        }
457        (CastValue::Bpchar(value), _) => cast_text(value.as_str(), target),
458        (
459            CastValue::TimestampTz(_),
460            BuiltinType::Date
461            | BuiltinType::Timestamp(_)
462            | BuiltinType::Time(_)
463            | BuiltinType::TimeTz(_)
464            | BuiltinType::Text
465            | BuiltinType::Varchar(_)
466            | BuiltinType::Bpchar(_),
467        )
468        | (CastValue::Date(_) | CastValue::Timestamp(_), BuiltinType::TimestampTz(_))
469        | (CastValue::Time(_), BuiltinType::TimeTz(_)) => Err(CastError::Unsupported),
470        // `booltext`.
471        (
472            CastValue::Boolean(value),
473            BuiltinType::Text | BuiltinType::Varchar(_) | BuiltinType::Bpchar(_),
474        ) => Ok(character(if value { "true" } else { "false" }, target)),
475        (value, BuiltinType::Text | BuiltinType::Varchar(_) | BuiltinType::Bpchar(_)) => {
476            Ok(character(&value.to_string(), target))
477        }
478        (CastValue::Boolean(value), BuiltinType::Boolean) => Ok(CastValue::Boolean(value)),
479        (CastValue::Boolean(value), BuiltinType::Integer) => Ok(CastValue::Integer(value.into())),
480        (CastValue::Integer(value), BuiltinType::Boolean) => Ok(CastValue::Boolean(value != 0)),
481        (CastValue::Smallint(value), _) if target.takes_integer() => integer(value.into(), target),
482        (CastValue::Integer(value), _) if target.takes_integer() => integer(value.into(), target),
483        (CastValue::Bigint(value), _) if target.takes_integer() => integer(value, target),
484        (CastValue::Numeric(value), BuiltinType::Numeric(typmod)) => numeric_typmod(value, typmod),
485        (CastValue::Numeric(value), _) if target.takes_integer() => {
486            let to = target.pg_type();
487            if value.is_nan() {
488                Err(CastError::CannotConvertNaN(to))
489            } else if value.is_infinite() {
490                Err(CastError::CannotConvertInfinity(to))
491            } else {
492                let value = value.to_i64_rounded().ok_or(CastError::OutOfRange(to))?;
493                integer(value, target)
494            }
495        }
496        (CastValue::Date(date), BuiltinType::Date) => Ok(CastValue::Date(date)),
497        (CastValue::Date(date), BuiltinType::Timestamp(precision)) => {
498            // `date2timestamp` raises only this error.
499            let at = date
500                .to_timestamp()
501                .map_err(|_| CastError::DateOutOfRangeForTimestamp)?;
502            Ok(CastValue::Timestamp(at.adjust_for_typmod(
503                precision.map(super::TimePrecision::get),
504            )))
505        }
506        (CastValue::Timestamp(at), BuiltinType::Date) => Ok(CastValue::Date(at.date())),
507        (CastValue::Timestamp(at), BuiltinType::Timestamp(precision)) => Ok(CastValue::Timestamp(
508            at.adjust_for_typmod(precision.map(super::TimePrecision::get)),
509        )),
510        (CastValue::TimestampTz(at), BuiltinType::TimestampTz(precision)) => Ok(
511            CastValue::TimestampTz(at.adjust_for_typmod(precision.map(super::TimePrecision::get))),
512        ),
513        (CastValue::Time(time), BuiltinType::Time(precision)) => Ok(CastValue::Time(
514            time.adjust_for_typmod(precision.map(super::TimePrecision::get)),
515        )),
516        // `timetz_time`, dropping the offset.
517        (CastValue::TimeTz(time), BuiltinType::Time(precision)) => Ok(CastValue::Time(
518            time.time()
519                .adjust_for_typmod(precision.map(super::TimePrecision::get)),
520        )),
521        (CastValue::TimeTz(time), BuiltinType::TimeTz(precision)) => Ok(CastValue::TimeTz(
522            time.adjust_for_typmod(precision.map(super::TimePrecision::get)),
523        )),
524        (CastValue::Uuid(value), BuiltinType::Uuid) => Ok(CastValue::Uuid(value)),
525        // `interval_time`, the clock of the microseconds, wrapped into one day.
526        (CastValue::Interval(span), BuiltinType::Time(precision)) => {
527            if !span.is_finite() {
528                return Err(CastError::CannotConvertInfiniteIntervalToTime);
529            }
530            let time = PgTime::from_micros(span.microseconds.rem_euclid(USECS_PER_DAY))
531                .expect("a remainder of a day is a time");
532            Ok(CastValue::Time(time.adjust_for_typmod(
533                precision.map(super::TimePrecision::get),
534            )))
535        }
536        (CastValue::Interval(span), BuiltinType::Interval(typmod)) => {
537            interval_value(span.adjust_for_typmod(typmod))
538        }
539        // `time_interval`.
540        (CastValue::Time(time), BuiltinType::Interval(typmod)) => {
541            let span = PgInterval {
542                months: 0,
543                days: 0,
544                microseconds: time.micros(),
545            };
546            interval_value(span.adjust_for_typmod(typmod))
547        }
548        _ => Err(cannot_cast),
549    }
550}
551
552impl BuiltinType {
553    /// Whether the target is an integer type or `numeric`, which every integer type casts to.
554    const fn takes_integer(self) -> bool {
555        matches!(
556            self,
557            Self::Smallint | Self::Integer | Self::Bigint | Self::Numeric(_)
558        )
559    }
560}
561
562impl CastValue {
563    /// The value's type, `text` for a `varchar`.
564    const fn pg_type(&self) -> BuiltinType {
565        match self {
566            Self::Boolean(_) => BuiltinType::Boolean,
567            Self::Smallint(_) => BuiltinType::Smallint,
568            Self::Integer(_) => BuiltinType::Integer,
569            Self::Bigint(_) => BuiltinType::Bigint,
570            Self::Numeric(_) => BuiltinType::Numeric(None),
571            Self::Text(_) => BuiltinType::Text,
572            Self::Bpchar(_) => BuiltinType::Bpchar(None),
573            Self::Date(_) => BuiltinType::Date,
574            Self::Timestamp(_) => BuiltinType::Timestamp(None),
575            Self::TimestampTz(_) => BuiltinType::TimestampTz(None),
576            Self::Time(_) => BuiltinType::Time(None),
577            Self::TimeTz(_) => BuiltinType::TimeTz(None),
578            Self::Jsonb(_) => BuiltinType::Jsonb,
579            Self::Uuid(_) => BuiltinType::Uuid,
580            Self::Interval(_) => BuiltinType::Interval(super::IntervalTypmod::UNMODIFIED),
581        }
582    }
583}
584
585/// The integer narrowings `int82`, `int84` and `int42`, or `int*_numeric` and the `numeric()`
586/// length coercion, of an integer to a target that [`BuiltinType::takes_integer`].
587fn integer(value: i64, target: BuiltinType) -> Result<CastValue, CastError> {
588    if let BuiltinType::Numeric(typmod) = target {
589        return numeric_typmod(PgNumeric::from(value), typmod);
590    }
591    IntegerType::try_from(target)
592        .expect("a target taking an integer is numeric or an integer type")
593        .value(value)
594}
595
596/// `numeric_in`, its refusal as the cast error.
597fn numeric_input(text: &str) -> Result<PgNumeric, CastError> {
598    PgNumeric::parse(text).map_err(numeric_input_error)
599}
600
601/// The cast error of a refusal by `numeric_in`, which raises only a syntax error or an overflow.
602fn numeric_input_error(error: NumericError) -> CastError {
603    if error == NumericError::InvalidInputSyntax {
604        CastError::InvalidInputSyntax(BuiltinType::Numeric(None))
605    } else {
606        CastError::NumericFormatOverflow
607    }
608}
609
610/// The cast error of a refusal by `jsonb_in`, the one by `numeric_in` for a number in it.
611fn jsonb_input_error(error: JsonbError) -> CastError {
612    match error {
613        JsonbError::Numeric(error) => numeric_input_error(error),
614        error => CastError::Jsonb(error),
615    }
616}
617
618/// An interval, its refusal as the cast error.
619fn interval_value(span: Result<PgInterval, IntervalError>) -> Result<CastValue, CastError> {
620    span.map(CastValue::Interval).map_err(|error| match error {
621        IntervalError::InvalidSyntax => {
622            CastError::InvalidInputSyntax(BuiltinType::Interval(super::IntervalTypmod::UNMODIFIED))
623        }
624        IntervalError::FieldValueOutOfRange => CastError::IntervalFieldValueOutOfRange,
625        IntervalError::OutOfRange => CastError::IntervalOutOfRange,
626        IntervalError::DivisionByZero => unreachable!("no cast divides an interval"),
627    })
628}
629
630/// The lexer's token for a numeric constant.
631enum NumberToken {
632    /// `decinteger`, `hexinteger`, `octinteger` or `bininteger`.
633    Integer,
634    /// `numeric` or `real`.
635    Decimal,
636}
637
638/// The token PostgreSQL 18's `scan.l` reads `bytes` as, or `None` when it is not one numeric
639/// constant.
640fn scan_number(bytes: &[u8]) -> Option<NumberToken> {
641    let (radix, digits) = match bytes {
642        [b'0', b'x' | b'X', digits @ ..] => (16, digits),
643        [b'0', b'o' | b'O', digits @ ..] => (8, digits),
644        [b'0', b'b' | b'B', digits @ ..] => (2, digits),
645        _ => return scan_decimal(bytes),
646    };
647    // `0[xX](_?{hexdigit})+`, where an underscore may follow the prefix.
648    let mut at = 0;
649    while at < digits.len() {
650        at += usize::from(digits[at] == b'_');
651        if !digits
652            .get(at)
653            .is_some_and(|&b| char::from(b).is_digit(radix))
654        {
655            return None;
656        }
657        at += 1;
658    }
659    (at > 0).then_some(NumberToken::Integer)
660}
661
662/// `decinteger`, `numeric` or `real`.
663fn scan_decimal(bytes: &[u8]) -> Option<NumberToken> {
664    let integer = scan_decinteger(bytes);
665    let mut at = integer;
666    let mut token = NumberToken::Integer;
667    if bytes.get(at) == Some(&b'.') {
668        token = NumberToken::Decimal;
669        at += 1;
670        let fraction = scan_decinteger(&bytes[at..]);
671        if integer == 0 && fraction == 0 {
672            return None;
673        }
674        at += fraction;
675    } else if integer == 0 {
676        return None;
677    }
678    if matches!(bytes.get(at), Some(b'e' | b'E')) {
679        token = NumberToken::Decimal;
680        at += 1;
681        at += usize::from(matches!(bytes.get(at), Some(b'+' | b'-')));
682        let exponent = scan_decinteger(&bytes[at..]);
683        if exponent == 0 {
684            return None;
685        }
686        at += exponent;
687    }
688    (at == bytes.len()).then_some(token)
689}
690
691/// The length of the leading `{decdigit}(_?{decdigit})*`, `0` when there is none.
692fn scan_decinteger(bytes: &[u8]) -> usize {
693    if !bytes.first().is_some_and(u8::is_ascii_digit) {
694        return 0;
695    }
696    let mut at = 1;
697    loop {
698        let next = at + usize::from(bytes.get(at) == Some(&b'_'));
699        if !bytes.get(next).is_some_and(u8::is_ascii_digit) {
700            return at;
701        }
702        at = next + 1;
703    }
704}
705
706/// The cast of an unknown literal, which reads it as [`cast_text`] does a `text` value, except
707/// that `coerce_type` hands `interval_in` the target's modifier, so the fields of an interval
708/// type pick the unit of a bare number, as in `interval '90' minute`.
709fn cast_quoted(text: &str, target: BuiltinType) -> Result<CastValue, CastError> {
710    match target {
711        BuiltinType::Interval(typmod) if !text.contains('\0') => {
712            interval_value(parse_interval_typmod(text, typmod))
713        }
714        _ => cast_text(text, target),
715    }
716}
717
718/// The I/O coercion of a `text` value, the target's input function without a modifier followed
719/// by the length coercion.
720fn cast_text(text: &str, target: BuiltinType) -> Result<CastValue, CastError> {
721    // A string never holds NUL, which ends a C string.
722    if text.contains('\0') {
723        return Err(CastError::Unsupported);
724    }
725    match target {
726        BuiltinType::Boolean => bool_in(text).map(CastValue::Boolean),
727        BuiltinType::Smallint => int_input(text, IntegerType::Smallint),
728        BuiltinType::Integer => int_input(text, IntegerType::Integer),
729        BuiltinType::Bigint => int_input(text, IntegerType::Bigint),
730        BuiltinType::Numeric(typmod) => numeric_typmod(numeric_input(text)?, typmod),
731        BuiltinType::Text | BuiltinType::Varchar(_) | BuiltinType::Bpchar(_) => {
732            Ok(character(text, target))
733        }
734        BuiltinType::Date => PgDate::parse(text, InputContext::new())
735            .map(CastValue::Date)
736            .map_err(datetime_error),
737        BuiltinType::Timestamp(precision) => PgTimestamp::parse(text, InputContext::new())
738            .map(|at| {
739                CastValue::Timestamp(at.adjust_for_typmod(precision.map(super::TimePrecision::get)))
740            })
741            .map_err(datetime_error),
742        BuiltinType::TimestampTz(precision) => PgTimestampTz::parse(text, InputContext::new())
743            .map(|at| {
744                CastValue::TimestampTz(
745                    at.adjust_for_typmod(precision.map(super::TimePrecision::get)),
746                )
747            })
748            .map_err(datetime_error),
749        BuiltinType::Time(precision) => PgTime::parse(text, InputContext::new())
750            .map(|time| {
751                CastValue::Time(time.adjust_for_typmod(precision.map(super::TimePrecision::get)))
752            })
753            .map_err(datetime_error),
754        BuiltinType::TimeTz(precision) => PgTimeTz::parse(text, InputContext::new())
755            .map(|time| {
756                CastValue::TimeTz(time.adjust_for_typmod(precision.map(super::TimePrecision::get)))
757            })
758            .map_err(datetime_error),
759        BuiltinType::Jsonb => PgJsonb::parse(text)
760            .map(CastValue::Jsonb)
761            .map_err(jsonb_input_error),
762        BuiltinType::Uuid => {
763            PgUuid::parse(text)
764                .map(CastValue::Uuid)
765                .map_err(|UuidError::InvalidInputSyntax| {
766                    CastError::InvalidInputSyntax(BuiltinType::Uuid)
767                })
768        }
769        BuiltinType::Interval(typmod) => {
770            interval_value(parse_interval(text).and_then(|span| span.adjust_for_typmod(typmod)))
771        }
772        _ => Err(CastError::Unsupported),
773    }
774}
775
776fn numeric_typmod(value: PgNumeric, typmod: Option<NumericTypmod>) -> Result<CastValue, CastError> {
777    match typmod {
778        Some(typmod) => value.apply_typmod(typmod),
779        None => Ok(value),
780    }
781    .map(CastValue::Numeric)
782}
783
784/// The `varchar()` or `bpchar()` length coercion of an explicit cast, which truncates to the
785/// length and, for `char(n)`, pads with blanks.
786fn character(text: &str, target: BuiltinType) -> CastValue {
787    match target {
788        BuiltinType::Varchar(Some(length)) => CastValue::Text(clip(text, length).into()),
789        BuiltinType::Bpchar(Some(length)) => {
790            let clipped = clip(text, length);
791            let mut padded = String::from(clipped);
792            let blanks = length.0 - clipped.chars().count();
793            padded.extend(core::iter::repeat_n(' ', blanks));
794            CastValue::Bpchar(PgBpchar::new(padded))
795        }
796        BuiltinType::Bpchar(None) => CastValue::Bpchar(PgBpchar::new(String::from(text))),
797        _ => CastValue::Text(text.into()),
798    }
799}
800
801/// The first `length` characters of `text`.
802fn clip(text: &str, length: CharLength) -> &str {
803    text.char_indices()
804        .nth(length.0)
805        .map_or(text, |(end, _)| &text[..end])
806}
807
808/// The C library's `isspace` in the C locale.
809pub(crate) const fn is_pg_space(byte: u8) -> bool {
810    matches!(byte, b' ' | b'\t' | b'\n' | 0x0B | 0x0C | b'\r')
811}
812
813pub(crate) fn trim_pg_space(bytes: &[u8]) -> &[u8] {
814    let start = bytes.iter().take_while(|&&b| is_pg_space(b)).count();
815    let end = bytes
816        .iter()
817        .rposition(|&b| !is_pg_space(b))
818        .map_or(start, |last| last + 1);
819    &bytes[start..end.max(start)]
820}
821
822/// `boolin`, reading a case-insensitive prefix of `true`, `false`, `yes` or `no`, `on`, `of` or
823/// `off`, or `1` or `0`, between blanks.
824fn bool_in(text: &str) -> Result<bool, CastError> {
825    let word = trim_pg_space(text.as_bytes());
826    let abbreviates = |full: &[u8]| {
827        full.get(..word.len())
828            .is_some_and(|prefix| prefix.eq_ignore_ascii_case(word))
829    };
830    let value = match word {
831        [b't' | b'T', ..] if abbreviates(b"true") => true,
832        [b'f' | b'F', ..] if abbreviates(b"false") => false,
833        [b'y' | b'Y', ..] if abbreviates(b"yes") => true,
834        [b'n' | b'N', ..] if abbreviates(b"no") => false,
835        [b'o' | b'O', _, ..] if abbreviates(b"on") => true,
836        [b'o' | b'O', _, ..] if abbreviates(b"off") => false,
837        b"1" => true,
838        b"0" => false,
839        _ => return Err(CastError::InvalidInputSyntax(BuiltinType::Boolean)),
840    };
841    Ok(value)
842}
843
844/// Why `pg_strtoint*` refuses text.
845enum IntInputError {
846    Syntax,
847    Range,
848}
849
850/// `int_in` read as `integer`, mapping its refusal to the error naming that type.
851fn int_input(text: &str, integer: IntegerType) -> Result<CastValue, CastError> {
852    let value = int_in(text, integer).map_err(|error| match error {
853        IntInputError::Syntax => CastError::InvalidInputSyntax(integer.into()),
854        IntInputError::Range => CastError::ValueOutOfRange(integer.into()),
855    })?;
856    Ok(integer
857        .value(value)
858        .expect("int_in kept the value in the type's range"))
859}
860
861/// `pg_strtoint16`, `pg_strtoint32` or `pg_strtoint64` by `integer`, reading blanks, a sign, a
862/// decimal, `0x`, `0o` or `0b` integer with single underscores between digits, then blanks. An
863/// overflow stops the read where it happens, before any trailing junk is seen.
864fn int_in(text: &str, integer: IntegerType) -> Result<i64, IntInputError> {
865    let bytes = text.as_bytes();
866    let mut at = bytes.iter().take_while(|&&b| is_pg_space(b)).count();
867    let negative = bytes.get(at) == Some(&b'-');
868    at += usize::from(matches!(bytes.get(at), Some(b'+' | b'-')));
869    let radix = match (bytes.get(at), bytes.get(at + 1)) {
870        (Some(b'0'), Some(b'x' | b'X')) => 16,
871        (Some(b'0'), Some(b'o' | b'O')) => 8,
872        (Some(b'0'), Some(b'b' | b'B')) => 2,
873        _ => 10,
874    };
875    if radix != 10 {
876        at += 2;
877    }
878    let first_digit = at;
879    let is_digit = |byte: Option<&u8>| byte.is_some_and(|&b| char::from(b).is_digit(radix));
880    // The magnitude of the type's minimum, which a negative value reaches.
881    let limit = integer.range().start().unsigned_abs();
882    let mut magnitude: u64 = 0;
883    loop {
884        match bytes.get(at) {
885            Some(&byte) if is_digit(Some(&byte)) => {
886                if magnitude > limit / u64::from(radix) {
887                    return Err(IntInputError::Range);
888                }
889                let digit = char::from(byte).to_digit(radix).expect("checked a digit");
890                magnitude = magnitude * u64::from(radix) + u64::from(digit);
891                at += 1;
892            }
893            Some(b'_') => {
894                if radix == 10 && at == first_digit {
895                    return Err(IntInputError::Syntax);
896                }
897                at += 1;
898                if !is_digit(bytes.get(at)) {
899                    return Err(IntInputError::Syntax);
900                }
901            }
902            _ => break,
903        }
904    }
905    if at == first_digit || !bytes[at..].iter().all(|&b| is_pg_space(b)) {
906        return Err(IntInputError::Syntax);
907    }
908    let value = if negative {
909        -i128::from(magnitude)
910    } else {
911        i128::from(magnitude)
912    };
913    i64::try_from(value)
914        .ok()
915        .filter(|value| integer.range().contains(value))
916        .ok_or(IntInputError::Range)
917}
918
919/// The cast error of a refusal by a date or time input function.
920fn datetime_error(error: DateTimeError) -> CastError {
921    match error {
922        DateTimeError::FieldValueOutOfRange => CastError::DateTimeFieldOutOfRange,
923        DateTimeError::TimeZoneDisplacementOutOfRange => CastError::TimeZoneDisplacementOutOfRange,
924        DateTimeError::DateOutOfRange => CastError::DateOutOfRange,
925        DateTimeError::TimestampOutOfRange => CastError::TimestampOutOfRange,
926
927        DateTimeError::InvalidInputSyntax(pg_type) => CastError::InvalidInputSyntax(pg_type),
928        DateTimeError::TimestampCannotBeNaN
929        | DateTimeError::OutsideJiffRange
930        | DateTimeError::NeedsTimeZone
931        | DateTimeError::NeedsDateOrder
932        | DateTimeError::NeedsCurrentTime
933        | DateTimeError::TimeZoneNotRecognized => CastError::Unsupported,
934    }
935}
936
937/// Each type's output function under `DateStyle` `ISO`, `IntervalStyle` `postgres` and
938/// `TimeZone` `UTC`.
939impl fmt::Display for CastValue {
940    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
941        match self {
942            Self::Boolean(value) => f.write_str(if *value { "t" } else { "f" }),
943            Self::Smallint(value) => write!(f, "{value}"),
944            Self::Integer(value) => write!(f, "{value}"),
945            Self::Bigint(value) => write!(f, "{value}"),
946            Self::Numeric(value) => write!(f, "{value}"),
947            Self::Text(text) => f.write_str(text),
948            Self::Bpchar(value) => write!(f, "{value}"),
949            Self::Date(date) => write!(f, "{date}"),
950            Self::Timestamp(at) => write!(f, "{at}"),
951            Self::TimestampTz(at) => write!(f, "{at}"),
952            Self::Time(time) => write!(f, "{time}"),
953            Self::TimeTz(time) => write!(f, "{time}"),
954            Self::Jsonb(value) => write!(f, "{value}"),
955            Self::Uuid(value) => write!(f, "{value}"),
956            Self::Interval(span) => write!(f, "{span}"),
957        }
958    }
959}