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)]
78pub enum PgType {
79 Boolean,
81 Smallint,
83 Integer,
85 Bigint,
87 Numeric,
89 Text,
91 Varchar,
93 Bpchar,
95 Date,
97 Timestamp,
99 TimestampTz,
101}
102
103impl fmt::Display for PgType {
104 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105 f.write_str(match self {
106 Self::Boolean => "boolean",
107 Self::Smallint => "smallint",
108 Self::Integer => "integer",
109 Self::Bigint => "bigint",
110 Self::Numeric => "numeric",
111 Self::Text => "text",
112 Self::Varchar => "character varying",
113 Self::Bpchar => "character",
114 Self::Date => "date",
115 Self::Timestamp => "timestamp without time zone",
116 Self::TimestampTz => "timestamp with time zone",
117 })
118 }
119}
120
121impl CastTarget {
122 #[must_use]
124 pub const fn pg_type(self) -> PgType {
125 match self {
126 Self::Boolean => PgType::Boolean,
127 Self::Smallint => PgType::Smallint,
128 Self::Integer => PgType::Integer,
129 Self::Bigint => PgType::Bigint,
130 Self::Numeric(_) => PgType::Numeric,
131 Self::Text => PgType::Text,
132 Self::Varchar(_) => PgType::Varchar,
133 Self::Bpchar(_) => PgType::Bpchar,
134 Self::Date => PgType::Date,
135 Self::Timestamp(_) => PgType::Timestamp,
136 Self::TimestampTz(_) => PgType::TimestampTz,
137 }
138 }
139}
140
141#[derive(Debug, Clone, PartialEq, Eq, Hash)]
144pub enum CastValue {
145 Boolean(bool),
147 Smallint(i16),
149 Integer(i32),
151 Bigint(i64),
153 Numeric(PgNumeric),
155 Text(String),
157 Bpchar(String),
160 Date(PgDate),
162 Timestamp(PgTimestamp),
164 TimestampTz(PgTimestampTz),
166}
167
168#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
171pub enum CastError {
172 #[error("invalid input syntax for type {0}")]
174 InvalidInputSyntax(PgType),
175 #[error("value is out of range for type {0}")]
177 ValueOutOfRange(PgType),
178 #[error("{0} out of range")]
180 OutOfRange(PgType),
181 #[error("numeric field overflow")]
184 NumericFieldOverflow,
185 #[error("value overflows numeric format")]
187 NumericFormatOverflow,
188 #[error("date/time field value out of range")]
190 DateTimeFieldOutOfRange,
191 #[error("date out of range")]
193 DateOutOfRange,
194 #[error("timestamp out of range")]
196 TimestampOutOfRange,
197 #[error("time zone displacement out of range")]
199 TimeZoneDisplacementOutOfRange,
200 #[error("cannot cast type {from} to {to}")]
202 CannotCast {
203 from: PgType,
205 to: PgType,
207 },
208 #[error("cast not modelled")]
212 Unsupported,
213}
214
215pub fn cast_literal(literal: Literal<'_>, target: CastTarget) -> Result<CastValue, CastError> {
275 match literal {
276 Literal::Quoted(text) => cast_quoted(text, target),
277 Literal::Number(text) => cast_constant(Constant::read(text)?, target),
278 }
279}
280
281enum Constant {
283 Integer(i32),
284 Bigint(i64),
285 Numeric(PgNumeric),
286}
287
288impl Constant {
289 fn read(text: &str) -> Result<Self, CastError> {
291 let unsigned = text.strip_prefix('-').unwrap_or(text);
292 match scan_number(unsigned.as_bytes()) {
293 None => Err(CastError::Unsupported),
294 Some(NumberToken::Integer) => {
295 if let Ok(value) = int_in(text, 32) {
296 Ok(Self::Integer(narrow(value)))
297 } else if let Ok(value) = int_in(text, 64) {
298 Ok(Self::Bigint(value))
299 } else {
300 PgNumeric::parse(text).map(Self::Numeric)
301 }
302 }
303 Some(NumberToken::Decimal) => PgNumeric::parse(text).map(Self::Numeric),
304 }
305 }
306
307 const fn pg_type(&self) -> PgType {
308 match self {
309 Self::Integer(_) => PgType::Integer,
310 Self::Bigint(_) => PgType::Bigint,
311 Self::Numeric(_) => PgType::Numeric,
312 }
313 }
314
315 fn into_i64(self) -> Option<i64> {
317 match self {
318 Self::Integer(value) => Some(i64::from(value)),
319 Self::Bigint(value) => Some(value),
320 Self::Numeric(value) => value.into_i64_rounded(),
321 }
322 }
323}
324
325enum NumberToken {
327 Integer,
329 Decimal,
331}
332
333fn scan_number(bytes: &[u8]) -> Option<NumberToken> {
336 let (radix, digits) = match bytes {
337 [b'0', b'x' | b'X', digits @ ..] => (16, digits),
338 [b'0', b'o' | b'O', digits @ ..] => (8, digits),
339 [b'0', b'b' | b'B', digits @ ..] => (2, digits),
340 _ => return scan_decimal(bytes),
341 };
342 let mut at = 0;
344 while at < digits.len() {
345 at += usize::from(digits[at] == b'_');
346 if !digits
347 .get(at)
348 .is_some_and(|&b| char::from(b).is_digit(radix))
349 {
350 return None;
351 }
352 at += 1;
353 }
354 (at > 0).then_some(NumberToken::Integer)
355}
356
357fn scan_decimal(bytes: &[u8]) -> Option<NumberToken> {
359 let integer = scan_decinteger(bytes);
360 let mut at = integer;
361 let mut token = NumberToken::Integer;
362 if bytes.get(at) == Some(&b'.') {
363 token = NumberToken::Decimal;
364 at += 1;
365 let fraction = scan_decinteger(&bytes[at..]);
366 if integer == 0 && fraction == 0 {
367 return None;
368 }
369 at += fraction;
370 } else if integer == 0 {
371 return None;
372 }
373 if matches!(bytes.get(at), Some(b'e' | b'E')) {
374 token = NumberToken::Decimal;
375 at += 1;
376 at += usize::from(matches!(bytes.get(at), Some(b'+' | b'-')));
377 let exponent = scan_decinteger(&bytes[at..]);
378 if exponent == 0 {
379 return None;
380 }
381 at += exponent;
382 }
383 (at == bytes.len()).then_some(token)
384}
385
386fn scan_decinteger(bytes: &[u8]) -> usize {
388 if !bytes.first().is_some_and(u8::is_ascii_digit) {
389 return 0;
390 }
391 let mut at = 1;
392 loop {
393 let next = at + usize::from(bytes.get(at) == Some(&b'_'));
394 if !bytes.get(next).is_some_and(u8::is_ascii_digit) {
395 return at;
396 }
397 at = next + 1;
398 }
399}
400
401fn cast_constant(constant: Constant, target: CastTarget) -> Result<CastValue, CastError> {
404 let from = constant.pg_type();
405 match target {
406 CastTarget::Boolean => match constant {
407 Constant::Integer(value) => Ok(CastValue::Boolean(value != 0)),
408 _ => Err(CastError::CannotCast {
409 from,
410 to: PgType::Boolean,
411 }),
412 },
413 CastTarget::Smallint => {
414 let value = constant.into_i64().and_then(|v| i16::try_from(v).ok());
415 value
416 .map(CastValue::Smallint)
417 .ok_or(CastError::OutOfRange(PgType::Smallint))
418 }
419 CastTarget::Integer => {
420 let value = constant.into_i64().and_then(|v| i32::try_from(v).ok());
421 value
422 .map(CastValue::Integer)
423 .ok_or(CastError::OutOfRange(PgType::Integer))
424 }
425 CastTarget::Bigint => constant
426 .into_i64()
427 .map(CastValue::Bigint)
428 .ok_or(CastError::OutOfRange(PgType::Bigint)),
429 CastTarget::Numeric(typmod) => {
430 let value = match constant {
431 Constant::Integer(value) => PgNumeric::from_i64(i64::from(value)),
432 Constant::Bigint(value) => PgNumeric::from_i64(value),
433 Constant::Numeric(value) => value,
434 };
435 numeric_typmod(value, typmod)
436 }
437 CastTarget::Text | CastTarget::Varchar(_) | CastTarget::Bpchar(_) => {
438 let text = match constant {
439 Constant::Integer(value) => value.to_string(),
440 Constant::Bigint(value) => value.to_string(),
441 Constant::Numeric(value) => value.to_string(),
442 };
443 Ok(character(&text, target))
444 }
445 CastTarget::Date | CastTarget::Timestamp(_) | CastTarget::TimestampTz(_) => {
446 Err(CastError::CannotCast {
447 from,
448 to: target.pg_type(),
449 })
450 }
451 }
452}
453
454fn cast_quoted(text: &str, target: CastTarget) -> Result<CastValue, CastError> {
457 if text.contains('\0') {
459 return Err(CastError::Unsupported);
460 }
461 match target {
462 CastTarget::Boolean => bool_in(text).map(CastValue::Boolean),
463 CastTarget::Smallint => int_input(text, 16, PgType::Smallint).map(|v| {
464 CastValue::Smallint(i16::try_from(v).expect("int_in kept the value in 16 bits"))
465 }),
466 CastTarget::Integer => {
467 int_input(text, 32, PgType::Integer).map(|v| CastValue::Integer(narrow(v)))
468 }
469 CastTarget::Bigint => int_input(text, 64, PgType::Bigint).map(CastValue::Bigint),
470 CastTarget::Numeric(typmod) => numeric_typmod(PgNumeric::parse(text)?, typmod),
471 CastTarget::Text | CastTarget::Varchar(_) | CastTarget::Bpchar(_) => {
472 Ok(character(text, target))
473 }
474 CastTarget::Date => PgDate::parse(text, InputContext::new())
475 .map(CastValue::Date)
476 .map_err(datetime_error),
477 CastTarget::Timestamp(precision) => {
478 let at = PgTimestamp::parse(text, InputContext::new()).map_err(datetime_error)?;
479 let micros = adjust_timestamp_for_typmod(at.pg_micros(), precision);
480 Ok(CastValue::Timestamp(PgTimestamp::from_stored(micros)))
481 }
482 CastTarget::TimestampTz(precision) => {
483 let at = PgTimestampTz::parse(text, InputContext::new()).map_err(datetime_error)?;
484 let micros = adjust_timestamp_for_typmod(at.pg_micros(), precision);
485 Ok(CastValue::TimestampTz(PgTimestampTz::from_stored(micros)))
486 }
487 }
488}
489
490fn narrow(value: i64) -> i32 {
492 i32::try_from(value).expect("int_in kept the value in 32 bits")
493}
494
495fn numeric_typmod(value: PgNumeric, typmod: Option<NumericTypmod>) -> Result<CastValue, CastError> {
496 match typmod {
497 Some(typmod) => value.apply_typmod(typmod),
498 None => Ok(value),
499 }
500 .map(CastValue::Numeric)
501}
502
503fn character(text: &str, target: CastTarget) -> CastValue {
506 match target {
507 CastTarget::Varchar(Some(length)) => CastValue::Text(clip(text, length).into()),
508 CastTarget::Bpchar(Some(length)) => {
509 let clipped = clip(text, length);
510 let mut padded = String::from(clipped);
511 let blanks = length.0 - clipped.chars().count();
512 padded.extend(core::iter::repeat_n(' ', blanks));
513 CastValue::Bpchar(padded)
514 }
515 CastTarget::Bpchar(None) => CastValue::Bpchar(text.into()),
516 _ => CastValue::Text(text.into()),
517 }
518}
519
520fn clip(text: &str, length: CharLength) -> &str {
522 text.char_indices()
523 .nth(length.0)
524 .map_or(text, |(end, _)| &text[..end])
525}
526
527pub(crate) const fn is_pg_space(byte: u8) -> bool {
529 matches!(byte, b' ' | b'\t' | b'\n' | 0x0B | 0x0C | b'\r')
530}
531
532pub(crate) fn trim_pg_space(bytes: &[u8]) -> &[u8] {
533 let start = bytes.iter().take_while(|&&b| is_pg_space(b)).count();
534 let end = bytes
535 .iter()
536 .rposition(|&b| !is_pg_space(b))
537 .map_or(start, |last| last + 1);
538 &bytes[start..end.max(start)]
539}
540
541fn bool_in(text: &str) -> Result<bool, CastError> {
544 let word = trim_pg_space(text.as_bytes());
545 let abbreviates = |full: &[u8]| {
546 full.get(..word.len())
547 .is_some_and(|prefix| prefix.eq_ignore_ascii_case(word))
548 };
549 let value = match word {
550 [b't' | b'T', ..] if abbreviates(b"true") => true,
551 [b'f' | b'F', ..] if abbreviates(b"false") => false,
552 [b'y' | b'Y', ..] if abbreviates(b"yes") => true,
553 [b'n' | b'N', ..] if abbreviates(b"no") => false,
554 [b'o' | b'O', _, ..] if abbreviates(b"on") => true,
555 [b'o' | b'O', _, ..] if abbreviates(b"off") => false,
556 b"1" => true,
557 b"0" => false,
558 _ => return Err(CastError::InvalidInputSyntax(PgType::Boolean)),
559 };
560 Ok(value)
561}
562
563enum IntInputError {
565 Syntax,
566 Range,
567}
568
569fn int_input(text: &str, bits: u32, pg_type: PgType) -> Result<i64, CastError> {
571 int_in(text, bits).map_err(|error| match error {
572 IntInputError::Syntax => CastError::InvalidInputSyntax(pg_type),
573 IntInputError::Range => CastError::ValueOutOfRange(pg_type),
574 })
575}
576
577fn int_in(text: &str, bits: u32) -> Result<i64, IntInputError> {
581 let bytes = text.as_bytes();
582 let mut at = bytes.iter().take_while(|&&b| is_pg_space(b)).count();
583 let negative = bytes.get(at) == Some(&b'-');
584 at += usize::from(matches!(bytes.get(at), Some(b'+' | b'-')));
585 let radix = match (bytes.get(at), bytes.get(at + 1)) {
586 (Some(b'0'), Some(b'x' | b'X')) => 16,
587 (Some(b'0'), Some(b'o' | b'O')) => 8,
588 (Some(b'0'), Some(b'b' | b'B')) => 2,
589 _ => 10,
590 };
591 if radix != 10 {
592 at += 2;
593 }
594 let first_digit = at;
595 let is_digit = |byte: Option<&u8>| byte.is_some_and(|&b| char::from(b).is_digit(radix));
596 let limit: u64 = 1 << (bits - 1);
598 let mut magnitude: u64 = 0;
599 loop {
600 match bytes.get(at) {
601 Some(&byte) if is_digit(Some(&byte)) => {
602 if magnitude > limit / u64::from(radix) {
603 return Err(IntInputError::Range);
604 }
605 let digit = char::from(byte).to_digit(radix).expect("checked a digit");
606 magnitude = magnitude * u64::from(radix) + u64::from(digit);
607 at += 1;
608 }
609 Some(b'_') => {
610 if radix == 10 && at == first_digit {
611 return Err(IntInputError::Syntax);
612 }
613 at += 1;
614 if !is_digit(bytes.get(at)) {
615 return Err(IntInputError::Syntax);
616 }
617 }
618 _ => break,
619 }
620 }
621 if at == first_digit || !bytes[at..].iter().all(|&b| is_pg_space(b)) {
622 return Err(IntInputError::Syntax);
623 }
624 let value = if negative {
625 -i128::from(magnitude)
626 } else {
627 i128::from(magnitude)
628 };
629 let range = -i128::from(limit)..i128::from(limit);
630 if range.contains(&value) {
631 Ok(i64::try_from(value).expect("a value within 64 bits fits i64"))
632 } else {
633 Err(IntInputError::Range)
634 }
635}
636
637fn adjust_timestamp_for_typmod(micros: i64, precision: Option<u8>) -> i64 {
641 let Some(precision @ 0..6) = precision else {
642 return micros;
643 };
644 if micros == i64::MAX || micros == i64::MIN {
645 return micros;
646 }
647 let scale = 10i64.pow(6 - u32::from(precision));
648 let offset = scale / 2;
649 if micros >= 0 {
650 (micros + offset) / scale * scale
651 } else {
652 -((-micros + offset) / scale * scale)
653 }
654}
655
656fn datetime_error(error: DateTimeError) -> CastError {
658 match error {
659 DateTimeError::FieldValueOutOfRange => CastError::DateTimeFieldOutOfRange,
660 DateTimeError::TimeZoneDisplacementOutOfRange => CastError::TimeZoneDisplacementOutOfRange,
661 DateTimeError::DateOutOfRange => CastError::DateOutOfRange,
662 DateTimeError::TimestampOutOfRange => CastError::TimestampOutOfRange,
663 DateTimeError::OutsideJiffRange
664 | DateTimeError::NeedsTimeZone
665 | DateTimeError::TimeZoneNotRecognized
666 | DateTimeError::Unsupported => CastError::Unsupported,
667 }
668}
669
670impl fmt::Display for CastValue {
672 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
673 match self {
674 Self::Boolean(value) => f.write_str(if *value { "t" } else { "f" }),
675 Self::Smallint(value) => write!(f, "{value}"),
676 Self::Integer(value) => write!(f, "{value}"),
677 Self::Bigint(value) => write!(f, "{value}"),
678 Self::Numeric(value) => write!(f, "{value}"),
679 Self::Text(text) | Self::Bpchar(text) => f.write_str(text),
680 Self::Date(date) => write!(f, "{date}"),
681 Self::Timestamp(at) => write!(f, "{at}"),
682 Self::TimestampTz(at) => write!(f, "{at}"),
683 }
684 }
685}