1use std::time::{Duration, SystemTime, UNIX_EPOCH};
18
19use crate::error::Error;
20pub use crate::protocol::Encoded;
21
22#[derive(Clone, Copy, PartialEq, Eq, Hash)]
24pub struct Type(u32);
25
26macro_rules! types {
27 ($($(#[$doc:meta])* $name:ident = $oid:expr, $sql:expr;)*) => {
28 impl Type {
29 $($(#[$doc])* pub const $name: Type = Type($oid);)*
30
31 pub fn name(self) -> Option<&'static str> {
33 match self.0 {
34 $($oid => Some($sql),)*
35 _ => None,
36 }
37 }
38 }
39 };
40}
41
42types! {
43 BOOL = 16, "boolean";
45 BYTEA = 17, "bytea";
47 CHAR = 18, "\"char\"";
49 NAME = 19, "name";
51 INT8 = 20, "bigint";
53 INT2 = 21, "smallint";
55 INT4 = 23, "integer";
57 TEXT = 25, "text";
59 OID = 26, "oid";
61 JSON = 114, "json";
63 FLOAT4 = 700, "real";
65 FLOAT8 = 701, "double precision";
67 UNKNOWN = 705, "unknown";
69 BPCHAR = 1042, "character";
71 VARCHAR = 1043, "character varying";
73 DATE = 1082, "date";
75 TIME = 1083, "time";
77 TIMESTAMP = 1114, "timestamp";
79 TIMESTAMPTZ = 1184, "timestamptz";
81 INTERVAL = 1186, "interval";
83 NUMERIC = 1700, "numeric";
85 UUID = 2950, "uuid";
87 JSONB = 3802, "jsonb";
89}
90
91impl Type {
92 pub fn from_oid(oid: u32) -> Self {
94 Type(oid)
95 }
96
97 pub fn oid(self) -> u32 {
99 self.0
100 }
101
102 fn is_text(self) -> bool {
105 matches!(
106 self,
107 Type::TEXT | Type::VARCHAR | Type::BPCHAR | Type::NAME | Type::UNKNOWN
108 )
109 }
110
111 pub(crate) fn binary_result(self) -> bool {
114 matches!(
115 self,
116 Type::BOOL
117 | Type::BYTEA
118 | Type::INT2
119 | Type::INT4
120 | Type::INT8
121 | Type::OID
122 | Type::FLOAT4
123 | Type::FLOAT8
124 | Type::TIMESTAMPTZ
125 )
126 }
127}
128
129impl std::fmt::Display for Type {
130 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131 match self.name() {
132 Some(name) => f.write_str(name),
133 None => write!(f, "type with OID {}", self.0),
134 }
135 }
136}
137
138impl std::fmt::Debug for Type {
139 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140 write!(f, "Type({self})")
141 }
142}
143
144#[derive(Clone, Copy, Debug, PartialEq, Eq)]
149pub enum Format {
150 Text,
152 Binary,
154}
155
156pub trait ToSql {
165 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error>;
170}
171
172fn wrong_param(rust: &str, ty: Type, instead: &str) -> Error {
173 Error::conversion(format!(
174 "{} cannot be {}{instead}",
175 crate::text::a(rust),
176 crate::text::a(&ty.to_string())
177 ))
178}
179
180fn suggestion(ty: Type) -> &'static str {
182 match ty {
183 Type::BOOL => "; pass a bool",
184 Type::INT2 | Type::INT4 | Type::INT8 | Type::OID => "; pass an i16, i32 or i64",
185 Type::FLOAT4 => "; pass an f32",
186 Type::FLOAT8 => "; pass an f64 or f32",
187 Type::BYTEA => "; pass a &[u8] or Vec<u8>",
188 Type::TIMESTAMPTZ => "; pass a SystemTime or a string such as \"2026-01-31 12:00:00+00\"",
189 t if t.is_text() => "; pass a &str or String",
190 _ => "; pass the value as a &str in the type's text form, or cast the parameter in SQL",
191 }
192}
193
194fn put_int(v: i64, rust: &str, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
195 let range = |name: &str| {
196 Error::conversion(format!(
197 "{v} does not fit in {}; change the column type or pass a smaller value",
198 crate::text::a(name)
199 ))
200 };
201 match ty {
202 Type::INT2 => {
203 let v = i16::try_from(v).map_err(|_| range("smallint"))?;
204 out.extend_from_slice(&v.to_be_bytes());
205 }
206 Type::INT4 => {
207 let v = i32::try_from(v).map_err(|_| range("integer"))?;
208 out.extend_from_slice(&v.to_be_bytes());
209 }
210 Type::INT8 => out.extend_from_slice(&v.to_be_bytes()),
211 Type::OID => {
212 let v = u32::try_from(v).map_err(|_| range("oid"))?;
213 out.extend_from_slice(&v.to_be_bytes());
214 }
215 Type::NUMERIC | Type::FLOAT4 | Type::FLOAT8 => {
218 out.extend_from_slice(v.to_string().as_bytes());
219 return Ok(Encoded::Text);
220 }
221 _ => return Err(wrong_param(rust, ty, suggestion(ty))),
222 }
223 Ok(Encoded::Binary)
224}
225
226macro_rules! int_to_sql {
227 ($($t:ty),*) => {$(
228 impl ToSql for $t {
229 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
230 put_int(i64::from(*self), stringify!($t), ty, out)
231 }
232 }
233 )*};
234}
235
236int_to_sql!(i16, i32, i64);
237
238impl ToSql for f64 {
239 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
240 match ty {
241 Type::FLOAT8 => out.extend_from_slice(&self.to_bits().to_be_bytes()),
242 Type::FLOAT4 => {
243 let narrow = *self as f32;
244 if f64::from(narrow) != *self && !self.is_nan() {
245 return Err(Error::conversion(format!(
246 "{self} cannot be stored in a real without losing precision; \
247 pass an f32, or make the column double precision"
248 )));
249 }
250 out.extend_from_slice(&narrow.to_bits().to_be_bytes());
251 }
252 Type::NUMERIC => return put_float_text(*self, out),
253 _ => return Err(wrong_param("f64", ty, suggestion(ty))),
254 }
255 Ok(Encoded::Binary)
256 }
257}
258
259impl ToSql for f32 {
260 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
261 match ty {
262 Type::FLOAT4 => out.extend_from_slice(&self.to_bits().to_be_bytes()),
263 Type::FLOAT8 => out.extend_from_slice(&f64::from(*self).to_bits().to_be_bytes()),
264 Type::NUMERIC => return put_float_text(f64::from(*self), out),
265 _ => return Err(wrong_param("f32", ty, suggestion(ty))),
266 }
267 Ok(Encoded::Binary)
268 }
269}
270
271fn put_float_text(v: f64, out: &mut Vec<u8>) -> Result<Encoded, Error> {
274 let text = if v.is_nan() {
275 "NaN".to_owned()
276 } else if v.is_infinite() {
277 if v > 0.0 { "Infinity" } else { "-Infinity" }.to_owned()
278 } else {
279 v.to_string()
280 };
281 out.extend_from_slice(text.as_bytes());
282 Ok(Encoded::Text)
283}
284
285impl ToSql for bool {
286 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
287 if ty != Type::BOOL {
288 return Err(wrong_param("bool", ty, suggestion(ty)));
289 }
290 out.push(*self as u8);
291 Ok(Encoded::Binary)
292 }
293}
294
295impl ToSql for str {
296 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
297 if ty == Type::BYTEA {
298 return Err(wrong_param("string", ty, "; pass a &[u8] or Vec<u8>"));
299 }
300 crate::protocol::check_text("a string parameter", self)?;
301 out.extend_from_slice(self.as_bytes());
302 Ok(if ty.is_text() {
305 Encoded::Binary
306 } else {
307 Encoded::Text
308 })
309 }
310}
311
312impl ToSql for String {
313 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
314 self.as_str().to_sql(ty, out)
315 }
316}
317
318impl ToSql for [u8] {
319 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
320 if ty != Type::BYTEA {
321 return Err(wrong_param("byte slice", ty, suggestion(ty)));
322 }
323 out.extend_from_slice(self);
324 Ok(Encoded::Binary)
325 }
326}
327
328impl ToSql for Vec<u8> {
329 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
330 self.as_slice().to_sql(ty, out)
331 }
332}
333
334impl<const N: usize> ToSql for [u8; N] {
335 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
336 self.as_slice().to_sql(ty, out)
337 }
338}
339
340const PG_EPOCH_MICROS: i64 = 946_684_800_000_000;
342
343impl ToSql for SystemTime {
344 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
345 if ty != Type::TIMESTAMPTZ {
346 let instead = if ty == Type::TIMESTAMP {
347 "; a timestamp without time zone has no fixed moment: make the column \
348 timestamptz, or pass the wall-clock time as a string"
349 } else {
350 suggestion(ty)
351 };
352 return Err(wrong_param("SystemTime", ty, instead));
353 }
354 let unix_micros = match self.duration_since(UNIX_EPOCH) {
355 Ok(after) => i64::try_from(after.as_micros()).ok(),
356 Err(before) => i64::try_from(before.duration().as_micros())
357 .ok()
358 .map(|m| -m),
359 };
360 let micros = unix_micros
361 .and_then(|m| m.checked_sub(PG_EPOCH_MICROS))
362 .ok_or_else(|| Error::conversion(format!("{self:?} is out of timestamptz's range")))?;
363 out.extend_from_slice(µs.to_be_bytes());
364 Ok(Encoded::Binary)
365 }
366}
367
368impl<T: ToSql> ToSql for Option<T> {
369 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
370 match self {
371 Some(v) => v.to_sql(ty, out),
372 None => Ok(Encoded::Null),
373 }
374 }
375}
376
377impl<T: ToSql + ?Sized> ToSql for &T {
378 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
379 (**self).to_sql(ty, out)
380 }
381}
382
383impl<T: ToSql + ?Sized> ToSql for Box<T> {
384 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
385 (**self).to_sql(ty, out)
386 }
387}
388
389pub trait FromSql<'a>: Sized {
430 fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error>;
435
436 fn from_null(ty: Type) -> Result<Self, Error> {
438 let _ = ty;
439 Err(Error::conversion(format!(
440 "the value is NULL; read it as Option<{}>",
441 crate::text::rust_name::<Self>()
442 )))
443 }
444}
445
446fn read_as(ty: Type) -> &'static str {
448 match ty {
449 Type::BOOL => "; read it as bool",
450 Type::INT2 | Type::INT4 | Type::INT8 => "; read it as i16, i32 or i64",
451 Type::OID => "; read it as i64",
452 Type::FLOAT4 => "; read it as f32 or f64",
453 Type::FLOAT8 => "; read it as f64",
454 Type::BYTEA => "; read it as Vec<u8> or &[u8]",
455 Type::TIMESTAMPTZ => "; read it as SystemTime, or cast it to text in SQL",
456 _ => "; read it as String or &str",
457 }
458}
459
460fn wrong_column<T>(ty: Type) -> Error {
461 Error::conversion(format!(
462 "{} cannot be read as {}{}",
463 crate::text::a(&ty.to_string()),
464 crate::text::rust_name::<T>(),
465 read_as(ty)
466 ))
467}
468
469fn fixed<const N: usize>(raw: &[u8], ty: Type) -> Result<[u8; N], Error> {
470 raw.try_into().map_err(|_| {
471 Error::conversion(format!(
472 "the server sent {} bytes for {}, which has {N}",
473 raw.len(),
474 crate::text::a(&ty.to_string())
475 ))
476 })
477}
478
479fn get_int(ty: Type, format: Format, raw: &[u8]) -> Option<Result<i64, Error>> {
480 if format != Format::Binary {
481 return None;
482 }
483 Some(match ty {
484 Type::INT2 => fixed::<2>(raw, ty).map(|b| i64::from(i16::from_be_bytes(b))),
485 Type::INT4 => fixed::<4>(raw, ty).map(|b| i64::from(i32::from_be_bytes(b))),
486 Type::INT8 => fixed::<8>(raw, ty).map(i64::from_be_bytes),
487 Type::OID => fixed::<4>(raw, ty).map(|b| i64::from(u32::from_be_bytes(b))),
488 _ => return None,
489 })
490}
491
492macro_rules! int_from_sql {
493 ($($t:ty),*) => {$(
494 impl<'a> FromSql<'a> for $t {
495 fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
496 let v = get_int(ty, format, raw).ok_or_else(|| wrong_column::<$t>(ty))??;
497 <$t>::try_from(v).map_err(|_| {
498 Error::conversion(format!(
499 "{v} does not fit in an {}; read it as i64", stringify!($t)
500 ))
501 })
502 }
503 }
504 )*};
505}
506
507int_from_sql!(i16, i32, i64);
508
509impl<'a> FromSql<'a> for f64 {
510 fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
511 match (ty, format) {
512 (Type::FLOAT8, Format::Binary) => {
513 Ok(f64::from_bits(u64::from_be_bytes(fixed(raw, ty)?)))
514 }
515 (Type::FLOAT4, Format::Binary) => Ok(f64::from(f32::from_bits(u32::from_be_bytes(
516 fixed(raw, ty)?,
517 )))),
518 _ => Err(wrong_column::<f64>(ty)),
519 }
520 }
521}
522
523impl<'a> FromSql<'a> for f32 {
524 fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
525 match (ty, format) {
526 (Type::FLOAT4, Format::Binary) => {
527 Ok(f32::from_bits(u32::from_be_bytes(fixed(raw, ty)?)))
528 }
529 (Type::FLOAT8, _) => Err(Error::conversion(
530 "a double precision cannot be read as f32 without losing precision; read it as f64",
531 )),
532 _ => Err(wrong_column::<f32>(ty)),
533 }
534 }
535}
536
537impl<'a> FromSql<'a> for bool {
538 fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
539 if (ty, format) != (Type::BOOL, Format::Binary) {
540 return Err(wrong_column::<bool>(ty));
541 }
542 Ok(fixed::<1>(raw, ty)?[0] != 0)
543 }
544}
545
546impl<'a> FromSql<'a> for &'a str {
547 fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
548 if format != Format::Text && !ty.is_text() {
549 return Err(wrong_column::<&str>(ty));
550 }
551 std::str::from_utf8(raw)
552 .map_err(|_| Error::conversion(format!("the {ty} value is not valid UTF-8")))
553 }
554}
555
556impl<'a> FromSql<'a> for String {
557 fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
558 if format != Format::Text && !ty.is_text() {
559 return Err(wrong_column::<String>(ty));
560 }
561 <&str>::from_sql(ty, format, raw).map(str::to_owned)
562 }
563}
564
565impl<'a> FromSql<'a> for &'a [u8] {
566 fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
567 if (ty, format) != (Type::BYTEA, Format::Binary) {
568 return Err(wrong_column::<&[u8]>(ty));
569 }
570 Ok(raw)
571 }
572}
573
574impl<'a> FromSql<'a> for Vec<u8> {
575 fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
576 <&[u8]>::from_sql(ty, format, raw).map(<[u8]>::to_vec)
577 }
578}
579
580impl<'a> FromSql<'a> for SystemTime {
581 fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
582 if (ty, format) != (Type::TIMESTAMPTZ, Format::Binary) {
583 return Err(wrong_column::<SystemTime>(ty));
584 }
585 let micros = i64::from_be_bytes(fixed(raw, ty)?);
586 if micros == i64::MAX || micros == i64::MIN {
587 return Err(Error::conversion(
588 "the timestamptz is infinity or -infinity, which SystemTime cannot hold; \
589 read it as Option and use NULL instead, or filter it out in SQL",
590 ));
591 }
592 let unix = micros
593 .checked_add(PG_EPOCH_MICROS)
594 .ok_or_else(|| Error::conversion("the timestamptz is out of SystemTime's range"))?;
595 let t = if unix >= 0 {
596 UNIX_EPOCH.checked_add(Duration::from_micros(unix as u64))
597 } else {
598 UNIX_EPOCH.checked_sub(Duration::from_micros(unix.unsigned_abs()))
599 };
600 t.ok_or_else(|| Error::conversion("the timestamptz is out of SystemTime's range"))
601 }
602}
603
604impl<'a, T: FromSql<'a>> FromSql<'a> for Option<T> {
605 fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
606 T::from_sql(ty, format, raw).map(Some)
607 }
608
609 fn from_null(_: Type) -> Result<Self, Error> {
610 Ok(None)
611 }
612}
613
614#[cfg(test)]
615mod tests {
616 use super::*;
617
618 fn enc(v: &dyn ToSql, ty: Type) -> Result<(Encoded, Vec<u8>), Error> {
619 let mut out = Vec::new();
620 v.to_sql(ty, &mut out).map(|e| (e, out))
621 }
622
623 #[test]
624 fn integers_convert_when_they_fit() {
625 assert_eq!(
626 enc(&7i64, Type::INT4).unwrap(),
627 (Encoded::Binary, vec![0, 0, 0, 7])
628 );
629 assert_eq!(enc(&7i16, Type::INT8).unwrap().1, 7i64.to_be_bytes());
630 assert_eq!(
631 enc(&7i32, Type::NUMERIC).unwrap(),
632 (Encoded::Text, b"7".to_vec())
633 );
634 let e = enc(&3_000_000_000i64, Type::INT4).unwrap_err();
635 assert!(e.to_string().contains("does not fit in an integer"), "{e}");
636 let e = enc(&1i32, Type::TEXT).unwrap_err();
637 assert!(e.to_string().contains("pass a &str"), "{e}");
638
639 assert_eq!(
640 i16::from_sql(Type::INT8, Format::Binary, &7i64.to_be_bytes()).unwrap(),
641 7
642 );
643 let e = i16::from_sql(Type::INT8, Format::Binary, &70_000i64.to_be_bytes()).unwrap_err();
644 assert!(e.to_string().contains("read it as i64"), "{e}");
645 assert!(i32::from_sql(Type::INT4, Format::Binary, &[0, 0, 7]).is_err());
646 assert!(i32::from_sql(Type::TEXT, Format::Text, b"7").is_err());
647 }
648
649 #[test]
650 fn floats_never_lose_precision_silently() {
651 assert!(enc(&0.5f64, Type::FLOAT4).is_ok());
652 assert!(enc(&0.1f64, Type::FLOAT4).is_err());
653 assert_eq!(enc(&0.1f64, Type::NUMERIC).unwrap().1, b"0.1");
654 assert_eq!(
655 enc(&f64::NEG_INFINITY, Type::NUMERIC).unwrap().1,
656 b"-Infinity"
657 );
658 let bits = 1.5f32.to_bits().to_be_bytes();
659 assert_eq!(
660 f64::from_sql(Type::FLOAT4, Format::Binary, &bits).unwrap(),
661 1.5
662 );
663 assert!(f32::from_sql(
664 Type::FLOAT8,
665 Format::Binary,
666 &1.5f64.to_bits().to_be_bytes()
667 )
668 .is_err());
669 }
670
671 #[test]
672 fn strings_go_as_text_to_types_the_server_parses() {
673 assert_eq!(enc(&"abc", Type::TEXT).unwrap().0, Encoded::Binary);
674 assert_eq!(
675 enc(&"6c1b0a3e-0000-4000-8000-000000000000", Type::UUID)
676 .unwrap()
677 .0,
678 Encoded::Text
679 );
680 assert!(enc(&"abc", Type::BYTEA).is_err());
681 assert!(enc(&"a\0c", Type::TEXT).is_err());
682 assert_eq!(
683 <&str>::from_sql(Type::UUID, Format::Text, b"x").unwrap(),
684 "x"
685 );
686 assert!(String::from_sql(Type::INT4, Format::Binary, &[0, 0, 0, 1]).is_err());
687 assert!(String::from_sql(Type::TEXT, Format::Text, &[0xff]).is_err());
688 }
689
690 #[test]
691 fn timestamps_round_trip() {
692 let t = UNIX_EPOCH + Duration::from_micros(1_767_225_600_123_456);
693 let (how, bytes) = enc(&t, Type::TIMESTAMPTZ).unwrap();
694 assert_eq!(how, Encoded::Binary);
695 assert_eq!(
696 SystemTime::from_sql(Type::TIMESTAMPTZ, Format::Binary, &bytes).unwrap(),
697 t
698 );
699 let before = UNIX_EPOCH - Duration::from_secs(86_400 * 365 * 40);
700 let (_, bytes) = enc(&before, Type::TIMESTAMPTZ).unwrap();
701 assert_eq!(
702 SystemTime::from_sql(Type::TIMESTAMPTZ, Format::Binary, &bytes).unwrap(),
703 before
704 );
705 let (_, bytes) = enc(
707 &(UNIX_EPOCH + Duration::from_secs(946_684_800)),
708 Type::TIMESTAMPTZ,
709 )
710 .unwrap();
711 assert_eq!(bytes, [0; 8]);
712 assert!(
713 SystemTime::from_sql(Type::TIMESTAMPTZ, Format::Binary, &i64::MAX.to_be_bytes())
714 .is_err()
715 );
716 assert!(enc(&t, Type::TIMESTAMP)
717 .unwrap_err()
718 .to_string()
719 .contains("timestamptz"));
720 }
721
722 #[test]
723 fn null_needs_an_option() {
724 assert_eq!(enc(&None::<i32>, Type::INT4).unwrap().0, Encoded::Null);
725 assert_eq!(Option::<i32>::from_null(Type::INT4).unwrap(), None);
726 let e = i32::from_null(Type::INT4).unwrap_err();
727 assert!(e.to_string().contains("Option<i32>"), "{e}");
728 }
729
730 #[test]
731 fn types_have_names() {
732 assert_eq!(Type::INT4.to_string(), "integer");
733 assert_eq!(Type::from_oid(99999).to_string(), "type with OID 99999");
734 }
735}