Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: bootstrap sqlx-jiff development #141

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ members = [
"jiff-cli",
"jiff-tzdb",
"jiff-tzdb-platform",
"sqlx-jiff",
"examples/*",
]

Expand Down
22 changes: 22 additions & 0 deletions sqlx-jiff/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
[package]
name = "sqlx-jiff"
version = "0.1.0"
license = "Unlicense OR MIT"
homepage = "https://github.com/BurntSushi/jiff/tree/master/sqlx-jiff"
repository = "https://github.com/BurntSushi/jiff"
documentation = "https://docs.rs/sqlx-jiff"
description = "Integration to use jiff structs for datetime types in sqlx."
categories = ["date-and-time"]
keywords = ["date", "time", "temporal", "zone", "iana"]
workspace = ".."
edition = "2021"
rust-version = "1.70"

[features]
default = []
postgres = ["sqlx/postgres"]

[dependencies]
jiff = { path = ".." }
serde = { version = "1.0" }
sqlx = { version = "0.8" }
34 changes: 34 additions & 0 deletions sqlx-jiff/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use serde::{Deserialize, Serialize};
use std::ops::{Deref, DerefMut};

#[cfg(feature = "postgres")]
mod postgres;

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Timestamp(pub jiff::Timestamp);
tisonkun marked this conversation as resolved.
Show resolved Hide resolved

impl From<Timestamp> for jiff::Timestamp {
fn from(ts: Timestamp) -> Self {
ts.0
}
}

impl From<jiff::Timestamp> for Timestamp {
fn from(ts: jiff::Timestamp) -> Self {
Self(ts)
}
}

impl Deref for Timestamp {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

impl AsRef also?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure how far we want to go here. In theory, there are a lot of different traits we might want to implement. In practice, I'm not sure how useful they all are or whether we even want to encourage their use. I'd start with a minimal useful set for now.

I'm actually not even sure about using Deref here. I'd leave that out for now.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK. Then I'd revoke #[derive(PartialEq, Eq, Serialize, Deserialize)] also but just make it an opaque wrapper type. Users should always call to_jiff and use jiff::Timestamp's method.

type Target = jiff::Timestamp;

fn deref(&self) -> &Self::Target {
&self.0
}
}

impl DerefMut for Timestamp {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
69 changes: 69 additions & 0 deletions sqlx-jiff/src/postgres.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
use crate::Timestamp;
use jiff::SignedDuration;
use sqlx::encode::IsNull;
use sqlx::error::BoxDynError;
use sqlx::postgres::types::Oid;
use sqlx::postgres::{
PgArgumentBuffer, PgHasArrayType, PgTypeInfo, PgValueFormat,
};
use sqlx::{Database, Decode, Encode, Postgres, Type};
use std::str::FromStr;

impl Type<Postgres> for Timestamp {
fn type_info() -> PgTypeInfo {
// 1184 => PgType::Timestamptz
PgTypeInfo::with_oid(Oid(1184))
}
}

impl PgHasArrayType for Timestamp {
fn array_type_info() -> PgTypeInfo {
// 1185 => PgType::TimestamptzArray
PgTypeInfo::with_oid(Oid(1185))
}
}

impl Encode<'_, Postgres> for Timestamp {
fn encode_by_ref(
&self,
buf: &mut PgArgumentBuffer,
) -> Result<IsNull, BoxDynError> {
// TIMESTAMP is encoded as the microseconds since the epoch
let micros =
self.0.duration_since(postgres_epoch_timestamp()).as_micros();
let micros = i64::try_from(micros).map_err(|_| {
format!("Timestamp {} out of range for Postgres: {micros}", self.0)
})?;
Encode::<Postgres>::encode(micros, buf)
}

fn size_hint(&self) -> usize {
size_of::<i64>()
}
}

impl<'r> Decode<'r, Postgres> for Timestamp {
fn decode(
value: <Postgres as Database>::ValueRef<'r>,
) -> Result<Self, BoxDynError> {
Ok(match value.format() {
PgValueFormat::Binary => {
// TIMESTAMP is encoded as the microseconds since the epoch
let us = Decode::<Postgres>::decode(value)?;
let ts = postgres_epoch_timestamp()
.checked_add(SignedDuration::from_micros(us))?;
Timestamp(ts)
}
PgValueFormat::Text => {
let s = value.as_str()?;
let ts = jiff::Timestamp::from_str(s)?;
Timestamp(ts)
}
})
}
}

fn postgres_epoch_timestamp() -> jiff::Timestamp {
jiff::Timestamp::from_str("2000-01-01T00:00:00Z")
.expect("2000-01-01T00:00:00Z is a valid timestamp")
}