diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e41a66dc..04027a95 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -60,6 +60,8 @@ jobs: run: cargo test --no-default-features - name: Run tests without tls run: cargo test --no-default-features --features server-api + - name: Run tests with optional date and time types + run: cargo test --lib --no-default-features --features server-api,pg-type-chrono,pg-type-jiff - name: Run tests on additional ring feature set run: cargo test --no-default-features --features server-api-ring - name: Run tests for client api diff --git a/CHANGELOG.md b/CHANGELOG.md index def981b0..403a1e3c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,17 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added + +- Add optional Jiff 1.0 support for PostgreSQL date and time types via `pg-type-jiff`. + +### Changed + +- Chrono type support is no longer enabled by default. Enable `pg-type-chrono` + to keep using Chrono types with pgwire. + ## [0.42.3] - 2026-11-13 ### Fixed diff --git a/Cargo.toml b/Cargo.toml index 8def4ae5..81e23148 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -51,6 +51,7 @@ reqwest = { version = "0.13", features = ["json", "rustls-no-provider"], optiona ## types postgres-types = { version = "0.2", features = ["array-impls"], optional = true } chrono = { version = "0.4", features = ["std"], optional = true } +jiff = { version = "1.0", default-features = false, features = ["std"], optional = true } rust_decimal = { version = "1.35", features = ["db-postgres"], optional = true } serde = { version = "1", optional = true } serde_json = { version = "1", optional = true } @@ -64,7 +65,7 @@ percent-encoding = { version = "2.0", optional = true } [features] default = ["server-api-aws-lc-rs", "pg-ext-types"] -pg-ext-types = ["pg-type-chrono", "pg-type-rust-decimal", "pg-type-serde-json"] +pg-ext-types = ["pg-type-rust-decimal", "pg-type-serde-json"] _ring = [ "dep:ring", "tokio-rustls/ring", @@ -114,6 +115,7 @@ client-api = [ client-api-ring = ["client-api", "_ring", "dep:rustls-pki-types"] client-api-aws-lc-rs = ["client-api", "_aws-lc-rs", "dep:rustls-pki-types"] pg-type-chrono = ["dep:chrono", "postgres-types/with-chrono-0_4"] +pg-type-jiff = ["dep:jiff", "postgres-types/with-jiff-1"] pg-type-rust-decimal = ["dep:rust_decimal"] pg-type-serde-json = ["dep:serde", "dep:serde_json", "postgres-types/with-serde_json-1"] pg-type-postgis = ["dep:postgis"] @@ -147,6 +149,10 @@ reqwest = { version = "0.13", features = ["json"] } [patch.crates-io] pgwire = { path = "." } +# Temporary until postgres-types releases with-jiff-1 (rust-postgres PR #1405). +# Patch the shared dependency so rust_decimal and pgwire use the same SQL traits. +postgres-types = { git = "https://github.com/rust-postgres/rust-postgres.git", rev = "7fbb21a61df820dc4f8d317b8d794f1982436ef5" } + [workspace] members = [ ".", @@ -169,7 +175,7 @@ required-features = ["server-api-aws-lc-rs"] [[example]] name = "gluesql" -required-features = ["server-api-aws-lc-rs"] +required-features = ["server-api-aws-lc-rs", "pg-type-chrono"] [[example]] name = "sqlite" diff --git a/README.md b/README.md index b78fdc47..fa6b8bd9 100644 --- a/README.md +++ b/README.md @@ -137,7 +137,7 @@ Examples are provided to demo the very basic usage of `pgwire` on server side: [pgwire-duckdb](https://github.com/sunng87/pgwire-duckdb) - `examples/gluesql.rs`: uses an in-memory [gluesql](https://github.com/gluesql/gluesql) at its core and serves - it with postgresql protocol. + it with postgresql protocol. `cargo run --features pg-type-chrono --example gluesql` - `examples/server.rs`: demos a server that always returns fixed results. - `examples/secure_server.rs`: demos a server with ssl support and always returns fixed results. diff --git a/src/lib.rs b/src/lib.rs index da64c9c2..21b16eb2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -91,9 +91,19 @@ //! //! Data types: //! -//! - `pg-ext-types` *(enabled by default)*: enables `chrono`, `rust_decimal` -//! and `serde_json` type support. The finer-grained `pg-type-*` features -//! (including `pg-type-postgis`) allow individual control. +//! - `pg-ext-types` *(enabled by default)*: enables `pg-type-rust-decimal` and +//! `pg-type-serde-json`. +//! - `pg-type-chrono`: enables Chrono 0.4 type support. Enable it explicitly +//! if you use Chrono values with pgwire. +//! - `pg-type-jiff`: enables Jiff 1.0 text and binary support for `civil::Date` +//! (`DATE`), `civil::Time` (`TIME`), `civil::DateTime` (`TIMESTAMP`), and +//! `Timestamp` (`TIMESTAMPTZ`). Text `TIMESTAMPTZ` output uses UTC; input +//! accepts numeric offsets and UTC, not other time zone abbreviations. +//! - `pg-type-postgis`: enables PostGIS geometry type support. +//! +//! Until `postgres-types` releases Jiff 1.0 support, projects depending on +//! this development branch must copy its `postgres-types` patch into their +//! workspace root manifest. //! //! Other: //! diff --git a/src/types/from_sql_text.rs b/src/types/from_sql_text.rs index f99ffab9..004c4e95 100644 --- a/src/types/from_sql_text.rs +++ b/src/types/from_sql_text.rs @@ -586,6 +586,7 @@ mod tests { #[cfg(feature = "pg-type-chrono")] use chrono::TimeZone; + #[cfg(feature = "pg-type-chrono")] macro_rules! test_parse_naive_date { ($sql_text:expr, $expected:expr) => { let result = @@ -595,6 +596,7 @@ mod tests { }; } + #[cfg(feature = "pg-type-chrono")] macro_rules! test_parse_naive_datetime { ($sql_text:expr, $expected:expr) => { let result = NaiveDateTime::from_sql_text( @@ -607,6 +609,7 @@ mod tests { }; } + #[cfg(feature = "pg-type-chrono")] macro_rules! test_parse_datetime_fixed_offset { ($sql_text:expr, $expected:expr) => { let result = DateTime::::from_sql_text( diff --git a/src/types/jiff.rs b/src/types/jiff.rs new file mode 100644 index 00000000..b61f3aa1 --- /dev/null +++ b/src/types/jiff.rs @@ -0,0 +1,172 @@ +use std::error::Error; + +use bytes::BytesMut; +use jiff::{ + Timestamp, + civil::{Date, DateTime, Time}, + fmt::strtime::{self, BrokenDownTime}, + tz::{Offset, TimeZone}, +}; +use postgres_types::{IsNull, Type, WrongType}; + +use super::{FromSqlText, ToSqlText, format::FormatOptions, format::date_style::DateStyle}; + +// PostgreSQL has microsecond precision. Use the same text precision as Chrono. +const TIME_FORMAT: &str = "%H:%M:%S%.6f"; + +macro_rules! impl_jiff_text { + ($rust:ty, $pg:ident, $array:ident, $parse:expr, $format:expr) => { + impl<'a> FromSqlText<'a> for $rust { + fn from_sql_text( + _ty: &Type, + input: &'a [u8], + options: &FormatOptions, + ) -> Result> { + let parse: fn(&str, &FormatOptions) -> Result = $parse; + Ok(parse(std::str::from_utf8(input)?, options)?) + } + } + + impl ToSqlText for $rust { + fn to_sql_text( + &self, + ty: &Type, + out: &mut BytesMut, + options: &FormatOptions, + ) -> Result> { + if !matches!(*ty, Type::$pg | Type::$array) { + return Err(Box::new(WrongType::new::(ty.clone()))); + } + let format: fn(&Self, &FormatOptions) -> Result = $format; + out.extend_from_slice(format(self, options)?.as_bytes()); + Ok(IsNull::No) + } + } + }; +} + +impl_jiff_text!( + Date, + DATE, + DATE_ARRAY, + |input, options| input + .parse() + .or_else(|_| Date::strptime(DateStyle::new(&options.date_style).date_format_str(), input)), + |date, options| strtime::format(DateStyle::new(&options.date_style).date_format_str(), *date) +); + +impl_jiff_text!( + Time, + TIME, + TIME_ARRAY, + |input, _| input.parse(), + |time, _| strtime::format(TIME_FORMAT, *time) +); + +impl_jiff_text!( + DateTime, + TIMESTAMP, + TIMESTAMP_ARRAY, + |input, options| input.parse().or_else(|_| DateTime::strptime( + DateStyle::new(&options.date_style).full_format_str(), + input + )), + |datetime, options| strtime::format( + DateStyle::new(&options.date_style).full_format_str(), + *datetime + ) +); + +impl_jiff_text!( + Timestamp, + TIMESTAMPTZ, + TIMESTAMPTZ_ARRAY, + parse_timestamp, + |timestamp, options| strtime::format( + DateStyle::new(&options.date_style).full_tz_format_str(), + ×tamp.to_zoned_datetime(TimeZone::UTC) + ) +); + +fn parse_timestamp(input: &str, options: &FormatOptions) -> Result { + // PostgreSQL's ISO format uses numeric offsets, which Jiff parses directly. + input.parse().or_else(|_| { + let style = DateStyle::new(&options.date_style); + let format = style.full_format_str(); + // Non-ISO DateStyles can end in a zone abbreviation. Support UTC + // (the output of our encoder), but don't guess at other abbreviations. + if let Some(datetime) = input.strip_suffix(" UTC") { + let mut parsed = BrokenDownTime::parse(format, datetime)?; + parsed.set_offset(Some(Offset::UTC)); + parsed.to_timestamp() + } else { + Timestamp::strptime(format!("{format} %:::z"), input) + } + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use postgres_types::{FromSql, ToSql}; + + fn roundtrip(ty: &Type, value: T, options: &FormatOptions) + where + T: for<'a> FromSqlText<'a> + ToSqlText + for<'a> FromSql<'a> + ToSql + PartialEq, + { + let mut text = BytesMut::new(); + value.to_sql_text(ty, &mut text, options).unwrap(); + assert_eq!(T::from_sql_text(ty, &text, options).unwrap(), value); + + let mut binary = BytesMut::new(); + value.to_sql_checked(ty, &mut binary).unwrap(); + assert_eq!(T::from_sql(ty, &binary).unwrap(), value); + } + + #[test] + fn text_and_binary_roundtrips() { + let date: Date = "1969-07-20".parse().unwrap(); + let time: Time = "20:17:40.123456".parse().unwrap(); + let datetime: DateTime = "1969-07-20 20:17:40.123456".parse().unwrap(); + let timestamp: Timestamp = "1969-07-20 21:17:40.123456+01".parse().unwrap(); + + for style in ["ISO", "SQL, DMY", "German", "Postgres, MDY"] { + let options = FormatOptions { + date_style: style.into(), + ..FormatOptions::default() + }; + roundtrip(&Type::DATE, date, &options); + roundtrip(&Type::TIME, time, &options); + roundtrip(&Type::TIMESTAMP, datetime, &options); + roundtrip(&Type::TIMESTAMPTZ, timestamp, &options); + roundtrip( + &Type::TIMESTAMPTZ_ARRAY, + vec![Some(timestamp), None], + &options, + ); + } + } + + #[test] + fn parses_postgres_iso_timestamp_with_offset() { + let options = FormatOptions::default(); + let timestamp = Timestamp::from_sql_text( + &Type::TIMESTAMPTZ, + b"2026-03-01 10:00:00.123456+05:30", + &options, + ) + .unwrap(); + assert_eq!(timestamp, "2026-03-01T04:30:00.123456Z".parse().unwrap()); + + let mut out = BytesMut::new(); + timestamp + .to_sql_text(&Type::TIMESTAMPTZ, &mut out, &options) + .unwrap(); + assert_eq!(&out[..], b"2026-03-01 04:30:00.123456+00"); + assert!( + timestamp + .to_sql_text(&Type::DATE, &mut out, &options) + .is_err() + ); + } +} diff --git a/src/types/mod.rs b/src/types/mod.rs index 35e84f50..83bd58ca 100644 --- a/src/types/mod.rs +++ b/src/types/mod.rs @@ -1,6 +1,8 @@ /// PostgreSQL text format configuration and helpers. pub mod format; mod from_sql_text; +#[cfg(feature = "pg-type-jiff")] +mod jiff; /// PostGIS geometry type text serialization support. #[cfg(feature = "pg-type-postgis")] pub mod postgis; diff --git a/tests-integration/test-server/Cargo.toml b/tests-integration/test-server/Cargo.toml index dac910da..fa65aff6 100644 --- a/tests-integration/test-server/Cargo.toml +++ b/tests-integration/test-server/Cargo.toml @@ -7,7 +7,7 @@ publish = false # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -pgwire = { path = "../../" } +pgwire = { path = "../../", features = ["pg-type-chrono"] } async-trait = "0.1" chrono = "0.4" futures = "0.3"