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