|
| 1 | +//! Log Sequence Number (LSN) type for PostgreSQL Write-Ahead Log |
| 2 | +//! (WAL), also known as the transaction log. |
| 3 | +
|
| 4 | +use bytes::BytesMut; |
| 5 | +use postgres_protocol::types; |
| 6 | +use std::error::Error; |
| 7 | +use std::fmt; |
| 8 | +use std::str::FromStr; |
| 9 | + |
| 10 | +use crate::{FromSql, IsNull, ToSql, Type}; |
| 11 | + |
| 12 | +/// Postgres `PG_LSN` type. |
| 13 | +#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)] |
| 14 | +pub struct PgLsn(u64); |
| 15 | + |
| 16 | +/// Error parsing LSN. |
| 17 | +#[derive(Debug)] |
| 18 | +pub struct ParseLsnError(()); |
| 19 | + |
| 20 | +impl From<u64> for PgLsn { |
| 21 | + fn from(lsn_u64: u64) -> Self { |
| 22 | + PgLsn(lsn_u64) |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +impl From<PgLsn> for u64 { |
| 27 | + fn from(lsn: PgLsn) -> u64 { |
| 28 | + lsn.0 |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +impl FromStr for PgLsn { |
| 33 | + type Err = ParseLsnError; |
| 34 | + |
| 35 | + fn from_str(lsn_str: &str) -> Result<Self, Self::Err> { |
| 36 | + let split: Vec<&str> = lsn_str.split('/').collect(); |
| 37 | + if split.len() == 2 { |
| 38 | + let (hi, lo) = ( |
| 39 | + u64::from_str_radix(split[0], 16).map_err(|_| ParseLsnError(()))?, |
| 40 | + u64::from_str_radix(split[1], 16).map_err(|_| ParseLsnError(()))?, |
| 41 | + ); |
| 42 | + Ok(PgLsn((hi << 32) | lo)) |
| 43 | + } else { |
| 44 | + Err(ParseLsnError(())) |
| 45 | + } |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +impl fmt::Display for PgLsn { |
| 50 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 51 | + write!(f, "{:X}/{:X}", self.0 >> 32, self.0 & 0x00000000ffffffff) |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +impl fmt::Debug for PgLsn { |
| 56 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 57 | + f.write_fmt(format_args!("{}", self)) |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +impl<'a> FromSql<'a> for PgLsn { |
| 62 | + fn from_sql(_: &Type, raw: &'a [u8]) -> Result<Self, Box<dyn Error + Sync + Send>> { |
| 63 | + let v = types::lsn_from_sql(raw)?; |
| 64 | + Ok(v.into()) |
| 65 | + } |
| 66 | + |
| 67 | + accepts!(PG_LSN); |
| 68 | +} |
| 69 | + |
| 70 | +impl ToSql for PgLsn { |
| 71 | + fn to_sql(&self, _: &Type, out: &mut BytesMut) -> Result<IsNull, Box<dyn Error + Sync + Send>> { |
| 72 | + types::lsn_to_sql((*self).into(), out); |
| 73 | + Ok(IsNull::No) |
| 74 | + } |
| 75 | + |
| 76 | + accepts!(PG_LSN); |
| 77 | + |
| 78 | + to_sql_checked!(); |
| 79 | +} |
0 commit comments