1use alloc::string::{String, ToString};
5use core::fmt;
6
7use crate::{
8 datetime::{DateTimeError, InputContext, PgDate, PgTimestamp, PgTimestampTz},
9 numeric::{NumericTypmod, PgNumeric},
10};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14pub enum Literal<'a> {
15 Quoted(&'a str),
18 Number(&'a str),
22}
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
26pub enum CastTarget {
27 Boolean,
29 Smallint,
31 Integer,
33 Bigint,
35 Numeric(Option<NumericTypmod>),
37 Text,
39 Varchar(Option<CharLength>),
41 Bpchar(Option<CharLength>),
43 Date,
45 Timestamp(Option<u8>),
47 TimestampTz(Option<u8>),
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
53pub struct CharLength(usize);
54
55const MAX_CHAR_LENGTH: usize = 10_485_760;
57
58impl CharLength {
59 #[must_use]
69 pub fn new(length: usize) -> Option<Self> {
70 (1..=MAX_CHAR_LENGTH)
71 .contains(&length)
72 .then_some(Self(length))
73 }
74}
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
87#[non_exhaustive]
88pub enum PgType {
89 Boolean,
91 Smallint,
93 Integer,
95 Bigint,
97 Numeric,
99 Text,
101 Varchar,
103 Bpchar,
105 Date,
107 Timestamp,
109 TimestampTz,
111 Time,
113 TimeTz,
115}
116
117impl fmt::Display for PgType {
118 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119 f.write_str(self.name())
120 }
121}
122
123impl PgType {
124 const fn name(self) -> &'static str {
126 match self {
127 Self::Boolean => "boolean",
128 Self::Smallint => "smallint",
129 Self::Integer => "integer",
130 Self::Bigint => "bigint",
131 Self::Numeric => "numeric",
132 Self::Text => "text",
133 Self::Varchar => "character varying",
134 Self::Bpchar => "character",
135 Self::Date => "date",
136 Self::Timestamp => "timestamp without time zone",
137 Self::TimestampTz => "timestamp with time zone",
138 Self::Time => "time without time zone",
139 Self::TimeTz => "time with time zone",
140 }
141 }
142
143 pub(crate) const fn input_name(self) -> &'static str {
146 match self {
147 Self::Timestamp => "timestamp",
148 Self::Time => "time",
149 other => other.name(),
150 }
151 }
152}
153
154impl CastTarget {
155 #[must_use]
157 pub const fn pg_type(self) -> PgType {
158 match self {
159 Self::Boolean => PgType::Boolean,
160 Self::Smallint => PgType::Smallint,
161 Self::Integer => PgType::Integer,
162 Self::Bigint => PgType::Bigint,
163 Self::Numeric(_) => PgType::Numeric,
164 Self::Text => PgType::Text,
165 Self::Varchar(_) => PgType::Varchar,
166 Self::Bpchar(_) => PgType::Bpchar,
167 Self::Date => PgType::Date,
168 Self::Timestamp(_) => PgType::Timestamp,
169 Self::TimestampTz(_) => PgType::TimestampTz,
170 }
171 }
172}
173
174#[derive(Debug, Clone, PartialEq, Eq, Hash)]
177pub enum CastValue {
178 Boolean(bool),
180 Smallint(i16),
182 Integer(i32),
184 Bigint(i64),
186 Numeric(PgNumeric),
188 Text(String),
190 Bpchar(String),
193 Date(PgDate),
195 Timestamp(PgTimestamp),
197 TimestampTz(PgTimestampTz),
199}
200
201#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
204#[non_exhaustive]
205pub enum CastError {
206 #[error("invalid input syntax for type {}", .0.input_name())]
208 InvalidInputSyntax(PgType),
209 #[error("value is out of range for type {0}")]
211 ValueOutOfRange(PgType),
212 #[error("{0} out of range")]
214 OutOfRange(PgType),
215 #[error("numeric field overflow")]
218 NumericFieldOverflow,
219 #[error("value overflows numeric format")]
221 NumericFormatOverflow,
222 #[error("date/time field value out of range")]
224 DateTimeFieldOutOfRange,
225 #[error("date out of range")]
227 DateOutOfRange,
228 #[error("timestamp out of range")]
230 TimestampOutOfRange,
231 #[error("time zone displacement out of range")]
233 TimeZoneDisplacementOutOfRange,
234 #[error("cannot cast type {from} to {to}")]
236 CannotCast {
237 from: PgType,
239 to: PgType,
241 },
242 #[error("cast not modelled")]
246 Unsupported,
247}
248
249pub fn cast_literal(literal: Literal<'_>, target: CastTarget) -> Result<CastValue, CastError> {
309 match literal {
310 Literal::Quoted(text) => cast_quoted(text, target),
311 Literal::Number(text) => cast_constant(Constant::read(text)?, target),
312 }
313}
314
315enum Constant {
317 Integer(i32),
318 Bigint(i64),
319 Numeric(PgNumeric),
320}
321
322impl Constant {
323 fn read(text: &str) -> Result<Self, CastError> {
325 let unsigned = text.strip_prefix('-').unwrap_or(text);
326 match scan_number(unsigned.as_bytes()) {
327 None => Err(CastError::Unsupported),
328 Some(NumberToken::Integer) => {
329 if let Ok(value) = int_in(text, 32) {
330 Ok(Self::Integer(narrow(value)))
331 } else if let Ok(value) = int_in(text, 64) {
332 Ok(Self::Bigint(value))
333 } else {
334 PgNumeric::parse(text).map(Self::Numeric)
335 }
336 }
337 Some(NumberToken::Decimal) => PgNumeric::parse(text).map(Self::Numeric),
338 }
339 }
340
341 const fn pg_type(&self) -> PgType {
342 match self {
343 Self::Integer(_) => PgType::Integer,
344 Self::Bigint(_) => PgType::Bigint,
345 Self::Numeric(_) => PgType::Numeric,
346 }
347 }
348
349 fn into_i64(self) -> Option<i64> {
351 match self {
352 Self::Integer(value) => Some(i64::from(value)),
353 Self::Bigint(value) => Some(value),
354 Self::Numeric(value) => value.into_i64_rounded(),
355 }
356 }
357}
358
359enum NumberToken {
361 Integer,
363 Decimal,
365}
366
367fn scan_number(bytes: &[u8]) -> Option<NumberToken> {
370 let (radix, digits) = match bytes {
371 [b'0', b'x' | b'X', digits @ ..] => (16, digits),
372 [b'0', b'o' | b'O', digits @ ..] => (8, digits),
373 [b'0', b'b' | b'B', digits @ ..] => (2, digits),
374 _ => return scan_decimal(bytes),
375 };
376 let mut at = 0;
378 while at < digits.len() {
379 at += usize::from(digits[at] == b'_');
380 if !digits
381 .get(at)
382 .is_some_and(|&b| char::from(b).is_digit(radix))
383 {
384 return None;
385 }
386 at += 1;
387 }
388 (at > 0).then_some(NumberToken::Integer)
389}
390
391fn scan_decimal(bytes: &[u8]) -> Option<NumberToken> {
393 let integer = scan_decinteger(bytes);
394 let mut at = integer;
395 let mut token = NumberToken::Integer;
396 if bytes.get(at) == Some(&b'.') {
397 token = NumberToken::Decimal;
398 at += 1;
399 let fraction = scan_decinteger(&bytes[at..]);
400 if integer == 0 && fraction == 0 {
401 return None;
402 }
403 at += fraction;
404 } else if integer == 0 {
405 return None;
406 }
407 if matches!(bytes.get(at), Some(b'e' | b'E')) {
408 token = NumberToken::Decimal;
409 at += 1;
410 at += usize::from(matches!(bytes.get(at), Some(b'+' | b'-')));
411 let exponent = scan_decinteger(&bytes[at..]);
412 if exponent == 0 {
413 return None;
414 }
415 at += exponent;
416 }
417 (at == bytes.len()).then_some(token)
418}
419
420fn scan_decinteger(bytes: &[u8]) -> usize {
422 if !bytes.first().is_some_and(u8::is_ascii_digit) {
423 return 0;
424 }
425 let mut at = 1;
426 loop {
427 let next = at + usize::from(bytes.get(at) == Some(&b'_'));
428 if !bytes.get(next).is_some_and(u8::is_ascii_digit) {
429 return at;
430 }
431 at = next + 1;
432 }
433}
434
435fn cast_constant(constant: Constant, target: CastTarget) -> Result<CastValue, CastError> {
438 let from = constant.pg_type();
439 match target {
440 CastTarget::Boolean => match constant {
441 Constant::Integer(value) => Ok(CastValue::Boolean(value != 0)),
442 _ => Err(CastError::CannotCast {
443 from,
444 to: PgType::Boolean,
445 }),
446 },
447 CastTarget::Smallint => {
448 let value = constant.into_i64().and_then(|v| i16::try_from(v).ok());
449 value
450 .map(CastValue::Smallint)
451 .ok_or(CastError::OutOfRange(PgType::Smallint))
452 }
453 CastTarget::Integer => {
454 let value = constant.into_i64().and_then(|v| i32::try_from(v).ok());
455 value
456 .map(CastValue::Integer)
457 .ok_or(CastError::OutOfRange(PgType::Integer))
458 }
459 CastTarget::Bigint => constant
460 .into_i64()
461 .map(CastValue::Bigint)
462 .ok_or(CastError::OutOfRange(PgType::Bigint)),
463 CastTarget::Numeric(typmod) => {
464 let value = match constant {
465 Constant::Integer(value) => PgNumeric::from_i64(i64::from(value)),
466 Constant::Bigint(value) => PgNumeric::from_i64(value),
467 Constant::Numeric(value) => value,
468 };
469 numeric_typmod(value, typmod)
470 }
471 CastTarget::Text | CastTarget::Varchar(_) | CastTarget::Bpchar(_) => {
472 let text = match constant {
473 Constant::Integer(value) => value.to_string(),
474 Constant::Bigint(value) => value.to_string(),
475 Constant::Numeric(value) => value.to_string(),
476 };
477 Ok(character(&text, target))
478 }
479 CastTarget::Date | CastTarget::Timestamp(_) | CastTarget::TimestampTz(_) => {
480 Err(CastError::CannotCast {
481 from,
482 to: target.pg_type(),
483 })
484 }
485 }
486}
487
488fn cast_quoted(text: &str, target: CastTarget) -> Result<CastValue, CastError> {
491 if text.contains('\0') {
493 return Err(CastError::Unsupported);
494 }
495 match target {
496 CastTarget::Boolean => bool_in(text).map(CastValue::Boolean),
497 CastTarget::Smallint => int_input(text, 16, PgType::Smallint).map(|v| {
498 CastValue::Smallint(i16::try_from(v).expect("int_in kept the value in 16 bits"))
499 }),
500 CastTarget::Integer => {
501 int_input(text, 32, PgType::Integer).map(|v| CastValue::Integer(narrow(v)))
502 }
503 CastTarget::Bigint => int_input(text, 64, PgType::Bigint).map(CastValue::Bigint),
504 CastTarget::Numeric(typmod) => numeric_typmod(PgNumeric::parse(text)?, typmod),
505 CastTarget::Text | CastTarget::Varchar(_) | CastTarget::Bpchar(_) => {
506 Ok(character(text, target))
507 }
508 CastTarget::Date => PgDate::parse(text, InputContext::new())
509 .map(CastValue::Date)
510 .map_err(datetime_error),
511 CastTarget::Timestamp(precision) => {
512 let at = PgTimestamp::parse(text, InputContext::new()).map_err(datetime_error)?;
513 let micros = adjust_timestamp_for_typmod(at.pg_micros(), precision);
514 Ok(CastValue::Timestamp(PgTimestamp::from_stored(micros)))
515 }
516 CastTarget::TimestampTz(precision) => {
517 let at = PgTimestampTz::parse(text, InputContext::new()).map_err(datetime_error)?;
518 let micros = adjust_timestamp_for_typmod(at.pg_micros(), precision);
519 Ok(CastValue::TimestampTz(PgTimestampTz::from_stored(micros)))
520 }
521 }
522}
523
524fn narrow(value: i64) -> i32 {
526 i32::try_from(value).expect("int_in kept the value in 32 bits")
527}
528
529fn numeric_typmod(value: PgNumeric, typmod: Option<NumericTypmod>) -> Result<CastValue, CastError> {
530 match typmod {
531 Some(typmod) => value.apply_typmod(typmod),
532 None => Ok(value),
533 }
534 .map(CastValue::Numeric)
535}
536
537fn character(text: &str, target: CastTarget) -> CastValue {
540 match target {
541 CastTarget::Varchar(Some(length)) => CastValue::Text(clip(text, length).into()),
542 CastTarget::Bpchar(Some(length)) => {
543 let clipped = clip(text, length);
544 let mut padded = String::from(clipped);
545 let blanks = length.0 - clipped.chars().count();
546 padded.extend(core::iter::repeat_n(' ', blanks));
547 CastValue::Bpchar(padded)
548 }
549 CastTarget::Bpchar(None) => CastValue::Bpchar(text.into()),
550 _ => CastValue::Text(text.into()),
551 }
552}
553
554fn clip(text: &str, length: CharLength) -> &str {
556 text.char_indices()
557 .nth(length.0)
558 .map_or(text, |(end, _)| &text[..end])
559}
560
561pub(crate) const fn is_pg_space(byte: u8) -> bool {
563 matches!(byte, b' ' | b'\t' | b'\n' | 0x0B | 0x0C | b'\r')
564}
565
566pub(crate) fn trim_pg_space(bytes: &[u8]) -> &[u8] {
567 let start = bytes.iter().take_while(|&&b| is_pg_space(b)).count();
568 let end = bytes
569 .iter()
570 .rposition(|&b| !is_pg_space(b))
571 .map_or(start, |last| last + 1);
572 &bytes[start..end.max(start)]
573}
574
575fn bool_in(text: &str) -> Result<bool, CastError> {
578 let word = trim_pg_space(text.as_bytes());
579 let abbreviates = |full: &[u8]| {
580 full.get(..word.len())
581 .is_some_and(|prefix| prefix.eq_ignore_ascii_case(word))
582 };
583 let value = match word {
584 [b't' | b'T', ..] if abbreviates(b"true") => true,
585 [b'f' | b'F', ..] if abbreviates(b"false") => false,
586 [b'y' | b'Y', ..] if abbreviates(b"yes") => true,
587 [b'n' | b'N', ..] if abbreviates(b"no") => false,
588 [b'o' | b'O', _, ..] if abbreviates(b"on") => true,
589 [b'o' | b'O', _, ..] if abbreviates(b"off") => false,
590 b"1" => true,
591 b"0" => false,
592 _ => return Err(CastError::InvalidInputSyntax(PgType::Boolean)),
593 };
594 Ok(value)
595}
596
597enum IntInputError {
599 Syntax,
600 Range,
601}
602
603fn int_input(text: &str, bits: u32, pg_type: PgType) -> Result<i64, CastError> {
605 int_in(text, bits).map_err(|error| match error {
606 IntInputError::Syntax => CastError::InvalidInputSyntax(pg_type),
607 IntInputError::Range => CastError::ValueOutOfRange(pg_type),
608 })
609}
610
611fn int_in(text: &str, bits: u32) -> Result<i64, IntInputError> {
615 let bytes = text.as_bytes();
616 let mut at = bytes.iter().take_while(|&&b| is_pg_space(b)).count();
617 let negative = bytes.get(at) == Some(&b'-');
618 at += usize::from(matches!(bytes.get(at), Some(b'+' | b'-')));
619 let radix = match (bytes.get(at), bytes.get(at + 1)) {
620 (Some(b'0'), Some(b'x' | b'X')) => 16,
621 (Some(b'0'), Some(b'o' | b'O')) => 8,
622 (Some(b'0'), Some(b'b' | b'B')) => 2,
623 _ => 10,
624 };
625 if radix != 10 {
626 at += 2;
627 }
628 let first_digit = at;
629 let is_digit = |byte: Option<&u8>| byte.is_some_and(|&b| char::from(b).is_digit(radix));
630 let limit: u64 = 1 << (bits - 1);
632 let mut magnitude: u64 = 0;
633 loop {
634 match bytes.get(at) {
635 Some(&byte) if is_digit(Some(&byte)) => {
636 if magnitude > limit / u64::from(radix) {
637 return Err(IntInputError::Range);
638 }
639 let digit = char::from(byte).to_digit(radix).expect("checked a digit");
640 magnitude = magnitude * u64::from(radix) + u64::from(digit);
641 at += 1;
642 }
643 Some(b'_') => {
644 if radix == 10 && at == first_digit {
645 return Err(IntInputError::Syntax);
646 }
647 at += 1;
648 if !is_digit(bytes.get(at)) {
649 return Err(IntInputError::Syntax);
650 }
651 }
652 _ => break,
653 }
654 }
655 if at == first_digit || !bytes[at..].iter().all(|&b| is_pg_space(b)) {
656 return Err(IntInputError::Syntax);
657 }
658 let value = if negative {
659 -i128::from(magnitude)
660 } else {
661 i128::from(magnitude)
662 };
663 let range = -i128::from(limit)..i128::from(limit);
664 if range.contains(&value) {
665 Ok(i64::try_from(value).expect("a value within 64 bits fits i64"))
666 } else {
667 Err(IntInputError::Range)
668 }
669}
670
671fn adjust_timestamp_for_typmod(micros: i64, precision: Option<u8>) -> i64 {
675 let Some(precision @ 0..6) = precision else {
676 return micros;
677 };
678 if micros == i64::MAX || micros == i64::MIN {
679 return micros;
680 }
681 let scale = 10i64.pow(6 - u32::from(precision));
682 let offset = scale / 2;
683 if micros >= 0 {
684 (micros + offset) / scale * scale
685 } else {
686 -((-micros + offset) / scale * scale)
687 }
688}
689
690fn datetime_error(error: DateTimeError) -> CastError {
692 match error {
693 DateTimeError::FieldValueOutOfRange => CastError::DateTimeFieldOutOfRange,
694 DateTimeError::TimeZoneDisplacementOutOfRange => CastError::TimeZoneDisplacementOutOfRange,
695 DateTimeError::DateOutOfRange => CastError::DateOutOfRange,
696 DateTimeError::TimestampOutOfRange => CastError::TimestampOutOfRange,
697 DateTimeError::InvalidInputSyntax(pg_type) => CastError::InvalidInputSyntax(pg_type),
698 DateTimeError::OutsideJiffRange
699 | DateTimeError::NeedsTimeZone
700 | DateTimeError::NeedsDateOrder
701 | DateTimeError::NeedsCurrentTime
702 | DateTimeError::TimeZoneNotRecognized => CastError::Unsupported,
703 }
704}
705
706impl fmt::Display for CastValue {
708 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
709 match self {
710 Self::Boolean(value) => f.write_str(if *value { "t" } else { "f" }),
711 Self::Smallint(value) => write!(f, "{value}"),
712 Self::Integer(value) => write!(f, "{value}"),
713 Self::Bigint(value) => write!(f, "{value}"),
714 Self::Numeric(value) => write!(f, "{value}"),
715 Self::Text(text) | Self::Bpchar(text) => f.write_str(text),
716 Self::Date(date) => write!(f, "{date}"),
717 Self::Timestamp(at) => write!(f, "{at}"),
718 Self::TimestampTz(at) => write!(f, "{at}"),
719 }
720 }
721}