use alloc::string::{String, ToString};
use core::fmt;
use chrono::{DateTime, Datelike, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime, Timelike, Utc};
use crate::{
interval::{ShiftError, chrono_timestamp, pg_microseconds, pg_timestamp, valid_timestamp},
numeric::{NumericTypmod, PgNumeric},
parse_pg_offset, parse_two_digits,
};
#[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>),
}
#[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)]
pub enum PgType {
Boolean,
Smallint,
Integer,
Bigint,
Numeric,
Text,
Varchar,
Bpchar,
Date,
Timestamp,
TimestampTz,
}
impl fmt::Display for PgType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_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",
})
}
}
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,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum CastValue {
Boolean(bool),
Smallint(i16),
Integer(i32),
Bigint(i64),
Numeric(PgNumeric),
Text(String),
Bpchar(String),
Date(NaiveDate),
Timestamp(NaiveDateTime),
TimestampTz(DateTime<Utc>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
pub enum CastError {
#[error("invalid input syntax for type {0}")]
InvalidInputSyntax(PgType),
#[error("value is out of range for type {0}")]
ValueOutOfRange(PgType),
#[error("{0} out of range")]
OutOfRange(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("cannot cast type {from} to {to}")]
CannotCast {
from: PgType,
to: PgType,
},
#[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_constant(Constant::read(text)?, target),
}
}
enum Constant {
Integer(i32),
Bigint(i64),
Numeric(PgNumeric),
}
impl Constant {
fn read(text: &str) -> Result<Self, CastError> {
let unsigned = text.strip_prefix('-').unwrap_or(text);
match scan_number(unsigned.as_bytes()) {
None => Err(CastError::Unsupported),
Some(NumberToken::Integer) => {
if let Ok(value) = int_in(text, 32) {
Ok(Self::Integer(narrow(value)))
} else if let Ok(value) = int_in(text, 64) {
Ok(Self::Bigint(value))
} else {
PgNumeric::parse(text).map(Self::Numeric)
}
}
Some(NumberToken::Decimal) => PgNumeric::parse(text).map(Self::Numeric),
}
}
const fn pg_type(&self) -> PgType {
match self {
Self::Integer(_) => PgType::Integer,
Self::Bigint(_) => PgType::Bigint,
Self::Numeric(_) => PgType::Numeric,
}
}
fn into_i64(self) -> Option<i64> {
match self {
Self::Integer(value) => Some(i64::from(value)),
Self::Bigint(value) => Some(value),
Self::Numeric(value) => value.into_i64_rounded(),
}
}
}
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_constant(constant: Constant, target: CastTarget) -> Result<CastValue, CastError> {
let from = constant.pg_type();
match target {
CastTarget::Boolean => match constant {
Constant::Integer(value) => Ok(CastValue::Boolean(value != 0)),
_ => Err(CastError::CannotCast {
from,
to: PgType::Boolean,
}),
},
CastTarget::Smallint => {
let value = constant.into_i64().and_then(|v| i16::try_from(v).ok());
value
.map(CastValue::Smallint)
.ok_or(CastError::OutOfRange(PgType::Smallint))
}
CastTarget::Integer => {
let value = constant.into_i64().and_then(|v| i32::try_from(v).ok());
value
.map(CastValue::Integer)
.ok_or(CastError::OutOfRange(PgType::Integer))
}
CastTarget::Bigint => constant
.into_i64()
.map(CastValue::Bigint)
.ok_or(CastError::OutOfRange(PgType::Bigint)),
CastTarget::Numeric(typmod) => {
let value = match constant {
Constant::Integer(value) => PgNumeric::from_i64(i64::from(value)),
Constant::Bigint(value) => PgNumeric::from_i64(value),
Constant::Numeric(value) => value,
};
numeric_typmod(value, typmod)
}
CastTarget::Text | CastTarget::Varchar(_) | CastTarget::Bpchar(_) => {
let text = match constant {
Constant::Integer(value) => value.to_string(),
Constant::Bigint(value) => value.to_string(),
Constant::Numeric(value) => value.to_string(),
};
Ok(character(&text, target))
}
CastTarget::Date | CastTarget::Timestamp(_) | CastTarget::TimestampTz(_) => {
Err(CastError::CannotCast {
from,
to: target.pg_type(),
})
}
}
}
fn cast_quoted(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, 16, PgType::Smallint).map(|v| {
CastValue::Smallint(i16::try_from(v).expect("int_in kept the value in 16 bits"))
}),
CastTarget::Integer => {
int_input(text, 32, PgType::Integer).map(|v| CastValue::Integer(narrow(v)))
}
CastTarget::Bigint => int_input(text, 64, PgType::Bigint).map(CastValue::Bigint),
CastTarget::Numeric(typmod) => numeric_typmod(PgNumeric::parse(text)?, typmod),
CastTarget::Text | CastTarget::Varchar(_) | CastTarget::Bpchar(_) => {
Ok(character(text, target))
}
CastTarget::Date => {
let literal = read_datetime(text)?;
if (literal.year, literal.month, literal.day) < (-4713, 11, 24) {
return Err(CastError::DateOutOfRange);
}
literal.date().map(CastValue::Date)
}
CastTarget::Timestamp(precision) => {
let literal = read_datetime(text)?;
if !literal.julian() {
return Err(CastError::TimestampOutOfRange);
}
let local = literal.date()?.and_time(literal.time);
let micros = pg_timestamp(local).map_err(shift_error)?;
let micros = round_timestamp(micros, precision);
chrono_timestamp(micros)
.map(CastValue::Timestamp)
.map_err(shift_error)
}
CastTarget::TimestampTz(precision) => {
let literal = read_datetime(text)?;
let offset = literal.offset.ok_or(CastError::Unsupported)?;
if !literal.julian() {
return Err(CastError::TimestampOutOfRange);
}
let local = pg_microseconds(literal.date()?.and_time(literal.time));
let utc = local - i64::from(offset.local_minus_utc()) * 1_000_000;
let micros = valid_timestamp(utc).map_err(shift_error)?;
let micros = round_timestamp(micros, precision);
chrono_timestamp(micros)
.map(|at| CastValue::TimestampTz(at.and_utc()))
.map_err(shift_error)
}
}
}
fn narrow(value: i64) -> i32 {
i32::try_from(value).expect("int_in kept the value in 32 bits")
}
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(padded)
}
CastTarget::Bpchar(None) => CastValue::Bpchar(text.into()),
_ => 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')
}
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, bits: u32, pg_type: PgType) -> Result<i64, CastError> {
int_in(text, bits).map_err(|error| match error {
IntInputError::Syntax => CastError::InvalidInputSyntax(pg_type),
IntInputError::Range => CastError::ValueOutOfRange(pg_type),
})
}
fn int_in(text: &str, bits: u32) -> 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: u64 = 1 << (bits - 1);
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)
};
let range = -i128::from(limit)..i128::from(limit);
if range.contains(&value) {
Ok(i64::try_from(value).expect("a value within 64 bits fits i64"))
} else {
Err(IntInputError::Range)
}
}
struct DateTimeLiteral {
year: i32,
month: u8,
day: u8,
time: NaiveTime,
offset: Option<FixedOffset>,
}
impl DateTimeLiteral {
fn julian(&self) -> bool {
(self.year, self.month) >= (-4713, 11)
}
fn date(&self) -> Result<NaiveDate, CastError> {
NaiveDate::from_ymd_opt(self.year, self.month.into(), self.day.into())
.ok_or(CastError::Unsupported)
}
}
fn read_datetime(text: &str) -> Result<DateTimeLiteral, CastError> {
let unsupported = CastError::Unsupported;
let trimmed = trim_pg_space(text.as_bytes());
let (body, bc) = match trimmed.strip_suffix(b" BC") {
Some(body) => (body, true),
None => (trimmed, false),
};
let year_len = body.iter().take_while(|b| b.is_ascii_digit()).count();
if !(4..=9).contains(&year_len) || (year_len > 4 && body[0] == b'0') {
return Err(unsupported);
}
let (year_digits, rest) = body.split_at(year_len);
let year = year_digits
.iter()
.fold(0i32, |year, &digit| year * 10 + i32::from(digit - b'0'));
let Some((&[b'-', m1, m2, b'-', d1, d2], rest)) = rest.split_first_chunk() else {
return Err(unsupported);
};
let month = parse_two_digits(&[m1, m2]).ok_or(unsupported)?;
let day = parse_two_digits(&[d1, d2]).ok_or(unsupported)?;
let (time, offset) = match rest.split_first() {
None => (NaiveTime::MIN, None),
Some((b' ' | b'T', clock)) => read_clock(clock).ok_or(unsupported)?,
Some(_) => return Err(unsupported),
};
if year == 0 || !(1..=12).contains(&month) {
return Err(CastError::DateTimeFieldOutOfRange);
}
let year = if bc { 1 - year } else { year };
let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
let month_days = match month {
2 if leap => 29,
2 => 28,
4 | 6 | 9 | 11 => 30,
_ => 31,
};
if !(1..=month_days).contains(&day) {
return Err(CastError::DateTimeFieldOutOfRange);
}
Ok(DateTimeLiteral {
year,
month,
day,
time,
offset,
})
}
fn read_clock(bytes: &[u8]) -> Option<(NaiveTime, Option<FixedOffset>)> {
let (&[h1, h2, b':', m1, m2], mut rest) = bytes.split_first_chunk()? else {
return None;
};
let mut second = 0;
let mut micros = 0;
if let Some((&[b':', s1, s2], after)) = rest.split_first_chunk() {
second = parse_two_digits(&[s1, s2])?;
rest = after;
if let Some((b'.', fraction)) = rest.split_first() {
let len = fraction.iter().take_while(|b| b.is_ascii_digit()).count();
if !(1..=6).contains(&len) {
return None;
}
let (digits, after) = fraction.split_at(len);
micros = digits
.iter()
.chain(core::iter::repeat_n(&b'0', 6 - len))
.fold(0u32, |micros, &digit| micros * 10 + u32::from(digit - b'0'));
rest = after;
}
}
let offset = match rest {
[] => None,
_ => Some(parse_pg_offset(rest).filter(|o| o.local_minus_utc().abs() < 16 * 3600)?),
};
let time = NaiveTime::from_hms_micro_opt(
parse_two_digits(&[h1, h2])?.into(),
parse_two_digits(&[m1, m2])?.into(),
second.into(),
micros,
)?;
Some((time, offset))
}
fn round_timestamp(micros: i64, precision: Option<u8>) -> i64 {
let Some(precision @ 0..6) = precision else {
return micros;
};
let scale = 10i64.pow(6 - u32::from(precision));
let offset = scale / 2;
if micros >= 0 {
(micros + offset) / scale * scale
} else {
-((-micros + offset) / scale * scale)
}
}
fn shift_error(error: ShiftError) -> CastError {
match error {
ShiftError::TimestampOutOfRange => CastError::TimestampOutOfRange,
_ => CastError::Unsupported,
}
}
fn write_date(f: &mut fmt::Formatter<'_>, date: NaiveDate) -> fmt::Result {
let year = date.year();
let shown = if year > 0 { year } else { 1 - year };
write!(f, "{shown:04}-{:02}-{:02}", date.month(), date.day())
}
fn write_timestamp(f: &mut fmt::Formatter<'_>, at: NaiveDateTime, zone: bool) -> fmt::Result {
write_date(f, at.date())?;
let time = at.time();
write!(
f,
" {:02}:{:02}:{:02}",
time.hour(),
time.minute(),
time.second()
)?;
let mut micros = time.nanosecond() / 1_000;
if micros > 0 {
let mut width = 6;
while micros.is_multiple_of(10) {
micros /= 10;
width -= 1;
}
write!(f, ".{micros:0width$}")?;
}
if zone {
f.write_str("+00")?;
}
if at.year() <= 0 {
f.write_str(" BC")?;
}
Ok(())
}
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) | Self::Bpchar(text) => f.write_str(text),
Self::Date(date) => {
write_date(f, *date)?;
if date.year() <= 0 {
f.write_str(" BC")?;
}
Ok(())
}
Self::Timestamp(at) => write_timestamp(f, *at, false),
Self::TimestampTz(at) => write_timestamp(f, at.naive_utc(), true),
}
}
}