use crate::{
ColumnKind, ColumnName, ColumnShape, CursorValue, FieldName, OrderLevel, column::column_eq,
};
use jiff::{civil, tz};
use super::LocalTimestamp;
#[cfg(test)]
mod tests;
pub(super) const LOCAL: &FieldName = FieldName::new("local");
pub(super) const OFFSET_SECONDS: &FieldName = FieldName::new("offset_seconds");
pub(super) const OFFSET_STATED: &FieldName = FieldName::new("offset_stated");
pub(super) const UTC_NANOS: &FieldName = FieldName::new("utc_nanos");
pub(super) const SEGMENTS: &[ColumnShape] = &[
ColumnShape::Plain(ColumnName::of(LOCAL)),
ColumnShape::Plain(ColumnName::of(OFFSET_SECONDS)),
ColumnShape::Plain(ColumnName::of(OFFSET_STATED)),
ColumnShape::Nullable(ColumnName::of(UTC_NANOS)),
];
pub(super) const ORDER: &[OrderLevel] = &[
OrderLevel::new(3),
OrderLevel::new(0),
OrderLevel::new(1),
OrderLevel::new(2),
];
impl ColumnKind for LocalTimestamp {
const SEGMENTS: &'static [ColumnShape] = SEGMENTS;
const ORDER: &'static [OrderLevel] = ORDER;
}
column_eq! { LocalTimestamp }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LocalTimestampLeaf {
Local(civil::DateTime),
OffsetSeconds(i32),
OffsetStated(bool),
UtcNanos(i64),
}
column_eq! { LocalTimestampLeaf }
impl crate::OrderLeaves for LocalTimestamp {
type Leaf = LocalTimestampLeaf;
fn leaf(&self, at: usize) -> Option<LocalTimestampLeaf> {
match at {
0 => Some(LocalTimestampLeaf::Local(self.local())),
1 => Some(LocalTimestampLeaf::OffsetSeconds(
self.offset().map_or(0, |offset| offset.seconds()),
)),
2 => Some(LocalTimestampLeaf::OffsetStated(self.is_zoned())),
3 => self.to_utc_nanos().ok().map(LocalTimestampLeaf::UtcNanos),
_ => None,
}
}
}
impl CursorValue for LocalTimestampLeaf {
fn write_cursor(&self, out: &mut Vec<u8>) {
match self {
Self::Local(local) => {
out.push(0);
write_civil(local, out);
}
Self::OffsetSeconds(seconds) => {
out.push(1);
CursorValue::write_cursor(seconds, out);
}
Self::OffsetStated(stated) => {
out.push(2);
CursorValue::write_cursor(stated, out);
}
Self::UtcNanos(nanos) => {
out.push(3);
CursorValue::write_cursor(nanos, out);
}
}
}
fn read_cursor(bytes: &[u8]) -> Option<Self> {
let (tag, value) = bytes.split_first()?;
match tag {
0 => read_civil(value).map(Self::Local),
1 => <i32 as CursorValue>::read_cursor(value).map(Self::OffsetSeconds),
2 => <bool as CursorValue>::read_cursor(value).map(Self::OffsetStated),
3 => <i64 as CursorValue>::read_cursor(value).map(Self::UtcNanos),
_ => None,
}
}
}
const CIVIL_WIDTH: usize = size_of::<i16>() + 5 + size_of::<i32>();
fn write_civil(local: &civil::DateTime, out: &mut Vec<u8>) {
out.extend_from_slice(&local.year().to_be_bytes());
out.push(local.month() as u8);
out.push(local.day() as u8);
out.push(local.hour() as u8);
out.push(local.minute() as u8);
out.push(local.second() as u8);
out.extend_from_slice(&local.subsec_nanosecond().to_be_bytes());
}
fn read_civil(bytes: &[u8]) -> Option<civil::DateTime> {
if bytes.len() != CIVIL_WIDTH {
return None;
}
let year = i16::from_be_bytes(bytes[0..2].try_into().ok()?);
let subsec = i32::from_be_bytes(bytes[7..11].try_into().ok()?);
civil::DateTime::new(
year,
bytes[2] as i8,
bytes[3] as i8,
bytes[4] as i8,
bytes[5] as i8,
bytes[6] as i8,
subsec,
)
.ok()
}
#[cfg(all(feature = "sqlx", feature = "time"))]
impl<Db> crate::Carrier<Db> for LocalTimestampLeaf
where
Db: sqlx::Database,
bool: crate::Carrier<Db>,
i32: crate::Carrier<Db>,
i64: crate::Carrier<Db>,
crate::Temporal<time::PrimitiveDateTime>: crate::Carrier<Db>,
{
fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
match self {
Self::Local(local) => {
<crate::Temporal<time::PrimitiveDateTime> as crate::Carrier<Db>>::push_bind(
&crate::Temporal::from(*local),
qb,
);
}
Self::OffsetSeconds(value) => <i32 as crate::Carrier<Db>>::push_bind(value, qb),
Self::OffsetStated(value) => <bool as crate::Carrier<Db>>::push_bind(value, qb),
Self::UtcNanos(value) => <i64 as crate::Carrier<Db>>::push_bind(value, qb),
}
}
}
#[cfg(feature = "time")]
impl<Db> crate::StoredAs<Db> for LocalTimestamp
where
bool: crate::StoredAs<Db>,
i32: crate::StoredAs<Db>,
i64: crate::StoredAs<Db>,
time::PrimitiveDateTime: crate::StoredAs<Db>,
{
const WORDS: &'static [&'static str] = &[
<time::PrimitiveDateTime as crate::StoredAs<Db>>::WORDS[0],
<i32 as crate::StoredAs<Db>>::WORDS[0],
<bool as crate::StoredAs<Db>>::WORDS[0],
<i64 as crate::StoredAs<Db>>::WORDS[0],
];
}
impl crate::CollectionElement for LocalTimestamp {}
impl CursorValue for LocalTimestamp {
fn write_cursor(&self, out: &mut Vec<u8>) {
write_civil(&self.local(), out);
CursorValue::write_cursor(&self.offset().map_or(0, |offset| offset.seconds()), out);
CursorValue::write_cursor(&self.is_zoned(), out);
}
fn read_cursor(bytes: &[u8]) -> Option<Self> {
let (local, rest) = bytes.split_at_checked(CIVIL_WIDTH)?;
let (seconds, stated) = rest.split_at_checked(size_of::<i32>())?;
let local = read_civil(local)?;
let seconds = <i32 as CursorValue>::read_cursor(seconds)?;
let stated = <bool as CursorValue>::read_cursor(stated)?;
offset_of(seconds, stated)
.ok()
.map(|offset| Self::new(local, offset))
}
}
#[cfg(all(feature = "sqlx", feature = "time"))]
impl<Db> crate::Carrier<Db> for LocalTimestamp
where
Db: sqlx::Database,
bool: crate::Carrier<Db>,
i32: crate::Carrier<Db>,
i64: crate::Carrier<Db>,
crate::Temporal<time::PrimitiveDateTime>: crate::Carrier<Db>,
{
fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
self.push_value_bind(qb);
qb.push(", ");
match self.to_utc_nanos() {
Ok(nanos) => <i64 as crate::Carrier<Db>>::push_bind(&nanos, qb),
Err(_) => {
qb.push("NULL");
}
}
}
fn push_value_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
<crate::Temporal<time::PrimitiveDateTime> as crate::Carrier<Db>>::push_bind(
&crate::Temporal::from(self.local()),
qb,
);
qb.push(", ");
<i32 as crate::Carrier<Db>>::push_bind(&self.offset().map_or(0, |offset| offset.seconds()), qb);
qb.push(", ");
<bool as crate::Carrier<Db>>::push_bind(&self.is_zoned(), qb);
}
}
#[cfg(all(feature = "sqlx", feature = "time"))]
impl<'a, R: sqlx::Row> crate::Assemble<'a, R> for LocalTimestamp
where
bool: crate::Assemble<'a, R>,
i32: crate::Assemble<'a, R>,
time::PrimitiveDateTime: crate::Assemble<'a, R>,
{
fn assemble(row: &'a R, under: Option<&crate::Path<'_>>) -> sqlx::Result<Self> {
let local: time::PrimitiveDateTime = crate::assembled(row, LOCAL, under)?;
let seconds: i32 = crate::assembled(row, OFFSET_SECONDS, under)?;
let stated: bool = crate::assembled(row, OFFSET_STATED, under)?;
let local = civil_of(local).map_err(|refused| sqlx::Error::ColumnDecode {
index: LOCAL.as_str().to_owned(),
source: Box::new(refused),
})?;
let offset = offset_of(seconds, stated).map_err(|refused| sqlx::Error::ColumnDecode {
index: OFFSET_SECONDS.as_str().to_owned(),
source: Box::new(refused),
})?;
Ok(Self::new(local, offset))
}
}
pub(super) fn civil_of(
stored: time::PrimitiveDateTime,
) -> Result<civil::DateTime, LocalTimestampPartsError> {
let year = i16::try_from(stored.year()).map_err(|_| LocalTimestampPartsError::Year {
year: stored.year(),
})?;
civil::DateTime::new(
year,
u8::from(stored.month()) as i8,
stored.day() as i8,
stored.hour() as i8,
stored.minute() as i8,
stored.second() as i8,
stored.nanosecond() as i32,
)
.map_err(LocalTimestampPartsError::Local)
}
pub(super) fn offset_of(
seconds: i32,
stated: bool,
) -> Result<Option<tz::Offset>, LocalTimestampPartsError> {
if !stated {
return if seconds == 0 {
Ok(None)
} else {
Err(LocalTimestampPartsError::Unstated { seconds })
};
}
tz::Offset::from_seconds(seconds)
.map(Some)
.map_err(LocalTimestampPartsError::Offset)
}
#[derive(Debug, Clone)]
pub enum LocalTimestampPartsError {
Year {
year: i32,
},
Local(jiff::Error),
Offset(jiff::Error),
Unstated {
seconds: i32,
},
}
impl core::fmt::Display for LocalTimestampPartsError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Year { year } => write!(
f,
"the stored year {year} is outside the -9999..=9999 span a wall clock is written in"
),
Self::Local(cause) => write!(f, "the stored fields are not a wall clock: {cause}"),
Self::Offset(cause) => write!(f, "the stored seconds are not a zone offset: {cause}"),
Self::Unstated { seconds } => write!(
f,
"the stored pair says no zone was stated and then states {seconds} seconds of one, which \
is not a spelling a capture time is written as"
),
}
}
}
impl core::error::Error for LocalTimestampPartsError {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
Self::Local(cause) | Self::Offset(cause) => Some(cause),
Self::Year { .. } | Self::Unstated { .. } => None,
}
}
}
#[cfg(feature = "mongo")]
impl crate::MongoCarrier for LocalTimestamp {
fn to_bson(&self) -> bson::Bson {
let mut held = bson::Document::new();
held.insert(
UTC_NANOS.as_str(),
match self.to_utc_nanos() {
Ok(nanos) => bson::Bson::Int64(nanos),
Err(_) => bson::Bson::Null,
},
);
held.insert(LOCAL.as_str(), self.local().to_string());
held.insert(
OFFSET_SECONDS.as_str(),
self.offset().map_or(0, |offset| offset.seconds()),
);
held.insert(OFFSET_STATED.as_str(), self.is_zoned());
bson::Bson::Document(held)
}
}
#[cfg(feature = "mongo")]
impl crate::query::mongo::MongoExtract for LocalTimestamp {
const BSON: &'static str = "object";
fn extract(value: Option<&bson::Bson>) -> Result<Self, crate::query::mongo::MongoTypeError> {
use crate::query::mongo::MongoTypeError;
const REFUSED: &str = "this field holds a `local`, `offset_seconds` and `offset_stated` triple \
that is not a capture time";
let held = match value {
Some(bson::Bson::Document(held)) => held,
Some(other) => {
return Err(MongoTypeError::wrong_type(
Self::BSON,
crate::query::mongo::alias(other),
));
}
None => return Err(MongoTypeError::Absent),
};
let local = match held.get(LOCAL.as_str()) {
Some(bson::Bson::String(text)) => text
.parse::<civil::DateTime>()
.map_err(|_| MongoTypeError::Range(REFUSED))?,
Some(other) => {
return Err(MongoTypeError::wrong_type(
"string",
crate::query::mongo::alias(other),
));
}
None => return Err(MongoTypeError::Absent),
};
let seconds = i32::extract(held.get(OFFSET_SECONDS.as_str()))?;
let stated = bool::extract(held.get(OFFSET_STATED.as_str()))?;
offset_of(seconds, stated)
.map(|offset| Self::new(local, offset))
.map_err(|_| MongoTypeError::Range(REFUSED))
}
}