Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
22 changes: 13 additions & 9 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 17 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -67,19 +67,33 @@ rangemap = { version = "1.5.1", features = ["serde1"] }
rcgen = { version = "0.11.1", features = ["x509-parser"] }
reqwest = { version = "0.12", default-features = false, features = ["http2", "rustls-tls", "rustls-tls-webpki-roots"] }
rhai = { version = "1.15.1", features = ["sync"] }
rusqlite = { version = "0.41.1", features = ["serde_json", "time", "bundled", "uuid", "array", "load_extension", "column_decltype", "vtab", "functions", "chrono", "series", "trace", "cache", "fallible_uint"] }
rusqlite = { version = "0.41.1", features = [
"serde_json",
"time",
"bundled",
"uuid",
"array",
"load_extension",
"column_decltype",
"vtab",
"functions",
"series",
"trace",
"cache",
"fallible_uint",
] }
rustls = { version = "0.23.0", default-features = false, features = ["ring"] }
seahash = "4.1.0"
serde = "1.0.159"
serde_json = { version = "1.0.95", features = ["raw_value"] }
serde_json = { version = "1.0.151", features = ["raw_value"] }
serde_with = "2.3.2"
smallvec = { version = "1.11.0", features = ["serde", "write", "union"] }
speedy = { version = "0.8.7", features = ["uuid", "smallvec", "indexmap", "indexmap_v2" ], package = "speedy" }
sqlite3-parser = "0.12.0"
strum = { version = "0.24.1", features = ["derive"] }
tempfile = "3.5.0"
thiserror = "1.0.40"
time = { version = "0.3.15", features = ["macros", "serde-well-known"] }
time = { version = "0.3.15", features = ["formatting", "macros", "parsing", "serde-well-known"] }
tokio = { version = "1.41", features = ["full"] }
tokio-metrics = "0.3.0"
tokio-serde = { version = "0.8", features = ["json"] }
Expand Down
4 changes: 2 additions & 2 deletions crates/corro-pg/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ hex = { workspace = true }
itertools = { workspace = true }
metrics = { workspace = true }
parking_lot.workspace = true
pgwire = { version = "0.37", default-features = false, features = ["server-api-ring", "server-api", "client-api", "pg-type-chrono"] }
pgwire = { version = "0.37", default-features = false, features = ["server-api-ring", "server-api", "client-api"] }
pin-project-lite.workspace = true
postgres-types = { version = "0.2", features = ["with-time-0_3"] }
rand = { workspace = true }
Expand All @@ -30,12 +30,12 @@ spawn = { path = "../spawn" }
sqlite3-parser = { workspace = true }
tempfile = { workspace = true }
thiserror = { workspace = true }
time.workspace = true
tokio = { workspace = true }
tokio-util = { workspace = true }
tracing = { workspace = true }
tripwire = { path = "../tripwire" }
sqlparser = { version = "0.58.0" }
chrono = { version = "0.4.31" }
socket2 = { version = "0.6", features = ["all"] }
tokio-rustls = { version = "0.26", default-features = false, features = ["logging", "tls12", "ring"] }
regex = "1.13.1"
Expand Down
21 changes: 4 additions & 17 deletions crates/corro-pg/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
mod codec;
pub mod sql_state;
mod ssl;
mod time;
pub mod utils;
mod vtab;

Expand All @@ -20,7 +21,6 @@ use std::{
time::Duration,
};

