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)]
146pub enum Format {
147 Text,
149 Binary,
151}
152
153pub trait ToSql {
162 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error>;
167}
168
169fn wrong_param(rust: &str, ty: Type, instead: &str) -> Error {
170 Error::conversion(format!("a {rust} cannot be a {ty}{instead}"))
171}
172
173fn suggestion(ty: Type) -> &'static str {
175 match ty {
176 Type::BOOL => "; pass a bool",
177 Type::INT2 | Type::INT4 | Type::INT8 | Type::OID => "; pass an i16, i32 or i64",
178 Type::FLOAT4 => "; pass an f32",
179 Type::FLOAT8 => "; pass an f64 or f32",
180 Type::BYTEA => "; pass a &[u8] or Vec<u8>",
181 Type::TIMESTAMPTZ => "; pass a SystemTime or a string such as \"2026-01-31 12:00:00+00\"",
182 t if t.is_text() => "; pass a &str or String",
183 _ => "; pass the value as a &str in the type's text form, or cast the parameter in SQL",
184 }
185}
186
187fn put_int(v: i64, rust: &str, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
188 let range = |name: &str| {
189 Error::conversion(format!(
190 "{v} does not fit in a {name}; change the column type or pass a smaller value"
191 ))
192 };
193 match ty {
194 Type::INT2 => {
195 let v = i16::try_from(v).map_err(|_| range("smallint"))?;
196 out.extend_from_slice(&v.to_be_bytes());
197 }
198 Type::INT4 => {
199 let v = i32::try_from(v).map_err(|_| range("integer"))?;
200 out.extend_from_slice(&v.to_be_bytes());
201 }
202 Type::INT8 => out.extend_from_slice(&v.to_be_bytes()),
203 Type::OID => {
204 let v = u32::try_from(v).map_err(|_| range("oid"))?;
205 out.extend_from_slice(&v.to_be_bytes());
206 }
207 Type::NUMERIC | Type::FLOAT4 | Type::FLOAT8 => {
210 out.extend_from_slice(v.to_string().as_bytes());
211 return Ok(Encoded::Text);
212 }
213 _ => return Err(wrong_param(rust, ty, suggestion(ty))),
214 }
215 Ok(Encoded::Binary)
216}
217
218macro_rules! int_to_sql {
219 ($($t:ty),*) => {$(
220 impl ToSql for $t {
221 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
222 put_int(i64::from(*self), stringify!($t), ty, out)
223 }
224 }
225 )*};
226}
227
228int_to_sql!(i16, i32, i64);
229
230impl ToSql for f64 {
231 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
232 match ty {
233 Type::FLOAT8 => out.extend_from_slice(&self.to_bits().to_be_bytes()),
234 Type::FLOAT4 => {
235 let narrow = *self as f32;
236 if f64::from(narrow) != *self && !self.is_nan() {
237 return Err(Error::conversion(format!(
238 "{self} cannot be stored in a real without losing precision; \
239 pass an f32, or make the column double precision"
240 )));
241 }
242 out.extend_from_slice(&narrow.to_bits().to_be_bytes());
243 }
244 Type::NUMERIC => return put_float_text(*self, out),
245 _ => return Err(wrong_param("f64", ty, suggestion(ty))),
246 }
247 Ok(Encoded::Binary)
248 }
249}
250
251impl ToSql for f32 {
252 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
253 match ty {
254 Type::FLOAT4 => out.extend_from_slice(&self.to_bits().to_be_bytes()),
255 Type::FLOAT8 => out.extend_from_slice(&f64::from(*self).to_bits().to_be_bytes()),
256 Type::NUMERIC => return put_float_text(f64::from(*self), out),
257 _ => return Err(wrong_param("f32", ty, suggestion(ty))),
258 }
259 Ok(Encoded::Binary)
260 }
261}
262
263fn put_float_text(v: f64, out: &mut Vec<u8>) -> Result<Encoded, Error> {
266 let text = if v.is_nan() {
267 "NaN".to_owned()
268 } else if v.is_infinite() {
269 if v > 0.0 { "Infinity" } else { "-Infinity" }.to_owned()
270 } else {
271 v.to_string()
272 };
273 out.extend_from_slice(text.as_bytes());
274 Ok(Encoded::Text)
275}
276
277impl ToSql for bool {
278 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
279 if ty != Type::BOOL {
280 return Err(wrong_param("bool", ty, suggestion(ty)));
281 }
282 out.push(*self as u8);
283 Ok(Encoded::Binary)
284 }
285}
286
287impl ToSql for str {
288 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
289 if ty == Type::BYTEA {
290 return Err(wrong_param("string", ty, "; pass a &[u8] or Vec<u8>"));
291 }
292 crate::protocol::check_text("a string parameter", self)?;
293 out.extend_from_slice(self.as_bytes());
294 Ok(if ty.is_text() {
297 Encoded::Binary
298 } else {
299 Encoded::Text
300 })
301 }
302}
303
304impl ToSql for String {
305 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
306 self.as_str().to_sql(ty, out)
307 }
308}
309
310impl ToSql for [u8] {
311 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
312 if ty != Type::BYTEA {
313 return Err(wrong_param("byte slice", ty, suggestion(ty)));
314 }
315 out.extend_from_slice(self);
316 Ok(Encoded::Binary)
317 }
318}
319
320impl ToSql for Vec<u8> {
321 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
322 self.as_slice().to_sql(ty, out)
323 }
324}
325
326impl<const N: usize> ToSql for [u8; N] {
327 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
328 self.as_slice().to_sql(ty, out)
329 }
330}
331
332const PG_EPOCH_MICROS: i64 = 946_684_800_000_000;
334
335impl ToSql for SystemTime {
336 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
337 if ty != Type::TIMESTAMPTZ {
338 let instead = if ty == Type::TIMESTAMP {
339 "; a timestamp without time zone has no fixed moment: make the column \
340 timestamptz, or pass the wall-clock time as a string"
341 } else {
342 suggestion(ty)
343 };
344 return Err(wrong_param("SystemTime", ty, instead));
345 }
346 let unix_micros = match self.duration_since(UNIX_EPOCH) {
347 Ok(after) => i64::try_from(after.as_micros()).ok(),
348 Err(before) => i64::try_from(before.duration().as_micros())
349 .ok()
350 .map(|m| -m),
351 };
352 let micros = unix_micros
353 .and_then(|m| m.checked_sub(PG_EPOCH_MICROS))
354 .ok_or_else(|| Error::conversion(format!("{self:?} is out of timestamptz's range")))?;
355 out.extend_from_slice(µs.to_be_bytes());
356 Ok(Encoded::Binary)
357 }
358}
359
360impl<T: ToSql> ToSql for Option<T> {
361 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
362 match self {
363 Some(v) => v.to_sql(ty, out),
364 None => Ok(Encoded::Null),
365 }
366 }
367}
368
369impl<T: ToSql + ?Sized> ToSql for &T {
370 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
371 (**self).to_sql(ty, out)
372 }
373}
374
375impl<T: ToSql + ?Sized> ToSql for Box<T> {
376 fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
377 (**self).to_sql(ty, out)
378 }
379}
380
381pub trait FromSql<'a>: Sized {
389 fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error>;
394
395 fn from_null(ty: Type) -> Result<Self, Error> {
397 let _ = ty;
398 Err(Error::conversion(format!(
399 "the value is NULL; read it as Option<{}>",
400 std::any::type_name::<Self>()
401 )))
402 }
403}
404
405fn read_as(ty: Type) -> &'static str {
407 match ty {
408 Type::BOOL => "; read it as bool",
409 Type::INT2 | Type::INT4 | Type::INT8 => "; read it as i16, i32 or i64",
410 Type::OID => "; read it as i64",
411 Type::FLOAT4 => "; read it as f32 or f64",
412 Type::FLOAT8 => "; read it as f64",
413 Type::BYTEA => "; read it as Vec<u8> or &[u8]",
414 Type::TIMESTAMPTZ => "; read it as SystemTime, or cast it to text in SQL",
415 _ => "; read it as String or &str",
416 }
417}
418
419fn wrong_column<T>(ty: Type) -> Error {
420 Error::conversion(format!(
421 "a {ty} cannot be read as {}{}",
422 std::any::type_name::<T>(),
423 read_as(ty)
424 ))
425}
426
427fn fixed<const N: usize>(raw: &[u8], ty: Type) -> Result<[u8; N], Error> {
428 raw.try_into().map_err(|_| {
429 Error::conversion(format!(
430 "the server sent {} bytes for a {ty}, which has {N}",
431 raw.len()
432 ))
433 })
434}
435
436fn get_int(ty: Type, format: Format, raw: &[u8]) -> Option<Result<i64, Error>> {
437 if format != Format::Binary {
438 return None;
439 }
440 Some(match ty {
441 Type::INT2 => fixed::<2>(raw, ty).map(|b| i64::from(i16::from_be_bytes(b))),
442 Type::INT4 => fixed::<4>(raw, ty).map(|b| i64::from(i32::from_be_bytes(b))),
443 Type::INT8 => fixed::<8>(raw, ty).map(i64::from_be_bytes),
444 Type::OID => fixed::<4>(raw, ty).map(|b| i64::from(u32::from_be_bytes(b))),
445 _ => return None,
446 })
447}
448
449macro_rules! int_from_sql {
450 ($($t:ty),*) => {$(
451 impl<'a> FromSql<'a> for $t {
452 fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
453 let v = get_int(ty, format, raw).ok_or_else(|| wrong_column::<$t>(ty))??;
454 <$t>::try_from(v).map_err(|_| {
455 Error::conversion(format!(
456 "{v} does not fit in an {}; read it as i64", stringify!($t)
457 ))
458 })
459 }
460 }
461 )*};
462}
463
464int_from_sql!(i16, i32, i64);
465
466impl<'a> FromSql<'a> for f64 {
467 fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
468 match (ty, format) {
469 (Type::FLOAT8, Format::Binary) => {
470 Ok(f64::from_bits(u64::from_be_bytes(fixed(raw, ty)?)))
471 }
472 (Type::FLOAT4, Format::Binary) => Ok(f64::from(f32::from_bits(u32::from_be_bytes(
473 fixed(raw, ty)?,
474 )))),
475 _ => Err(wrong_column::<f64>(ty)),
476 }
477 }
478}
479
480impl<'a> FromSql<'a> for f32 {
481 fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
482 match (ty, format) {
483 (Type::FLOAT4, Format::Binary) => {
484 Ok(f32::from_bits(u32::from_be_bytes(fixed(raw, ty)?)))
485 }
486 (Type::FLOAT8, _) => Err(Error::conversion(
487 "a double precision cannot be read as f32 without losing precision; read it as f64",
488 )),
489 _ => Err(wrong_column::<f32>(ty)),
490 }
491 }
492}
493
494impl<'a> FromSql<'a> for bool {
495 fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
496 if (ty, format) != (Type::BOOL, Format::Binary) {
497 return Err(wrong_column::<bool>(ty));
498 }
499 Ok(fixed::<1>(raw, ty)?[0] != 0)
500 }
501}
502
503impl<'a> FromSql<'a> for &'a str {
504 fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
505 if format != Format::Text && !ty.is_text() {
506 return Err(wrong_column::<&str>(ty));
507 }
508 std::str::from_utf8(raw)
509 .map_err(|_| Error::conversion(format!("the {ty} value is not valid UTF-8")))
510 }
511}
512
513impl<'a> FromSql<'a> for String {
514 fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
515 if format != Format::Text && !ty.is_text() {
516 return Err(wrong_column::<String>(ty));
517 }
518 <&str>::from_sql(ty, format, raw).map(str::to_owned)
519 }
520}
521
522impl<'a> FromSql<'a> for &'a [u8] {
523 fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
524 if (ty, format) != (Type::BYTEA, Format::Binary) {
525 return Err(wrong_column::<&[u8]>(ty));
526 }
527 Ok(raw)
528 }
529}
530
531impl<'a> FromSql<'a> for Vec<u8> {
532 fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
533 <&[u8]>::from_sql(ty, format, raw).map(<[u8]>::to_vec)
534 }
535}
536
537impl<'a> FromSql<'a> for SystemTime {
538 fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
539 if (ty, format) != (Type::TIMESTAMPTZ, Format::Binary) {
540 return Err(wrong_column::<SystemTime>(ty));
541 }
542 let micros = i64::from_be_bytes(fixed(raw, ty)?);
543 if micros == i64::MAX || micros == i64::MIN {
544 return Err(Error::conversion(
545 "the timestamptz is infinity or -infinity, which SystemTime cannot hold; \
546 read it as Option and use NULL instead, or filter it out in SQL",
547 ));
548 }
549 let unix = micros
550 .checked_add(PG_EPOCH_MICROS)
551 .ok_or_else(|| Error::conversion("the timestamptz is out of SystemTime's range"))?;
552 let t = if unix >= 0 {
553 UNIX_EPOCH.checked_add(Duration::from_micros(unix as u64))
554 } else {
555 UNIX_EPOCH.checked_sub(Duration::from_micros(unix.unsigned_abs()))
556 };
557 t.ok_or_else(|| Error::conversion("the timestamptz is out of SystemTime's range"))
558 }
559}
560
561impl<'a, T: FromSql<'a>> FromSql<'a> for Option<T> {
562 fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
563 T::from_sql(ty, format, raw).map(Some)
564 }
565
566 fn from_null(_: Type) -> Result<Self, Error> {
567 Ok(None)
568 }
569}
570
571#[cfg(test)]
572mod tests {
573 use super::*;
574
575 fn enc(v: &dyn ToSql, ty: Type) -> Result<(Encoded, Vec<u8>), Error> {
576 let mut out = Vec::new();
577 v.to_sql(ty, &mut out).map(|e| (e, out))
578 }
579
580 #[test]
581 fn integers_convert_when_they_fit() {
582 assert_eq!(
583 enc(&7i64, Type::INT4).unwrap(),
584 (Encoded::Binary, vec![0, 0, 0, 7])
585 );
586 assert_eq!(enc(&7i16, Type::INT8).unwrap().1, 7i64.to_be_bytes());
587 assert_eq!(
588 enc(&7i32, Type::NUMERIC).unwrap(),
589 (Encoded::Text, b"7".to_vec())
590 );
591 let e = enc(&3_000_000_000i64, Type::INT4).unwrap_err();
592 assert!(
593 e.to_string().contains("does not fit in a integer")
594 || e.to_string().contains("does not fit in a"),
595 "{e}"
596 );
597 let e = enc(&1i32, Type::TEXT).unwrap_err();
598 assert!(e.to_string().contains("pass a &str"), "{e}");
599
600 assert_eq!(
601 i16::from_sql(Type::INT8, Format::Binary, &7i64.to_be_bytes()).unwrap(),
602 7
603 );
604 let e = i16::from_sql(Type::INT8, Format::Binary, &70_000i64.to_be_bytes()).unwrap_err();
605 assert!(e.to_string().contains("read it as i64"), "{e}");
606 assert!(i32::from_sql(Type::INT4, Format::Binary, &[0, 0, 7]).is_err());
607 assert!(i32::from_sql(Type::TEXT, Format::Text, b"7").is_err());
608 }
609
610 #[test]
611 fn floats_never_lose_precision_silently() {
612 assert!(enc(&0.5f64, Type::FLOAT4).is_ok());
613 assert!(enc(&0.1f64, Type::FLOAT4).is_err());
614 assert_eq!(enc(&0.1f64, Type::NUMERIC).unwrap().1, b"0.1");
615 assert_eq!(
616 enc(&f64::NEG_INFINITY, Type::NUMERIC).unwrap().1,
617 b"-Infinity"
618 );
619 let bits = 1.5f32.to_bits().to_be_bytes();
620 assert_eq!(
621 f64::from_sql(Type::FLOAT4, Format::Binary, &bits).unwrap(),
622 1.5
623 );
624 assert!(f32::from_sql(
625 Type::FLOAT8,
626 Format::Binary,
627 &1.5f64.to_bits().to_be_bytes()
628 )
629 .is_err());
630 }
631
632 #[test]
633 fn strings_go_as_text_to_types_the_server_parses() {
634 assert_eq!(enc(&"abc", Type::TEXT).unwrap().0, Encoded::Binary);
635 assert_eq!(
636 enc(&"6c1b0a3e-0000-4000-8000-000000000000", Type::UUID)
637 .unwrap()
638 .0,
639 Encoded::Text
640 );
641 assert!(enc(&"abc", Type::BYTEA).is_err());
642 assert!(enc(&"a\0c", Type::TEXT).is_err());
643 assert_eq!(
644 <&str>::from_sql(Type::UUID, Format::Text, b"x").unwrap(),
645 "x"
646 );
647 assert!(String::from_sql(Type::INT4, Format::Binary, &[0, 0, 0, 1]).is_err());
648 assert!(String::from_sql(Type::TEXT, Format::Text, &[0xff]).is_err());
649 }
650
651 #[test]
652 fn timestamps_round_trip() {
653 let t = UNIX_EPOCH + Duration::from_micros(1_767_225_600_123_456);
654 let (how, bytes) = enc(&t, Type::TIMESTAMPTZ).unwrap();
655 assert_eq!(how, Encoded::Binary);
656 assert_eq!(
657 SystemTime::from_sql(Type::TIMESTAMPTZ, Format::Binary, &bytes).unwrap(),
658 t
659 );
660 let before = UNIX_EPOCH - Duration::from_secs(86_400 * 365 * 40);
661 let (_, bytes) = enc(&before, Type::TIMESTAMPTZ).unwrap();
662 assert_eq!(
663 SystemTime::from_sql(Type::TIMESTAMPTZ, Format::Binary, &bytes).unwrap(),
664 before
665 );
666 let (_, bytes) = enc(
668 &(UNIX_EPOCH + Duration::from_secs(946_684_800)),
669 Type::TIMESTAMPTZ,
670 )
671 .unwrap();
672 assert_eq!(bytes, [0; 8]);
673 assert!(
674 SystemTime::from_sql(Type::TIMESTAMPTZ, Format::Binary, &i64::MAX.to_be_bytes())
675 .is_err()
676 );
677 assert!(enc(&t, Type::TIMESTAMP)
678 .unwrap_err()
679 .to_string()
680 .contains("timestamptz"));
681 }
682
683 #[test]
684 fn null_needs_an_option() {
685 assert_eq!(enc(&None::<i32>, Type::INT4).unwrap().0, Encoded::Null);
686 assert_eq!(Option::<i32>::from_null(Type::INT4).unwrap(), None);
687 let e = i32::from_null(Type::INT4).unwrap_err();
688 assert!(e.to_string().contains("Option<i32>"), "{e}");
689 }
690
691 #[test]
692 fn types_have_names() {
693 assert_eq!(Type::INT4.to_string(), "integer");
694 assert_eq!(Type::from_oid(99999).to_string(), "type with OID 99999");
695 }
696}