diff --git a/Cargo.lock b/Cargo.lock index 87864a7b4..4ed49f0be 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1050,7 +1050,6 @@ version = "0.1.0" dependencies = [ "bytes", "camino", - "chrono", "compact_str 0.7.1", "corro-tests", "corro-types", @@ -1075,6 +1074,7 @@ dependencies = [ "sqlparser", "tempfile", "thiserror 1.0.69", + "time", "tokio", "tokio-postgres", "tokio-postgres-rustls", @@ -2848,7 +2848,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "07033963ba89ebaf1584d767badaa2e8fcec21aedea6b8c0346d487d49c28667" dependencies = [ "cfg-if", - "windows-targets 0.48.5", + "windows-targets 0.53.3", ] [[package]] @@ -3589,7 +3589,6 @@ dependencies = [ "async-trait", "base64 0.22.1", "bytes", - "chrono", "derive-new", "futures", "hex", @@ -3789,7 +3788,6 @@ checksum = "851ca9db4932932d69f3ea811b1abe63087a0f740a47692619dd40d4899b68be" dependencies = [ "array-init", "bytes", - "chrono", "fallible-iterator 0.2.0", "postgres-protocol", "time", @@ -4431,7 +4429,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da9bba6f3506135e120a6586df05be18b48d18896600646a4bec8f993d91a594" dependencies = [ "bitflags 2.13.2", - "chrono", "fallible-iterator 0.3.0", "fallible-streaming-iterator", "hashlink", @@ -4714,14 +4711,15 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.143" +version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d401abef1d108fbd9cbaebc3e46611f4b1021f714a0597a71f41ee463f5f4a5a" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ "itoa", "memchr", - "ryu", "serde", + "serde_core", + "zmij", ] [[package]] @@ -6303,7 +6301,7 @@ version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0978bf7171b3d90bac376700cb56d606feb40f251a475a5d6634613564460b22" dependencies = [ - "windows-sys 0.48.0", + "windows-sys 0.60.2", ] [[package]] @@ -6977,6 +6975,12 @@ dependencies = [ "syn 2.0.106", ] +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + [[package]] name = "zstd" version = "0.13.3" diff --git a/Cargo.toml b/Cargo.toml index e76adc972..422bf0b99 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -67,11 +67,25 @@ 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" } @@ -79,7 +93,7 @@ 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"] } diff --git a/crates/corro-pg/Cargo.toml b/crates/corro-pg/Cargo.toml index 663c7eba2..a394326fe 100644 --- a/crates/corro-pg/Cargo.toml +++ b/crates/corro-pg/Cargo.toml @@ -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 } @@ -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" diff --git a/crates/corro-pg/src/lib.rs b/crates/corro-pg/src/lib.rs index c0eaefe68..f8d80c4dc 100644 --- a/crates/corro-pg/src/lib.rs +++ b/crates/corro-pg/src/lib.rs @@ -1,6 +1,7 @@ mod codec; pub mod sql_state; mod ssl; +mod time; pub mod utils; mod vtab; @@ -20,7 +21,6 @@ use std::{ time::Duration, }; -use chrono::NaiveDateTime; use compact_str::CompactString; use corro_types::{ agent::{Agent, BookieWriteGuard, ChangeError}, @@ -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)?; } @@ -4323,7 +4310,7 @@ impl<'conn> Session<'conn> { t @ &Type::TIMESTAMP => { encoder .encode_field_with_type_and_format( - &row.get::<_, Option>(idx)?, + &row.get::<_, Option>(idx)?, t, format, format_opts, diff --git a/crates/corro-pg/src/time.rs b/crates/corro-pg/src/time.rs new file mode 100644 index 000000000..24f4dc9c0 --- /dev/null +++ b/crates/corro-pg/src/time.rs @@ -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> { + 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::::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> { + 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 { + 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> + where + Self: Sized, + { + self.0.to_sql(ty, out) + } + + fn to_sql_checked( + &self, + ty: &postgres_types::Type, + out: &mut bytes::BytesMut, + ) -> Result> { + self.0.to_sql_checked(ty, out) + } + + fn accepts(ty: &postgres_types::Type) -> bool + where + Self: Sized, + { + PlainDateTime::accepts(ty) + } +} diff --git a/crates/corro-pg/tests/tests.rs b/crates/corro-pg/tests/tests.rs index ede6528c8..62b9ace3c 100644 --- a/crates/corro-pg/tests/tests.rs +++ b/crates/corro-pg/tests/tests.rs @@ -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::{ @@ -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; @@ -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::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::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 @@ -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], ) diff --git a/crates/corro-types/Cargo.toml b/crates/corro-types/Cargo.toml index 0910010ae..f439f0434 100644 --- a/crates/corro-types/Cargo.toml +++ b/crates/corro-types/Cargo.toml @@ -21,7 +21,7 @@ config = { workspace = true } consul-client = { version = "0.2.0-alpha.0", path = "../consul-client" } corro-api-types = { version = "0.2.0-alpha.0", path = "../corro-api-types" } corro-base-types = { version = "0.1.0-alpha.1", path = "../corro-base-types" } -corro-utils = { path = "../corro-utils"} +corro-utils = { path = "../corro-utils" } deadpool = { workspace = true } papaya = { workspace = true } enquote = { workspace = true } diff --git a/crates/corro-types/src/lib.rs b/crates/corro-types/src/lib.rs index 6d623101f..7828661d9 100644 --- a/crates/corro-types/src/lib.rs +++ b/crates/corro-types/src/lib.rs @@ -1,4 +1,5 @@ #![allow(clippy::manual_slice_size_calculation, clippy::collapsible_match)] + pub mod actor; pub mod agent; pub mod api;