use chrono::NaiveDateTime;
use compact_str::CompactString;
use corro_types::{
agent::{Agent, BookieWriteGuard, ChangeError},
Expand Down Expand Up @@ -3435,21 +3435,8 @@ pub async fn start(
}

t @ &Type::TIMESTAMP => {
let dt = match format_code {
FormatCode::Text => {
let s =
String::from_utf8_lossy(b);
NaiveDateTime::parse_from_str(&s, "%Y-%m-%d %H:%M:%S%.f").map_err(ToParamError::Parse)?
}
FormatCode::Binary => {
NaiveDateTime::from_sql(t, b)
.map_err(
ToParamError::<
chrono::format::ParseError
>::FromSql,
)?
}
};
let dt = time::from_sql(t, b, format_code)?;

prepped
.raw_bind_parameter(idx, dt)?;
}
Expand Down Expand Up @@ -4323,7 +4310,7 @@ impl<'conn> Session<'conn> {
t @ &Type::TIMESTAMP => {
encoder
.encode_field_with_type_and_format(
&row.get::<_, Option<NaiveDateTime>>(idx)?,
&row.get::<_, Option<time::OurDateTime>>(idx)?,
t,
format,
format_opts,
Expand Down
106 changes: 106 additions & 0 deletions crates/corro-pg/src/time.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
use time::PlainDateTime;

fn fmt_desc() -> &'static time::format_description::OwnedFormatItem {
static mut FMT: time::format_description::OwnedFormatItem =
time::format_description::OwnedFormatItem::Component(
time::format_description::Component::End(
time::format_description::modifier::End::default(),
),
);
static INIT: std::sync::Once = std::sync::Once::new();

unsafe {
INIT.call_once(|| {
// pgwire doesn't support time, only chrono, which is unmaintained, so for now we manually implement this
// until either time is supported, or jiff 1.0 is:
//
// - https://github.com/sunng87/pgwire/pull/491
// - https://github.com/rust-postgres/rust-postgres/pull/1405
// - https://github.com/rusqlite/rusqlite/pull/1963
//
// https://github.com/sunng87/pgwire/blob/c01c5cf69b326cc1004aae17af4fda877001f3bb/src/types/format/date_style.rs#L95
FMT = time::format_description::parse_strftime_owned("%Y-%m-%d %H:%M:%S%.6f")
.expect("failed to parse strftime string");
});
#[allow(static_mut_refs)]
&FMT
}
}

pub(super) fn from_sql(
typ: &postgres_types::Type,
val: &[u8],
format: crate::FormatCode,
) -> Result<PlainDateTime, crate::ToParamError<time::Error>> {
match format {
crate::FormatCode::Text => {
let s = std::str::from_utf8(val)?;
PlainDateTime::parse(s, fmt_desc())
.map_err(|err| crate::ToParamError::Parse(err.into()))
}
crate::FormatCode::Binary => {
use postgres_types::FromSql;
PlainDateTime::from_sql(typ, val).map_err(crate::ToParamError::<time::Error>::FromSql)
}
}
}

pub(super) struct OurDateTime(PlainDateTime);

impl std::fmt::Debug for OurDateTime {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.0)
}
}

impl pgwire::types::ToSqlText for OurDateTime {
fn to_sql_text(
&self,
ty: &pgwire::api::Type,
out: &mut bytes::BytesMut,
_format_options: &pgwire::types::format::FormatOptions,
) -> Result<postgres_types::IsNull, Box<dyn std::error::Error + Sync + Send>> {
assert!(
matches!(ty, &pgwire::api::Type::TIMESTAMP),
"this is the only timestamp type corro-pg uses"
);

use bytes::BufMut;
self.0.format_into(&mut out.writer(), fmt_desc())?;
Ok(postgres_types::IsNull::No)
}
}

impl rusqlite::types::FromSql for OurDateTime {
fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult<Self> {
PlainDateTime::column_result(value).map(Self)
}
}

impl postgres_types::ToSql for OurDateTime {
fn to_sql(
&self,
ty: &postgres_types::Type,
out: &mut bytes::BytesMut,
) -> Result<postgres_types::IsNull, Box<dyn std::error::Error + Sync + Send>>
where
Self: Sized,
{
self.0.to_sql(ty, out)
}

fn to_sql_checked(
&self,
ty: &postgres_types::Type,
out: &mut bytes::BytesMut,
) -> Result<postgres_types::IsNull, Box<dyn std::error::Error + Sync + Send>> {
self.0.to_sql_checked(ty, out)
}

fn accepts(ty: &postgres_types::Type) -> bool
where
Self: Sized,
{
PlainDateTime::accepts(ty)
}
}
32 changes: 20 additions & 12 deletions crates/corro-pg/tests/tests.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::time::{Duration, Instant};

use camino::Utf8PathBuf;
use chrono::{DateTime, NaiveDateTime, Utc};
use corro_pg::{start, PgServer};
use corro_tests::{launch_test_agent, TestAgent};
use corro_types::{
Expand All @@ -14,6 +13,7 @@ use rcgen::Certificate;
use rustls::pki_types::pem::PemObject;
use spawn::wait_for_all_pending_handles;
use tempfile::TempDir;
use time::PlainDateTime;
use tokio_postgres::NoTls;
use tokio_postgres_rustls::MakeRustlsConnect;
use tripwire::Tripwire;
Expand Down Expand Up @@ -720,42 +720,50 @@ async fn test_pg() {
println!("t.text: {:?}", row.try_get::<_, String>(1));
println!("t2text: {:?}", row.try_get::<_, String>(2));

let now: DateTime<Utc> = Utc::now();
fn plain_now() -> PlainDateTime {
// time wants you to "transmute" this to a PlainDateTime since internally it's already that, but that would
// require unsafe and would completely break if the layout changed in the future
let n = time::UtcDateTime::now();

PlainDateTime::new(n.date(), n.time())
}

let now = plain_now();
println!("NOW: {now:?}");

let row = client
.query_one(
"INSERT INTO kitchensink (other_ts, id, updated_at) VALUES (?1, ?2, ?1) RETURNING updated_at",
&[&now.naive_utc(), &1i64],
&[&now, &1i64],
)
.await.unwrap();

println!("ROW: {row:?}");
let updated_at = row.try_get::<_, NaiveDateTime>(0).unwrap();
let updated_at = row.try_get::<_, PlainDateTime>(0).unwrap();
println!("updated_at: {updated_at:?}");

assert_eq!(
now.timestamp_micros(),
updated_at.and_utc().timestamp_micros()
now.as_utc().unix_timestamp(),
updated_at.as_utc().unix_timestamp()
);

let future: DateTime<Utc> = Utc::now() + Duration::from_secs(1);
let future = plain_now() + Duration::from_secs(1);
println!("NOW: {future:?}");

let row = client
.query_one(
"UPDATE kitchensink SET other_ts = $ts, updated_at = $ts WHERE id = $id AND updated_at > ? RETURNING updated_at",
&[&future.naive_utc(), &1i64, &(now - Duration::from_secs(1)).naive_utc()],
&[&future, &1i64, &(now - Duration::from_secs(1))],
)
.await.unwrap();

println!("ROW: {row:?}");
let updated_at = row.try_get::<_, NaiveDateTime>(0).unwrap();
let updated_at = row.try_get::<_, PlainDateTime>(0).unwrap();
println!("updated_at: {updated_at:?}");

assert_eq!(
future.timestamp_micros(),
updated_at.and_utc().timestamp_micros()
future.as_utc().unix_timestamp(),
updated_at.as_utc().unix_timestamp()
);

let row = client
Expand Down Expand Up @@ -1982,7 +1990,7 @@ async fn test_unnest_vtab() {
let joiner = [1i64, 2];
let rows = client
.query(
"SELECT t.id, t.text, CAST(u.value0 AS int) FROM tests t
"SELECT t.id, t.text, CAST(u.value0 AS int) FROM tests t
JOIN unnest(CAST($1 AS int[])) u ON t.id = u.value0",
&[&joiner],
)
Expand Down
Loading