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