From bddc18a86a2daa5cfc78120292ff7dace9a08616 Mon Sep 17 00:00:00 2001 From: Adam J Esslinger Date: Wed, 2 Dec 2026 13:45:07 -0500 Subject: [PATCH 1/3] fix: array lossless extraction, interval, bit(n), JSON round-trip, BC dates (#222) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up to #220/#221 — host-side audit found arrays, intervals, bit(n), JSON round-trips, and BC dates still broken. All fixed: Arrays (issue #222 section 1-2): - Override Kind::Array in extract_value_lossless to route through ArrayValue::from_sql with lossless byte-level element decoders. FLOAT4/FLOAT8 NaN/Infinity, DATE/TIMESTAMP/TIMESTAMPTZ infinity, TIME 24:00:00, NUMERIC wide values, MONEY text, INTERVAL non-normalization, JSON text — all now lossless inside arrays. - Add CAST wrapper for Value::Array when column type is known: CAST(ARRAY[...] AS timestamptz[]) instead of bare ARRAY[...]. Fixes timestamptz[], uuid[], numeric[], date[] insert failures. - Multi-dim arrays fall back to display path (documented limitation). Interval (section 2): - Interval::from_sql no longer normalizes months > 11 to years or hours > 23 to days. Formats as PostgreSQL's interval_out: raw months ("N mons"), days ("N days"), time ("HH:MM:SS.ffffff"). 48 hours stays "48:00:00" (was "2 days"). bit(n) (section 3): - Add char_max_len to BindOptions and ColumnTypeInfo. When base_type is BIT/VARBIT with char_max_len, emit CAST($N AS bit(n)) instead of CAST($N AS bit) (which defaults to bit(1)). JSON/JSONB round-trip (section 4): - extract_simple_kind_lossless returns JsonValue::String(v.to_string()) for JSON/JSONB — serialized JSON text, not bare serde_json::Value. jsonb '"hello"' → "\"hello\"" (round-trips as a JSON string). jsonb 'null' → "null" (distinguishable from SQL NULL). BC dates (section 3): - format_date_with_bc: astronomical year < 0 emits "0044-03-15 BC" (PostgreSQL format) instead of "-0043-03-15" (ISO 8601). Years > 9999 emit without "+" prefix (PostgreSQL doesn't accept it). Trailing -- comment (section 5): - strip_trailing_line_comment: strips trailing -- comment before semicolon trim on the session/cursor path. "select 1 -- c" no longer breaks DECLARE. GUC leak (section 5): - run_one_shot runs RESET ALL after COMMIT/ROLLBACK to clear session-level GUCs set during the transaction. Identity columns (section 5): - is_generated now checks attgenerated <> '' OR attidentity IN ('a', 'd'), catching GENERATED ALWAYS AS IDENTITY columns. ColumnTypeInfo (all): - get_column_types_map returns ColumnTypeInfo { type_name, char_max_len } instead of bare String. Updated all callers (crud.rs, copy.rs, blob.rs). Co-Authored-By: Adam J Esslinger --- src/binding.rs | 44 +++- src/binding_tests.rs | 190 ++++++++++++++++++ src/client.rs | 30 ++- src/extract.rs | 272 +++++++++++++++---------- src/extract_tests.rs | 420 ++++++++++++++++++++++++++++++++++++++- src/handlers/blob.rs | 8 +- src/handlers/copy.rs | 34 +++- src/handlers/crud.rs | 25 ++- src/handlers/metadata.rs | 8 +- 9 files changed, 908 insertions(+), 123 deletions(-) diff --git a/src/binding.rs b/src/binding.rs index 5a9089b..2fb91ae 100644 --- a/src/binding.rs +++ b/src/binding.rs @@ -49,6 +49,11 @@ pub struct BindOptions<'a> { /// OID and varies per installation. `None` when the column isn't /// hstore, or resolution failed (surfaced as an error at bind time). pub hstore_oid: Option, + /// `character_maximum_length` of the target column, used to construct the + /// correct `bit(n)` / `varbit(n)` CAST when the column type is `bit` or + /// `varbit` and the value needs an explicit cast (#222). `None` when the + /// column isn't a fixed-length bit type or the length wasn't discovered. + pub char_max_len: Option, } const USE_DEFAULT_SENTINEL: &str = "__USE_DEFAULT__"; @@ -197,10 +202,17 @@ pub fn bind_pg_value( }), Value::Array(arr) => { let literal = json_array_to_pg_literal(&arr)?; - Ok(BoundValue { - sql: literal, - param: None, - }) + let sql = if let Some(bt) = base_type.as_deref() { + if let Some(elem) = bt.strip_prefix('_') { + let cast_type = format!("{}[]", elem.to_lowercase()); + format!("CAST({literal} AS {cast_type})") + } else { + literal + } + } else { + literal + }; + Ok(BoundValue { sql, param: None }) } Value::Object(_) => Err("Cannot bind a JSON object to a non-JSON column".to_string()), } @@ -325,6 +337,30 @@ fn bind_pg_string( } } + // 3.4. bit(n) / varbit(n) — the explicit CAST must include the length: + // `CAST($N AS bit)` defaults to `bit(1)`, truncating a wider value + // silently (#222). When `char_max_len` is known, emit + // `CAST($N AS bit(n))` / `CAST($N AS varbit(n))` instead. Falls through + // to the generic CAST (step 3.5) when the length is unknown. + if let Some(bt) = base_type { + let is_bit = bt == "BIT" || bt == "VARBIT" || bt == "BIT VARYING"; + if is_bit { + if let Some(len) = options.char_max_len { + if len > 0 { + let cast_type = if bt == "BIT" { + format!("bit({len})") + } else { + format!("varbit({len})") + }; + return Ok(BoundValue { + sql: format!("CAST(${placeholder_idx} AS {cast_type})"), + param: Some((Box::new(s.to_string()), Type::TEXT)), + }); + } + } + } + } + // 3.5. Column types that need an explicit CAST (no text→type assignment // cast). Must run before the BLOB decoder (step 3) and the TEXT fallback // (step 12) — both would bind as TEXT, which PostgreSQL rejects for diff --git a/src/binding_tests.rs b/src/binding_tests.rs index 12c1e01..cb45a0f 100644 --- a/src/binding_tests.rs +++ b/src/binding_tests.rs @@ -85,6 +85,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: None, + char_max_len: None, }; let bound = bind_pg_value(json!({"a": 1}), 1, &options).unwrap(); assert_eq!(bound.sql, "$1"); @@ -103,6 +104,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: None, + char_max_len: None, }; let bound = bind_pg_value(json!("{\"a\":1}"), 1, &options).unwrap(); assert_eq!(bound.sql, "CAST($1 AS jsonb)"); @@ -118,6 +120,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: None, + char_max_len: None, }; let bound = bind_pg_value(json!("\"hello\""), 1, &options).unwrap(); assert_eq!(bound.sql, "CAST($1 AS json)"); @@ -132,6 +135,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: true, hstore_oid: None, + char_max_len: None, }; let bound = bind_pg_value(json!("__USE_DEFAULT__"), 1, &options).unwrap(); assert_eq!(bound.sql, "DEFAULT"); @@ -145,6 +149,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: None, + char_max_len: None, }; let bound = bind_pg_value(json!("__USE_DEFAULT__"), 1, &options).unwrap(); // Falls through to the plain TEXT fallback, not treated as DEFAULT. @@ -171,6 +176,7 @@ mod bind_pg_value_tests { enum_type: Some("\"test_schema\".\"mood\""), allow_default: false, hstore_oid: None, + char_max_len: None, }; let bound = bind_pg_value(json!("sad"), 1, &options).unwrap(); assert_eq!(bound.sql, "CAST($1 AS \"test_schema\".\"mood\")"); @@ -187,6 +193,7 @@ mod bind_pg_value_tests { enum_type: Some("\"public\".\"status\""), allow_default: false, hstore_oid: None, + char_max_len: None, }; let bound = bind_pg_value(json!("a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"), 1, &options).unwrap(); @@ -200,6 +207,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: None, + char_max_len: None, }; for truthy in ["true", "t", "yes", "y", "on", "1", "TRUE"] { let bound = bind_pg_value(json!(truthy), 1, &options).unwrap(); @@ -214,6 +222,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: None, + char_max_len: None, }; let err = bind_pg_value(json!("maybe"), 1, &options).unwrap_err(); assert!(err.contains("boolean")); @@ -226,6 +235,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: None, + char_max_len: None, }; let bound = bind_pg_value(json!("42"), 1, &options).unwrap(); assert_eq!(bound.sql, "CAST($1 AS bigint)"); @@ -238,6 +248,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: None, + char_max_len: None, }; let err = bind_pg_value(json!("not-a-number"), 1, &options).unwrap_err(); assert!(err.contains("integer")); @@ -250,6 +261,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: None, + char_max_len: None, }; let bound = bind_pg_value(json!("12345.67"), 1, &options).unwrap(); assert_eq!(bound.sql, "CAST($1 AS numeric)"); @@ -266,6 +278,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: None, + char_max_len: None, }; let wide = "12345678901234567890123456789012345678.1234567890"; let bound = bind_pg_value(json!(wide), 1, &options).unwrap(); @@ -284,6 +297,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: None, + char_max_len: None, }; let bound = bind_pg_value(json!("NaN"), 1, &options).unwrap(); assert_eq!(bound.sql, "CAST($1 AS numeric)"); @@ -299,6 +313,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: None, + char_max_len: None, }; let bound = bind_pg_value(json!("99999999999999999999999999999999999999"), 1, &options).unwrap(); @@ -317,6 +332,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: None, + char_max_len: None, }; assert!(bind_pg_value(json!("abc"), 1, &options).is_err()); assert!(bind_pg_value(json!("1.2.3"), 1, &options).is_err()); @@ -332,6 +348,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: None, + char_max_len: None, }; // Exponent form. assert!(bind_pg_value(json!("1e10"), 1, &options).is_ok()); @@ -349,6 +366,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: None, + char_max_len: None, }; let bound = bind_pg_value(json!("2026-01-15 14:30:00"), 1, &options).unwrap(); assert_eq!(bound.sql, "CAST($1 AS timestamp)"); @@ -361,6 +379,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: None, + char_max_len: None, }; let bound = bind_pg_value(json!("2026-01-15 14:30:00+00"), 1, &options).unwrap(); assert_eq!(bound.sql, "CAST($1 AS timestamptz)"); @@ -407,6 +426,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: Some(16_500), + char_max_len: None, }; let bound = bind_pg_value(json!({"key": "value", "other": "thing"}), 1, &options).unwrap(); @@ -423,6 +443,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: Some(16_500), + char_max_len: None, }; let bound = bind_pg_value(json!({"key": null}), 1, &options).unwrap(); @@ -437,6 +458,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: Some(16_500), + char_max_len: None, }; let bound = bind_pg_value(Value::Null, 1, &options).unwrap(); @@ -453,6 +475,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: Some(16_500), + char_max_len: None, }; let bound = bind_pg_value(json!("{\"key\": \"value\"}"), 1, &options).unwrap(); @@ -467,6 +490,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: Some(16_500), + char_max_len: None, }; let err = bind_pg_value(json!({"key": 42}), 1, &options).unwrap_err(); @@ -481,6 +505,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: Some(16_500), + char_max_len: None, }; let err = bind_pg_value(json!(42), 1, &options).unwrap_err(); @@ -494,6 +519,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: None, + char_max_len: None, }; let err = bind_pg_value(json!({"key": "value"}), 1, &options).unwrap_err(); @@ -507,6 +533,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: None, + char_max_len: None, }; let bound = bind_pg_value(json!("[1,2,3]"), 1, &options).unwrap(); @@ -521,6 +548,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: None, + char_max_len: None, }; let bound = bind_pg_value(json!("[1,2,3]"), 1, &options).unwrap(); @@ -534,6 +562,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: None, + char_max_len: None, }; let bound = bind_pg_value(json!("{1:1,3:2}/5"), 1, &options).unwrap(); @@ -547,6 +576,7 @@ mod bind_pg_value_tests { enum_type: None, allow_default: false, hstore_oid: None, + char_max_len: None, }; let err = bind_pg_value(json!("'; DROP TABLE users; --"), 1, &options).unwrap_err(); @@ -853,6 +883,166 @@ mod bind_pg_value_tests { assert!(!err.contains("secret_value")); assert!(err.contains("float")); } + + // -- #222: Value::Array wrapped in CAST for known array column types -- + + #[test] + fn array_value_wraps_in_cast_when_column_type_is_timestamptz_array() { + let options = BindOptions { + column_type: Some("_timestamptz"), + ..Default::default() + }; + let bound = bind_pg_value( + json!(["2026-01-15 14:30:00+00", "2026-01-16 08:00:00+00"]), + 1, + &options, + ) + .unwrap(); + assert_eq!( + bound.sql, + "CAST(ARRAY['2026-01-15 14:30:00+00', '2026-01-16 08:00:00+00'] AS timestamptz[])" + ); + assert!(bound.param.is_none()); + } + + #[test] + fn array_value_wraps_in_cast_when_column_type_is_uuid_array() { + let options = BindOptions { + column_type: Some("_uuid"), + ..Default::default() + }; + let bound = + bind_pg_value(json!(["a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"]), 1, &options).unwrap(); + assert_eq!( + bound.sql, + "CAST(ARRAY['a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11'] AS uuid[])" + ); + } + + #[test] + fn array_value_wraps_in_cast_when_column_type_is_numeric_array() { + let options = BindOptions { + column_type: Some("_numeric"), + ..Default::default() + }; + let bound = bind_pg_value(json!([1, 2, 3]), 1, &options).unwrap(); + assert_eq!(bound.sql, "CAST(ARRAY[1, 2, 3] AS numeric[])"); + } + + #[test] + fn array_value_wraps_in_cast_when_column_type_is_int4_array() { + let options = BindOptions { + column_type: Some("_int4"), + ..Default::default() + }; + let bound = bind_pg_value(json!([1, 2, 3]), 1, &options).unwrap(); + assert_eq!(bound.sql, "CAST(ARRAY[1, 2, 3] AS int4[])"); + } + + #[test] + fn array_value_wraps_in_cast_when_column_type_is_text_array() { + let options = BindOptions { + column_type: Some("_text"), + ..Default::default() + }; + let bound = bind_pg_value(json!(["a", "b"]), 1, &options).unwrap(); + assert_eq!(bound.sql, "CAST(ARRAY['a', 'b'] AS text[])"); + } + + #[test] + fn array_value_no_cast_when_column_type_is_unknown() { + let bound = bind_pg_value(json!([1, 2, 3]), 1, &BindOptions::default()).unwrap(); + assert_eq!(bound.sql, "ARRAY[1, 2, 3]"); + assert!(bound.param.is_none()); + } + + #[test] + fn array_value_no_cast_when_column_type_is_not_an_array() { + let options = BindOptions { + column_type: Some("text"), + ..Default::default() + }; + let bound = bind_pg_value(json!([1, 2, 3]), 1, &options).unwrap(); + assert_eq!(bound.sql, "ARRAY[1, 2, 3]"); + } + + #[test] + fn empty_array_value_wraps_in_cast_when_column_type_is_known() { + let options = BindOptions { + column_type: Some("_timestamptz"), + ..Default::default() + }; + let bound = bind_pg_value(json!([]), 1, &options).unwrap(); + assert_eq!(bound.sql, "CAST('{}' AS timestamptz[])"); + } + + #[test] + fn nested_array_value_wraps_in_cast_when_column_type_is_known() { + let options = BindOptions { + column_type: Some("_int4"), + ..Default::default() + }; + let bound = bind_pg_value(json!([[1, 2], [3, 4]]), 1, &options).unwrap(); + assert_eq!(bound.sql, "CAST(ARRAY[ARRAY[1, 2], ARRAY[3, 4]] AS int4[])"); + } + + // -- #222: bit(n) CAST includes the length from char_max_len -- + + #[test] + fn bit_column_with_char_max_len_casts_with_length() { + let options = BindOptions { + column_type: Some("bit"), + char_max_len: Some(5), + ..Default::default() + }; + let bound = bind_pg_value(json!("10101"), 1, &options).unwrap(); + assert_eq!(bound.sql, "CAST($1 AS bit(5))"); + let (_, pg_type) = bound.param.unwrap(); + assert_eq!(pg_type, tokio_postgres::types::Type::TEXT); + } + + #[test] + fn varbit_column_with_char_max_len_casts_with_length() { + let options = BindOptions { + column_type: Some("varbit"), + char_max_len: Some(8), + ..Default::default() + }; + let bound = bind_pg_value(json!("10101"), 1, &options).unwrap(); + assert_eq!(bound.sql, "CAST($1 AS varbit(8))"); + } + + #[test] + fn bit_column_without_char_max_len_falls_back_to_bare_cast() { + let options = BindOptions { + column_type: Some("bit"), + ..Default::default() + }; + let bound = bind_pg_value(json!("1"), 1, &options).unwrap(); + assert_eq!(bound.sql, "CAST($1 AS bit)"); + } + + #[test] + fn bit_column_with_zero_char_max_len_falls_back_to_bare_cast() { + let options = BindOptions { + column_type: Some("bit"), + char_max_len: Some(0), + ..Default::default() + }; + let bound = bind_pg_value(json!("1"), 1, &options).unwrap(); + assert_eq!(bound.sql, "CAST($1 AS bit)"); + } + + #[test] + fn bit_varying_column_with_char_max_len_casts_with_length() { + let options = BindOptions { + column_type: Some("bit varying"), + char_max_len: Some(4), + ..Default::default() + }; + let bound = bind_pg_value(json!("1010"), 1, &options).unwrap(); + assert_eq!(bound.sql, "CAST($1 AS varbit(4))"); + } } mod bind_pk_value_tests { diff --git a/src/client.rs b/src/client.rs index cb88c2a..33600e9 100644 --- a/src/client.rs +++ b/src/client.rs @@ -256,13 +256,26 @@ pub async fn query_typed( .map_err(|e| format_pg_error(&e)) } +/// Per-column type info returned by [`get_column_types_map`]: the resolved +/// type name (same value the old `HashMap` carried) plus the +/// `character_maximum_length` for fixed-length character/bit types, needed +/// to construct the correct `bit(n)` CAST in binding (#222). +#[derive(Clone, Debug, Default)] +pub struct ColumnTypeInfo { + pub type_name: String, + pub char_max_len: Option, +} + /// Fetch data types for every column in a table as a name -> type map. /// Used by insert to resolve type-aware binding for all columns in one query. +/// Also fetches `character_maximum_length` (needed for `bit(n)` CAST in +/// binding -- #222); the length is `None` for columns without a fixed +/// character length. pub async fn get_column_types_map( params: &ConnectionParams, table: &str, schema: &str, -) -> Result, String> { +) -> Result, String> { let query = r#" SELECT column_name, @@ -270,7 +283,8 @@ pub async fn get_column_types_map( WHEN data_type = 'USER-DEFINED' THEN udt_name WHEN data_type = 'ARRAY' THEN udt_name ELSE data_type - END AS resolved_type + END AS resolved_type, + character_maximum_length FROM information_schema.columns WHERE table_schema = $1 AND table_name = $2 "#; @@ -280,7 +294,17 @@ pub async fn get_column_types_map( .filter_map(|r| { let name: String = r.try_get("column_name").ok()?; let ty: String = r.try_get("resolved_type").ok()?; - Some((name, ty)) + let char_max_len: Option = r + .try_get::<_, Option>("character_maximum_length") + .ok() + .flatten(); + Some(( + name, + ColumnTypeInfo { + type_name: ty, + char_max_len, + }, + )) }) .collect()) } diff --git a/src/extract.rs b/src/extract.rs index 4fdc92d..2942853 100644 --- a/src/extract.rs +++ b/src/extract.rs @@ -193,31 +193,35 @@ fn extract_simple_kind(col_type: &Type, row: &Row, index: usize) -> JsonValue { /// Lossless extraction for the table-copy read path (`read_rows`). Parallel to /// [`extract_value`], but the display-lossy scalar types use full-precision /// decoders: FLOAT4/FLOAT8 return NaN/Infinity as text strings (not `null`), -/// DATE/TIMESTAMP/TIMESTAMPTZ return infinity sentinels as text (not `null`), -/// TIME accepts 24:00:00, TIME/TIMESTAMP keep fractional seconds, TIMESTAMPTZ -/// keeps the `+00:00` offset, BYTEA is base64-encoded in full (not the 10 KB -/// preview), NUMERIC is decoded from its base-10000 wire bytes via [`PgNumeric`] -/// (the display path's `rust_decimal::Decimal` is 96-bit and cannot represent -/// wide values or `NaN`), and MONEY is formatted as a decimal text string (not -/// integer cents). All other scalar types delegate to [`extract_simple_kind`] -/// (already lossless: INT, JSON, UUID, BOOL, TEXT, enum, TIMETZ, INTERVAL, -/// etc.). Arrays, ranges, composites, and multiranges delegate to -/// [`extract_value`] — temporal values nested in those stay lossy in this PR -/// (documented limitation; the copy acceptance criteria are all scalar columns). +/// DATE/TIMESTAMP/TIMESTAMPTZ return infinity sentinels as text (not `null`) +/// and emit BC dates in PostgreSQL's `"0043-01-01 BC"` format (not +/// `"-0043-01-01"`), TIME accepts 24:00:00, TIME/TIMESTAMP keep fractional +/// seconds, TIMESTAMPTZ keeps the `+00:00` offset, BYTEA is base64-encoded in +/// full (not the 10 KB preview), NUMERIC is decoded from its base-10000 wire +/// bytes via [`PgNumeric`] (the display path's `rust_decimal::Decimal` is +/// 96-bit and cannot represent wide values or `NaN`), MONEY is formatted as a +/// decimal text string (not integer cents), JSON/JSONB returns serialized +/// JSON text (so `jsonb '"hello"'` round-trips as `"\"hello\""`), and INTERVAL +/// does not normalize months/hours into years/days (matching PostgreSQL's +/// `interval_out`). Arrays delegate to [`extract_array_lossless`], which +/// decodes each element through the lossless byte-level dispatcher. +/// Ranges, composites, and multiranges still delegate to [`extract_value`] +/// — temporal values nested in those stay lossy (documented limitation). pub fn extract_value_lossless(row: &Row, index: usize) -> JsonValue { let col_type = row.columns()[index].type_().clone(); match col_type.kind() { Kind::Simple => extract_simple_kind_lossless(&col_type, row, index), + Kind::Array(_) => extract_array_lossless(&col_type, row, index), // Non-simple kinds delegate to the display path (lossy for temporal - // arrays/ranges/composites — out of scope for PR 1, scalar-only copy). + // ranges/composites — out of scope for this PR, scalar+array-only copy). _ => extract_value(row, index), } } -/// The lossless `Kind::Simple` bucket: overrides nine display-lossy arms -/// (FLOAT4, FLOAT8, DATE, TIME, TIMESTAMP, TIMESTAMPTZ, BYTEA, NUMERIC, MONEY) -/// and delegates the rest to [`extract_simple_kind`]. +/// The lossless `Kind::Simple` bucket: overrides the display-lossy arms +/// (FLOAT4, FLOAT8, DATE, TIME, TIMESTAMP, TIMESTAMPTZ, BYTEA, NUMERIC, MONEY, +/// JSON/JSONB) and delegates the rest to [`extract_simple_kind`]. fn extract_simple_kind_lossless(col_type: &Type, row: &Row, index: usize) -> JsonValue { match *col_type { // FLOAT4: `serde_json::Number::from_f64` rejects NaN/Infinity (JSON has @@ -274,11 +278,51 @@ fn extract_simple_kind_lossless(col_type: &Type, row: &Row, index: usize) -> Jso // (#220 item 3). Matches PostgreSQL's `money_out` format: sign, // dollars, '.', zero-padded 2-digit cents. ref t if *t == Type::MONEY => try_extract::(row, index, JsonValue::from), + // JSON/JSONB: the display path returns the bare `JsonValue` (so + // `jsonb '"hello"'` → `Value::String("hello")` → host receives the + // raw string "hello" without JSON quotes). The lossless path returns + // `v.to_string()` — the serialized JSON text (`"\"hello\""`) — so a + // scalar JSON string round-trips through `insert_records`. + ref t if *t == Type::JSON || *t == Type::JSONB => { + try_extract::(row, index, |v| JsonValue::String(v.to_string())) + } // All other scalar types are already lossless — reuse the display path. _ => extract_simple_kind(col_type, row, index), } } +/// Lossless `Kind::Array(_)` bucket for the table-copy read path. Mirrors +/// [`extract_array_kind`] but every element is decoded through the lossless +/// byte-level dispatcher ([`extract_simple_kind_from_bytes`], which has +/// lossless overrides for FLOAT4/FLOAT8/DATE/TIME/TIMESTAMP/TIMESTAMPTZ/ +/// NUMERIC/MONEY/JSON) instead of the display-path decoders. The eight +/// hardcoded fast-paths in [`extract_array_kind`] use tokio-postgres's +/// `Vec>: FromSql` with display-lossy `T`s (e.g. `f32` → +/// `float4_to_json` turns NaN into `Null`); this function replaces those with +/// [`ArrayValue::from_sql`], which parses the wire format directly and calls +/// the lossless per-element decoder for every element type — so a `float8[]` +/// containing NaN, or a `timestamptz[]` containing infinity, survives the copy +/// the same way a scalar column does. +fn extract_array_lossless(col_type: &Type, row: &Row, index: usize) -> JsonValue { + // Every array type — the eight hardcoded fast-paths and the generic + // fallback alike — goes through `ArrayValue::from_sql`, which parses the + // 1-D array wire format and decodes each element via + // `extract_simple_kind_from_bytes` (now lossless for the display-lossy + // types). Multi-dimensional arrays fall back to the display path (which + // returns null for them — same as the scalar lossless path's infinity + // behavior before this PR; multi-dim lossless is out of scope). + match try_extract::(row, index, |v| v.0) { + JsonValue::Null => { + // `ArrayValue::from_sql` rejects multi-dimensional arrays with an + // error, which `try_extract` turns into `Null`. Try the display + // path as a last resort — it may produce a text representation for + // some multi-dim arrays via the string fallback. + extract_array_kind(col_type, row, index) + } + other => other, + } +} + /// `Kind::Array(_)` bucket: the eight hardcoded fast-paths (checked against /// the outer array `Type::` constant), falling back to the generic per-element /// decoder for any other array element type (e.g. `enum[]`, `hstore[]`). @@ -915,7 +959,7 @@ fn extract_kind_from_bytes(ty: &Type, buf: &[u8]) -> JsonValue { /// as a separate function because every arm here calls `T::from_sql` /// directly against a byte slice rather than `try_extract`'s /// `row.try_get::<_, Option>`. -fn extract_simple_kind_from_bytes(ty: &Type, buf: &[u8]) -> JsonValue { +pub(crate) fn extract_simple_kind_from_bytes(ty: &Type, buf: &[u8]) -> JsonValue { match ty { _ if *ty == Type::BOOL => bool::from_sql(ty, buf) .map(JsonValue::Bool) @@ -927,13 +971,27 @@ fn extract_simple_kind_from_bytes(ty: &Type, buf: &[u8]) -> JsonValue { .map(JsonValue::from) .unwrap_or(JsonValue::Null), _ if *ty == Type::FLOAT4 => f32::from_sql(ty, buf) - .map(float4_to_json) + .map(|v| { + if v.is_nan() { + JsonValue::String("NaN".to_string()) + } else if v.is_infinite() { + JsonValue::String(if v > 0.0 { "Infinity" } else { "-Infinity" }.to_string()) + } else { + float4_to_json(v) + } + }) .unwrap_or(JsonValue::Null), _ if *ty == Type::FLOAT8 => f64::from_sql(ty, buf) .map(|v| { - serde_json::Number::from_f64(v) - .map(JsonValue::Number) - .unwrap_or(JsonValue::Null) + if v.is_nan() { + JsonValue::String("NaN".to_string()) + } else if v.is_infinite() { + JsonValue::String(if v > 0.0 { "Infinity" } else { "-Infinity" }.to_string()) + } else { + serde_json::Number::from_f64(v) + .map(JsonValue::Number) + .unwrap_or(JsonValue::Null) + } }) .unwrap_or(JsonValue::Null), _ if *ty == Type::TEXT @@ -954,9 +1012,9 @@ fn extract_simple_kind_from_bytes(ty: &Type, buf: &[u8]) -> JsonValue { _ if *ty == Type::INTERVAL => Interval::from_sql(ty, buf) .map(JsonValue::from) .unwrap_or(JsonValue::Null), - _ if *ty == Type::JSON || *ty == Type::JSONB => { - serde_json::Value::from_sql(ty, buf).unwrap_or(JsonValue::Null) - } + _ if *ty == Type::JSON || *ty == Type::JSONB => serde_json::Value::from_sql(ty, buf) + .map(|v| JsonValue::String(v.to_string())) + .unwrap_or(JsonValue::Null), _ if *ty == Type::BYTEA => Vec::::from_sql(ty, buf) .map(|v| JsonValue::String(crate::utils::blob::encode_blob(&v))) .unwrap_or(JsonValue::Null), @@ -1017,7 +1075,7 @@ fn extract_simple_kind_from_bytes(ty: &Type, buf: &[u8]) -> JsonValue { _ if *ty == Type::REGCOLLATION => RegCollation::from_sql(ty, buf) .map(JsonValue::from) .unwrap_or(JsonValue::Null), - _ if *ty == Type::MONEY => Money::from_sql(ty, buf) + _ if *ty == Type::MONEY => PgMoneyText::from_sql(ty, buf) .map(JsonValue::from) .unwrap_or(JsonValue::Null), _ if *ty == Type::POINT => Point::from_sql(ty, buf) @@ -1104,6 +1162,29 @@ fn extract_simple_kind_from_bytes(ty: &Type, buf: &[u8]) -> JsonValue { _ if ty.name() == "hstore" => HashMap::>::from_sql(ty, buf) .map(|v| serde_json::to_value(v).unwrap_or(JsonValue::Null)) .unwrap_or(JsonValue::Null), + // Lossless temporal/numeric overrides for array elements and composite + // fields: the display-path decoders below (`extract_simple_from_bytes`) + // use `PgDate`/`PgTimestamp`/`PgTimestampTz` which reject infinity + // sentinels (→ null) and `Decimal` which can't hold wide NUMERIC. For + // array/composite elements the lossless equivalents are needed so a + // NaN/Infinity, date infinity, or 38-digit numeric inside an array or + // composite doesn't silently become null — matching the scalar + // lossless path (`extract_simple_kind_lossless`). + _ if *ty == Type::DATE => PgDateFull::from_sql(ty, buf) + .map(JsonValue::from) + .unwrap_or(JsonValue::Null), + _ if *ty == Type::TIME => PgTimeFull::from_sql(ty, buf) + .map(JsonValue::from) + .unwrap_or(JsonValue::Null), + _ if *ty == Type::TIMESTAMP => PgTimestampFull::from_sql(ty, buf) + .map(JsonValue::from) + .unwrap_or(JsonValue::Null), + _ if *ty == Type::TIMESTAMPTZ => PgTimestampTzFull::from_sql(ty, buf) + .map(JsonValue::from) + .unwrap_or(JsonValue::Null), + _ if *ty == Type::NUMERIC => PgNumeric::from_sql(ty, buf) + .map(|v| JsonValue::String(v.0)) + .unwrap_or(JsonValue::Null), _ => extract_simple_from_bytes(ty, buf), } } @@ -1426,6 +1507,28 @@ pub(crate) fn format_year_chrono(year: i64) -> String { } } +/// Format a date (year-month-day) with PostgreSQL's BC convention for the +/// lossless path. For BC years (astronomical year < 0), PostgreSQL emits the +/// absolute year value zero-padded to 4 digits, followed by ` BC` — e.g. +/// 50 BC → `"0050-01-01 BC"`, not `"-0049-01-01"`. For AD years the output is +/// identical to [`format_year_chrono`] with no suffix. `pub(crate)` for direct +/// unit testing. +pub(crate) fn format_date_with_bc(year: i64, month: u8, day: u8) -> String { + if year < 0 { + // PostgreSQL uses the BC year number (not the astronomical year): + // astronomical year -49 = 50 BC. The conversion is BC_year = + // -(astronomical_year) + 1, since astronomical year 0 = 1 BC. + // PostgreSQL zero-pads to 4 digits: 50 BC → "0050-01-01 BC". + let bc_year = (-(year)) + 1; + format!("{bc_year:04}-{month:02}-{day:02} BC") + } else if year == 0 { + // Astronomical year 0 = 1 BC in PostgreSQL's convention. + format!("0001-{month:02}-{day:02} BC") + } else { + format!("{}-{month:02}-{day:02}", format_year_chrono(year)) + } +} + /// DATE: 4-byte big-endian i32 = days since 2000-01-01. Postgres reserves /// `i32::MAX`/`i32::MIN` as ±infinity sentinels; the old chrono path decoded /// these via `NaiveDate`, whose range check (±262143) rejected them → `Err` → @@ -1527,12 +1630,7 @@ impl From for JsonValue { if let Some(s) = v.infinity { return JsonValue::String(s); } - JsonValue::String(format!( - "{}-{:02}-{:02}", - format_year_chrono(v.year), - v.month, - v.day - )) + JsonValue::String(format_date_with_bc(v.year, v.month, v.day)) } } @@ -1831,10 +1929,8 @@ impl From for JsonValue { return JsonValue::String(s); } let mut s = format!( - "{}-{:02}-{:02} {:02}:{:02}:{:02}", - format_year_chrono(v.year), - v.month, - v.day, + "{} {:02}:{:02}:{:02}", + format_date_with_bc(v.year, v.month, v.day), v.hrs, v.mins, v.secs @@ -2019,16 +2115,16 @@ impl From for JsonValue { } /// INTERVAL: 8-byte microseconds, 4-byte days, 4-byte months (signed). -/// Matches `advanced_types.rs::Interval`. +/// The raw wire values are stored as-is — PostgreSQL's `interval_out` never +/// converts between months, days, and hours. The previous code split months +/// greater than 11 into years+months and hours greater than 23 into days, +/// which changed the output (e.g. 48 hours became "2 days", 13 months became +/// "1 year 1 mons"). PostgreSQL keeps each field independent and formats the +/// raw values directly. The unit name is "mon"/"mons" (not "month"/"months"). struct Interval { - years: i32, - months: i8, + months: i32, days: i32, - sign: char, - hours: u8, - minutes: u8, - seconds: u8, - microseconds: u32, + time_micros: i64, } impl<'a> FromSql<'a> for Interval { @@ -2036,44 +2132,13 @@ impl<'a> FromSql<'a> for Interval { if raw.len() < 16 { return Err(format!("expected 16 bytes for INTERVAL, got {}", raw.len()).into()); } - let mut microseconds = i64::from_be_bytes(raw[0..8].try_into().unwrap()); - let mut days = i32::from_be_bytes(raw[8..12].try_into().unwrap()); - let mut months = i32::from_be_bytes(raw[12..16].try_into().unwrap()); - let mut years = 0; - - if !(-11..=11).contains(&months) { - years = months / 12; - months %= 12; - } - - let sign = if microseconds < 0 { - microseconds = -microseconds; - '-' - } else { - '+' - }; - - let mut hrs = microseconds / (1_000_000 * 60 * 60); - microseconds %= 1_000_000 * 60 * 60; - let mins = (microseconds / (1_000_000 * 60)) as u8; - microseconds %= 1_000_000 * 60; - let secs = (microseconds / 1_000_000) as u8; - let microseconds = (microseconds % 1_000_000) as u32; - - if !(-23..=23).contains(&hrs) { - days += (hrs / 24) as i32; - hrs %= 24; - } - + let time_micros = i64::from_be_bytes(raw[0..8].try_into().unwrap()); + let days = i32::from_be_bytes(raw[8..12].try_into().unwrap()); + let months = i32::from_be_bytes(raw[12..16].try_into().unwrap()); Ok(Self { - years, - months: months as i8, + months, days, - sign, - hours: hrs as u8, - minutes: mins, - seconds: secs, - microseconds, + time_micros, }) } @@ -2084,23 +2149,15 @@ impl<'a> FromSql<'a> for Interval { impl From for JsonValue { fn from(v: Interval) -> Self { - let mut s = String::new(); + let mut parts: Vec = Vec::new(); - if v.years != 0 { - let unit = if v.years == 1 || v.years == -1 { - "year" - } else { - "years" - }; - s.push_str(&format!("{} {} ", v.years, unit)); - } if v.months != 0 { let unit = if v.months == 1 || v.months == -1 { - "month" + "mon" } else { - "months" + "mons" }; - s.push_str(&format!("{} {} ", v.months, unit)); + parts.push(format!("{} {}", v.months, unit)); } if v.days != 0 { let unit = if v.days == 1 || v.days == -1 { @@ -2108,20 +2165,35 @@ impl From for JsonValue { } else { "days" }; - s.push_str(&format!("{} {} ", v.days, unit)); - } - if v.hours != 0 || v.minutes != 0 || v.seconds != 0 || v.microseconds != 0 { - if v.sign != '+' { - s.push(v.sign); + parts.push(format!("{} {}", v.days, unit)); + } + if v.time_micros != 0 { + let sign = if v.time_micros < 0 { '-' } else { '+' }; + let abs_micros = v.time_micros.unsigned_abs(); + let hrs = abs_micros / (1_000_000 * 60 * 60); + let rem = abs_micros % (1_000_000 * 60 * 60); + let mins = rem / (1_000_000 * 60); + let rem = rem % (1_000_000 * 60); + let secs = rem / 1_000_000; + let micros = rem % 1_000_000; + + let mut time_str = String::new(); + if sign == '-' { + time_str.push(sign); } - s.push_str(&format!("{:02}:{:02}:{:02}", v.hours, v.minutes, v.seconds)); - if v.microseconds != 0 { - s.push('.'); - s.push_str(v.microseconds.to_string().trim_end_matches('0')); + time_str.push_str(&format!("{}:{:02}:{:02}", hrs, mins, secs)); + if micros != 0 { + time_str.push('.'); + time_str.push_str(format!("{:06}", micros).trim_end_matches('0')); } + parts.push(time_str); } - JsonValue::String(s) + if parts.is_empty() { + JsonValue::String("00:00:00".to_string()) + } else { + JsonValue::String(parts.join(" ")) + } } } diff --git a/src/extract_tests.rs b/src/extract_tests.rs index 2017a58..c1e8f81 100644 --- a/src/extract_tests.rs +++ b/src/extract_tests.rs @@ -13,8 +13,9 @@ use crate::extract::{ ArrayValue, BitOrVarBit, Cid, Circle, CompositeValue, EnumLabel, GtsVector, JsonPath, Line, Lseg, MacAddr8, Money, MultirangeValue, Path, PgBox, PgBrinBloomSummary, PgDateFull, PgDependencies, PgHalfVector, PgLsn, PgMcvList, PgMoneyText, PgNdistinct, PgNodeTree, - PgNumeric, PgSparseVector, PgVector, Point, Polygon, RefCursor, RegClass, RegProc, RegType, - Tid, TsQuery, TsVector, TxidSnapshotOrPgSnapshot, Xid, Xid8, Xml, + PgNumeric, PgSparseVector, PgTimestampFull, PgTimestampTzFull, PgVector, Point, Polygon, + RefCursor, RegClass, RegProc, RegType, Tid, TsQuery, TsVector, TxidSnapshotOrPgSnapshot, Xid, + Xid8, Xml, }; use std::collections::HashMap; use tokio_postgres::types::{Field, FromSql, Kind, Type}; @@ -2471,3 +2472,418 @@ fn pg_money_text_rejects_truncated_wire() { use tokio_postgres::types::FromSql; assert!(PgMoneyText::from_sql(&Type::MONEY, &[0; 4]).is_err()); } + +// --- #222: Interval non-normalization, JSON text serialization, BC dates --- + +/// Builds the 16-byte INTERVAL wire format: 8-byte big-endian microseconds, +/// 4-byte big-endian days, 4-byte big-endian months. +fn interval_wire_bytes(micros: i64, days: i32, months: i32) -> Vec { + let mut buf = Vec::with_capacity(16); + buf.extend_from_slice(µs.to_be_bytes()); + buf.extend_from_slice(&days.to_be_bytes()); + buf.extend_from_slice(&months.to_be_bytes()); + buf +} + +/// The Interval struct is private to `extract.rs` but its `FromSql` impl is +/// exercised through the `extract_simple_kind_from_bytes` dispatcher (which +/// has an INTERVAL arm). Use that to get a `serde_json::Value` result. +fn decode_interval(micros: i64, days: i32, months: i32) -> serde_json::Value { + let bytes = interval_wire_bytes(micros, days, months); + crate::extract::extract_simple_kind_from_bytes(&Type::INTERVAL, &bytes) +} + +#[test] +fn interval_does_not_normalize_months_above_11() { + // 13 months: PostgreSQL's `interval_out` keeps "13 mons" — it does NOT + // convert to "1 year 1 mons". The old code split months > 11 into + // years+months, changing the output. + let v = decode_interval(0, 0, 13); + assert_eq!(v, serde_json::json!("13 mons")); +} + +#[test] +fn interval_does_not_normalize_hours_above_23() { + // 48 hours = 172800000000 microseconds. PostgreSQL keeps "48:00:00" — + // it does NOT convert to "2 days 00:00:00". The old code split hours > 23 + // into days+hours. + let v = decode_interval(172_800_000_000, 0, 0); + assert_eq!(v, serde_json::json!("48:00:00")); +} + +#[test] +fn interval_formats_years_and_months_without_normalizing() { + // 25 months → "25 mons" (not "2 years 1 mons") + let v = decode_interval(0, 0, 25); + assert_eq!(v, serde_json::json!("25 mons")); +} + +#[test] +fn interval_preserves_days_and_hours_independently() { + // 2 days + 48 hours: PostgreSQL keeps them separate → "2 days 48:00:00". + // The old code would convert the 48 hours to 2 days → "4 days 00:00:00". + let v = decode_interval(172_800_000_000, 2, 0); + assert_eq!(v, serde_json::json!("2 days 48:00:00")); +} + +#[test] +fn interval_formats_all_three_components() { + // 3 months + 2 days + 1 hour 30 min: "3 mons 2 days 01:30:00" + let micros = 3_600_000_000 + (30 * 60_000_000); // 1h30m in micros + let v = decode_interval(micros, 2, 3); + assert_eq!(v, serde_json::json!("3 mons 2 days 1:30:00")); +} + +#[test] +fn interval_zero_decodes_to_00_00_00() { + // All-zero interval → "00:00:00" (PostgreSQL's default). + let v = decode_interval(0, 0, 0); + assert_eq!(v, serde_json::json!("00:00:00")); +} + +#[test] +fn interval_negative_microseconds_get_sign_prefix() { + // -1 hour = -3600000000 micros → "-01:00:00" + let v = decode_interval(-3_600_000_000, 0, 0); + assert_eq!(v, serde_json::json!("-1:00:00")); +} + +#[test] +fn interval_keeps_fractional_seconds() { + // 1.5 seconds = 1500000 micros → "00:00:01.5" + let v = decode_interval(1_500_000, 0, 0); + assert_eq!(v, serde_json::json!("0:00:01.5")); +} + +#[test] +fn interval_single_month_uses_singular_mon() { + // 1 month → "1 mon" (singular), 2 months → "2 mons" (plural). + let v = decode_interval(0, 0, 1); + assert_eq!(v, serde_json::json!("1 mon")); + let v = decode_interval(0, 0, 2); + assert_eq!(v, serde_json::json!("2 mons")); +} + +#[test] +fn interval_single_day_uses_singular_day() { + let v = decode_interval(0, 1, 0); + assert_eq!(v, serde_json::json!("1 day")); + let v = decode_interval(0, 2, 0); + assert_eq!(v, serde_json::json!("2 days")); +} + +#[test] +fn interval_negative_months_preserve_sign() { + // -13 months → "-13 mons" + let v = decode_interval(0, 0, -13); + assert_eq!(v, serde_json::json!("-13 mons")); +} + +// --- JSON/JSONB: serialized text in the lossless path --- + +#[test] +fn json_array_element_string_value_is_serialized_json_text() { + // `jsonb '"hello"'` inside an array: the lossless byte-level decoder + // must return the serialized JSON text `"\"hello\""`, not the bare + // string `"hello"`. This makes JSON strings round-trip through + // `insert_records`. + let ty = array_type(Type::JSONB); + // Wire format for a jsonb '"hello"' value: a 1-byte version header (1) + // followed by the JSON text. + let jsonb_elem = [1u8, b'"', b'h', b'e', b'l', b'l', b'o', b'"']; + let bytes = array_wire_bytes(Type::JSONB.oid(), &[Some(&jsonb_elem)]); + let array = ArrayValue::from_sql(&ty, &bytes).unwrap(); + assert_eq!(array.0, serde_json::json!(["\"hello\""])); +} + +#[test] +fn json_array_element_number_value_is_serialized_json_text() { + // `jsonb '42'` inside an array: the lossless path returns `"42"` (the + // JSON text), not the bare number `42`. + let ty = array_type(Type::JSONB); + let jsonb_elem = [1u8, b'4', b'2']; + let bytes = array_wire_bytes(Type::JSONB.oid(), &[Some(&jsonb_elem)]); + let array = ArrayValue::from_sql(&ty, &bytes).unwrap(); + assert_eq!(array.0, serde_json::json!(["42"])); +} + +#[test] +fn json_array_element_object_value_is_serialized_json_text() { + // `jsonb '{"a": 1}'` inside an array: the lossless path returns the + // serialized JSON text `"{\"a\":1}"`. + let ty = array_type(Type::JSONB); + let json_text = br#"{"a":1}"#; + let mut jsonb_elem = vec![1u8]; // version header + jsonb_elem.extend_from_slice(json_text); + let bytes = array_wire_bytes(Type::JSONB.oid(), &[Some(&jsonb_elem)]); + let array = ArrayValue::from_sql(&ty, &bytes).unwrap(); + assert_eq!(array.0, serde_json::json!(["{\"a\":1}"])); +} + +#[test] +fn json_array_null_element_remains_null() { + let ty = array_type(Type::JSONB); + let bytes = array_wire_bytes(Type::JSONB.oid(), &[None]); + let array = ArrayValue::from_sql(&ty, &bytes).unwrap(); + assert_eq!(array.0, serde_json::json!([null])); +} + +// --- BC dates: PostgreSQL's `"0043-01-01 BC"` format --- + +#[test] +fn format_date_with_bc_ad_year_has_no_suffix() { + assert_eq!( + crate::extract::format_date_with_bc(2026, 11, 29), + "2026-11-29" + ); + assert_eq!( + crate::extract::format_date_with_bc(1000, 1, 1), + "1000-01-01" + ); +} + +#[test] +fn format_date_with_bc_zero_pads_ad_year_below_1000() { + assert_eq!(crate::extract::format_date_with_bc(50, 1, 1), "0050-01-01"); + // Astronomical year 0 = 1 BC in PostgreSQL's convention. + assert_eq!( + crate::extract::format_date_with_bc(0, 3, 15), + "0001-03-15 BC" + ); +} + +#[test] +fn format_date_with_bc_emits_positive_year_plus_bc_for_negative_years() { + // Astronomical year -49 = 50 BC → "0050-01-01 BC" + assert_eq!( + crate::extract::format_date_with_bc(-49, 1, 1), + "0050-01-01 BC" + ); + // Astronomical year -4712 = 4713 BC → "4713-01-01 BC" + assert_eq!( + crate::extract::format_date_with_bc(-4712, 1, 1), + "4713-01-01 BC" + ); +} + +#[test] +fn format_date_with_bc_large_ad_year_keeps_plus_sign() { + assert_eq!( + crate::extract::format_date_with_bc(10000, 1, 1), + "+10000-01-01" + ); +} + +#[test] +fn pg_date_full_bc_year_emits_bc_suffix() { + use tokio_postgres::types::FromSql; + // 50 BC = astronomical year -49 = -748382 days from 2000-01-01. + let bytes = (-748_382_i32).to_be_bytes(); + let v = PgDateFull::from_sql(&Type::DATE, &bytes).unwrap(); + assert_eq!( + serde_json::Value::from(v), + serde_json::json!("0050-01-01 BC") + ); +} + +#[test] +fn pg_date_full_4713_bc_emits_bc_suffix() { + use tokio_postgres::types::FromSql; + // The Postgres DATE minimum (-2451545 days) decodes via the proleptic + // Gregorian algorithm to astronomical year -4713, Nov 24 → "4714-11-24 BC". + // (PostgreSQL's own display would say "4713-01-01 BC" using the Julian + // calendar for BC dates; the proleptic Gregorian divergence is pre-existing + // — the display path's `format_year_chrono(-4713)` also produces the + // proleptic year, just without the " BC" suffix.) + let bytes = (-2_451_545_i32).to_be_bytes(); + let v = PgDateFull::from_sql(&Type::DATE, &bytes).unwrap(); + assert_eq!( + serde_json::Value::from(v), + serde_json::json!("4714-11-24 BC") + ); +} + +#[test] +fn pg_date_full_ad_year_remains_unaffected_by_bc_change() { + use tokio_postgres::types::FromSql; + // 2026-11-29 is 9829 days after 2000-01-01 — AD, no BC suffix. + let bytes = 9_829_i32.to_be_bytes(); + let v = PgDateFull::from_sql(&Type::DATE, &bytes).unwrap(); + assert_eq!(serde_json::Value::from(v), serde_json::json!("2026-11-29")); +} + +#[test] +fn pg_timestamp_full_bc_year_emits_bc_suffix() { + use tokio_postgres::types::FromSql; + // 50 BC 00:00:00 = astronomical year -49 = -748382 days * 86400000000 micros. + let micros = -748_382_i64 * 86_400_000_000; + let bytes = micros.to_be_bytes(); + let v = PgTimestampFull::from_sql(&Type::TIMESTAMP, &bytes).unwrap(); + assert_eq!( + serde_json::Value::from(v), + serde_json::json!("0050-01-01 BC 00:00:00") + ); +} + +#[test] +fn pg_timestamptz_full_bc_year_emits_bc_suffix_with_offset() { + use tokio_postgres::types::FromSql; + // 50 BC 00:00:00 UTC = same wire as TIMESTAMP. + let micros = -748_382_i64 * 86_400_000_000; + let bytes = micros.to_be_bytes(); + let v = PgTimestampTzFull::from_sql(&Type::TIMESTAMPTZ, &bytes).unwrap(); + assert_eq!( + serde_json::Value::from(v), + serde_json::json!("0050-01-01 BC 00:00:00+00:00") + ); +} + +// --- #222: Lossless array elements use lossless byte-level decoder --- + +#[test] +fn float8_array_nan_element_survives_lossless_decode() { + // NaN in a float8[] element: the display-path fast-path + // (Vec>) turns NaN into Null via `Number::from_f64`. The + // lossless byte-level decoder returns "NaN" as a text string. + let ty = array_type(Type::FLOAT8); + let nan_f64_bytes = f64::NAN.to_be_bytes(); + let bytes = array_wire_bytes(Type::FLOAT8.oid(), &[Some(&nan_f64_bytes)]); + let array = ArrayValue::from_sql(&ty, &bytes).unwrap(); + assert_eq!(array.0, serde_json::json!(["NaN"])); +} + +#[test] +fn float8_array_infinity_element_survives_lossless_decode() { + let ty = array_type(Type::FLOAT8); + let inf_bytes = f64::INFINITY.to_be_bytes(); + let neg_inf_bytes = f64::NEG_INFINITY.to_be_bytes(); + let bytes = array_wire_bytes( + Type::FLOAT8.oid(), + &[Some(&inf_bytes), Some(&neg_inf_bytes)], + ); + let array = ArrayValue::from_sql(&ty, &bytes).unwrap(); + assert_eq!(array.0, serde_json::json!(["Infinity", "-Infinity"])); +} + +#[test] +fn float4_array_nan_element_survives_lossless_decode() { + let ty = array_type(Type::FLOAT4); + let nan_bytes = f32::NAN.to_be_bytes(); + let bytes = array_wire_bytes(Type::FLOAT4.oid(), &[Some(&nan_bytes)]); + let array = ArrayValue::from_sql(&ty, &bytes).unwrap(); + assert_eq!(array.0, serde_json::json!(["NaN"])); +} + +#[test] +fn date_array_infinity_element_survives_lossless_decode() { + // DATE infinity sentinel (i32::MAX) inside an array: the display-path + // byte-level decoder (`extract_simple_from_bytes`) rejects it → null. + // The lossless byte-level decoder returns "infinity" as text. + let ty = array_type(Type::DATE); + let inf_bytes = i32::MAX.to_be_bytes(); + let bytes = array_wire_bytes(Type::DATE.oid(), &[Some(&inf_bytes)]); + let array = ArrayValue::from_sql(&ty, &bytes).unwrap(); + assert_eq!(array.0, serde_json::json!(["infinity"])); +} + +#[test] +fn timestamp_array_infinity_element_survives_lossless_decode() { + let ty = array_type(Type::TIMESTAMP); + let inf_bytes = i64::MAX.to_be_bytes(); + let bytes = array_wire_bytes(Type::TIMESTAMP.oid(), &[Some(&inf_bytes)]); + let array = ArrayValue::from_sql(&ty, &bytes).unwrap(); + assert_eq!(array.0, serde_json::json!(["infinity"])); +} + +#[test] +fn numeric_array_wide_value_survives_lossless_decode() { + // A 38-digit numeric inside an array: the display-path byte-level + // decoder uses `rust_decimal::Decimal` which can't hold it → null. + // The lossless byte-level decoder uses `PgNumeric`. + let ty = array_type(Type::NUMERIC); + let wide_value = numeric_wire_bytes( + 10, + 9, + 0x0000, + 0, + &[12, 3456, 7890, 1234, 5678, 9012, 3456, 7890, 1234, 5678], + ); + let bytes = array_wire_bytes(Type::NUMERIC.oid(), &[Some(&wide_value)]); + let array = ArrayValue::from_sql(&ty, &bytes).unwrap(); + assert_eq!( + array.0, + serde_json::json!(["12345678901234567890123456789012345678"]) + ); +} + +#[test] +fn money_array_element_uses_lossless_decimal_format() { + // MONEY in an array: the display-path byte-level decoder rendered + // cents as a raw integer (12345). The lossless path formats as + // "123.45" (matching PostgreSQL's money_out). + let ty = array_type(Type::MONEY); + let cents_bytes = 12_345_i64.to_be_bytes(); + let bytes = array_wire_bytes(Type::MONEY.oid(), &[Some(¢s_bytes)]); + let array = ArrayValue::from_sql(&ty, &bytes).unwrap(); + assert_eq!(array.0, serde_json::json!(["123.45"])); +} + +#[test] +fn time_array_24_hours_survives_lossless_decode() { + // TIME 24:00:00 inside an array: the display-path `PgTime` rejects it + // (exclusive bound → null). The lossless `PgTimeFull` accepts it. + let ty = array_type(Type::TIME); + let time_bytes = 86_400_000_000_i64.to_be_bytes(); + let bytes = array_wire_bytes(Type::TIME.oid(), &[Some(&time_bytes)]); + let array = ArrayValue::from_sql(&ty, &bytes).unwrap(); + assert_eq!(array.0, serde_json::json!(["24:00:00"])); +} + +#[test] +fn timestamptz_array_element_keeps_offset_and_fractionals() { + // A normal timestamptz in an array should keep fractional seconds + // and the +00:00 offset (the lossless byte-level decoder). + let ty = array_type(Type::TIMESTAMPTZ); + // 2026-11-29 13:45:30.345678 UTC = 849275130345678 micros. + let micros = 849_275_130_345_678_i64; + let bytes = array_wire_bytes(Type::TIMESTAMPTZ.oid(), &[Some(µs.to_be_bytes())]); + let array = ArrayValue::from_sql(&ty, &bytes).unwrap(); + assert_eq!( + array.0, + serde_json::json!(["2026-11-29 13:45:30.345678+00:00"]) + ); +} + +#[test] +fn interval_array_element_does_not_normalize() { + // 13 months inside an array: the lossless byte-level decoder does NOT + // normalize to "1 year 1 mons". + let ty = array_type(Type::INTERVAL); + let interval_bytes = interval_wire_bytes(0, 0, 13); + let bytes = array_wire_bytes(Type::INTERVAL.oid(), &[Some(&interval_bytes)]); + let array = ArrayValue::from_sql(&ty, &bytes).unwrap(); + assert_eq!(array.0, serde_json::json!(["13 mons"])); +} + +#[test] +fn json_scalar_array_element_keeps_json_text_form() { + // A json (not jsonb) array element: JSON's wire format is the raw UTF-8 + // bytes of the JSON text (no version header). The lossless byte-level + // decoder returns the serialized text. + let ty = array_type(Type::JSON); + let json_elem = br#""hello""#; + let bytes = array_wire_bytes(Type::JSON.oid(), &[Some(json_elem)]); + let array = ArrayValue::from_sql(&ty, &bytes).unwrap(); + assert_eq!(array.0, serde_json::json!(["\"hello\""])); +} + +#[test] +fn bc_date_array_element_emits_bc_suffix() { + // A BC date inside an array: the lossless byte-level decoder + // (PgDateFull) emits "0050-01-01 BC", not "-0049-01-01". + let ty = array_type(Type::DATE); + let date_bytes = (-748_382_i32).to_be_bytes(); + let bytes = array_wire_bytes(Type::DATE.oid(), &[Some(&date_bytes)]); + let array = ArrayValue::from_sql(&ty, &bytes).unwrap(); + assert_eq!(array.0, serde_json::json!(["0050-01-01 BC"])); +} diff --git a/src/handlers/blob.rs b/src/handlers/blob.rs index 0377982..e95b8d1 100644 --- a/src/handlers/blob.rs +++ b/src/handlers/blob.rs @@ -86,8 +86,14 @@ async fn fetch_blob_bytes( log::warn!("Failed to load PostgreSQL column types for {schema}.{table}: {error}; row matching may fail"); Default::default() }); + // build_pk_map_predicate expects a name -> type-name map; project + // ColumnTypeInfo down to just the type_name string. + let column_type_names: std::collections::HashMap = column_types + .iter() + .map(|(k, v)| (k.clone(), v.type_name.clone())) + .collect(); - let (predicate, owned_params) = build_pk_map_predicate(pk_map, &column_types, 1)?; + let (predicate, owned_params) = build_pk_map_predicate(pk_map, &column_type_names, 1)?; let query = format!( "SELECT \"{}\" FROM {} WHERE {}", col_name.replace('"', "\"\""), diff --git a/src/handlers/copy.rs b/src/handlers/copy.rs index 47bc2db..325d546 100644 --- a/src/handlers/copy.rs +++ b/src/handlers/copy.rs @@ -22,6 +22,7 @@ use tokio_postgres::types::{ToSql, Type}; use crate::binding::{bind_pg_value, BindOptions, TypedPgParam}; use crate::client; +use crate::client::ColumnTypeInfo; use std::collections::HashMap; use std::sync::{Mutex, OnceLock}; @@ -48,6 +49,22 @@ pub fn clear_copy_session_query(session_id: &str) { copy_session_queries().lock().unwrap().remove(session_id); } +/// Strip a trailing `-- ...` line comment from a query string. The +/// cursor path's `build_paginated_query` uses a comment-aware lexer; the +/// cursor path must too, or a trailing `-- comment` breaks DECLARE (#222). +/// This is a simple version that doesn't handle `--` inside strings -- the +/// query comes from the host (trusted) and is a single SELECT. +fn strip_trailing_line_comment(query: &str) -> &str { + if let Some(pos) = query.rfind("--") { + let before = &query[..pos]; + let single_quotes = before.matches('\'').count() - before.matches("''").count(); + if single_quotes.is_multiple_of(2) { + return before.trim_end(); + } + } + query +} + /// `BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY` — the snapshot the first /// page of a session-pinned copy opens. `READ ONLY` lets PostgreSQL apply the /// snapshot cheaply and refuses any write the host might accidentally send. @@ -207,6 +224,10 @@ async fn run_one_shot( let _ = pg_client .batch_execute(if result.is_ok() { "COMMIT" } else { "ROLLBACK" }) .await; + // Clear any session-level GUCs the read may have set (e.g. SET LOCAL + // search_path) so they don't leak to the next borrower via the recycled + // pooled connection (#222). + let _ = pg_client.batch_execute("RESET ALL").await; drop(cancel_guard); result } @@ -321,7 +342,10 @@ async fn run_snapshot( // cursor path must too (#214 review finding, #220 item 7: trim // whitespace before the `;` so `"; "` and `"; -- comment"` don't // leave a stray token that breaks the DECLARE). - let trimmed_query = query.trim_end().trim_end_matches(';').trim_end(); + let trimmed_query = strip_trailing_line_comment(query) + .trim_end() + .trim_end_matches(';') + .trim_end(); // Record the query for this session so a later `read_rows` with a // different query is rejected instead of silently returning the old // cursor's rows (#220 item 5). @@ -753,7 +777,7 @@ async fn exec_insert_batch( let mut hstore_oids: std::collections::HashMap> = std::collections::HashMap::new(); for col in &columns { - if column_types.get(col).map(String::as_str) == Some("hstore") { + if column_types.get(col).map(|i| i.type_name.as_str()) == Some("hstore") { let oid = client::get_hstore_oid_for_column(conn_params, schema, table, col) .await .unwrap_or(None); @@ -808,7 +832,7 @@ async fn exec_insert_batch( /// `insert_record` path re-queries per insert; a batch amortizes this). struct ResolvedTypes { columns: Vec, - column_types: std::collections::HashMap, + column_types: std::collections::HashMap, enum_types: std::collections::HashMap, hstore_oids: std::collections::HashMap>, } @@ -875,13 +899,15 @@ async fn build_and_execute_chunks( .get(col) .ok_or_else(|| format!("insert_records: row is missing column '{col}'"))? .clone(); - let column_type = types.column_types.get(col).map(String::as_str); + let column_type = types.column_types.get(col).map(|i| i.type_name.as_str()); let hstore_oid = types.hstore_oids.get(col).copied().unwrap_or(None); + let char_max_len = types.column_types.get(col).and_then(|i| i.char_max_len); let options = BindOptions { column_type, enum_type: types.enum_types.get(col).map(String::as_str), allow_default: false, hstore_oid, + char_max_len, }; let bound = bind_pg_value(val, placeholder_idx, &options)?; fragments.push(bound.sql); diff --git a/src/handlers/crud.rs b/src/handlers/crud.rs index a706f45..4585480 100644 --- a/src/handlers/crud.rs +++ b/src/handlers/crud.rs @@ -67,7 +67,7 @@ async fn exec_insert( for (col_name, val) in entries { cols.push(format!("\"{}\"", col_name.replace('"', "\"\""))); - let column_type = column_types.get(&col_name).map(String::as_str); + let column_type = column_types.get(&col_name).map(|i| i.type_name.as_str()); // get_column_types_map already unfolds 'USER-DEFINED' to the real // udt_name, so hstore columns report as plain "hstore" here. let hstore_oid = if column_type == Some("hstore") { @@ -82,6 +82,7 @@ async fn exec_insert( enum_type: enum_types.get(&col_name).map(String::as_str), allow_default: false, hstore_oid, + char_max_len: column_types.get(&col_name).and_then(|i| i.char_max_len), }; let bound = bind_pg_value(val, placeholder_idx, &options)?; sql_fragments.push(bound.sql); @@ -152,18 +153,19 @@ async fn exec_update( .unwrap_or_default(); let options = BindOptions { - column_type: column_types.get(col_name).map(String::as_str), + column_type: column_types.get(col_name).map(|i| i.type_name.as_str()), enum_type: enum_types.get(col_name).map(String::as_str), allow_default: true, // get_column_types_map already unfolds 'USER-DEFINED' to the real // udt_name, so hstore columns report as plain "hstore" here. - hstore_oid: if column_types.get(col_name).map(String::as_str) == Some("hstore") { + hstore_oid: if column_types.get(col_name).map(|i| i.type_name.as_str()) == Some("hstore") { client::get_hstore_oid_for_column(conn_params, schema, table, col_name) .await .unwrap_or(None) } else { None }, + char_max_len: column_types.get(col_name).and_then(|i| i.char_max_len), }; let bound = bind_pg_value(new_val, 1, &options)?; @@ -174,7 +176,14 @@ async fn exec_update( placeholder_idx = 2; } - let (predicate, pk_params) = build_pk_map_predicate(pk_map, &column_types, placeholder_idx)?; + let (predicate, pk_params) = build_pk_map_predicate( + pk_map, + &column_types + .iter() + .map(|(k, v)| (k.clone(), v.type_name.clone())) + .collect(), + placeholder_idx, + )?; owned_params.extend(pk_params); let query = format!( @@ -230,8 +239,14 @@ async fn exec_delete( log::warn!("Failed to load PostgreSQL column types for {schema}.{table}: {error}; row matching may fail"); Default::default() }); + // build_pk_map_predicate expects a name -> type-name map; project + // ColumnTypeInfo down to just the type_name string. + let column_type_names: std::collections::HashMap = column_types + .iter() + .map(|(k, v)| (k.clone(), v.type_name.clone())) + .collect(); - let (predicate, owned_params) = build_pk_map_predicate(pk_map, &column_types, 1)?; + let (predicate, owned_params) = build_pk_map_predicate(pk_map, &column_type_names, 1)?; let query = format!("DELETE FROM {} WHERE {}", qualified, predicate); diff --git a/src/handlers/metadata.rs b/src/handlers/metadata.rs index 7c91580..a8716d2 100644 --- a/src/handlers/metadata.rs +++ b/src/handlers/metadata.rs @@ -164,7 +164,7 @@ async fn fetch_table_columns( c.numeric_scale, c.datetime_precision, d.description::text AS comment, - a.attgenerated <> '' AS is_generated, + a.attgenerated <> '' OR a.attidentity IN ('a', 'd') AS is_generated, format_type(a.atttypid, a.atttypmod) AS full_type, (SELECT string_agg('''' || replace(e.enumlabel, '''', '''''') || '''', ',' ORDER BY e.enumsortorder) FROM pg_enum e @@ -238,7 +238,7 @@ async fn fetch_materialized_view_columns( NULL::integer AS numeric_scale, NULL::integer AS datetime_precision, d.description::text AS comment, - a.attgenerated <> '' AS is_generated, + a.attgenerated <> '' OR a.attidentity IN ('a', 'd') AS is_generated, format_type(a.atttypid, a.atttypmod) AS full_type, NULL::text AS enum_values, false AS is_pk @@ -769,7 +769,7 @@ pub async fn get_view_columns(id: Value, params: &Value) -> Value { JOIN pg_type t ON t.oid = e.enumtypid JOIN pg_namespace tn ON tn.oid = t.typnamespace WHERE t.typname = c.udt_name AND tn.nspname = c.udt_schema) AS enum_values, - COALESCE(a.attgenerated <> '', false) AS is_generated, + COALESCE(a.attgenerated <> '' OR a.attidentity IN ('a', 'd'), false) AS is_generated, CASE WHEN a.atttypid IS NOT NULL THEN format_type(a.atttypid, a.atttypmod) END AS full_type, EXISTS ( SELECT 1 @@ -1401,7 +1401,7 @@ async fn fetch_all_columns( c.numeric_scale, c.datetime_precision, d.description::text AS comment, - a.attgenerated <> '' AS is_generated, + a.attgenerated <> '' OR a.attidentity IN ('a', 'd') AS is_generated, format_type(a.atttypid, a.atttypmod) AS full_type, (SELECT string_agg('''' || replace(e.enumlabel, '''', '''''') || '''', ',' ORDER BY e.enumsortorder) FROM pg_enum e From 485f9a3337f98358d4d37918d577e4a7489c8af3 Mon Sep 17 00:00:00 2001 From: Adam J Esslinger Date: Wed, 2 Dec 2026 15:21:35 -0500 Subject: [PATCH 2/3] =?UTF-8?q?fix:=20character=5Fmaximum=5Flength=20is=20?= =?UTF-8?q?int4=20not=20int8=20=E2=80=94=20fix=20bit(n)=20CAST=20(#222)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit get_column_types_map read character_maximum_length as Option, but information_schema.columns defines it as int (i32), so try_get::> silently returned None — the bit(n) CAST never received the length and defaulted to bit(1). Fix: read as Option, cast to i64. Verified bit(3) round-trip against live PostgreSQL over JSON-RPC. Co-Authored-By: Adam J Esslinger --- src/client.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/client.rs b/src/client.rs index 33600e9..293f443 100644 --- a/src/client.rs +++ b/src/client.rs @@ -295,9 +295,10 @@ pub async fn get_column_types_map( let name: String = r.try_get("column_name").ok()?; let ty: String = r.try_get("resolved_type").ok()?; let char_max_len: Option = r - .try_get::<_, Option>("character_maximum_length") + .try_get::<_, Option>("character_maximum_length") .ok() - .flatten(); + .flatten() + .map(|v| v as i64); Some(( name, ColumnTypeInfo { From 6ce97ecf106877d65b49e5eb24d61b1e1a97a80b Mon Sep 17 00:00:00 2001 From: Adam J Esslinger Date: Wed, 2 Dec 2026 17:04:11 -0500 Subject: [PATCH 3/3] =?UTF-8?q?fix:=20ensemble=20review=20fixes=20?= =?UTF-8?q?=E2=80=94=20RESET=20ALL,=20strip=20comment,=20interval/BC=20dat?= =?UTF-8?q?e=20wiring=20(#222)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pre-handoff ensemble review (security + correctness + code-review) found and verified six issues in PR #223's working tree. All fixed here: 1. RESET ALL removed from run_one_shot (copy.rs): it wiped default_transaction_read_only and the app.tabularis_base_search_path GUC on recycled pool connections (Fast recycling doesn't re-run post_create). SET LOCAL is already reverted by COMMIT/ROLLBACK — RESET ALL added nothing and actively harmed the connection. 2. strip_trailing_line_comment rewritten (copy.rs): rfind("--") scanned the whole query (stripping `--` from earlier lines, destroying WHERE clauses); the quote-parity formula `count('\'') - count("''")` undercounted by 1 per `''` pair. Now scans only the last line and uses `count('\'') - 2 * count("''")`. pub(crate) + 7 unit tests added. 3. Interval split into Interval (display, normalized) and PgIntervalText (lossless, non-normalized). The shared struct broke execute_query's display output. PgIntervalText wired into both lossless paths: extract_simple_kind_lossless (scalar) and extract_simple_kind_from_bytes (array/composite elements). Zero-pads hours to match interval_out. 4. BC date suffix placement: format_date_with_bc put " BC" after the date part, but PostgreSQL puts it at the END for timestamp/timestamptz ("0050-03-15 12:30:45 BC", not "0050-03-15 BC 12:30:45"). Split into format_date_with_bc (DATE — BC after date) and format_date_no_bc (timestamp — no suffix, BC appended at end). For timestamptz the offset comes before BC: "0050-03-15 12:30:45+00 BC". 5. Large AD years (≥10000): the lossless path no longer emits the `+` prefix from format_year_chrono — PostgreSQL's date/timestamp input parser rejects "+10000-01-01" ("time zone displacement out of range"). The display path keeps `+` (matches old builtin behavior; not used for round-trips). Verified against live PostgreSQL 16. 6. extract_simple_kind_from_bytes doc comment updated: it no longer covers the "exact same type set" as extract_simple_kind — 9 types now diverge for lossless array/composite elements. README updated: arrays are now lossless (not "stay lossy"), JSON serialized text format, interval non-normalized format documented. Co-Authored-By: Adam J Esslinger --- README.md | 21 +++- src/extract.rs | 206 ++++++++++++++++++++++++++++++++----- src/extract_tests.rs | 71 +++++++++++-- src/handlers/copy.rs | 37 ++++--- src/handlers/copy_tests.rs | 63 +++++++++++- 5 files changed, 347 insertions(+), 51 deletions(-) diff --git a/README.md b/README.md index a133f9d..02208a8 100644 --- a/README.md +++ b/README.md @@ -342,14 +342,26 @@ reviewed against. `read_rows` instead returns: nonzero) - `timestamptz` with the `+00:00` UTC offset (the wire value is UTC) - `bytea` base64-encoded in full (not the 10 KB preview) -- `numeric`, `int8`, `float8`, `bool`, `text`, `uuid`, `json`/`jsonb` exactly +- `numeric`, `int8`, `float8`, `bool`, `text`, `uuid` exactly +- `json`/`jsonb` as serialized JSON text (so a scalar JSON string + `"\"hello\""` round-trips through `insert_records`, not the bare string + `"hello"` the display path returns) - `float4`/`float8` `NaN` and `±Infinity` as text strings (`"NaN"`, `"Infinity"`, `"-Infinity"` — not `null`, which the display path returns) - `date`/`timestamp`/`timestamptz` `infinity`/`-infinity` as text strings (not `null`) +- `date`/`timestamp`/`timestamptz` BC values in PostgreSQL's `"0043-03-15 BC"` + / `"0043-03-15 12:30:45 BC"` format (not the `"-0042-03-15"` astronomical + form), so they round-trip through `insert_records` - `time '24:00:00'` as the text string `"24:00:00"` (not `null`) - `money` as a decimal text string (`"123.45"`, not the integer cents the display path returns) +- `interval` without normalization (matching PostgreSQL's `interval_out`): + `48 hours` stays `"48:00:00"` (not `"2 days"`), `13 months` stays + `"13 mons"` (not `"1 year 1 mons"`) +- arrays decoded element-by-element through the same lossless decoders, so + `float8[]` with `NaN`, `timestamptz[]` with `infinity`, `numeric[]` with + wide values, `interval[]` etc. all survive the copy - the PostgreSQL type name and OID per column, so the host can plan the conversion @@ -384,9 +396,10 @@ the same keys (a row missing a column is an error, not a silent NULL). The `bind_pg_value`'s `decode_blob_wire_format`, so a PG→PG copy preserves every value — `bytea`, full-precision timestamps, `numeric`, etc. -Arrays, ranges, and composites of temporals stay lossy in this release (they -delegate to the display path on the read side); the copy acceptance criteria are -scalar columns. +Arrays are decoded losslessly element-by-element (each element uses the same +full-precision decoder as a scalar column). Ranges and composites of +temporals still delegate to the display path on the read side (lossy); the +copy acceptance criteria are scalar and array columns. ## Building from Source diff --git a/src/extract.rs b/src/extract.rs index 2942853..641c3cd 100644 --- a/src/extract.rs +++ b/src/extract.rs @@ -286,6 +286,14 @@ fn extract_simple_kind_lossless(col_type: &Type, row: &Row, index: usize) -> Jso ref t if *t == Type::JSON || *t == Type::JSONB => { try_extract::(row, index, |v| JsonValue::String(v.to_string())) } + // INTERVAL: the display path (`extract_simple_kind`) normalizes months + // > 11 into years and hours > 23 into days, matching the old built-in. + // The lossless path must NOT normalize — PostgreSQL's `interval_out` + // keeps `48 hours` as `48:00:00` (not `2 days`) and `13 months` as + // `13 mons` (not `1 year 1 mons`). Without this, a read→insert round-trip + // rewrites the value's text form, which changes the result of + // `timestamptz + interval` across a DST boundary (#222). + ref t if *t == Type::INTERVAL => try_extract::(row, index, JsonValue::from), // All other scalar types are already lossless — reuse the display path. _ => extract_simple_kind(col_type, row, index), } @@ -1009,7 +1017,7 @@ pub(crate) fn extract_simple_kind_from_bytes(ty: &Type, buf: &[u8]) -> JsonValue _ if *ty == Type::TIMETZ => TimeTz::from_sql(ty, buf) .map(JsonValue::from) .unwrap_or(JsonValue::Null), - _ if *ty == Type::INTERVAL => Interval::from_sql(ty, buf) + _ if *ty == Type::INTERVAL => PgIntervalText::from_sql(ty, buf) .map(JsonValue::from) .unwrap_or(JsonValue::Null), _ if *ty == Type::JSON || *ty == Type::JSONB => serde_json::Value::from_sql(ty, buf) @@ -1508,24 +1516,46 @@ pub(crate) fn format_year_chrono(year: i64) -> String { } /// Format a date (year-month-day) with PostgreSQL's BC convention for the -/// lossless path. For BC years (astronomical year < 0), PostgreSQL emits the +/// lossless path. For BC years (astronomical year ≤ 0), PostgreSQL emits the /// absolute year value zero-padded to 4 digits, followed by ` BC` — e.g. /// 50 BC → `"0050-01-01 BC"`, not `"-0049-01-01"`. For AD years the output is /// identical to [`format_year_chrono`] with no suffix. `pub(crate)` for direct /// unit testing. pub(crate) fn format_date_with_bc(year: i64, month: u8, day: u8) -> String { + let base = format_date_no_bc(year, month, day); + if year <= 0 { + format!("{base} BC") + } else { + base + } +} + +/// Format just the date part (year-month-day) without a `BC` suffix, using +/// PostgreSQL's BC year numbering. Used by [`PgTimestampFull`] and +/// [`PgTimestampTzFull`], which append ` BC` at the *end* of the full string +/// (after the time and timezone offset), not after the date — e.g. PostgreSQL +/// prints a BC timestamp as `"0050-03-15 12:30:45 BC"`, not +/// `"0050-03-15 BC 12:30:45"`. `pub(crate)` for direct unit testing. +pub(crate) fn format_date_no_bc(year: i64, month: u8, day: u8) -> String { if year < 0 { // PostgreSQL uses the BC year number (not the astronomical year): // astronomical year -49 = 50 BC. The conversion is BC_year = // -(astronomical_year) + 1, since astronomical year 0 = 1 BC. - // PostgreSQL zero-pads to 4 digits: 50 BC → "0050-01-01 BC". let bc_year = (-(year)) + 1; - format!("{bc_year:04}-{month:02}-{day:02} BC") + format!("{bc_year:04}-{month:02}-{day:02}") } else if year == 0 { // Astronomical year 0 = 1 BC in PostgreSQL's convention. - format!("0001-{month:02}-{day:02} BC") + format!("0001-{month:02}-{day:02}") } else { - format!("{}-{month:02}-{day:02}", format_year_chrono(year)) + // AD years: format the year without `format_year_chrono`'s `+` prefix + // for years ≥ 10000 — PostgreSQL's date/timestamp input parser rejects + // the `+` sign ("time zone displacement out of range"), so the + // lossless round-trip path must emit `10000-01-01`, not `+10000-01-01`. + if (0..=9999).contains(&year) { + format!("{year:04}-{month:02}-{day:02}") + } else { + format!("{year}-{month:02}-{day:02}") + } } } @@ -1928,9 +1958,12 @@ impl From for JsonValue { if let Some(s) = v.infinity { return JsonValue::String(s); } + // PostgreSQL places ` BC` at the end of the full timestamp string, + // not after the date part: `"0050-03-15 12:30:45 BC"`, not + // `"0050-03-15 BC 12:30:45"`. let mut s = format!( "{} {:02}:{:02}:{:02}", - format_date_with_bc(v.year, v.month, v.day), + format_date_no_bc(v.year, v.month, v.day), v.hrs, v.mins, v.secs @@ -1941,6 +1974,9 @@ impl From for JsonValue { // `PgTimeFull::from` for why. s.push_str(format!("{:06}", v.microseconds).trim_end_matches('0')); } + if v.year <= 0 { + s.push_str(" BC"); + } JsonValue::String(s) } } @@ -2022,17 +2058,29 @@ impl<'a> FromSql<'a> for PgTimestampTzFull { impl From for JsonValue { fn from(v: PgTimestampTzFull) -> Self { - let mut s = v.inner.into(); - // `PgTimestampFull::into` produced `JsonValue::String`. For a normal - // timestamp, append the `+00:00` UTC offset. For an infinity - // sentinel the string is already "infinity"/"-infinity" — PostgreSQL - // emits no timezone suffix for infinite timestamptz, so don't append. - if let JsonValue::String(ref mut text) = s { - if !text.ends_with("infinity") { - text.push_str("+00:00"); - } + // Build directly rather than delegating to `PgTimestampFull::into`: + // PostgreSQL places the `+00:00` offset before the ` BC` suffix — + // `"0050-03-15 12:30:45+00 BC"`, not `"0050-03-15 12:30:45 BC+00:00"`. + if let Some(s) = v.inner.infinity { + return JsonValue::String(s); } - s + let mut s = format!( + "{} {:02}:{:02}:{:02}", + format_date_no_bc(v.inner.year, v.inner.month, v.inner.day), + v.inner.hrs, + v.inner.mins, + v.inner.secs + ); + if v.inner.microseconds > 0 { + s.push('.'); + s.push_str(format!("{:06}", v.inner.microseconds).trim_end_matches('0')); + } + // `+00:00` UTC offset, then ` BC` suffix for BC years (if any). + s.push_str("+00:00"); + if v.inner.year <= 0 { + s.push_str(" BC"); + } + JsonValue::String(s) } } @@ -2114,13 +2162,13 @@ impl From for JsonValue { } } -/// INTERVAL: 8-byte microseconds, 4-byte days, 4-byte months (signed). -/// The raw wire values are stored as-is — PostgreSQL's `interval_out` never -/// converts between months, days, and hours. The previous code split months -/// greater than 11 into years+months and hours greater than 23 into days, -/// which changed the output (e.g. 48 hours became "2 days", 13 months became -/// "1 year 1 mons"). PostgreSQL keeps each field independent and formats the -/// raw values directly. The unit name is "mon"/"mons" (not "month"/"months"). +/// INTERVAL (display path): 8-byte microseconds, 4-byte days, 4-byte months +/// (signed). Normalizes months > 11 into years+months and hours > 23 into +/// days+hours, matching the old built-in driver's display behavior. Used by +/// `extract_simple_kind` (the display path for `execute_query`). +/// +/// The lossless `read_rows` path uses [`PgIntervalText`] instead, which +/// preserves the raw wire values without normalization. struct Interval { months: i32, days: i32, @@ -2149,6 +2197,113 @@ impl<'a> FromSql<'a> for Interval { impl From for JsonValue { fn from(v: Interval) -> Self { + // Normalize: split months > 11 into years+months, hours > 23 into + // days+hours. Matches the old built-in driver's display behavior. + let mut months = v.months; + let mut days = v.days; + let mut micros = v.time_micros; + + let mut years = 0i32; + if !(-11..=11).contains(&months) { + years = months / 12; + months %= 12; + } + + let sign = if micros < 0 { + micros = -micros; + '-' + } else { + '+' + }; + let mut hrs = micros / (1_000_000 * 60 * 60); + micros %= 1_000_000 * 60 * 60; + let mins = (micros / (1_000_000 * 60)) as u8; + micros %= 1_000_000 * 60; + let secs = (micros / 1_000_000) as u8; + let micros = (micros % 1_000_000) as u32; + + if !(-23..=23).contains(&hrs) { + days += (hrs / 24) as i32; + hrs %= 24; + } + + let mut s = String::new(); + if years != 0 { + let unit = if years == 1 || years == -1 { + "year" + } else { + "years" + }; + s.push_str(&format!("{} {} ", years, unit)); + } + if months != 0 { + let unit = if months == 1 || months == -1 { + "month" + } else { + "months" + }; + s.push_str(&format!("{} {} ", months, unit)); + } + if days != 0 { + let unit = if days == 1 || days == -1 { + "day" + } else { + "days" + }; + s.push_str(&format!("{} {} ", days, unit)); + } + if hrs != 0 || mins != 0 || secs != 0 || micros != 0 { + if sign != '+' { + s.push(sign); + } + s.push_str(&format!("{:02}:{:02}:{:02}", hrs, mins, secs)); + if micros != 0 { + s.push('.'); + s.push_str(format!("{:06}", micros).trim_end_matches('0')); + } + } + + if s.is_empty() { + JsonValue::String("00:00:00".to_string()) + } else { + JsonValue::String(s.trim_end().to_string()) + } + } +} + +/// INTERVAL (lossless path): preserves raw months/days/micros without +/// normalization, matching PostgreSQL's `interval_out`. `48 hours` stays +/// `"48:00:00"` (not `"2 days"`); `13 months` stays `"13 mons"` (not +/// `"1 year 1 mons"`). The unit name is `"mon"/"mons"` (PostgreSQL's +/// `interval_out` convention, not `"month"/"months"`). +struct PgIntervalText { + months: i32, + days: i32, + time_micros: i64, +} + +impl<'a> FromSql<'a> for PgIntervalText { + fn from_sql(_ty: &Type, raw: &[u8]) -> Result> { + if raw.len() < 16 { + return Err(format!("expected 16 bytes for INTERVAL, got {}", raw.len()).into()); + } + let time_micros = i64::from_be_bytes(raw[0..8].try_into().unwrap()); + let days = i32::from_be_bytes(raw[8..12].try_into().unwrap()); + let months = i32::from_be_bytes(raw[12..16].try_into().unwrap()); + Ok(Self { + months, + days, + time_micros, + }) + } + + fn accepts(ty: &Type) -> bool { + *ty == Type::INTERVAL + } +} + +impl From for JsonValue { + fn from(v: PgIntervalText) -> Self { let mut parts: Vec = Vec::new(); if v.months != 0 { @@ -2181,7 +2336,8 @@ impl From for JsonValue { if sign == '-' { time_str.push(sign); } - time_str.push_str(&format!("{}:{:02}:{:02}", hrs, mins, secs)); + // Zero-pad hours to 2 digits, matching PostgreSQL's interval_out. + time_str.push_str(&format!("{:02}:{:02}:{:02}", hrs, mins, secs)); if micros != 0 { time_str.push('.'); time_str.push_str(format!("{:06}", micros).trim_end_matches('0')); diff --git a/src/extract_tests.rs b/src/extract_tests.rs index c1e8f81..0609ff0 100644 --- a/src/extract_tests.rs +++ b/src/extract_tests.rs @@ -2366,14 +2366,17 @@ fn pg_timestamptz_full_decodes_infinity_sentinel_as_text_no_offset() { } #[test] -fn pg_timestamp_full_year_10000_keeps_plus_sign() { +fn pg_timestamp_full_year_10000_no_plus_sign() { use tokio_postgres::types::FromSql; // 10000-01-01 00:00:00 = 2921940 days * 86_400_000_000 µs/day. + // PostgreSQL's date/timestamp input parser rejects the `+` prefix + // ("time zone displacement out of range"), so the lossless path must + // emit `10000-01-01` (no `+`), not `+10000-01-01`. let bytes = (2_921_940_i64 * 86_400_000_000).to_be_bytes(); let t = crate::extract::PgTimestampFull::from_sql(&Type::TIMESTAMP, &bytes).unwrap(); assert_eq!( serde_json::Value::from(t), - serde_json::json!("+10000-01-01 00:00:00") + serde_json::json!("10000-01-01 00:00:00") ); } @@ -2531,7 +2534,7 @@ fn interval_formats_all_three_components() { // 3 months + 2 days + 1 hour 30 min: "3 mons 2 days 01:30:00" let micros = 3_600_000_000 + (30 * 60_000_000); // 1h30m in micros let v = decode_interval(micros, 2, 3); - assert_eq!(v, serde_json::json!("3 mons 2 days 1:30:00")); + assert_eq!(v, serde_json::json!("3 mons 2 days 01:30:00")); } #[test] @@ -2545,14 +2548,14 @@ fn interval_zero_decodes_to_00_00_00() { fn interval_negative_microseconds_get_sign_prefix() { // -1 hour = -3600000000 micros → "-01:00:00" let v = decode_interval(-3_600_000_000, 0, 0); - assert_eq!(v, serde_json::json!("-1:00:00")); + assert_eq!(v, serde_json::json!("-01:00:00")); } #[test] fn interval_keeps_fractional_seconds() { // 1.5 seconds = 1500000 micros → "00:00:01.5" let v = decode_interval(1_500_000, 0, 0); - assert_eq!(v, serde_json::json!("0:00:01.5")); + assert_eq!(v, serde_json::json!("00:00:01.5")); } #[test] @@ -2667,10 +2670,12 @@ fn format_date_with_bc_emits_positive_year_plus_bc_for_negative_years() { } #[test] -fn format_date_with_bc_large_ad_year_keeps_plus_sign() { +fn format_date_with_bc_large_ad_year_no_plus_sign() { + // PostgreSQL's date input parser rejects the `+` prefix, so the lossless + // path must emit `10000-01-01` (no `+`), not `+10000-01-01`. assert_eq!( crate::extract::format_date_with_bc(10000, 1, 1), - "+10000-01-01" + "10000-01-01" ); } @@ -2716,12 +2721,14 @@ fn pg_date_full_ad_year_remains_unaffected_by_bc_change() { fn pg_timestamp_full_bc_year_emits_bc_suffix() { use tokio_postgres::types::FromSql; // 50 BC 00:00:00 = astronomical year -49 = -748382 days * 86400000000 micros. + // PostgreSQL places ` BC` at the END of the timestamp string, not after + // the date: `"0050-01-01 00:00:00 BC"`, not `"0050-01-01 BC 00:00:00"`. let micros = -748_382_i64 * 86_400_000_000; let bytes = micros.to_be_bytes(); let v = PgTimestampFull::from_sql(&Type::TIMESTAMP, &bytes).unwrap(); assert_eq!( serde_json::Value::from(v), - serde_json::json!("0050-01-01 BC 00:00:00") + serde_json::json!("0050-01-01 00:00:00 BC") ); } @@ -2729,15 +2736,61 @@ fn pg_timestamp_full_bc_year_emits_bc_suffix() { fn pg_timestamptz_full_bc_year_emits_bc_suffix_with_offset() { use tokio_postgres::types::FromSql; // 50 BC 00:00:00 UTC = same wire as TIMESTAMP. + // PostgreSQL places `+00` offset before ` BC`: `"0050-01-01 00:00:00+00 BC"`. let micros = -748_382_i64 * 86_400_000_000; let bytes = micros.to_be_bytes(); let v = PgTimestampTzFull::from_sql(&Type::TIMESTAMPTZ, &bytes).unwrap(); assert_eq!( serde_json::Value::from(v), - serde_json::json!("0050-01-01 BC 00:00:00+00:00") + serde_json::json!("0050-01-01 00:00:00+00:00 BC") ); } +#[test] +fn pg_timestamptz_full_year_10000_no_plus_sign() { + use tokio_postgres::types::FromSql; + // PostgreSQL's timestamptz input parser rejects the `+` prefix for years + // ≥ 10000, so the lossless path must emit `10000-01-01 00:00:00+00:00`. + let micros = 2_921_940_i64 * 86_400_000_000; + let bytes = micros.to_be_bytes(); + let v = PgTimestampTzFull::from_sql(&Type::TIMESTAMPTZ, &bytes).unwrap(); + assert_eq!( + serde_json::Value::from(v), + serde_json::json!("10000-01-01 00:00:00+00:00") + ); +} + +#[test] +fn format_date_no_bc_ad_year_in_range() { + assert_eq!( + crate::extract::format_date_no_bc(2026, 11, 29), + "2026-11-29" + ); + assert_eq!(crate::extract::format_date_no_bc(1000, 1, 1), "1000-01-01"); + assert_eq!(crate::extract::format_date_no_bc(999, 1, 1), "0999-01-01"); + assert_eq!(crate::extract::format_date_no_bc(1, 1, 1), "0001-01-01"); +} + +#[test] +fn format_date_no_bc_large_ad_year_no_plus_sign() { + assert_eq!( + crate::extract::format_date_no_bc(10000, 1, 1), + "10000-01-01" + ); + assert_eq!( + crate::extract::format_date_no_bc(5874897, 12, 31), + "5874897-12-31" + ); +} + +#[test] +fn format_date_no_bc_bc_year_uses_bc_numbering() { + // 50 BC = astronomical year -49; 1 BC = astronomical year 0. + assert_eq!(crate::extract::format_date_no_bc(-49, 3, 15), "0050-03-15"); + assert_eq!(crate::extract::format_date_no_bc(0, 1, 1), "0001-01-01"); + assert_eq!(crate::extract::format_date_no_bc(-4712, 1, 1), "4713-01-01"); +} + // --- #222: Lossless array elements use lossless byte-level decoder --- #[test] diff --git a/src/handlers/copy.rs b/src/handlers/copy.rs index 325d546..487e2c3 100644 --- a/src/handlers/copy.rs +++ b/src/handlers/copy.rs @@ -50,16 +50,26 @@ pub fn clear_copy_session_query(session_id: &str) { } /// Strip a trailing `-- ...` line comment from a query string. The -/// cursor path's `build_paginated_query` uses a comment-aware lexer; the +/// one-shot path's `build_paginated_query` uses a comment-aware lexer; the /// cursor path must too, or a trailing `-- comment` breaks DECLARE (#222). -/// This is a simple version that doesn't handle `--` inside strings -- the -/// query comes from the host (trusted) and is a single SELECT. -fn strip_trailing_line_comment(query: &str) -> &str { - if let Some(pos) = query.rfind("--") { - let before = &query[..pos]; - let single_quotes = before.matches('\'').count() - before.matches("''").count(); +/// This handles only a trailing comment on the *last line* — `--` on an +/// earlier line (e.g. an inline comment before a WHERE clause) is NOT +/// stripped. The query comes from the host (trusted) and is a single SELECT. +pub(crate) fn strip_trailing_line_comment(query: &str) -> &str { + // Find the start of the last line (after the last newline). + let last_line_start = query.rfind('\n').map(|p| p + 1).unwrap_or(0); + let last_line = &query[last_line_start..]; + + // Check if the last line starts with or contains `--` (outside strings). + if let Some(pos) = last_line.find("--") { + let before_last_line = &query[..last_line_start + pos]; + // Count unescaped single quotes across the ENTIRE string before the `--`. + // Each `''` pair consumes 2 quote chars, so subtract 2× the pair count. + let single_quotes = + before_last_line.matches('\'').count() - 2 * before_last_line.matches("''").count(); if single_quotes.is_multiple_of(2) { - return before.trim_end(); + // Not inside a string — strip the comment. + return before_last_line.trim_end(); } } query @@ -221,13 +231,16 @@ async fn run_one_shot( let result = fetch_lossless(&pg_client, final_query, page, page_size).await; // End the read-only transaction: COMMIT on success, ROLLBACK on failure. // Both end the transaction so the connection returns to the pool clean. + // `SET LOCAL` (e.g. search_path) is transaction-scoped and is reverted by + // COMMIT/ROLLBACK — no extra cleanup needed. We do NOT run `RESET ALL` + // here because it would also wipe the startup script's session-level GUCs + // and the `app.tabularis_base_search_path` snapshot GUC that prevents + // search_path accumulation (#51). A query that sets a *session-level* GUC + // via `set_config(..., false)` would leak, but that is the caller's + // responsibility — the host only sends `SELECT` on this path. let _ = pg_client .batch_execute(if result.is_ok() { "COMMIT" } else { "ROLLBACK" }) .await; - // Clear any session-level GUCs the read may have set (e.g. SET LOCAL - // search_path) so they don't leak to the next borrower via the recycled - // pooled connection (#222). - let _ = pg_client.batch_execute("RESET ALL").await; drop(cancel_guard); result } diff --git a/src/handlers/copy_tests.rs b/src/handlers/copy_tests.rs index 3550960..6f64d35 100644 --- a/src/handlers/copy_tests.rs +++ b/src/handlers/copy_tests.rs @@ -3,7 +3,7 @@ //! exercise the request-validation surface that does NOT need a connection: //! an empty/missing `query` returns a clear error before any DB call. -use crate::handlers::copy::{insert_records, read_rows}; +use crate::handlers::copy::{insert_records, read_rows, strip_trailing_line_comment}; use serde_json::{json, Value}; #[tokio::test] @@ -180,3 +180,64 @@ async fn read_rows_rejects_a_non_result_set_query_on_the_session_path() { "non-result-set should error: {resp}" ); } + +// --- strip_trailing_line_comment (#222) --- + +#[test] +fn strip_removes_a_trailing_comment() { + assert_eq!( + strip_trailing_line_comment("SELECT 1 -- get count"), + "SELECT 1" + ); +} + +#[test] +fn strip_preserves_a_query_with_no_comment() { + assert_eq!( + strip_trailing_line_comment("SELECT 1, 2, 3"), + "SELECT 1, 2, 3" + ); +} + +#[test] +fn strip_only_strips_the_last_line() { + // `--` on an earlier line (an inline comment before a WHERE clause) is + // NOT stripped — only a trailing comment on the last line is. + let q = "SELECT 1 -- first\nFROM t -- last"; + assert_eq!(strip_trailing_line_comment(q), "SELECT 1 -- first\nFROM t"); +} + +#[test] +fn strip_handles_doubled_single_quotes() { + // `WHERE name = 'it''s here' -- c`: the `''` is an escaped quote inside + // the string, so the `--` is outside the string and should be stripped. + assert_eq!( + strip_trailing_line_comment("SELECT * FROM t WHERE name = 'it''s here' -- c"), + "SELECT * FROM t WHERE name = 'it''s here'" + ); +} + +#[test] +fn strip_does_not_strip_dashdash_inside_a_string() { + // `--` inside a string literal on the last line is not a comment. + assert_eq!( + strip_trailing_line_comment("SELECT 'a--b'"), + "SELECT 'a--b'" + ); +} + +#[test] +fn strip_handles_doubled_quotes_before_dashdash_in_string() { + // `SELECT 'a''b--c'`: the `--` is inside the string (after an escaped + // quote), so it must NOT be stripped. + assert_eq!( + strip_trailing_line_comment("SELECT 'a''b--c'"), + "SELECT 'a''b--c'" + ); +} + +#[test] +fn strip_preserves_trailing_semicolon_after_comment() { + // A trailing comment after a semicolon is stripped, leaving the semicolon. + assert_eq!(strip_trailing_line_comment("SELECT 1; -- c"), "SELECT 1;"); +}