use alloc::string::{String, ToString};
use core::fmt;
use super::{
bpchar::PgBpchar,
datetime::{
DateTimeError, InputContext, PgDate, PgTime, PgTimeTz, PgTimestamp, PgTimestampTz,
USECS_PER_DAY,
},
integer::IntegerType,
interval::{IntervalError, IntervalTypmod, PgInterval, parse_interval, parse_interval_typmod},
jsonb::{JsonbError, JsonbKind, PgJsonb},
numeric::{NumericError, NumericTypmod, PgNumeric},
uuid::{PgUuid, UuidError},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Literal<'a> {
Quoted(&'a str),
Number(&'a str),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CastTarget {
Boolean,
Smallint,
Integer,
Bigint,
Numeric(Option<NumericTypmod>),
Text,
Varchar(Option<CharLength>),
Bpchar(Option<CharLength>),
Date,
Timestamp(Option<u8>),
TimestampTz(Option<u8>),
Time(Option<u8>),
TimeTz(Option<u8>),
Jsonb,
Uuid,
Interval(IntervalTypmod),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CharLength(usize);
const MAX_CHAR_LENGTH: usize = 10_485_760;
impl CharLength {
#[must_use]
pub fn new(length: usize) -> Option<Self> {
(1..=MAX_CHAR_LENGTH)
.contains(&length)
.then_some(Self(length))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PgType {
Boolean,
Smallint,
Integer,
Bigint,
Numeric,
Text,
Varchar,
Bpchar,
Date,
Timestamp,
TimestampTz,
Time,
TimeTz,
Jsonb,
Interval,
Uuid,
}
impl fmt::Display for PgType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
impl PgType {
const fn name(self) -> &'static str {
match self {
Self::Boolean => "boolean",
Self::Smallint => "smallint",
Self::Integer => "integer",
Self::Bigint => "bigint",
Self::Numeric => "numeric",
Self::Text => "text",
Self::Varchar => "character varying",
Self::Bpchar => "character",
Self::Date => "date",
Self::Timestamp => "timestamp without time zone",
Self::TimestampTz => "timestamp with time zone",
Self::Time => "time without time zone",
Self::TimeTz => "time with time zone",
Self::Jsonb => "jsonb",
Self::Interval => "interval",
Self::Uuid => "uuid",
}
}
pub(crate) const fn input_name(self) -> &'static str {
match self {
Self::Timestamp => "timestamp",
Self::Time => "time",
other => other.name(),
}
}
}
impl CastTarget {
#[must_use]
pub const fn pg_type(self) -> PgType {
match self {
Self::Boolean => PgType::Boolean,
Self::Smallint => PgType::Smallint,
Self::Integer => PgType::Integer,
Self::Bigint => PgType::Bigint,
Self::Numeric(_) => PgType::Numeric,
Self::Text => PgType::Text,
Self::Varchar(_) => PgType::Varchar,
Self::Bpchar(_) => PgType::Bpchar,
Self::Date => PgType::Date,
Self::Timestamp(_) => PgType::Timestamp,
Self::TimestampTz(_) => PgType::TimestampTz,
Self::Time(_) => PgType::Time,
Self::TimeTz(_) => PgType::TimeTz,
Self::Jsonb => PgType::Jsonb,
Self::Uuid => PgType::Uuid,
Self::Interval(_) => PgType::Interval,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum CastValue {
Boolean(bool),
Smallint(i16),
Integer(i32),
Bigint(i64),
Numeric(PgNumeric),
Text(String),
Bpchar(PgBpchar<'static>),
Date(PgDate),
Timestamp(PgTimestamp),
TimestampTz(PgTimestampTz),
Time(PgTime),
TimeTz(PgTimeTz),
Jsonb(PgJsonb),
Uuid(PgUuid),
Interval(PgInterval),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
#[non_exhaustive]
pub enum CastError {
#[error("invalid input syntax for type {}", .0.input_name())]
InvalidInputSyntax(PgType),
#[error("value is out of range for type {0}")]
ValueOutOfRange(PgType),
#[error("{0} out of range")]
OutOfRange(PgType),
#[error("cannot convert NaN to {0}")]
CannotConvertNaN(PgType),
#[error("cannot convert infinity to {0}")]
CannotConvertInfinity(PgType),
#[error("numeric field overflow")]
NumericFieldOverflow,
#[error("value overflows numeric format")]
NumericFormatOverflow,
#[error("date/time field value out of range")]
DateTimeFieldOutOfRange,
#[error("date out of range")]
DateOutOfRange,
#[error("timestamp out of range")]
TimestampOutOfRange,
#[error("date out of range for timestamp")]
DateOutOfRangeForTimestamp,
#[error("time zone displacement out of range")]
TimeZoneDisplacementOutOfRange,
#[error("interval field value out of range")]
IntervalFieldValueOutOfRange,
#[error("interval out of range")]
IntervalOutOfRange,
#[error("cannot convert infinite interval to time")]
CannotConvertInfiniteIntervalToTime,
#[error("cannot cast type {from} to {to}")]
CannotCast {
from: PgType,
to: PgType,
},
#[error("cannot cast jsonb {from} to type {to}")]
CannotCastJsonb {
from: JsonbKind,
to: PgType,
},
#[error(transparent)]
Jsonb(JsonbError),
#[error("malformed array literal")]
MalformedArrayLiteral,
#[error("number of array dimensions exceeds the maximum allowed (6)")]
ArrayDimensionsExceeded,
#[error("upper bound cannot be less than lower bound")]
UpperBoundLessThanLower,
#[error("array upper bound is too large: {0}")]
ArrayUpperBoundTooLarge(i32),
#[error("array size exceeds the maximum allowed (134217727)")]
ArraySizeExceeded,
#[error("array bound is out of integer range")]
ArrayBoundOutOfRange,
#[error("cast not modelled")]
Unsupported,
}
pub fn cast_literal(literal: Literal<'_>, target: CastTarget) -> Result<CastValue, CastError> {
match literal {
Literal::Quoted(text) => cast_quoted(text, target),
Literal::Number(text) => cast_non_null(number_constant(text)?, target),
}
}
pub fn number_constant(text: &str) -> Result<CastValue, CastError> {
let unsigned = text.strip_prefix('-').unwrap_or(text);
match scan_number(unsigned.as_bytes()) {
None => Err(CastError::Unsupported),
Some(NumberToken::Integer) => [IntegerType::Integer, IntegerType::Bigint]
.into_iter()
.find_map(|integer| int_input(text, integer).ok())
.map_or_else(|| numeric_input(text).map(CastValue::Numeric), Ok),
Some(NumberToken::Decimal) => numeric_input(text).map(CastValue::Numeric),
}
}
pub fn cast_value(value: CastValue, target: CastTarget) -> Result<Option<CastValue>, CastError> {
match (value, target) {
(CastValue::Jsonb(value), _) => cast_jsonb(value, target),
(CastValue::Timestamp(at), CastTarget::Time(precision)) => Ok(at
.time()
.map(|time| CastValue::Time(time.adjust_for_typmod(precision)))),
(value, _) => cast_non_null(value, target).map(Some),
}
}
fn cast_jsonb(value: PgJsonb, target: CastTarget) -> Result<Option<CastValue>, CastError> {
let to = target.pg_type();
let cannot_cast = |from| CastError::CannotCastJsonb { from, to };
match target {
CastTarget::Boolean => Ok(value
.to_bool()
.map_err(cannot_cast)?
.map(CastValue::Boolean)),
CastTarget::Smallint
| CastTarget::Integer
| CastTarget::Bigint
| CastTarget::Numeric(_) => value
.into_numeric()
.map_err(cannot_cast)?
.map(|number| cast_non_null(CastValue::Numeric(number), target))
.transpose(),
CastTarget::Text | CastTarget::Varchar(_) | CastTarget::Bpchar(_) => {
Ok(Some(character(&value.to_string(), target)))
}
CastTarget::Jsonb => Ok(Some(CastValue::Jsonb(value))),
CastTarget::Date
| CastTarget::Timestamp(_)
| CastTarget::TimestampTz(_)
| CastTarget::Time(_)
| CastTarget::TimeTz(_)
| CastTarget::Uuid
| CastTarget::Interval(_) => Err(CastError::CannotCast {
from: PgType::Jsonb,
to,
}),
}
}
fn cast_non_null(value: CastValue, target: CastTarget) -> Result<CastValue, CastError> {
let cannot_cast = CastError::CannotCast {
from: value.pg_type(),
to: target.pg_type(),
};
match (value, target) {
(CastValue::Text(text), _) => cast_text(&text, target),
(CastValue::Bpchar(value), CastTarget::Text | CastTarget::Varchar(_)) => {
Ok(character(value.as_text(), target))
}
(CastValue::Bpchar(value), _) => cast_text(value.as_str(), target),
(
CastValue::TimestampTz(_),
CastTarget::Date
| CastTarget::Timestamp(_)
| CastTarget::Time(_)
| CastTarget::TimeTz(_)
| CastTarget::Text
| CastTarget::Varchar(_)
| CastTarget::Bpchar(_),
)
| (CastValue::Date(_) | CastValue::Timestamp(_), CastTarget::TimestampTz(_))
| (CastValue::Time(_), CastTarget::TimeTz(_)) => Err(CastError::Unsupported),
(
CastValue::Boolean(value),
CastTarget::Text | CastTarget::Varchar(_) | CastTarget::Bpchar(_),
) => Ok(character(if value { "true" } else { "false" }, target)),
(value, CastTarget::Text | CastTarget::Varchar(_) | CastTarget::Bpchar(_)) => {
Ok(character(&value.to_string(), target))
}
(CastValue::Boolean(value), CastTarget::Boolean) => Ok(CastValue::Boolean(value)),
(CastValue::Boolean(value), CastTarget::Integer) => Ok(CastValue::Integer(value.into())),
(CastValue::Integer(value), CastTarget::Boolean) => Ok(CastValue::Boolean(value != 0)),
(CastValue::Smallint(value), _) if target.takes_integer() => integer(value.into(), target),
(CastValue::Integer(value), _) if target.takes_integer() => integer(value.into(), target),
(CastValue::Bigint(value), _) if target.takes_integer() => integer(value, target),
(CastValue::Numeric(value), CastTarget::Numeric(typmod)) => numeric_typmod(value, typmod),
(CastValue::Numeric(value), _) if target.takes_integer() => {
let to = target.pg_type();
if value.is_nan() {
Err(CastError::CannotConvertNaN(to))
} else if value.is_infinite() {
Err(CastError::CannotConvertInfinity(to))
} else {
let value = value.into_i64_rounded().ok_or(CastError::OutOfRange(to))?;
integer(value, target)
}
}
(CastValue::Date(date), CastTarget::Date) => Ok(CastValue::Date(date)),
(CastValue::Date(date), CastTarget::Timestamp(precision)) => {
let at = date
.to_timestamp()
.map_err(|_| CastError::DateOutOfRangeForTimestamp)?;
Ok(CastValue::Timestamp(at.adjust_for_typmod(precision)))
}
(CastValue::Timestamp(at), CastTarget::Date) => Ok(CastValue::Date(at.date())),
(CastValue::Timestamp(at), CastTarget::Timestamp(precision)) => {
Ok(CastValue::Timestamp(at.adjust_for_typmod(precision)))
}
(CastValue::TimestampTz(at), CastTarget::TimestampTz(precision)) => {
Ok(CastValue::TimestampTz(at.adjust_for_typmod(precision)))
}
(CastValue::Time(time), CastTarget::Time(precision)) => {
Ok(CastValue::Time(time.adjust_for_typmod(precision)))
}
(CastValue::TimeTz(time), CastTarget::Time(precision)) => {
Ok(CastValue::Time(time.time().adjust_for_typmod(precision)))
}
(CastValue::TimeTz(time), CastTarget::TimeTz(precision)) => {
Ok(CastValue::TimeTz(time.adjust_for_typmod(precision)))
}
(CastValue::Uuid(value), CastTarget::Uuid) => Ok(CastValue::Uuid(value)),
(CastValue::Interval(span), CastTarget::Time(precision)) => {
if !span.is_finite() {
return Err(CastError::CannotConvertInfiniteIntervalToTime);
}
let time = PgTime::from_micros(span.microseconds.rem_euclid(USECS_PER_DAY))
.expect("a remainder of a day is a time");
Ok(CastValue::Time(time.adjust_for_typmod(precision)))
}
(CastValue::Interval(span), CastTarget::Interval(typmod)) => {
interval_value(span.adjust_for_typmod(typmod))
}
(CastValue::Time(time), CastTarget::Interval(typmod)) => {
let span = PgInterval {
months: 0,
days: 0,
microseconds: time.micros(),
};
interval_value(span.adjust_for_typmod(typmod))
}
_ => Err(cannot_cast),
}
}
impl CastTarget {
const fn takes_integer(self) -> bool {
matches!(
self,
Self::Smallint | Self::Integer | Self::Bigint | Self::Numeric(_)
)
}
}
impl CastValue {
const fn pg_type(&self) -> PgType {
match self {
Self::Boolean(_) => PgType::Boolean,
Self::Smallint(_) => PgType::Smallint,
Self::Integer(_) => PgType::Integer,
Self::Bigint(_) => PgType::Bigint,
Self::Numeric(_) => PgType::Numeric,
Self::Text(_) => PgType::Text,
Self::Bpchar(_) => PgType::Bpchar,
Self::Date(_) => PgType::Date,
Self::Timestamp(_) => PgType::Timestamp,
Self::TimestampTz(_) => PgType::TimestampTz,
Self::Time(_) => PgType::Time,
Self::TimeTz(_) => PgType::TimeTz,
Self::Jsonb(_) => PgType::Jsonb,
Self::Uuid(_) => PgType::Uuid,
Self::Interval(_) => PgType::Interval,
}
}
}
fn integer(value: i64, target: CastTarget) -> Result<CastValue, CastError> {
if let CastTarget::Numeric(typmod) = target {
return numeric_typmod(PgNumeric::from(value), typmod);
}
IntegerType::try_from(target)
.expect("a target taking an integer is numeric or an integer type")
.value(value)
}
fn numeric_input(text: &str) -> Result<PgNumeric, CastError> {
PgNumeric::parse(text).map_err(numeric_input_error)
}
fn numeric_input_error(error: NumericError) -> CastError {
if error == NumericError::InvalidInputSyntax {
CastError::InvalidInputSyntax(PgType::Numeric)
} else {
CastError::NumericFormatOverflow
}
}
fn jsonb_input_error(error: JsonbError) -> CastError {
match error {
JsonbError::Numeric(error) => numeric_input_error(error),
error => CastError::Jsonb(error),
}
}
fn interval_value(span: Result<PgInterval, IntervalError>) -> Result<CastValue, CastError> {
span.map(CastValue::Interval).map_err(|error| match error {
IntervalError::InvalidSyntax => CastError::InvalidInputSyntax(PgType::Interval),
IntervalError::FieldValueOutOfRange => CastError::IntervalFieldValueOutOfRange,
IntervalError::OutOfRange => CastError::IntervalOutOfRange,
IntervalError::DivisionByZero => unreachable!("no cast divides an interval"),
})
}
enum NumberToken {
Integer,
Decimal,
}
fn scan_number(bytes: &[u8]) -> Option<NumberToken> {
let (radix, digits) = match bytes {
[b'0', b'x' | b'X', digits @ ..] => (16, digits),
[b'0', b'o' | b'O', digits @ ..] => (8, digits),
[b'0', b'b' | b'B', digits @ ..] => (2, digits),
_ => return scan_decimal(bytes),
};
let mut at = 0;
while at < digits.len() {
at += usize::from(digits[at] == b'_');
if !digits
.get(at)
.is_some_and(|&b| char::from(b).is_digit(radix))
{
return None;
}
at += 1;
}
(at > 0).then_some(NumberToken::Integer)
}
fn scan_decimal(bytes: &[u8]) -> Option<NumberToken> {
let integer = scan_decinteger(bytes);
let mut at = integer;
let mut token = NumberToken::Integer;
if bytes.get(at) == Some(&b'.') {
token = NumberToken::Decimal;
at += 1;
let fraction = scan_decinteger(&bytes[at..]);
if integer == 0 && fraction == 0 {
return None;
}
at += fraction;
} else if integer == 0 {
return None;
}
if matches!(bytes.get(at), Some(b'e' | b'E')) {
token = NumberToken::Decimal;
at += 1;
at += usize::from(matches!(bytes.get(at), Some(b'+' | b'-')));
let exponent = scan_decinteger(&bytes[at..]);
if exponent == 0 {
return None;
}
at += exponent;
}
(at == bytes.len()).then_some(token)
}
fn scan_decinteger(bytes: &[u8]) -> usize {
if !bytes.first().is_some_and(u8::is_ascii_digit) {
return 0;
}
let mut at = 1;
loop {
let next = at + usize::from(bytes.get(at) == Some(&b'_'));
if !bytes.get(next).is_some_and(u8::is_ascii_digit) {
return at;
}
at = next + 1;
}
}
fn cast_quoted(text: &str, target: CastTarget) -> Result<CastValue, CastError> {
match target {
CastTarget::Interval(typmod) if !text.contains('\0') => {
interval_value(parse_interval_typmod(text, typmod))
}
_ => cast_text(text, target),
}
}
fn cast_text(text: &str, target: CastTarget) -> Result<CastValue, CastError> {
if text.contains('\0') {
return Err(CastError::Unsupported);
}
match target {
CastTarget::Boolean => bool_in(text).map(CastValue::Boolean),
CastTarget::Smallint => int_input(text, IntegerType::Smallint),
CastTarget::Integer => int_input(text, IntegerType::Integer),
CastTarget::Bigint => int_input(text, IntegerType::Bigint),
CastTarget::Numeric(typmod) => numeric_typmod(numeric_input(text)?, typmod),
CastTarget::Text | CastTarget::Varchar(_) | CastTarget::Bpchar(_) => {
Ok(character(text, target))
}
CastTarget::Date => PgDate::parse(text, InputContext::new())
.map(CastValue::Date)
.map_err(datetime_error),
CastTarget::Timestamp(precision) => PgTimestamp::parse(text, InputContext::new())
.map(|at| CastValue::Timestamp(at.adjust_for_typmod(precision)))
.map_err(datetime_error),
CastTarget::TimestampTz(precision) => PgTimestampTz::parse(text, InputContext::new())
.map(|at| CastValue::TimestampTz(at.adjust_for_typmod(precision)))
.map_err(datetime_error),
CastTarget::Time(precision) => PgTime::parse(text, InputContext::new())
.map(|time| CastValue::Time(time.adjust_for_typmod(precision)))
.map_err(datetime_error),
CastTarget::TimeTz(precision) => PgTimeTz::parse(text, InputContext::new())
.map(|time| CastValue::TimeTz(time.adjust_for_typmod(precision)))
.map_err(datetime_error),
CastTarget::Jsonb => PgJsonb::parse(text)
.map(CastValue::Jsonb)
.map_err(jsonb_input_error),
CastTarget::Uuid => PgUuid::parse(text)
.map(CastValue::Uuid)
.map_err(|UuidError::InvalidInputSyntax| CastError::InvalidInputSyntax(PgType::Uuid)),
CastTarget::Interval(typmod) => {
interval_value(parse_interval(text).and_then(|span| span.adjust_for_typmod(typmod)))
}
}
}
fn numeric_typmod(value: PgNumeric, typmod: Option<NumericTypmod>) -> Result<CastValue, CastError> {
match typmod {
Some(typmod) => value.apply_typmod(typmod),
None => Ok(value),
}
.map(CastValue::Numeric)
}
fn character(text: &str, target: CastTarget) -> CastValue {
match target {
CastTarget::Varchar(Some(length)) => CastValue::Text(clip(text, length).into()),
CastTarget::Bpchar(Some(length)) => {
let clipped = clip(text, length);
let mut padded = String::from(clipped);
let blanks = length.0 - clipped.chars().count();
padded.extend(core::iter::repeat_n(' ', blanks));
CastValue::Bpchar(PgBpchar::new(padded))
}
CastTarget::Bpchar(None) => CastValue::Bpchar(PgBpchar::new(String::from(text))),
_ => CastValue::Text(text.into()),
}
}
fn clip(text: &str, length: CharLength) -> &str {
text.char_indices()
.nth(length.0)
.map_or(text, |(end, _)| &text[..end])
}
pub(crate) const fn is_pg_space(byte: u8) -> bool {
matches!(byte, b' ' | b'\t' | b'\n' | 0x0B | 0x0C | b'\r')
}
pub(crate) fn trim_pg_space(bytes: &[u8]) -> &[u8] {
let start = bytes.iter().take_while(|&&b| is_pg_space(b)).count();
let end = bytes
.iter()
.rposition(|&b| !is_pg_space(b))
.map_or(start, |last| last + 1);
&bytes[start..end.max(start)]
}
fn bool_in(text: &str) -> Result<bool, CastError> {
let word = trim_pg_space(text.as_bytes());
let abbreviates = |full: &[u8]| {
full.get(..word.len())
.is_some_and(|prefix| prefix.eq_ignore_ascii_case(word))
};
let value = match word {
[b't' | b'T', ..] if abbreviates(b"true") => true,
[b'f' | b'F', ..] if abbreviates(b"false") => false,
[b'y' | b'Y', ..] if abbreviates(b"yes") => true,
[b'n' | b'N', ..] if abbreviates(b"no") => false,
[b'o' | b'O', _, ..] if abbreviates(b"on") => true,
[b'o' | b'O', _, ..] if abbreviates(b"off") => false,
b"1" => true,
b"0" => false,
_ => return Err(CastError::InvalidInputSyntax(PgType::Boolean)),
};
Ok(value)
}
enum IntInputError {
Syntax,
Range,
}
fn int_input(text: &str, integer: IntegerType) -> Result<CastValue, CastError> {
let value = int_in(text, integer).map_err(|error| match error {
IntInputError::Syntax => CastError::InvalidInputSyntax(integer.into()),
IntInputError::Range => CastError::ValueOutOfRange(integer.into()),
})?;
Ok(integer
.value(value)
.expect("int_in kept the value in the type's range"))
}
fn int_in(text: &str, integer: IntegerType) -> Result<i64, IntInputError> {
let bytes = text.as_bytes();
let mut at = bytes.iter().take_while(|&&b| is_pg_space(b)).count();
let negative = bytes.get(at) == Some(&b'-');
at += usize::from(matches!(bytes.get(at), Some(b'+' | b'-')));
let radix = match (bytes.get(at), bytes.get(at + 1)) {
(Some(b'0'), Some(b'x' | b'X')) => 16,
(Some(b'0'), Some(b'o' | b'O')) => 8,
(Some(b'0'), Some(b'b' | b'B')) => 2,
_ => 10,
};
if radix != 10 {
at += 2;
}
let first_digit = at;
let is_digit = |byte: Option<&u8>| byte.is_some_and(|&b| char::from(b).is_digit(radix));
let limit = integer.range().start().unsigned_abs();
let mut magnitude: u64 = 0;
loop {
match bytes.get(at) {
Some(&byte) if is_digit(Some(&byte)) => {
if magnitude > limit / u64::from(radix) {
return Err(IntInputError::Range);
}
let digit = char::from(byte).to_digit(radix).expect("checked a digit");
magnitude = magnitude * u64::from(radix) + u64::from(digit);
at += 1;
}
Some(b'_') => {
if radix == 10 && at == first_digit {
return Err(IntInputError::Syntax);
}
at += 1;
if !is_digit(bytes.get(at)) {
return Err(IntInputError::Syntax);
}
}
_ => break,
}
}
if at == first_digit || !bytes[at..].iter().all(|&b| is_pg_space(b)) {
return Err(IntInputError::Syntax);
}
let value = if negative {
-i128::from(magnitude)
} else {
i128::from(magnitude)
};
i64::try_from(value)
.ok()
.filter(|value| integer.range().contains(value))
.ok_or(IntInputError::Range)
}
fn datetime_error(error: DateTimeError) -> CastError {
match error {
DateTimeError::FieldValueOutOfRange => CastError::DateTimeFieldOutOfRange,
DateTimeError::TimeZoneDisplacementOutOfRange => CastError::TimeZoneDisplacementOutOfRange,
DateTimeError::DateOutOfRange => CastError::DateOutOfRange,
DateTimeError::TimestampOutOfRange => CastError::TimestampOutOfRange,
DateTimeError::InvalidInputSyntax(pg_type) => CastError::InvalidInputSyntax(pg_type),
DateTimeError::TimestampCannotBeNaN
| DateTimeError::OutsideJiffRange
| DateTimeError::NeedsTimeZone
| DateTimeError::NeedsDateOrder
| DateTimeError::NeedsCurrentTime
| DateTimeError::TimeZoneNotRecognized => CastError::Unsupported,
}
}
impl fmt::Display for CastValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Boolean(value) => f.write_str(if *value { "t" } else { "f" }),
Self::Smallint(value) => write!(f, "{value}"),
Self::Integer(value) => write!(f, "{value}"),
Self::Bigint(value) => write!(f, "{value}"),
Self::Numeric(value) => write!(f, "{value}"),
Self::Text(text) => f.write_str(text),
Self::Bpchar(value) => write!(f, "{value}"),
Self::Date(date) => write!(f, "{date}"),
Self::Timestamp(at) => write!(f, "{at}"),
Self::TimestampTz(at) => write!(f, "{at}"),
Self::Time(time) => write!(f, "{time}"),
Self::TimeTz(time) => write!(f, "{time}"),
Self::Jsonb(value) => write!(f, "{value}"),
Self::Uuid(value) => write!(f, "{value}"),
Self::Interval(span) => write!(f, "{span}"),
}
}
}