From 9622142f3be0c2352d6638dc1ed9afb8f6cffc48 Mon Sep 17 00:00:00 2001 From: Adam J Esslinger Date: Thu, 3 Dec 2026 09:53:03 -0500 Subject: [PATCH 1/3] fix: read non-native copy columns as server text, close remaining copy gaps (#225) read_rows now projects every column that is not a native JSON type through ::text inside the read transaction (money via ::numeric::text), so values are the server's own output instead of hand-written binary decoders. This closes multi-dimensional arrays, array lower bounds, 1e400 and wide jsonb numbers, json duplicate keys, tstzrange offsets and interval normalization in one mechanism, and deletes the lossless decoders that kept diverging. Column metadata comes from prepare, so a zero-row result reports its columns. - one-shot reads always ROLLBACK, so set_config(..., false) cannot leak into the pooled connection - trailing comments and semicolons are trimmed with the pagination lexer, fixing `select 1 -- c\n` on the session path - a negative or non-integer limit is a -32602 error, not 1000 - insert_records casts otherwise-unrecognized values to the column's qualified type (composites, lower-bound arrays) and accepts objects in jsonb[] arrays Co-Authored-By: Adam J Esslinger --- README.md | 70 +-- src/binding.rs | 46 +- src/binding_tests.rs | 107 ++++ src/client.rs | 10 +- src/client_live_tests.rs | 224 +++++++- src/extract.rs | 1009 ++++----------------------------- src/extract_tests.rs | 952 +------------------------------ src/handlers/copy.rs | 405 +++++++------ src/handlers/copy_tests.rs | 116 ++-- src/handlers/crud.rs | 6 + src/utils/pagination.rs | 20 + src/utils/pagination_tests.rs | 50 +- 12 files changed, 904 insertions(+), 2111 deletions(-) diff --git a/README.md b/README.md index ddd1b1a..5d32070 100644 --- a/README.md +++ b/README.md @@ -197,7 +197,7 @@ instead of reconnecting. | `get_triggers` / `get_trigger_definition` / `create_trigger` / `drop_trigger` | Trigger lifecycle | | `execute_query` / `execute_query_batch` / `explain_query` | Query execution, multi-statement batches, and query plans. Both query methods accept an optional `session_id` that keeps the connection while an explicit transaction is open, and `manual_commit` for an editor tab in Manual commit (see [Manual commit](#manual-commit)) | | `execute_read_only_query` | Same request and response as `execute_query`, run in a transaction the database itself will not let write (see [Protected read-only queries](#protected-read-only-queries)) | -| `read_rows` | Lossless, optionally-snapshot read for host-driven table-to-table copy (see [Table copy](#table-copy)). Returns full-precision values (`timestamp(6)` fractional seconds, `timestamptz` offset, full `bytea`) plus the PostgreSQL type name + OID per column. An optional `session_id` pins a `REPEATABLE READ READ ONLY` snapshot across pages; release with `release_session`. Gated by the `table_copy` capability | +| `read_rows` | Lossless, optionally-snapshot read for host-driven table-to-table copy (see [Table copy](#table-copy)). Returns every non-native value as the server's own `::text` output (full `bytea` as base64) plus the PostgreSQL type name + OID per column. An optional `session_id` pins a `REPEATABLE READ READ ONLY` snapshot across pages; release with `release_session`. Gated by the `table_copy` capability | | `insert_records` | Batch typed insert for the table-copy write side (see [Table copy](#table-copy)). Reuses the type-aware binding cascade with column types discovered once per batch, in one transaction so a failed batch writes none of its rows. Gated by the `table_copy` capability | | `release_session` | Rolls back and releases the connection a session pinned for an open transaction | | `commit_session` / `rollback_session` / `get_session_state` | End a session's transaction, or report whether it holds one (see [Manual commit](#manual-commit)) | @@ -377,41 +377,43 @@ capability. The host gates its Transfer feature on that capability and calls preview, drops fractional seconds on `time`/`timestamp`, and drops both the fractional seconds and the timezone offset on `timestamptz`. A copy built on that format cannot meet the "reject any lossy conversion" rule the table transfer was -reviewed against. `read_rows` instead returns: - -- `timestamp(6)` / `time` with full fractional seconds (`HH:MM:SS.ffffff` when - 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` 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 +reviewed against. + +`read_rows` does not decode values itself where PostgreSQL's text form is the +contract (issue #225). It runs `prepare` on the query for the column metadata, +then selects every column that is not a native JSON type through `::text`, so +the value is exactly what the server's own output function prints: + +- native, decoded from the binary wire format: `bool`, `int2`/`int4`/`int8`, + `oid` (JSON numbers/booleans), `text`/`varchar`/`bpchar`/`name`, `uuid` + (strings), `float4`/`float8` (numbers, with `NaN` and `±Infinity` as the + strings `"NaN"`, `"Infinity"`, `"-Infinity"`), and `bytea` (base64 in full, + not the 10 KB preview) +- `money` as `::numeric::text` (`"123.45"`, not a locale-formatted amount) +- everything else as `::text`: `numeric`, dates and times (full fractional + seconds, BC values as `"0043-03-15 BC"`, `infinity`), `timestamptz` with the + session offset (`"2026-11-29 13:45:30.345678+00"`), `interval`, `json`/`jsonb` + (exact text, so `1e400`, wide numbers and `json` duplicate keys survive), + enums, `inet`, and arrays, ranges, multiranges and composites as PostgreSQL + text (`"{{1,2},{3,4}}"`, `"[2:3]={1,2}"`, `"[1,5)"`, `"(1,2)"`) — not JSON + arrays or objects - the PostgreSQL type name and OID per column, so the host can plan the - conversion + conversion; also returned for a result with zero rows + +The read transaction sets `DateStyle = 'ISO, MDY'`, `IntervalStyle = +'postgres'` and `extra_float_digits = 3` with `SET LOCAL`, so the text does not +depend on the connection's startup script, and always ends with `ROLLBACK`, so +a query that changes a setting with `set_config(…, false)` cannot leak it into +the pooled connection. With a `session_id`, the first page opens a `BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY` transaction on a pinned connection; subsequent pages reuse that connection and its snapshot, so rows are not skipped or repeated when the source table changes between pages. Release the snapshot with `release_session` (ROLLBACK). Without a `session_id`, the read is one-shot and not a snapshot, -and returns at most `limit` rows (no byte budget). +and returns at most `limit` rows (no byte budget). `limit` defaults to 1000 +and is clamped to 1..`MAX_PAGE_SIZE`; a negative or non-integer `limit` is +rejected with `-32602` instead of falling back to the default. With a `session_id`, a single response is bounded by a 16 MB byte budget (`MAX_RESPONSE_BYTES`): rows are fetched one at a time from the cursor and @@ -437,10 +439,12 @@ 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 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. +A value that no earlier step of the cascade recognizes (an array with explicit +lower bounds, a composite, a range, …) is bound as text and cast to the +column's schema-qualified type, `CAST($N AS public.point2d)`, so the text +`read_rows` returns for it is parsed by the target's own input function. Text +columns are never cast. A `jsonb[]` array may contain JSON objects; each one +is written as its JSON text. ## Building from Source diff --git a/src/binding.rs b/src/binding.rs index 2fb91ae..4f997ab 100644 --- a/src/binding.rs +++ b/src/binding.rs @@ -54,6 +54,12 @@ pub struct BindOptions<'a> { /// `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, + /// Schema-qualified, already-quoted type of the target column (see + /// `client::ColumnTypeInfo::qualified_type`). When a string value reaches + /// the end of the cascade for a column whose type takes no text assignment + /// (a composite, `jsonb[]`, a domain over one), it is bound as + /// `CAST($N AS )` so the type's input function parses it (#225). + pub cast_type: Option<&'a str>, } const USE_DEFAULT_SENTINEL: &str = "__USE_DEFAULT__"; @@ -476,13 +482,45 @@ fn bind_pg_string( } } - // 12. Final fallback: plain TEXT + // 12. A column whose type isn't text-like: let its input function parse + // the value. This is the text `read_rows` returns for composites, arrays, + // ranges and other types the steps above don't name (#225). Binding a + // TEXT parameter would fail for them anyway (no assignment cast), so this + // only changes values that used to error. No typmod: assignment to the + // column still enforces length/precision. + if let Some(cast_type) = options.cast_type { + if !is_text_like(base_type) { + return Ok(BoundValue { + sql: format!("CAST(${placeholder_idx} AS {cast_type})"), + param: Some((Box::new(s.to_string()), Type::TEXT)), + }); + } + } + + // 13. Final fallback: plain TEXT Ok(BoundValue { sql: format!("${}", placeholder_idx), param: Some((Box::new(s.to_string()), Type::TEXT)), }) } +/// Text-family target types, which take a plain TEXT parameter as is. +fn is_text_like(base_type: Option<&str>) -> bool { + matches!( + base_type, + None | Some( + "TEXT" + | "CHARACTER VARYING" + | "VARCHAR" + | "CHARACTER" + | "CHAR" + | "BPCHAR" + | "NAME" + | "CITEXT" + ) + ) +} + /// Bind a value into an enum column via `CAST($N AS )`. /// The placeholder is pinned to `TEXT` so tokio-postgres does not reject the /// bound `String` client-side before the CAST resolves it server-side. @@ -613,7 +651,9 @@ fn json_array_to_pg_literal(arr: &[Value]) -> Result { } Value::Null => "NULL".to_string(), Value::Array(nested) => json_array_to_pg_literal(nested)?, - Value::Object(_) => return Err("Unsupported array element type".to_string()), + // A JSON object element (a `jsonb[]` value given as objects): its + // JSON text, for the `CAST(… AS jsonb[])` around the array (#225). + Value::Object(_) => format!("'{}'", elem.to_string().replace('\'', "''")), }; parts.push(part); } @@ -711,7 +751,7 @@ fn bind_pg_numeric_string( // the round-trip (a `numeric(40,36)` value would lose precision with // no error). Always-TEXT+CAST avoids that: PostgreSQL's own `numeric` // parser preserves the full precision, and `NaN`/`Infinity` are - // accepted exactly as `read_rows`' `PgNumeric` emits them (#214 item 1 + // accepted exactly as `read_rows` emits them (`numeric::text`) (#214 item 1 // + review finding). Mirrors the UUID-shape fallback's TEXT+CAST // pattern below. A non-numeric string is still rejected client-side by // `looks_like_numeric_literal` so the PK path keeps its early rejection. diff --git a/src/binding_tests.rs b/src/binding_tests.rs index cb45a0f..1eeffda 100644 --- a/src/binding_tests.rs +++ b/src/binding_tests.rs @@ -86,6 +86,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: None, char_max_len: None, + cast_type: None, }; let bound = bind_pg_value(json!({"a": 1}), 1, &options).unwrap(); assert_eq!(bound.sql, "$1"); @@ -105,6 +106,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: None, char_max_len: None, + cast_type: None, }; let bound = bind_pg_value(json!("{\"a\":1}"), 1, &options).unwrap(); assert_eq!(bound.sql, "CAST($1 AS jsonb)"); @@ -121,6 +123,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: None, char_max_len: None, + cast_type: None, }; let bound = bind_pg_value(json!("\"hello\""), 1, &options).unwrap(); assert_eq!(bound.sql, "CAST($1 AS json)"); @@ -136,6 +139,7 @@ mod bind_pg_value_tests { allow_default: true, hstore_oid: None, char_max_len: None, + cast_type: None, }; let bound = bind_pg_value(json!("__USE_DEFAULT__"), 1, &options).unwrap(); assert_eq!(bound.sql, "DEFAULT"); @@ -150,6 +154,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: None, char_max_len: None, + cast_type: None, }; let bound = bind_pg_value(json!("__USE_DEFAULT__"), 1, &options).unwrap(); // Falls through to the plain TEXT fallback, not treated as DEFAULT. @@ -177,6 +182,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: None, char_max_len: None, + cast_type: None, }; let bound = bind_pg_value(json!("sad"), 1, &options).unwrap(); assert_eq!(bound.sql, "CAST($1 AS \"test_schema\".\"mood\")"); @@ -194,6 +200,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: None, char_max_len: None, + cast_type: None, }; let bound = bind_pg_value(json!("a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"), 1, &options).unwrap(); @@ -208,6 +215,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: None, char_max_len: None, + cast_type: None, }; for truthy in ["true", "t", "yes", "y", "on", "1", "TRUE"] { let bound = bind_pg_value(json!(truthy), 1, &options).unwrap(); @@ -223,6 +231,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: None, char_max_len: None, + cast_type: None, }; let err = bind_pg_value(json!("maybe"), 1, &options).unwrap_err(); assert!(err.contains("boolean")); @@ -236,6 +245,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: None, char_max_len: None, + cast_type: None, }; let bound = bind_pg_value(json!("42"), 1, &options).unwrap(); assert_eq!(bound.sql, "CAST($1 AS bigint)"); @@ -249,6 +259,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: None, char_max_len: None, + cast_type: None, }; let err = bind_pg_value(json!("not-a-number"), 1, &options).unwrap_err(); assert!(err.contains("integer")); @@ -262,6 +273,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: None, char_max_len: None, + cast_type: None, }; let bound = bind_pg_value(json!("12345.67"), 1, &options).unwrap(); assert_eq!(bound.sql, "CAST($1 AS numeric)"); @@ -279,6 +291,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: None, char_max_len: None, + cast_type: None, }; let wide = "12345678901234567890123456789012345678.1234567890"; let bound = bind_pg_value(json!(wide), 1, &options).unwrap(); @@ -298,6 +311,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: None, char_max_len: None, + cast_type: None, }; let bound = bind_pg_value(json!("NaN"), 1, &options).unwrap(); assert_eq!(bound.sql, "CAST($1 AS numeric)"); @@ -314,6 +328,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: None, char_max_len: None, + cast_type: None, }; let bound = bind_pg_value(json!("99999999999999999999999999999999999999"), 1, &options).unwrap(); @@ -333,6 +348,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: None, char_max_len: None, + cast_type: None, }; assert!(bind_pg_value(json!("abc"), 1, &options).is_err()); assert!(bind_pg_value(json!("1.2.3"), 1, &options).is_err()); @@ -349,6 +365,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: None, char_max_len: None, + cast_type: None, }; // Exponent form. assert!(bind_pg_value(json!("1e10"), 1, &options).is_ok()); @@ -367,6 +384,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: None, char_max_len: None, + cast_type: None, }; let bound = bind_pg_value(json!("2026-01-15 14:30:00"), 1, &options).unwrap(); assert_eq!(bound.sql, "CAST($1 AS timestamp)"); @@ -380,6 +398,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: None, char_max_len: None, + cast_type: 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)"); @@ -427,6 +446,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: Some(16_500), char_max_len: None, + cast_type: None, }; let bound = bind_pg_value(json!({"key": "value", "other": "thing"}), 1, &options).unwrap(); @@ -444,6 +464,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: Some(16_500), char_max_len: None, + cast_type: None, }; let bound = bind_pg_value(json!({"key": null}), 1, &options).unwrap(); @@ -459,6 +480,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: Some(16_500), char_max_len: None, + cast_type: None, }; let bound = bind_pg_value(Value::Null, 1, &options).unwrap(); @@ -476,6 +498,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: Some(16_500), char_max_len: None, + cast_type: None, }; let bound = bind_pg_value(json!("{\"key\": \"value\"}"), 1, &options).unwrap(); @@ -491,6 +514,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: Some(16_500), char_max_len: None, + cast_type: None, }; let err = bind_pg_value(json!({"key": 42}), 1, &options).unwrap_err(); @@ -506,6 +530,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: Some(16_500), char_max_len: None, + cast_type: None, }; let err = bind_pg_value(json!(42), 1, &options).unwrap_err(); @@ -520,6 +545,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: None, char_max_len: None, + cast_type: None, }; let err = bind_pg_value(json!({"key": "value"}), 1, &options).unwrap_err(); @@ -534,6 +560,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: None, char_max_len: None, + cast_type: None, }; let bound = bind_pg_value(json!("[1,2,3]"), 1, &options).unwrap(); @@ -549,6 +576,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: None, char_max_len: None, + cast_type: None, }; let bound = bind_pg_value(json!("[1,2,3]"), 1, &options).unwrap(); @@ -563,6 +591,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: None, char_max_len: None, + cast_type: None, }; let bound = bind_pg_value(json!("{1:1,3:2}/5"), 1, &options).unwrap(); @@ -577,6 +606,7 @@ mod bind_pg_value_tests { allow_default: false, hstore_oid: None, char_max_len: None, + cast_type: None, }; let err = bind_pg_value(json!("'; DROP TABLE users; --"), 1, &options).unwrap_err(); @@ -1303,3 +1333,80 @@ mod build_pk_map_predicate_tests { assert_eq!(err, "pk_map must not be empty"); } } + +// --- #225: last-resort CAST to the column's own type, jsonb[] objects --- +mod cast_type_fallback_tests { + use super::*; + + fn opts<'a>(column_type: &'a str, cast_type: &'a str) -> BindOptions<'a> { + BindOptions { + column_type: Some(column_type), + cast_type: Some(cast_type), + ..BindOptions::default() + } + } + + #[test] + fn composite_text_casts_to_the_composite_type() { + // read_rows returns a composite as its `::text`; binding it as TEXT + // would fail (no assignment cast), so it goes through the type. + let bound = + bind_pg_value(json!("(1,2)"), 3, &opts("point2d", r#"public.point2d"#)).unwrap(); + assert_eq!(bound.sql, "CAST($3 AS public.point2d)"); + assert_eq!(bound.param.unwrap().1, tokio_postgres::types::Type::TEXT); + } + + #[test] + fn array_text_with_lower_bounds_casts_to_the_array_type() { + let bound = + bind_pg_value(json!("[2:3]={1,2}"), 1, &opts("_int4", "pg_catalog._int4")).unwrap(); + assert_eq!(bound.sql, "CAST($1 AS pg_catalog._int4)"); + } + + #[test] + fn text_family_columns_still_bind_plain_text() { + for ty in ["text", "character varying", "character", "citext"] { + let bound = bind_pg_value(json!("(1,2)"), 1, &opts(ty, "pg_catalog.text")).unwrap(); + assert_eq!(bound.sql, "$1", "{ty}"); + } + } + + #[test] + fn earlier_cascade_steps_win_over_the_fallback() { + // A typed step that already handles the column type is unchanged. + let bound = bind_pg_value(json!("10.0.0.1"), 1, &opts("inet", "pg_catalog.inet")).unwrap(); + assert_eq!(bound.sql, "CAST($1 AS inet)"); + let bound = bind_pg_value( + json!("1 year 2 mons"), + 1, + &opts("interval", r#"pg_catalog."interval""#), + ) + .unwrap(); + assert_eq!(bound.sql, "CAST($1 AS interval)"); + } + + #[test] + fn without_a_cast_type_the_text_fallback_is_unchanged() { + let options = BindOptions { + column_type: Some("point2d"), + ..BindOptions::default() + }; + let bound = bind_pg_value(json!("(1,2)"), 1, &options).unwrap(); + assert_eq!(bound.sql, "$1"); + } + + #[test] + fn jsonb_array_of_objects_binds_each_object_as_json_text() { + let bound = bind_pg_value( + json!([{"a": 1}, {"b": "it's"}]), + 1, + &opts("_jsonb", "pg_catalog._jsonb"), + ) + .unwrap(); + assert_eq!( + bound.sql, + r#"CAST(ARRAY['{"a":1}', '{"b":"it''s"}'] AS jsonb[])"# + ); + assert!(bound.param.is_none()); + } +} diff --git a/src/client.rs b/src/client.rs index 293f443..e783c1e 100644 --- a/src/client.rs +++ b/src/client.rs @@ -264,6 +264,11 @@ pub async fn query_typed( pub struct ColumnTypeInfo { pub type_name: String, pub char_max_len: Option, + /// Schema-qualified, quoted type name without a typmod (e.g. + /// `pg_catalog._int4`, `public.point2d`), from `format('%I.%I')` so it is + /// safe to splice into `CAST($N AS …)`. Binding's last resort for a type + /// with no text→type assignment cast (#225). + pub qualified_type: Option, } /// Fetch data types for every column in a table as a name -> type map. @@ -284,7 +289,8 @@ pub async fn get_column_types_map( WHEN data_type = 'ARRAY' THEN udt_name ELSE data_type END AS resolved_type, - character_maximum_length + character_maximum_length, + format('%I.%I', udt_schema, udt_name) AS qualified_type FROM information_schema.columns WHERE table_schema = $1 AND table_name = $2 "#; @@ -299,11 +305,13 @@ pub async fn get_column_types_map( .ok() .flatten() .map(|v| v as i64); + let qualified_type: Option = r.try_get("qualified_type").ok(); Some(( name, ColumnTypeInfo { type_name: ty, char_max_len, + qualified_type, }, )) }) diff --git a/src/client_live_tests.rs b/src/client_live_tests.rs index f1bbea0..2b59ff5 100644 --- a/src/client_live_tests.rs +++ b/src/client_live_tests.rs @@ -442,10 +442,11 @@ async fn read_rows_returns_lossless_values_for_table_copy() { json!("2026-11-29 13:45:30.345678"), "timestamp(6): {row:?}" ); - // timestamptz — fractional seconds AND +00:00 offset preserved. + // timestamptz — the server's own text: fractional seconds and the + // session-TimeZone offset (#225: read as `::text`, not hand-formatted). assert_eq!( row[2], - json!("2026-11-29 13:45:30.345678+00:00"), + json!("2026-11-29 13:45:30.345678+00"), "timestamptz: {row:?}" ); // bytea >10 KB — full base64 (not the 10 KB preview). The BLOB header's @@ -462,7 +463,7 @@ async fn read_rows_returns_lossless_values_for_table_copy() { payload_len > 14_000, "bytea payload should be full (>10KB), got {payload_len} chars" ); - // numeric(38,10) — exact decimal string, full scale (PgNumeric keeps the + // numeric(38,10) — exact decimal string, full scale (the server's numeric_out keeps the // trailing scale-10 zero that the old rust_decimal path trimmed). assert_eq!( row[4], @@ -470,7 +471,7 @@ async fn read_rows_returns_lossless_values_for_table_copy() { "numeric(38,10): {row:?}" ); // numeric(48,10) with 38 integer digits — beyond rust_decimal's 96-bit - // mantissa; the old lossless path returned Null here. PgNumeric keeps the + // mantissa; the old lossless path returned Null here. `::text` keeps the // full-precision string (#214 item 1). assert_eq!( row[5], @@ -478,7 +479,7 @@ async fn read_rows_returns_lossless_values_for_table_copy() { "numeric(48,10) wide: {row:?}" ); // numeric NaN — rust_decimal cannot represent it (the old path returned - // Null); PgNumeric returns the "NaN" string (#214 item 1). + // Null); `::text` returns the "NaN" string (#214 item 1). assert_eq!(row[6], json!("NaN"), "numeric NaN: {row:?}"); // float8 — native number. assert_eq!(row[7], json!(2.5), "float8: {row:?}"); @@ -498,6 +499,219 @@ async fn read_rows_returns_lossless_values_for_table_copy() { POOLS.lock().unwrap().remove(&key); } +/// #225: every value `read_rows` doesn't decode natively must be exactly the +/// server's own `col::text`, on both the one-shot and the session path — the +/// shapes #220/#222/#225 found hand-written decoders getting wrong. Then +/// `insert_records` must write that text back so the copy is identical, and an +/// empty source must still report `columns`. +#[tokio::test] +#[ignore = "needs a live PostgreSQL (PG_PLUGIN_TEST_HOST=127.0.0.1 ... podman 54320)"] +async fn read_rows_returns_the_servers_text_for_every_non_native_type() { + use crate::client; + use crate::handlers::copy::{insert_records, read_rows}; + use crate::handlers::query::release_session; + use serde_json::json; + + let _guard = POOLS_TEST_LOCK.lock().await; + let params = live_params(&correct_password()).expect("PG_PLUGIN_TEST_HOST not set"); + let tag = uuid::Uuid::new_v4().simple().to_string(); + let (src, dst, ty) = ( + format!("plugin_test_225_src_{tag}"), + format!("plugin_test_225_dst_{tag}"), + format!("plugin_test_225_pt_{tag}"), + ); + let cols = "id int primary key, md int[], lb int[], jbig jsonb, jnum jsonb, jdup json, \ + tz tstzrange, iv14 interval, iv48 interval, comp {ty}, ja jsonb[], m money, \ + bc date, y10k timestamp, tsbc timestamptz, n numeric, f8 float8, by bytea"; + for stmt in [ + format!("DROP TABLE IF EXISTS {src}"), + format!("DROP TABLE IF EXISTS {dst}"), + format!("DROP TYPE IF EXISTS {ty}"), + format!("CREATE TYPE {ty} AS (x int, y text)"), + format!("CREATE TABLE {src} ({})", cols.replace("{ty}", &ty)), + format!("CREATE TABLE {dst} ({})", cols.replace("{ty}", &ty)), + format!( + "INSERT INTO {src} VALUES (1, '{{{{1,2}},{{3,4}}}}', '[2:3]={{1,2}}', '1e400', \ + '{{\"a\": 12345678901234567890123.5}}', '{{\"a\":1,\"a\":2}}', \ + '[\"2024-01-01 00:00:00+05\",\"2024-02-01 00:00:00+00\")', '14 months', \ + '48 hours', '(1,\"it''s\")', ARRAY['{{\"k\": 1e400}}'::jsonb, 'null'], 123.45, \ + '0044-03-15 BC', '10000-01-01 00:00:00', '0050-03-15 12:30:45+00 BC', \ + '123456789012345678901234567890.123456789', 'NaN', '\\x00ff')" + ), + ] { + client::execute_typed(¶ms, &stmt, &[]) + .await + .unwrap_or_else(|e| panic!("setup failed ({stmt}): {e}")); + } + + let names = [ + "md", "lb", "jbig", "jnum", "jdup", "tz", "iv14", "iv48", "comp", "ja", "bc", "y10k", + "tsbc", "n", + ]; + // The server's own text for each, in a session with the same settings. + let expect_sql = format!( + "SELECT {} FROM {src}", + names.map(|c| format!("{c}::text")).join(", ") + ); + let expected = client::query_rows(¶ms, &expect_sql, &[]).await.unwrap(); + let expected: Vec = (0..names.len()).map(|i| expected[0].get(i)).collect(); + + let conn = json!({ + "driver": "postgresql", + "host": params.host, "port": params.port, + "database": params.database, "username": params.username, "password": params.password, + }); + let mut req = conn.clone(); + // A trailing comment plus newline, the way a pasted statement ends (#225). + req["query"] = json!(format!("SELECT * FROM {src} -- copy\n")); + let mut session_req = req.clone(); + session_req["session_id"] = json!(format!("copy225_{tag}")); + + for (label, r) in [("one-shot", &req), ("session", &session_req)] { + let resp = read_rows(json!(1), r).await; + let result = resp + .get("result") + .unwrap_or_else(|| panic!("{label}: read_rows failed: {resp}")); + let columns = result["columns"].as_array().unwrap(); + let row = result["rows"][0].as_array().unwrap(); + let at = |name: &str| { + let i = columns.iter().position(|c| c["name"] == name).unwrap(); + (&columns[i], &row[i]) + }; + for (name, want) in names.iter().zip(&expected) { + let (_, got) = at(name); + assert_eq!(got, &json!(want), "{label}: {name}"); + } + // Metadata is the source type, not the `text` the value was read as. + assert_eq!(at("md").0["type"], "_int4", "{label}"); + assert_eq!(at("tz").0["type"], "tstzrange", "{label}"); + // Natives and the special encodings are unchanged. + assert_eq!(*at("id").1, json!(1), "{label}"); + assert_eq!(*at("m").1, json!("123.45"), "{label}"); + assert_eq!(*at("f8").1, json!("NaN"), "{label}"); + assert_eq!( + *at("by").1, + json!("BLOB:2:application/octet-stream:AP8="), + "{label}" + ); + } + release_session( + json!(2), + &json!({"session_id": format!("copy225_{tag}"), "params": conn}), + ) + .await; + + // Round trip: write the read values to `dst`, then compare as text. + let resp = read_rows(json!(3), &req).await; + let result = &resp["result"]; + let columns: Vec<&str> = result["columns"] + .as_array() + .unwrap() + .iter() + .map(|c| c["name"].as_str().unwrap()) + .collect(); + let row = result["rows"][0].as_array().unwrap(); + let obj: serde_json::Map = columns + .iter() + .zip(row) + .map(|(c, v)| (c.to_string(), v.clone())) + .collect(); + let mut ins = conn.clone(); + ins["table"] = json!(dst); + ins["schema"] = json!("public"); + ins["rows"] = json!([obj]); + let resp = insert_records(json!(4), &ins).await; + assert!(resp.get("error").is_none(), "insert_records: {resp}"); + let diff = client::query_rows( + ¶ms, + &format!( + "SELECT count(*) FROM ((SELECT t::text FROM {src} t) EXCEPT (SELECT t::text FROM {dst} t)) d" + ), + &[], + ) + .await + .unwrap(); + assert_eq!( + diff[0].get::<_, i64>(0), + 0, + "copied row differs from source" + ); + + // An empty source still reports its columns. + let mut empty = conn.clone(); + empty["query"] = json!(format!("SELECT id, md FROM {src} WHERE false")); + let resp = read_rows(json!(5), &empty).await; + assert_eq!( + resp["result"]["columns"], + json!([{"name": "id", "type": "int4", "oid": 23}, {"name": "md", "type": "_int4", "oid": 1007}]), + "{resp}" + ); + + for stmt in [ + format!("DROP TABLE IF EXISTS {src}"), + format!("DROP TABLE IF EXISTS {dst}"), + format!("DROP TYPE IF EXISTS {ty}"), + ] { + let _ = client::execute_typed(¶ms, &stmt, &[]).await; + } + POOLS.lock().unwrap().remove(&connection_key(¶ms)); +} + +/// #225: a one-shot `read_rows` that sets a session-level GUC must not leak it +/// to the next borrower of the pooled connection — the read transaction always +/// ROLLBACKs — while a GUC from the connection's startup script survives. +#[tokio::test] +#[ignore = "needs a live PostgreSQL (PG_PLUGIN_TEST_HOST=127.0.0.1 ... podman 54320)"] +async fn read_rows_one_shot_does_not_leak_session_gucs() { + use crate::handlers::copy::read_rows; + use serde_json::json; + + let _guard = POOLS_TEST_LOCK.lock().await; + let mut params = live_params(&correct_password()).expect("PG_PLUGIN_TEST_HOST not set"); + params.startup_script = Some("SET application_name = 'startup_225'".into()); + POOLS.lock().unwrap().remove(&connection_key(¶ms)); + let req = |query: &str| { + json!({ + "driver": "postgresql", "host": params.host, "port": params.port, + "database": params.database, "username": params.username, + "password": params.password, "startup_script": params.startup_script, + "query": query, + }) + }; + let first = |resp: serde_json::Value| resp["result"]["rows"][0].clone(); + + let set = first( + read_rows( + json!(1), + &req("SELECT set_config('probe.leak', 'yes', false), pg_backend_pid()"), + ) + .await, + ); + let pid = set[1].clone(); + for _ in 0..5 { + let row = first( + read_rows( + json!(2), + &req( + "SELECT coalesce(current_setting('probe.leak', true), ''), \ + current_setting('application_name'), pg_backend_pid()", + ), + ) + .await, + ); + assert_eq!(row[2], pid, "expected the same pooled backend"); + // After a rollback PostgreSQL keeps the custom GUC's placeholder with + // an empty value; what must not survive is the value the query set. + assert_ne!(row[0], json!("yes"), "session GUC leaked: {row}"); + assert_eq!( + row[1], + json!("startup_225"), + "startup script GUC lost: {row}" + ); + } + POOLS.lock().unwrap().remove(&connection_key(¶ms)); +} + /// A `read_rows` with a `session_id` pages through a server-side cursor inside /// a `REPEATABLE READ` snapshot (#214 item 4): page 1 DECLAREs the cursor and /// FETCHes the first page; page 2 FETCHes the next page from the same cursor diff --git a/src/extract.rs b/src/extract.rs index 641c3cd..cfa98f2 100644 --- a/src/extract.rs +++ b/src/extract.rs @@ -190,147 +190,47 @@ 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`) -/// 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). +/// Extraction for the table-copy read path (`read_rows`). `read_rows` casts +/// every column it doesn't decode natively to `::text` server-side +/// (`handlers::copy::classify_column`), so this only sees bool, integers, +/// floats, bytea, text-like types and uuid. It differs from [`extract_value`] +/// in two ways: FLOAT4/FLOAT8 NaN and ±Infinity come back as the strings +/// PostgreSQL prints (`"NaN"`, `"Infinity"`, `"-Infinity"`) instead of `null` +/// (JSON has no literal for them), and BYTEA is base64-encoded in full instead +/// of as the 10 KB display preview. 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 - // ranges/composites — out of scope for this PR, scalar+array-only copy). - _ => extract_value(row, index), - } -} - -/// 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 - // no representation for them) and the display path's `float4_to_json` - // silently turns them into `Null` for the same reason. The lossless - // path returns the text strings PostgreSQL uses (`'nan'::float4` → - // "NaN"), so a NaN/Infinity survives the copy instead of becoming NULL. - ref t if *t == Type::FLOAT4 => try_extract::(row, index, |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) - } + match *row.columns()[index].type_() { + Type::FLOAT4 => try_extract::(row, index, |v| { + float_special(f64::from(v)).unwrap_or_else(|| float4_to_json(v)) }), - ref t if *t == Type::FLOAT8 => try_extract::(row, index, |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 { + Type::FLOAT8 => try_extract::(row, index, |v| { + float_special(v).unwrap_or_else(|| { serde_json::Number::from_f64(v) .map(JsonValue::Number) .unwrap_or(JsonValue::Null) - } + }) }), - ref t if *t == Type::DATE => try_extract::(row, index, JsonValue::from), - ref t if *t == Type::TIME => try_extract::(row, index, JsonValue::from), - ref t if *t == Type::TIMESTAMP => { - try_extract::(row, index, JsonValue::from) - } - ref t if *t == Type::TIMESTAMPTZ => { - try_extract::(row, index, JsonValue::from) - } - ref t if *t == Type::BYTEA => try_extract::>(row, index, |v| { + Type::BYTEA => try_extract::>(row, index, |v| { JsonValue::String(crate::utils::blob::encode_blob_full(&v)) }), - // NUMERIC: the display path (`extract_simple_kind`) decodes through - // `rust_decimal::Decimal`, a 96-bit mantissa that cannot represent - // values beyond ~28-29 significant digits or `NaN` — they silently - // become `Null`. The lossless path must keep wide values and `NaN`, - // so it decodes the base-10000 wire bytes directly via `PgNumeric` - // (#214 item 1). The display path keeps `Decimal` (truncation is - // acceptable there). - ref t if *t == Type::NUMERIC => { - try_extract::(row, index, |v| JsonValue::String(v.0)) - } - // MONEY: the display path decodes the i64 cents and renders them as - // a JS-safe integer via `i64_to_json` — losing the decimal-point - // semantics (`$123.45` → `12345`, a raw integer). The lossless path - // formats the cents as a decimal string (`12345` → `"123.45"`), so - // the value round-trips through `insert_records`'s money parser - // (#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())) - } - // 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), - } -} - -/// 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, + _ => extract_value(row, index), } } +/// PostgreSQL's text for a non-finite float, which JSON numbers can't carry. +fn float_special(v: f64) -> Option { + let s = if v.is_nan() { + "NaN" + } else if v == f64::INFINITY { + "Infinity" + } else if v == f64::NEG_INFINITY { + "-Infinity" + } else { + return None; + }; + Some(JsonValue::String(s.to_string())) +} + /// `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[]`). @@ -967,7 +867,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>`. -pub(crate) fn extract_simple_kind_from_bytes(ty: &Type, buf: &[u8]) -> JsonValue { +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) @@ -979,27 +879,13 @@ pub(crate) 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(|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) - } - }) + .map(float4_to_json) .unwrap_or(JsonValue::Null), _ if *ty == Type::FLOAT8 => f64::from_sql(ty, buf) .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 { - serde_json::Number::from_f64(v) - .map(JsonValue::Number) - .unwrap_or(JsonValue::Null) - } + serde_json::Number::from_f64(v) + .map(JsonValue::Number) + .unwrap_or(JsonValue::Null) }) .unwrap_or(JsonValue::Null), _ if *ty == Type::TEXT @@ -1017,12 +903,12 @@ 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 => PgIntervalText::from_sql(ty, buf) + _ 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) - .map(|v| JsonValue::String(v.to_string())) - .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::BYTEA => Vec::::from_sql(ty, buf) .map(|v| JsonValue::String(crate::utils::blob::encode_blob(&v))) .unwrap_or(JsonValue::Null), @@ -1083,7 +969,7 @@ pub(crate) 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 => PgMoneyText::from_sql(ty, buf) + _ if *ty == Type::MONEY => Money::from_sql(ty, buf) .map(JsonValue::from) .unwrap_or(JsonValue::Null), _ if *ty == Type::POINT => Point::from_sql(ty, buf) @@ -1170,29 +1056,6 @@ pub(crate) 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), } } @@ -1215,15 +1078,11 @@ impl<'a> FromSql<'a> for EnumLabel { } } -/// MONEY (display path): total value in cents (or the smallest fractional -/// unit of the database's locale). Wire format is identical to INT8 — a -/// big-endian i64 — so decoding just reinterprets those bytes and reuses -/// `i64_to_json` for the same JS-safe-integer stringification `INT8` gets. -/// Matches `src-tauri/src/drivers/postgres/extract/advanced_types.rs::Money`. -/// -/// The lossless `read_rows` path uses [`PgMoneyText`] instead, which formats -/// the cents as a decimal string (`"123.45"`) so the value round-trips -/// through `insert_records` without a 100x scale error. +/// MONEY: total value in cents (or the smallest fractional unit of the +/// database's locale). Wire format is identical to INT8 — a big-endian +/// i64 — so decoding just reinterprets those bytes and reuses `i64_to_json` +/// for the same JS-safe-integer stringification `INT8` gets. Matches +/// `src-tauri/src/drivers/postgres/extract/advanced_types.rs::Money`. pub(crate) struct Money(i64); impl<'a> FromSql<'a> for Money { @@ -1245,219 +1104,6 @@ impl From for JsonValue { } } -/// Lossless MONEY decoder for the table-copy read path. The display path's -/// [`Money`] renders the raw i64 cents as a JS-safe integer (`12345` → -/// `12345`), losing the decimal semantics. This decoder formats the cents as -/// a decimal string matching PostgreSQL's `money_out`: sign, dollars, `.`, -/// zero-padded 2-digit cents (`12345` → `"123.45"`, `-3` → `"-0.03"`). The -/// string round-trips through `insert_records`'s money parser (#220 item 3). -pub(crate) struct PgMoneyText(String); - -impl<'a> FromSql<'a> for PgMoneyText { - fn from_sql( - _ty: &Type, - raw: &'a [u8], - ) -> Result> { - if raw.len() < 8 { - return Err(format!("expected 8 bytes for MONEY, got {}", raw.len()).into()); - } - let cents = i64::from_be_bytes(raw[0..8].try_into().unwrap()); - let sign = if cents < 0 { "-" } else { "" }; - let abs = cents.unsigned_abs(); - let dollars = abs / 100; - let remaining_cents = abs % 100; - Ok(Self(format!("{sign}{dollars}.{remaining_cents:02}"))) - } - - fn accepts(ty: &Type) -> bool { - *ty == Type::MONEY - } -} - -impl From for JsonValue { - fn from(v: PgMoneyText) -> Self { - JsonValue::String(v.0) - } -} - -/// NUMERIC's base-10000 wire format, decoded to its exact decimal text for the -/// lossless `read_rows` path (#214 item 1). `rust_decimal::Decimal` (the -/// display path's decoder, `extract_simple_kind`) holds a 96-bit mantissa -/// (~28–29 significant digits) and cannot represent `NaN`, so a -/// `numeric(38,10)` value over 29 digits or a `NaN` makes `Decimal::from_sql` -/// return `Err`; `try_extract`'s `String` fallback rejects `NUMERIC`, so the -/// cell silently becomes `Null`. This decoder reads the wire bytes directly -/// and builds the decimal string with no big-number crate, reproducing -/// PostgreSQL 16's `numeric_out`/`get_str_from_var` (`numeric.c`, -/// `DEC_DIGITS = 4`, `NBASE = 10000`) so a wide value or `NaN` survives the -/// copy instead of turning into `NULL`. -pub(crate) struct PgNumeric(pub String); - -/// NUMERIC sign flags, from `numeric.c` / `rust_decimal`'s driver. -const NUMERIC_NEG: u16 = 0x4000; -const NUMERIC_SPECIAL: u16 = 0xC000; -const NUMERIC_NAN: u16 = 0xC000; -const NUMERIC_PINF: u16 = 0xD000; -const NUMERIC_NINF: u16 = 0xF000; - -impl<'a> FromSql<'a> for PgNumeric { - fn from_sql( - _ty: &Type, - raw: &'a [u8], - ) -> Result> { - use std::io::Cursor; - let mut cur = Cursor::new(raw); - let two = |c: &mut Cursor<&[u8]>| -> std::io::Result { - let mut b = [0u8; 2]; - std::io::Read::read_exact(c, &mut b)?; - Ok(u16::from_be_bytes(b)) - }; - - let ndigits = two(&mut cur)?; - let weight = two(&mut cur)? as i16; - let sign = two(&mut cur)?; - let dscale = two(&mut cur)?; - - // Specials (NaN, ±Infinity): `numeric_out` returns the bare string; - // dscale is ignored. A value whose sign has the special high bits is a - // special regardless of its digit array. An unrecognized special sign - // (e.g. 0xE000) is an error, not a silent "NaN" — a corrupted/ - // non-canonical wire payload must not fabricate a value (#214 review). - if (sign & NUMERIC_SPECIAL) == NUMERIC_SPECIAL { - return Ok(Self(match sign { - NUMERIC_NAN => "NaN".to_string(), - NUMERIC_PINF => "Infinity".to_string(), - NUMERIC_NINF => "-Infinity".to_string(), - _ => { - return Err(format!("PgNumeric: unrecognized special sign 0x{sign:04X}").into()) - } - })); - } - // A non-special sign other than 0x0000 (positive) or 0x4000 (negative) - // is not defined by PostgreSQL's numeric wire format — reject it - // rather than silently decoding as positive (#214 review finding). - if sign != 0x0000 && sign != NUMERIC_NEG { - return Err(format!("PgNumeric: unrecognized sign 0x{sign:04X}").into()); - } - - let mut digits = Vec::with_capacity(ndigits as usize); - for _ in 0..ndigits { - let dig = two(&mut cur)?; - // Each base-10000 group must be 0..=9999. A group >= 10000 would - // make the digit-extraction arithmetic emit non-digit ASCII chars - // (e.g. (b'0' + 10) = ':') into the output — reject it instead of - // silently producing garbage (#214 review finding). - if dig > 9999 { - return Err( - format!("PgNumeric: digit group {dig} exceeds base-10000 range").into(), - ); - } - digits.push(dig); - } - - // Reproduce `get_str_from_var` (PostgreSQL 16, `DEC_DIGITS == 4`). - let mut out = String::new(); - if sign == NUMERIC_NEG { - out.push('-'); - } - - // Integer part: iterate d = 0..=weight, reading digit d from the - // array when in range, else 0. The first group suppresses leading - // zeros; if weight < 0 a single '0' is emitted and `d` is set to - // `weight + 1` so the fractional loop starts there — reading leading - // zero groups (d < 0 → digit 0) before reaching `digits[0]`. This - // matches PostgreSQL's `get_str_from_var`, which sets `d = weight + 1` - // in the weight < 0 case. Without this, `0.00001234` (weight=-2, - // digits=[1234], dscale=8) would decode as `0.12340000` — silent data - // corruption on any value below 0.0001. - let mut d: i32 = if weight < 0 { - out.push('0'); - weight as i32 + 1 - } else { - 0 - }; - if weight >= 0 { - while d <= weight as i32 { - let dig = if (d as usize) < digits.len() { - digits[d as usize] - } else { - 0 - }; - let mut putit = d > 0; - // Extract the four decimal digits of this base-10000 group, - // most-significant first, suppressing leading zeros only in the - // first group (`d == 0`). - let mut rem = dig; - let d1 = rem / 1000; - rem -= d1 * 1000; - putit |= d1 > 0; - if putit { - out.push((b'0' + d1 as u8) as char); - } - let d1 = rem / 100; - rem -= d1 * 100; - putit |= d1 > 0; - if putit { - out.push((b'0' + d1 as u8) as char); - } - let d1 = rem / 10; - rem -= d1 * 10; - putit |= d1 > 0; - if putit { - out.push((b'0' + d1 as u8) as char); - } - out.push((b'0' + rem as u8) as char); - d += 1; - } - } - - // Fractional part: if dscale > 0, emit '.' then exactly dscale digits - // (four per group, continuing `d` past the integer groups and reading 0 - // for missing digits). Truncate to dscale total. - if dscale > 0 { - out.push('.'); - let mut emitted = 0u16; - while emitted < dscale { - let dig = if d >= 0 && (d as usize) < digits.len() { - digits[d as usize] - } else { - 0 - }; - let mut rem = dig; - let d1 = rem / 1000; - rem -= d1 * 1000; - if emitted < dscale { - out.push((b'0' + d1 as u8) as char); - emitted += 1; - } - let d1 = rem / 100; - rem -= d1 * 100; - if emitted < dscale { - out.push((b'0' + d1 as u8) as char); - emitted += 1; - } - let d1 = rem / 10; - rem -= d1 * 10; - if emitted < dscale { - out.push((b'0' + d1 as u8) as char); - emitted += 1; - } - if emitted < dscale { - out.push((b'0' + rem as u8) as char); - emitted += 1; - } - d += 1; - } - } - - Ok(Self(out)) - } - - fn accepts(ty: &Type) -> bool { - *ty == Type::NUMERIC - } -} - /// Convert days-since-2000-01-01 to (astronomical_year, month, day) over the /// full Postgres DATE range (4713 BC – ~5.88M AD). Uses Howard Hinnant's /// `civil_from_days` algorithm (https://howardhinnant.github.io/date_algorithms.html), @@ -1515,50 +1161,6 @@ 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 { - 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. - let bc_year = (-(year)) + 1; - 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}") - } else { - // 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}") - } - } -} - /// 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` → @@ -1603,67 +1205,6 @@ impl From for JsonValue { } } -/// Lossless variant of [`PgDate`] for the table-copy read path. The display -/// `PgDate` rejects the `i32::MAX`/`i32::MIN` infinity sentinels with `Err` -/// (→ `null` via `try_extract`); this variant returns the text -/// `"infinity"` / `"-infinity"` PostgreSQL uses, so a DATE infinity survives -/// the copy instead of becoming `NULL` (#220 item 2b). -pub(crate) struct PgDateFull { - /// `Some` for infinity sentinels; `None` for a real date (fields below). - infinity: Option, - year: i64, - month: u8, - day: u8, -} - -impl<'a> FromSql<'a> for PgDateFull { - fn from_sql( - _ty: &Type, - raw: &'a [u8], - ) -> Result> { - if raw.len() < 4 { - return Err(format!("expected 4 bytes for DATE, got {}", raw.len()).into()); - } - let days = i32::from_be_bytes(raw[0..4].try_into().unwrap()); - if days == i32::MAX { - return Ok(Self { - infinity: Some("infinity".to_string()), - year: 0, - month: 0, - day: 0, - }); - } - if days == i32::MIN { - return Ok(Self { - infinity: Some("-infinity".to_string()), - year: 0, - month: 0, - day: 0, - }); - } - let (year, month, day) = days_since_2000_to_ymd(i64::from(days)); - Ok(Self { - infinity: None, - year, - month, - day, - }) - } - - fn accepts(ty: &Type) -> bool { - *ty == Type::DATE - } -} - -impl From for JsonValue { - fn from(v: PgDateFull) -> Self { - if let Some(s) = v.infinity { - return JsonValue::String(s); - } - JsonValue::String(format_date_with_bc(v.year, v.month, v.day)) - } -} - /// TIME: 8-byte big-endian i64 = microseconds since midnight (0..86_400_000_000). /// Fractional seconds are truncated (matches chrono `%S`, not `TimeTz`'s /// `.ffffff` emission — this is the whole-seconds output contract). @@ -1814,276 +1355,6 @@ impl From for JsonValue { } } -/// Lossless variant of [`PgTime`] that retains the sub-second micros, for the -/// table-copy read path (`extract_value_lossless`). The display path's `PgTime` -/// truncates to whole seconds (`HH:MM:SS`); this emits `HH:MM:SS.ffffff` when -/// microseconds are nonzero, exactly matching `TimeTz`'s fractional emission. -pub(crate) struct PgTimeFull { - hrs: u8, - mins: u8, - secs: u8, - microseconds: u32, -} - -impl<'a> FromSql<'a> for PgTimeFull { - fn from_sql( - _ty: &Type, - raw: &'a [u8], - ) -> Result> { - if raw.len() < 8 { - return Err(format!("expected 8 bytes for TIME, got {}", raw.len()).into()); - } - let micros = i64::from_be_bytes(raw[0..8].try_into().unwrap()); - // Inclusive upper bound: 86_400_000_000 µs = 24:00:00, a valid - // PostgreSQL TIME value (`'24:00:00'::time` round-trips). The display - // path's `PgTime` uses an exclusive bound (rejects it → null); the - // lossless path must keep it (#220 item 2c). At 86_400_000_000 µs the - // arithmetic produces hrs=24, mins=0, secs=0 → "24:00:00". - if !(0..=86_400_000_000).contains(µs) { - return Err(format!("time microseconds out of range: {micros}").into()); - } - let hrs = (micros / 3_600_000_000) as u8; - let rem = micros % 3_600_000_000; - let mins = (rem / 60_000_000) as u8; - let rem = rem % 60_000_000; - let secs = (rem / 1_000_000) as u8; - let microseconds = (rem % 1_000_000) as u32; - Ok(Self { - hrs, - mins, - secs, - microseconds, - }) - } - - fn accepts(ty: &Type) -> bool { - *ty == Type::TIME - } -} - -impl From for JsonValue { - fn from(v: PgTimeFull) -> Self { - let mut s = format!("{:02}:{:02}:{:02}", v.hrs, v.mins, v.secs); - if v.microseconds > 0 { - s.push('.'); - // Zero-pad to 6 digits first, then trim trailing zeros, so 100µs - // → "000100" → "0001" → ".0001" (correct), not "100" → "1" → ".1" - // (which PostgreSQL parses as 100,000µs — a 1000× error). - s.push_str(format!("{:06}", v.microseconds).trim_end_matches('0')); - } - JsonValue::String(s) - } -} - -/// Lossless variant of [`PgTimestamp`] that retains sub-second micros, for the -/// table-copy read path. Emits `YYYY-MM-DD HH:MM:SS.ffffff` when micros are -/// nonzero (matching `TimeTz`/`Interval`'s fractional emission). -pub(crate) struct PgTimestampFull { - year: i64, - month: u8, - day: u8, - hrs: u8, - mins: u8, - secs: u8, - microseconds: u32, - /// Set to `Some("infinity")` / `Some("-infinity")` when the wire value is - /// the `i64::MAX` / `i64::MIN` sentinel. When `Some`, all other fields are - /// zero and `From for JsonValue` emits the string directly — so a - /// TIMESTAMP infinity survives the lossless copy as the text PostgreSQL - /// uses, instead of the `null` the display path produces (#220 item 2b). - infinity: Option, -} - -impl<'a> FromSql<'a> for PgTimestampFull { - fn from_sql( - _ty: &Type, - raw: &'a [u8], - ) -> Result> { - if raw.len() < 8 { - return Err(format!("expected 8 bytes for TIMESTAMP, got {}", raw.len()).into()); - } - let micros = i64::from_be_bytes(raw[0..8].try_into().unwrap()); - if micros == i64::MAX { - return Ok(Self { - year: 0, - month: 0, - day: 0, - hrs: 0, - mins: 0, - secs: 0, - microseconds: 0, - infinity: Some("infinity".to_string()), - }); - } - if micros == i64::MIN { - return Ok(Self { - year: 0, - month: 0, - day: 0, - hrs: 0, - mins: 0, - secs: 0, - microseconds: 0, - infinity: Some("-infinity".to_string()), - }); - } - let days = micros.div_euclid(86_400_000_000); - let rem = micros.rem_euclid(86_400_000_000); - let (year, month, day) = days_since_2000_to_ymd(days); - let hrs = (rem / 3_600_000_000) as u8; - let rem = rem % 3_600_000_000; - let mins = (rem / 60_000_000) as u8; - let rem = rem % 60_000_000; - let secs = (rem / 1_000_000) as u8; - let microseconds = (rem % 1_000_000) as u32; - Ok(Self { - year, - month, - day, - hrs, - mins, - secs, - microseconds, - infinity: None, - }) - } - - fn accepts(ty: &Type) -> bool { - *ty == Type::TIMESTAMP - } -} - -impl From for JsonValue { - fn from(v: PgTimestampFull) -> Self { - 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_no_bc(v.year, v.month, v.day), - v.hrs, - v.mins, - v.secs - ); - if v.microseconds > 0 { - s.push('.'); - // Zero-pad to 6 digits first, then trim trailing zeros — see - // `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) - } -} - -/// Lossless variant of [`PgTimestampTz`] that retains sub-second micros and -/// appends the `+00:00` UTC offset, for the table-copy read path. The wire -/// value is UTC micros; `+00:00` is PostgreSQL's native `timestamptz` text -/// format for UTC and round-trips through `bind_pg_temporal_string`. The -/// display path's `PgTimestampTz` drops both the fractional seconds and the -/// offset. -pub(crate) struct PgTimestampTzFull { - inner: PgTimestampFull, -} - -impl<'a> FromSql<'a> for PgTimestampTzFull { - fn from_sql( - _ty: &Type, - raw: &'a [u8], - ) -> Result> { - if raw.len() < 8 { - return Err(format!("expected 8 bytes for TIMESTAMPTZ, got {}", raw.len()).into()); - } - let micros = i64::from_be_bytes(raw[0..8].try_into().unwrap()); - if micros == i64::MAX { - return Ok(Self { - inner: PgTimestampFull { - year: 0, - month: 0, - day: 0, - hrs: 0, - mins: 0, - secs: 0, - microseconds: 0, - infinity: Some("infinity".to_string()), - }, - }); - } - if micros == i64::MIN { - return Ok(Self { - inner: PgTimestampFull { - year: 0, - month: 0, - day: 0, - hrs: 0, - mins: 0, - secs: 0, - microseconds: 0, - infinity: Some("-infinity".to_string()), - }, - }); - } - let days = micros.div_euclid(86_400_000_000); - let rem = micros.rem_euclid(86_400_000_000); - let (year, month, day) = days_since_2000_to_ymd(days); - let hrs = (rem / 3_600_000_000) as u8; - let rem = rem % 3_600_000_000; - let mins = (rem / 60_000_000) as u8; - let rem = rem % 60_000_000; - let secs = (rem / 1_000_000) as u8; - let microseconds = (rem % 1_000_000) as u32; - Ok(Self { - inner: PgTimestampFull { - year, - month, - day, - hrs, - mins, - secs, - microseconds, - infinity: None, - }, - }) - } - - fn accepts(ty: &Type) -> bool { - *ty == Type::TIMESTAMPTZ - } -} - -impl From for JsonValue { - fn from(v: PgTimestampTzFull) -> Self { - // 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); - } - 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) - } -} - /// TIMETZ: time-of-day + UTC offset. Wire format: 8-byte microseconds since /// midnight (i64, always non-negative), then a 4-byte signed offset in /// seconds (positive = west of UTC, hence the sign flip below). Matches @@ -2162,17 +1433,17 @@ impl From for JsonValue { } } -/// 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. +/// INTERVAL: 8-byte microseconds, 4-byte days, 4-byte months (signed). +/// Matches `advanced_types.rs::Interval`. struct Interval { - months: i32, + years: i32, + months: i8, days: i32, - time_micros: i64, + sign: char, + hours: u8, + minutes: u8, + seconds: u8, + microseconds: u32, } impl<'a> FromSql<'a> for Interval { @@ -2180,120 +1451,44 @@ impl<'a> FromSql<'a> for Interval { 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: 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 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; - let mut years = 0i32; if !(-11..=11).contains(&months) { years = months / 12; months %= 12; } - let sign = if micros < 0 { - micros = -micros; + let sign = if microseconds < 0 { + microseconds = -microseconds; '-' } 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; + + 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 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, + years, + months: months as i8, days, - time_micros, + sign, + hours: hrs as u8, + minutes: mins, + seconds: secs, + microseconds, }) } @@ -2302,17 +1497,25 @@ impl<'a> FromSql<'a> for PgIntervalText { } } -impl From for JsonValue { - fn from(v: PgIntervalText) -> Self { - let mut parts: Vec = Vec::new(); +impl From for JsonValue { + fn from(v: Interval) -> Self { + let mut s = String::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 { - "mon" + "month" } else { - "mons" + "months" }; - parts.push(format!("{} {}", v.months, unit)); + s.push_str(&format!("{} {} ", v.months, unit)); } if v.days != 0 { let unit = if v.days == 1 || v.days == -1 { @@ -2320,36 +1523,20 @@ impl From for JsonValue { } else { "days" }; - 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!("{} {} ", v.days, unit)); + } + if v.hours != 0 || v.minutes != 0 || v.seconds != 0 || v.microseconds != 0 { + if v.sign != '+' { + s.push(v.sign); } - // 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')); + 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')); } - parts.push(time_str); } - if parts.is_empty() { - JsonValue::String("00:00:00".to_string()) - } else { - JsonValue::String(parts.join(" ")) - } + JsonValue::String(s) } } diff --git a/src/extract_tests.rs b/src/extract_tests.rs index 0609ff0..afda2a7 100644 --- a/src/extract_tests.rs +++ b/src/extract_tests.rs @@ -11,11 +11,10 @@ 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, PgTimestampFull, PgTimestampTzFull, PgVector, Point, Polygon, - RefCursor, RegClass, RegProc, RegType, Tid, TsQuery, TsVector, TxidSnapshotOrPgSnapshot, Xid, - Xid8, Xml, + Lseg, MacAddr8, Money, MultirangeValue, Path, PgBox, PgBrinBloomSummary, PgDependencies, + PgHalfVector, PgLsn, PgMcvList, PgNdistinct, PgNodeTree, PgSparseVector, 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}; @@ -88,232 +87,6 @@ fn money_at_the_lowest_int8_becomes_a_string_without_overflowing() { ); } -/// Builds the NUMERIC wire format from its header fields + base-10000 digit -/// groups. Layout: `u16 ndigits`, `i16 weight`, `u16 sign`, `u16 dscale`, then -/// `ndigits` × `u16` digit groups (each 0–9999). Matches what -/// `rust_decimal`'s `FromSql` and PostgreSQL's `numeric_out` read. -fn numeric_wire_bytes( - ndigits: u16, - weight: i16, - sign: u16, - dscale: u16, - digits: &[u16], -) -> Vec { - assert_eq!(digits.len(), ndigits as usize); - let mut out = Vec::with_capacity(8 + ndigits as usize * 2); - out.extend_from_slice(&ndigits.to_be_bytes()); - out.extend_from_slice(&weight.to_be_bytes()); - out.extend_from_slice(&sign.to_be_bytes()); - out.extend_from_slice(&dscale.to_be_bytes()); - for &dig in digits { - out.extend_from_slice(&dig.to_be_bytes()); - } - out -} - -#[test] -fn pg_numeric_accepts_only_the_numeric_type() { - assert!(PgNumeric::accepts(&Type::NUMERIC)); - assert!(!PgNumeric::accepts(&Type::MONEY)); - assert!(!PgNumeric::accepts(&Type::INT8)); -} - -#[test] -fn pg_numeric_decodes_a_simple_integer() { - // 3950.123456: ndigits=3, weight=0, sign=0, dscale=6, digits=[3950,1234,5600] - // (matches rust_decimal's worked example in driver.rs). Each digit is the - // base-10000 group as an integer (0–9999), e.g. 3950 not 0x3950. - let bytes = numeric_wire_bytes(3, 0, 0x0000, 6, &[3950, 1234, 5600]); - let n = PgNumeric::from_sql(&Type::NUMERIC, &bytes).unwrap(); - assert_eq!(n.0, "3950.123456"); -} - -#[test] -fn pg_numeric_decodes_a_38_digit_integer_beyond_decimal_s_96_bit_ceiling() { - // 12345678901234567890123456789012345678 (38 integer digits, dscale 0). - // 38 = 9*4 + 2, so 10 base-10000 groups with a 2-digit leading group: - // 12 | 3456 | 7890 | 1234 | 5678 | 9012 | 3456 | 7890 | 1234 | 5678 - // stored as the integer groups [12, 3456, 7890, 1234, 5678, 9012, 3456, - // 7890, 1234, 5678] (each a u16 0–9999), weight = 9. The leading group 12 - // must decode to "12" (two leading zeros suppressed). `rust_decimal::Decimal` - // cannot hold this (28-29 significant digits); the old lossless path returned - // `Null` for it. - let bytes = numeric_wire_bytes( - 10, - 9, - 0x0000, - 0, - &[12, 3456, 7890, 1234, 5678, 9012, 3456, 7890, 1234, 5678], - ); - let n = PgNumeric::from_sql(&Type::NUMERIC, &bytes).unwrap(); - assert_eq!(n.0, "12345678901234567890123456789012345678"); -} - -#[test] -fn pg_numeric_decodes_a_30_digit_integer() { - // 123456789012345678901234567890 (30 digits, dscale 0). 30 = 7*4 + 2, so - // 8 groups with a 2-digit leading group: 12 | 3456 | 7890 | 1234 | 5678 | - // 9012 | 3456 | 7890, weight = 7. - let bytes = numeric_wire_bytes( - 8, - 7, - 0x0000, - 0, - &[12, 3456, 7890, 1234, 5678, 9012, 3456, 7890], - ); - let n = PgNumeric::from_sql(&Type::NUMERIC, &bytes).unwrap(); - assert_eq!(n.0, "123456789012345678901234567890"); -} - -#[test] -fn pg_numeric_decodes_a_negative_38_digit_integer() { - let bytes = numeric_wire_bytes( - 10, - 9, - 0x4000, - 0, - &[12, 3456, 7890, 1234, 5678, 9012, 3456, 7890, 1234, 5678], - ); - let n = PgNumeric::from_sql(&Type::NUMERIC, &bytes).unwrap(); - assert_eq!(n.0, "-12345678901234567890123456789012345678"); -} - -#[test] -fn pg_numeric_decodes_nan_as_the_string_nan() { - // NaN: sign = 0xC000. ndigits/dscale are ignored; ndigits=0 is canonical. - let bytes = numeric_wire_bytes(0, 0, 0xC000, 0, &[]); - let n = PgNumeric::from_sql(&Type::NUMERIC, &bytes).unwrap(); - assert_eq!(n.0, "NaN"); -} - -#[test] -fn pg_numeric_decodes_positive_infinity() { - let bytes = numeric_wire_bytes(0, 0, 0xD000, 0, &[]); - let n = PgNumeric::from_sql(&Type::NUMERIC, &bytes).unwrap(); - assert_eq!(n.0, "Infinity"); -} - -#[test] -fn pg_numeric_decodes_negative_infinity() { - let bytes = numeric_wire_bytes(0, 0, 0xF000, 0, &[]); - let n = PgNumeric::from_sql(&Type::NUMERIC, &bytes).unwrap(); - assert_eq!(n.0, "-Infinity"); -} - -#[test] -fn pg_numeric_preserves_dscale_trailing_zeros() { - // 12345678901234567890.1234567890: integer part is 20 digits = 5 full - // base-10000 groups (1234 5678 9012 3456 7890, weight=4), then 10 - // fractional digits = groups 1234, 5678 (8 digits) + 9000 (truncated to - // "90", 2 digits) = dscale 10. digits = [1234,5678,9012,3456,7890, - // 1234,5678,9000]; ndigits=8, weight=4, dscale=10. The old `Decimal` path - // trimmed trailing zeros and lost the scale; `PgNumeric` must keep all 10 - // fraction digits. - let bytes = numeric_wire_bytes( - 8, - 4, - 0x0000, - 10, - &[1234, 5678, 9012, 3456, 7890, 1234, 5678, 9000], - ); - let n = PgNumeric::from_sql(&Type::NUMERIC, &bytes).unwrap(); - assert_eq!(n.0, "12345678901234567890.1234567890"); -} - -#[test] -fn pg_numeric_zero_with_dscale_emits_trailing_zeros() { - // 0 with dscale=2 → "0.00". ndigits=0, weight=0, dscale=2: the integer loop - // (weight>=0) reads digit 0 = 0 (past ndigits) → emits "0" (first group - // suppresses leading zeros, the fourth digit is still "0"), then ".00". - let bytes = numeric_wire_bytes(0, 0, 0x0000, 2, &[]); - let n = PgNumeric::from_sql(&Type::NUMERIC, &bytes).unwrap(); - assert_eq!(n.0, "0.00"); -} - -#[test] -fn pg_numeric_small_fractional_value() { - // 0.1234567890: weight=-1, dscale=10, digits=[1234,5678,9000] (ndigits=3). - // weight<0 → integer "0", d starts at weight+1 = 0, then 10 fractional - // digits: groups 1234 (4) + 5678 (4) + 9000 (truncated to 2 → "90"), giving - // "0.1234567890". The third group 9000 emits "9000" but dscale caps output - // at 10 digits. - let bytes = numeric_wire_bytes(3, -1, 0x0000, 10, &[1234, 5678, 9000]); - let n = PgNumeric::from_sql(&Type::NUMERIC, &bytes).unwrap(); - assert_eq!(n.0, "0.1234567890"); -} - -/// Regression for the weight < -1 data-corruption bug: when weight is more -/// negative than -1, the fractional loop must read leading zero groups (d < 0 -/// → digit 0) before reaching digits[0]. Without setting `d = weight + 1` in -/// the weight<0 branch, `d` stayed 0 and `digits[0]` was read as the first -/// fractional group — turning `0.00001234` into `0.12340000`. Any value below -/// 0.0001 hit this (found by kilo code bot review of PR #216). -#[test] -fn pg_numeric_weight_below_minus_one_reads_leading_zero_groups() { - // 0.00001234: weight=-2 (10000^-2 = 10^-8), digits=[1234], dscale=8. - // d starts at weight+1 = -1: group d=-1 → 0 ("0000"), group d=0 → 1234 - // ("1234") → 8 fractional digits "00001234" → "0.00001234". - let bytes = numeric_wire_bytes(1, -2, 0x0000, 8, &[1234]); - let n = PgNumeric::from_sql(&Type::NUMERIC, &bytes).unwrap(); - assert_eq!(n.0, "0.00001234"); -} - -/// A value with weight=-3 and multiple leading zero groups: 0.000000001234 -/// (weight=-3, digits=[1234], dscale=12). Three leading zero groups then 1234. -#[test] -fn pg_numeric_weight_minus_three_emits_three_leading_zero_groups() { - let bytes = numeric_wire_bytes(1, -3, 0x0000, 12, &[1234]); - let n = PgNumeric::from_sql(&Type::NUMERIC, &bytes).unwrap(); - assert_eq!(n.0, "0.000000001234"); -} - -#[test] -fn pg_numeric_rejects_truncated_wire() { - // Header claims 3 digit groups but provides none — read_exact must error - // rather than silently decode a partial value. Build the bytes directly - // (the helper asserts ndigits == digits.len()). - let mut bytes = Vec::new(); - bytes.extend_from_slice(&3u16.to_be_bytes()); // ndigits = 3 - bytes.extend_from_slice(&0i16.to_be_bytes()); // weight = 0 - bytes.extend_from_slice(&0u16.to_be_bytes()); // sign = 0 - bytes.extend_from_slice(&0u16.to_be_bytes()); // dscale = 0 - // no digit bytes follow - assert!(PgNumeric::from_sql(&Type::NUMERIC, &bytes).is_err()); -} - -/// A base-10000 digit group >= 10000 must be rejected, not silently emit -/// non-digit ASCII chars (e.g. (b'0'+10)=':') into the output (#214 review). -#[test] -fn pg_numeric_rejects_digit_group_above_base_range() { - let bytes = numeric_wire_bytes(1, 0, 0x0000, 0, &[10000]); - assert!(PgNumeric::from_sql(&Type::NUMERIC, &bytes).is_err()); -} - -/// An unrecognized special sign (0xE000 — top bits set but not NaN/PINF/NINF) -/// must error, not silently decode to "NaN" (#214 review). -#[test] -fn pg_numeric_rejects_unrecognized_special_sign() { - let mut bytes = Vec::new(); - bytes.extend_from_slice(&0u16.to_be_bytes()); // ndigits = 0 - bytes.extend_from_slice(&0i16.to_be_bytes()); // weight = 0 - bytes.extend_from_slice(&0xE000u16.to_be_bytes()); // sign = 0xE000 - bytes.extend_from_slice(&0u16.to_be_bytes()); // dscale = 0 - assert!(PgNumeric::from_sql(&Type::NUMERIC, &bytes).is_err()); -} - -/// An unrecognized non-special sign (0x2000 — not 0x0000/0x4000/special) must -/// error, not silently decode as positive (#214 review). -#[test] -fn pg_numeric_rejects_unrecognized_non_special_sign() { - let mut bytes = Vec::new(); - bytes.extend_from_slice(&1u16.to_be_bytes()); // ndigits = 1 - bytes.extend_from_slice(&0i16.to_be_bytes()); // weight = 0 - bytes.extend_from_slice(&0x2000u16.to_be_bytes()); // sign = 0x2000 - bytes.extend_from_slice(&0u16.to_be_bytes()); // dscale = 0 - bytes.extend_from_slice(&42u16.to_be_bytes()); // digits = [42] - assert!(PgNumeric::from_sql(&Type::NUMERIC, &bytes).is_err()); -} - fn hstore_type() -> Type { Type::new( "hstore".to_string(), @@ -2223,720 +1996,3 @@ fn time_truncates_fractional_seconds() { let t = crate::extract::PgTime::from_sql(&Type::TIME, &bytes).unwrap(); assert_eq!(serde_json::Value::from(t), serde_json::json!("13:45:30")); } - -// --- Lossless Full temporal types (table-copy read path, issue #207) --- -// -// `PgTimeFull`/`PgTimestampFull`/`PgTimestampTzFull` retain sub-second micros -// (the display `PgTime`/`PgTimestamp`/`PgTimestampTz` drop them) and emit -// `.ffffff` when nonzero (matching `TimeTz`/`Interval`). `PgTimestampTzFull` -// appends `+00:00` (the display path drops the offset). These power -// `extract_value_lossless`, used by `read_rows`. - -#[test] -fn pg_time_full_keeps_fractional_seconds() { - use tokio_postgres::types::FromSql; - // 13:45:30.345678 = 49_530_345_678 µs since midnight. - let bytes = 49_530_345_678_i64.to_be_bytes(); - let t = crate::extract::PgTimeFull::from_sql(&Type::TIME, &bytes).unwrap(); - assert_eq!( - serde_json::Value::from(t), - serde_json::json!("13:45:30.345678") - ); -} - -#[test] -fn pg_time_full_omits_fraction_when_zero() { - use tokio_postgres::types::FromSql; - // 13:45:30 exactly — no fractional part, no `.ffffff`. - let bytes = 49_530_000_000_i64.to_be_bytes(); - let t = crate::extract::PgTimeFull::from_sql(&Type::TIME, &bytes).unwrap(); - assert_eq!(serde_json::Value::from(t), serde_json::json!("13:45:30")); -} - -#[test] -fn pg_time_full_trims_trailing_zeros_in_fraction() { - use tokio_postgres::types::FromSql; - // 13:45:30.100000 = 100,000 µs → ".1" (trailing zeros trimmed). - let bytes = 49_530_100_000_i64.to_be_bytes(); - let t = crate::extract::PgTimeFull::from_sql(&Type::TIME, &bytes).unwrap(); - assert_eq!(serde_json::Value::from(t), serde_json::json!("13:45:30.1")); -} - -#[test] -fn pg_time_full_zero_pads_leading_zeros_in_fraction() { - use tokio_postgres::types::FromSql; - // 13:45:30.000100 = 100 µs → ".0001" (zero-padded to 6, then trimmed). - // Without the zero-pad, to_string() would give "100" → "1" → ".1", - // which PostgreSQL parses as 100,000 µs — a 1000× error. - let bytes = 49_530_000_100_i64.to_be_bytes(); - let t = crate::extract::PgTimeFull::from_sql(&Type::TIME, &bytes).unwrap(); - assert_eq!( - serde_json::Value::from(t), - serde_json::json!("13:45:30.0001") - ); -} - -#[test] -fn pg_timestamp_full_zero_pads_leading_zeros_in_fraction() { - use tokio_postgres::types::FromSql; - // 2026-11-29 13:45:30.000100 = 849275130000100 µs since 2000-01-01. - let bytes = 849_275_130_000_100_i64.to_be_bytes(); - let t = crate::extract::PgTimestampFull::from_sql(&Type::TIMESTAMP, &bytes).unwrap(); - assert_eq!( - serde_json::Value::from(t), - serde_json::json!("2026-11-29 13:45:30.0001") - ); -} - -#[test] -fn pg_timestamp_full_keeps_fractional_seconds() { - use tokio_postgres::types::FromSql; - // 2026-11-29 13:45:30.345678 = 849275130345678 µs since 2000-01-01. - let bytes = 849_275_130_345_678_i64.to_be_bytes(); - let t = crate::extract::PgTimestampFull::from_sql(&Type::TIMESTAMP, &bytes).unwrap(); - assert_eq!( - serde_json::Value::from(t), - serde_json::json!("2026-11-29 13:45:30.345678") - ); -} - -#[test] -fn pg_timestamp_full_omits_fraction_when_zero() { - use tokio_postgres::types::FromSql; - let bytes = 849_275_130_000_000_i64.to_be_bytes(); - let t = crate::extract::PgTimestampFull::from_sql(&Type::TIMESTAMP, &bytes).unwrap(); - assert_eq!( - serde_json::Value::from(t), - serde_json::json!("2026-11-29 13:45:30") - ); -} - -#[test] -fn pg_timestamptz_full_keeps_fractional_seconds_and_offset() { - use tokio_postgres::types::FromSql; - // Same wire as TIMESTAMP (UTC micros); output appends +00:00. - let bytes = 849_275_130_345_678_i64.to_be_bytes(); - let t = crate::extract::PgTimestampTzFull::from_sql(&Type::TIMESTAMPTZ, &bytes).unwrap(); - assert_eq!( - serde_json::Value::from(t), - serde_json::json!("2026-11-29 13:45:30.345678+00:00") - ); -} - -#[test] -fn pg_timestamptz_full_omits_fraction_when_zero_but_keeps_offset() { - use tokio_postgres::types::FromSql; - let bytes = 849_275_130_000_000_i64.to_be_bytes(); - let t = crate::extract::PgTimestampTzFull::from_sql(&Type::TIMESTAMPTZ, &bytes).unwrap(); - // No fractional seconds, but the +00:00 offset is always present. - assert_eq!( - serde_json::Value::from(t), - serde_json::json!("2026-11-29 13:45:30+00:00") - ); -} - -#[test] -fn pg_timestamp_full_decodes_infinity_sentinel_as_text() { - use tokio_postgres::types::FromSql; - // The lossless path returns the text "infinity"/"-infinity" for the - // i64::MAX / i64::MIN sentinels (the display path rejects them → null). - let v = crate::extract::PgTimestampFull::from_sql(&Type::TIMESTAMP, &i64::MAX.to_be_bytes()) - .unwrap(); - assert_eq!(serde_json::Value::from(v), serde_json::json!("infinity")); - - let v = crate::extract::PgTimestampFull::from_sql(&Type::TIMESTAMP, &i64::MIN.to_be_bytes()) - .unwrap(); - assert_eq!(serde_json::Value::from(v), serde_json::json!("-infinity")); -} - -#[test] -fn pg_timestamptz_full_decodes_infinity_sentinel_as_text_no_offset() { - use tokio_postgres::types::FromSql; - // TIMESTAMPTZ infinity: PostgreSQL emits no timezone suffix for infinite - // values, so the +00:00 offset must NOT be appended. - let v = - crate::extract::PgTimestampTzFull::from_sql(&Type::TIMESTAMPTZ, &i64::MAX.to_be_bytes()) - .unwrap(); - assert_eq!(serde_json::Value::from(v), serde_json::json!("infinity")); - - let v = - crate::extract::PgTimestampTzFull::from_sql(&Type::TIMESTAMPTZ, &i64::MIN.to_be_bytes()) - .unwrap(); - assert_eq!(serde_json::Value::from(v), serde_json::json!("-infinity")); -} - -#[test] -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") - ); -} - -// --- #220 items 2a/2b/2c/3: lossless overrides for special values ----------- - -// Item 2a: FLOAT4/FLOAT8 NaN/Infinity → text string (not null) - -#[test] -fn pg_date_full_accepts_only_the_date_type() { - assert!(PgDateFull::accepts(&Type::DATE)); - assert!(!PgDateFull::accepts(&Type::TIMESTAMP)); - assert!(!PgDateFull::accepts(&Type::TIMESTAMPTZ)); -} - -#[test] -fn pg_date_full_decodes_infinity_sentinel_as_text() { - use tokio_postgres::types::FromSql; - let v = PgDateFull::from_sql(&Type::DATE, &i32::MAX.to_be_bytes()).unwrap(); - assert_eq!(serde_json::Value::from(v), serde_json::json!("infinity")); -} - -#[test] -fn pg_date_full_decodes_negative_infinity_sentinel_as_text() { - use tokio_postgres::types::FromSql; - let v = PgDateFull::from_sql(&Type::DATE, &i32::MIN.to_be_bytes()).unwrap(); - assert_eq!(serde_json::Value::from(v), serde_json::json!("-infinity")); -} - -#[test] -fn pg_date_full_decodes_a_normal_date() { - use tokio_postgres::types::FromSql; - // 2026-11-29 is 9829 days after 2000-01-01. - 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")); -} - -// Item 2c: TIME 24:00:00 → text string (not null) - -#[test] -fn pg_time_full_accepts_24_hours() { - use tokio_postgres::types::FromSql; - // 86_400_000_000 µs = 24:00:00. The display `PgTime` rejects this (exclusive - // upper bound → null); the lossless `PgTimeFull` accepts it (inclusive). - let bytes = 86_400_000_000_i64.to_be_bytes(); - let t = crate::extract::PgTimeFull::from_sql(&Type::TIME, &bytes).unwrap(); - assert_eq!(serde_json::Value::from(t), serde_json::json!("24:00:00")); -} - -// Item 3: MONEY → text string (cents formatted as decimal) - -#[test] -fn pg_money_text_accepts_only_the_money_type() { - assert!(PgMoneyText::accepts(&Type::MONEY)); - assert!(!PgMoneyText::accepts(&Type::INT8)); - assert!(!PgMoneyText::accepts(&Type::NUMERIC)); -} - -#[test] -fn pg_money_text_formats_positive_cents_as_decimal() { - use tokio_postgres::types::FromSql; - // 12345 cents = $123.45 - let bytes = 12_345_i64.to_be_bytes(); - let v = PgMoneyText::from_sql(&Type::MONEY, &bytes).unwrap(); - assert_eq!(serde_json::Value::from(v), serde_json::json!("123.45")); -} - -#[test] -fn pg_money_text_formats_negative_cents_as_decimal() { - use tokio_postgres::types::FromSql; - // -3 cents = -$0.03 - let bytes = (-3_i64).to_be_bytes(); - let v = PgMoneyText::from_sql(&Type::MONEY, &bytes).unwrap(); - assert_eq!(serde_json::Value::from(v), serde_json::json!("-0.03")); -} - -#[test] -fn pg_money_text_formats_zero_cents_as_decimal() { - use tokio_postgres::types::FromSql; - let bytes = 0_i64.to_be_bytes(); - let v = PgMoneyText::from_sql(&Type::MONEY, &bytes).unwrap(); - assert_eq!(serde_json::Value::from(v), serde_json::json!("0.00")); -} - -#[test] -fn pg_money_text_formats_single_digit_cents_with_zero_padding() { - use tokio_postgres::types::FromSql; - // 105 cents = $1.05 (not $1.5) - let bytes = 105_i64.to_be_bytes(); - let v = PgMoneyText::from_sql(&Type::MONEY, &bytes).unwrap(); - assert_eq!(serde_json::Value::from(v), serde_json::json!("1.05")); -} - -#[test] -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 01: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!("-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!("00: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_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" - ); -} - -#[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. - // 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 00:00:00 BC") - ); -} - -#[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. - // 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 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] -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/copy.rs b/src/handlers/copy.rs index 487e2c3..93bda98 100644 --- a/src/handlers/copy.rs +++ b/src/handlers/copy.rs @@ -3,9 +3,11 @@ //! - `read_rows` — a lossless, optionally-snapshot read. Unlike `execute_query`, //! which formats values for display (truncates `BYTEA` to a 10 KB preview, //! drops fractional seconds and the timezone offset on timestamps), -//! `read_rows` extracts full-precision values via -//! [`extract::extract_value_lossless`] and returns the PostgreSQL type name + -//! OID per column so the host can plan the conversion. With a `session_id`, +//! `read_rows` returns every value the way PostgreSQL itself prints it +//! (`col::text`), except types whose JSON form is native (bool, integers, +//! floats) or that need an encoding (`bytea` → `BLOB:` base64) — see +//! [`classify_column`]. It also returns the source type name + OID per +//! column so the host can plan the conversion. With a `session_id`, //! the first call opens a `REPEATABLE READ READ ONLY` transaction on a pinned //! connection; subsequent pages reuse that connection and its snapshot, so //! rows are not skipped or repeated when the table changes between pages. @@ -30,16 +32,22 @@ use crate::extract::extract_value_lossless; use crate::handlers::query::{apply_search_path_local, returns_result_set}; use crate::models::{inner_params, ConnectionParams}; use crate::session; -use crate::utils::pagination::build_paginated_query; +use crate::utils::pagination::{build_paginated_query, trim_statement_end}; use deadpool_postgres::Object as PgClient; -/// Tracks the query each active copy session DECLAREd its cursor for, so a -/// second `read_rows` call with the same `session_id` but a *different* -/// query is rejected instead of silently returning the old cursor's rows -/// (#220 item 5). Cleared on `release_session`. -fn copy_session_queries() -> &'static Mutex> { - static QUERIES: OnceLock>> = OnceLock::new(); +/// The query and source column metadata each active copy session DECLAREd its +/// cursor for, so a second `read_rows` call with the same `session_id` but a +/// *different* query is rejected instead of silently returning the old +/// cursor's rows (#220 item 5), and later pages report the same `columns` +/// without re-preparing. Cleared on `release_session`. +struct CopySession { + query: String, + columns: Vec, +} + +fn copy_session_queries() -> &'static Mutex> { + static QUERIES: OnceLock>> = OnceLock::new(); QUERIES.get_or_init(|| Mutex::new(HashMap::new())) } @@ -49,30 +57,102 @@ 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 -/// 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 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) { - // Not inside a string — strip the comment. - return before_last_line.trim_end(); - } +/// Pins the server's text output format for the read, so values don't depend +/// on the connection's startup script: ISO dates, `postgres` intervals, +/// shortest-exact floats, hex bytea. `SET LOCAL` — reverted when the read +/// transaction ends. +const TEXT_OUTPUT_SETTINGS: &str = "SET LOCAL DateStyle = 'ISO, MDY'; \ + SET LOCAL IntervalStyle = 'postgres'; \ + SET LOCAL extra_float_digits = 3"; + +/// How `read_rows` returns one column of the source query. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ColumnRead { + /// Decode the binary value: its JSON form is a native JSON type (bool, + /// integer, float) or needs an encoding the text form doesn't give (bytea + /// → `BLOB:` base64), or the text form is the value itself (text, uuid). + Native, + /// `col::numeric::text` — money as a plain decimal (`"123.45"`), not the + /// locale-formatted `$123.45` (#220 item 3). + MoneyAsNumeric, + /// `col::text` — PostgreSQL's own output function. Everything else: dates + /// and times, interval, numeric, json/jsonb, enums, network types, bit, + /// arrays, ranges, multiranges and composites (#225). Hand-written + /// decoders for these kept diverging from the server's text (#220, #222). + Text, +} + +pub(crate) fn classify_column(ty: &Type) -> ColumnRead { + match *ty { + Type::BOOL + | Type::INT2 + | Type::INT4 + | Type::INT8 + | Type::OID + | Type::FLOAT4 + | Type::FLOAT8 + | Type::BYTEA + | Type::TEXT + | Type::VARCHAR + | Type::BPCHAR + | Type::NAME + | Type::UUID => ColumnRead::Native, + Type::MONEY => ColumnRead::MoneyAsNumeric, + _ => ColumnRead::Text, } - query +} + +/// `query` wrapped so every non-native column comes back as server-produced +/// text, or `None` when no column needs it (the query then runs unchanged). +/// The positional alias list (`AS tabularis_q(c1, …)`) makes duplicate or +/// unnamed source columns (`SELECT 1, 1`) addressable. `query` must already be +/// trimmed with [`trim_statement_end`]; it sits on its own lines so a +/// trailing comment can't swallow the closing paren. +pub(crate) fn text_projection(query: &str, reads: &[ColumnRead]) -> Option { + if reads.iter().all(|r| *r == ColumnRead::Native) { + return None; + } + let select: Vec = reads + .iter() + .enumerate() + .map(|(i, r)| match r { + ColumnRead::Native => format!("c{}", i + 1), + ColumnRead::MoneyAsNumeric => format!("c{}::numeric::text", i + 1), + ColumnRead::Text => format!("c{}::text", i + 1), + }) + .collect(); + let aliases: Vec = (1..=reads.len()).map(|i| format!("c{i}")).collect(); + Some(format!( + "SELECT {} FROM (\n{query}\n) AS tabularis_q({})", + select.join(", "), + aliases.join(", ") + )) +} + +/// Prepare `query` to learn its source columns: the `columns` metadata the +/// response reports (the source type, not `text`), and how to read each. +/// Works for a zero-row result, unlike reading metadata off the first row. +/// The statement is dropped right away; it's prepared inside the read +/// transaction, so a transaction pooler keeps it on this backend (#160). +async fn describe_columns( + pg_client: &PgClient, + query: &str, +) -> Result<(Vec, Vec), String> { + let stmt = pg_client + .prepare(query) + .await + .map_err(|e| format!("read_rows: query failed: {}", client::format_pg_error(&e)))?; + let columns = stmt + .columns() + .iter() + .map(|c| json!({ "name": c.name(), "type": c.type_().name(), "oid": c.type_().oid() })) + .collect(); + let reads = stmt + .columns() + .iter() + .map(|c| classify_column(c.type_())) + .collect(); + Ok((columns, reads)) } /// `BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY` — the snapshot the first @@ -123,21 +203,10 @@ pub async fn read_rows(id: Value, params: &Value) -> Value { .and_then(Value::as_u64) .unwrap_or(1) .max(1); - let page_size: u32 = params - .get("limit") - .and_then(Value::as_u64) - .and_then(|n| u32::try_from(n).ok()) - .unwrap_or(DEFAULT_PAGE_SIZE) - // Floor at 1: `FETCH FORWARD 0` is a no-op that returns 0 rows, and - // the cursor `has_more = rows_returned >= page_size` rule would be - // permanently `0 >= 0 = true` → infinite empty-page loop. The one-shot - // path's `has_more = rows.len() > page_size` happens to terminate at - // 0, but `LIMIT 0` is still a nonsensical request; reject it here for - // both paths (#214 review finding). - // Cap at MAX_PAGE_SIZE: the cursor-path FETCH loop does one round-trip - // per row when the byte budget is hit; an unbounded limit drives - // millions of round-trips for small-row tables (#215 review finding). - .clamp(1, MAX_PAGE_SIZE); + let page_size = match parse_page_size(params.get("limit")) { + Ok(n) => n, + Err(e) => return crate::rpc::error_response(id, -32602, &e), + }; let schema = params .get("schema") .and_then(Value::as_str) @@ -163,6 +232,24 @@ pub async fn read_rows(id: Value, params: &Value) -> Value { } } +/// Parse `read_rows`'s `limit`. Absent or `null` → [`DEFAULT_PAGE_SIZE`]. A +/// negative or non-integer value is an error rather than a silent default +/// (#225). Otherwise clamped to `1..=MAX_PAGE_SIZE`: +/// - Floor at 1: `FETCH FORWARD 0` returns 0 rows and the cursor +/// `has_more = rows_returned >= page_size` rule would loop forever on empty +/// pages (#214 review finding). +/// - Cap at `MAX_PAGE_SIZE`: the cursor FETCH loop does one round-trip per row +/// when the byte budget is hit (#215 review finding). +pub(crate) fn parse_page_size(limit: Option<&Value>) -> Result { + let n = match limit { + None | Some(Value::Null) => return Ok(DEFAULT_PAGE_SIZE), + Some(v) => v + .as_u64() + .ok_or_else(|| format!("read_rows: 'limit' must be a non-negative integer, got {v}"))?, + }; + Ok(u32::try_from(n).unwrap_or(u32::MAX).clamp(1, MAX_PAGE_SIZE)) +} + async fn run_read_rows( conn_params: &ConnectionParams, query: &str, @@ -188,11 +275,7 @@ async fn run_read_rows( // promise), so it still gets the paginated statement. match session_id { Some(sid) => run_snapshot(conn_params, query, page, page_size, schema, sid, id).await, - None => { - let final_query = - build_paginated_query(query, page_size, u32::try_from(page).unwrap_or(u32::MAX)); - run_one_shot(conn_params, &final_query, page, page_size, schema, id).await - } + None => run_one_shot(conn_params, query, page, page_size, schema, id).await, } } @@ -206,7 +289,7 @@ async fn run_read_rows( /// outside a transaction is a no-op. async fn run_one_shot( conn_params: &ConnectionParams, - final_query: &str, + query: &str, page: u64, page_size: u32, schema: Option, @@ -221,26 +304,36 @@ async fn run_one_shot( .await .map_err(|e| format!("read_rows: BEGIN failed: {}", client::format_pg_error(&e)))?; - if let Some(schema) = &schema { - if let Err(e) = apply_search_path_local(&pg_client, schema).await { - let _ = pg_client.batch_execute("ROLLBACK").await; - return Err(e); + let result = async { + pg_client + .batch_execute(TEXT_OUTPUT_SETTINGS) + .await + .map_err(|e| format!("read_rows: setup failed: {}", client::format_pg_error(&e)))?; + if let Some(schema) = &schema { + apply_search_path_local(&pg_client, schema).await?; } + let paged = + build_paginated_query(query, page_size, u32::try_from(page).unwrap_or(u32::MAX)); + let paged = trim_statement_end(&paged); + let (columns, reads) = describe_columns(&pg_client, paged).await?; + let final_query = text_projection(paged, &reads); + fetch_lossless( + &pg_client, + final_query.as_deref().unwrap_or(paged), + columns, + page, + page_size, + ) + .await } - - 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; + .await; + // Always ROLLBACK: a read-only transaction has nothing to commit, and + // ROLLBACK also reverts any session-level GUC the query set inside it + // (`set_config(.., false)`, plain `SET`), which COMMIT would leak to the + // next borrower of this pooled connection (#225). GUCs set before BEGIN — + // the startup script and `app.tabularis_base_search_path` (#51) — are + // untouched, which is why this is not `RESET ALL`. + let _ = pg_client.batch_execute("ROLLBACK").await; drop(cancel_guard); result } @@ -262,14 +355,6 @@ async fn run_one_shot( /// A cursor is linear in the table size (one scan, no `OFFSET` re-read) and /// gives one stable row order — unlike the `LIMIT/OFFSET` paging the one-shot /// path uses (#214 item 4). -/// -/// Note: an empty source table still reports `columns: []` here. `query_typed` -/// returns only `Vec`; a zero-row `FETCH` has no rows to read column -/// metadata from, so the cursor path does NOT fix the empty-page column gap -/// (despite `DECLARE` exposing a `RowDescription` at the protocol level — -/// tokio-postgres does not surface it on a zero-row `query_typed`). The host -/// falls back to `get_columns` (which now carries `type`/`oid` too) for an -/// empty source, as it does for the one-shot path. async fn run_snapshot( conn_params: &ConnectionParams, query: &str, @@ -324,7 +409,7 @@ async fn run_snapshot( .lock() .unwrap() .get(&session_id) - .is_some_and(|stored| stored != query); + .is_some_and(|stored| stored.query != query); if mismatch { drop(cancel_guard); cleanup_on_error(&pg_client, true).await; @@ -338,8 +423,56 @@ async fn run_snapshot( // `schema` (SET LOCAL search_path) must run before DECLARE so the query // resolves names under it. Skip on later pages — already in effect. if needs_declare { - if let Some(schema) = &schema { - if let Err(e) = apply_search_path_local(&pg_client, schema).await { + let declared = async { + pg_client + .batch_execute(TEXT_OUTPUT_SETTINGS) + .await + .map_err(|e| format!("read_rows: setup failed: {}", client::format_pg_error(&e)))?; + if let Some(schema) = &schema { + apply_search_path_local(&pg_client, schema).await?; + } + // The lexer-based trim drops trailing comments, `;` and whitespace + // (#214, #220 item 7, #222, #225: `select 1 -- c\n`). `describe_columns` + // prepares it via the extended protocol, so a multi-statement `query` + // is rejected here the same way the one-shot path rejects it. + let trimmed = trim_statement_end(query); + let (columns, reads) = describe_columns(&pg_client, trimmed).await?; + let cursor_query = text_projection(trimmed, &reads); + let cursor_query = cursor_query.as_deref().unwrap_or(trimmed); + // `SCROLL` (not `NO SCROLL`): the byte-budget row loop may `MOVE + // BACKWARD` to rewind rows it fetched but didn't return (budget hit), + // which requires a scrollable cursor. Verified cheap: a SCROLL cursor + // on a 200K-row table with ORDER BY streams in ~40 ms (does not + // materialize), and MOVE BACKWARD 500 is 0.2 ms. The query sits in + // parentheses on its own lines so a trailing clause (e.g. `ORDER BY`) + // binds to the subquery and a comment can't swallow the `)`. + let declare = format!( + "DECLARE {} SCROLL CURSOR FOR (\n{cursor_query}\n)", + cursor_name(&session_id) + ); + pg_client.query_typed(&declare, &[]).await.map_err(|e| { + format!( + "read_rows: DECLARE cursor failed: {}", + client::format_pg_error(&e) + ) + })?; + Ok::<_, String>(columns) + } + .await; + match declared { + // 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). + Ok(columns) => { + copy_session_queries().lock().unwrap().insert( + session_id.clone(), + CopySession { + query: query.to_string(), + columns, + }, + ); + } + Err(e) => { // Drop the cancel guard BEFORE cleanup so a re-sent cancel // can't interrupt the ROLLBACK itself (the guard's registered // action would fire pg_cancel_backend at this connection). @@ -348,48 +481,16 @@ async fn run_snapshot( return Err(e); } } - let cursor = cursor_name(&session_id); - // Trim a trailing ';' (and any whitespace before/after it) so - // `DECLARE ... FOR (query;)` doesn't produce a dangling-`)` syntax - // error. `build_paginated_query` does this for the one-shot path; the - // 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 = 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). - copy_session_queries() - .lock() - .unwrap() - .insert(session_id.clone(), query.to_string()); - // `SCROLL` (not `NO SCROLL`): the byte-budget row loop may `MOVE - // BACKWARD` to rewind rows it fetched but didn't return (budget hit), - // which requires a scrollable cursor. Verified cheap: a SCROLL cursor - // on a 200K-row table with ORDER BY streams in ~40 ms (does not - // materialize), and MOVE BACKWARD 500 is 0.2 ms. The query is wrapped - // in parentheses so a trailing clause (e.g. `ORDER BY`) binds to the - // subquery, not the cursor declaration. Sent via `query_typed` (the - // extended protocol), NOT `batch_execute` (the simple query protocol), - // so a multi-statement `query` fails the same way the one-shot path - // rejects it ("cannot insert multiple commands into a prepared - // statement") — restoring the single-statement invariant (#214, #215). - let declare = format!("DECLARE {cursor} SCROLL CURSOR FOR ({trimmed_query})"); - if let Err(e) = pg_client.query_typed(&declare, &[]).await { - drop(cancel_guard); - cleanup_on_error(&pg_client, true).await; - return Err(format!( - "read_rows: DECLARE cursor failed: {}", - client::format_pg_error(&e) - )); - } } + let columns = copy_session_queries() + .lock() + .unwrap() + .get(&session_id) + .map(|s| s.columns.clone()) + .unwrap_or_default(); let cursor = cursor_name(&session_id); - match fetch_cursor(&pg_client, &cursor, page, page_size).await { + match fetch_cursor(&pg_client, &cursor, columns, page, page_size).await { Ok(result) => { drop(cancel_guard); slot.pin(pg_client); @@ -455,11 +556,12 @@ fn cursor_name(session_id: &str) -> String { /// count) so the host does not treat a short page as the end — it loops on /// `has_more` only. /// -/// An empty source reports `columns: []` (no rows to read metadata from). -/// The host falls back to `get_columns` for column metadata on an empty source. +/// `columns` is the source metadata from [`describe_columns`], so an empty +/// page still reports it. async fn fetch_cursor( pg_client: &PgClient, cursor: &str, + columns: Vec, page: u64, page_size: u32, ) -> Result { @@ -471,25 +573,6 @@ async fn fetch_cursor( .await .map_err(|e| format!("read_rows: FETCH failed: {}", client::format_pg_error(&e)))?; - // Column metadata from the first row when rows exist; an empty FETCH has - // no rows to read columns from, so `columns` is `[]` and the host falls - // back to `get_columns`. - let columns: Vec = if rows.is_empty() { - Vec::new() - } else { - rows[0] - .columns() - .iter() - .map(|c| { - json!({ - "name": c.name(), - "type": c.type_().name(), - "oid": c.type_().oid(), - }) - }) - .collect() - }; - let mut result_rows: Vec = Vec::new(); let mut accumulated_bytes: usize = 0; let mut budget_hit = false; @@ -579,18 +662,14 @@ async fn cleanup_on_error(pg_client: &PgClient, txn_is_open: bool) { } } -/// Run the paginated query on `pg_client` and extract lossless rows + column -/// type metadata. The `+1` row probe (page_size + 1, set by -/// `build_paginated_query`) determines `has_more`. -/// -/// Column metadata is harvested from the first row when rows exist; an empty -/// result set reports `columns: []` (there is no prepared-statement handle to -/// introspect with `query_typed`'s unnamed protocol). The host reads table -/// schema separately via `get_columns` when it needs column metadata for an -/// empty source. +/// Run the paginated query on `pg_client` and extract lossless rows. The +/// `+1` row probe (page_size + 1, set by `build_paginated_query`) determines +/// `has_more`. `columns` is the source metadata from [`describe_columns`], so +/// an empty result still reports it. async fn fetch_lossless( pg_client: &PgClient, final_query: &str, + columns: Vec, page: u64, page_size: u32, ) -> Result { @@ -599,24 +678,6 @@ async fn fetch_lossless( .await .map_err(|e| format!("read_rows: query failed: {}", client::format_pg_error(&e)))?; - // Column metadata from the first row (or an empty array if no rows — see - // the doc comment above for the empty-result limitation). - let columns: Vec = if rows.is_empty() { - Vec::new() - } else { - rows[0] - .columns() - .iter() - .map(|c| { - json!({ - "name": c.name(), - "type": c.type_().name(), - "oid": c.type_().oid(), - }) - }) - .collect() - }; - let has_more = rows.len() > page_size as usize; let result_rows: Vec = rows .iter() @@ -921,6 +982,10 @@ async fn build_and_execute_chunks( allow_default: false, hstore_oid, char_max_len, + cast_type: types + .column_types + .get(col) + .and_then(|i| i.qualified_type.as_deref()), }; let bound = bind_pg_value(val, placeholder_idx, &options)?; fragments.push(bound.sql); diff --git a/src/handlers/copy_tests.rs b/src/handlers/copy_tests.rs index 6f64d35..7209a27 100644 --- a/src/handlers/copy_tests.rs +++ b/src/handlers/copy_tests.rs @@ -3,8 +3,11 @@ //! 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, strip_trailing_line_comment}; +use crate::handlers::copy::{ + classify_column, insert_records, parse_page_size, read_rows, text_projection, ColumnRead, +}; use serde_json::{json, Value}; +use tokio_postgres::types::Type; #[tokio::test] async fn read_rows_rejects_a_missing_query() { @@ -181,63 +184,98 @@ async fn read_rows_rejects_a_non_result_set_query_on_the_session_path() { ); } -// --- strip_trailing_line_comment (#222) --- +// --- parse_page_size (#225: a negative limit is an error, not 1000) --- #[test] -fn strip_removes_a_trailing_comment() { - assert_eq!( - strip_trailing_line_comment("SELECT 1 -- get count"), - "SELECT 1" - ); +fn limit_absent_or_null_is_the_default() { + assert_eq!(parse_page_size(None), Ok(1000)); + assert_eq!(parse_page_size(Some(&json!(null))), Ok(1000)); } #[test] -fn strip_preserves_a_query_with_no_comment() { - assert_eq!( - strip_trailing_line_comment("SELECT 1, 2, 3"), - "SELECT 1, 2, 3" - ); +fn limit_zero_clamps_to_one_and_huge_clamps_to_max() { + assert_eq!(parse_page_size(Some(&json!(0))), Ok(1)); + assert_eq!(parse_page_size(Some(&json!(250))), Ok(250)); + assert_eq!(parse_page_size(Some(&json!(u64::MAX))), Ok(100_000)); } #[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"); +fn limit_negative_fractional_or_string_is_an_error() { + for bad in [json!(-1), json!(1.5), json!("10")] { + let err = parse_page_size(Some(&bad)).unwrap_err(); + assert!(err.contains("'limit'"), "{bad}: {err}"); + } } -#[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'" - ); +#[tokio::test] +async fn read_rows_rejects_a_negative_limit_before_connecting() { + let params = json!({"query": "SELECT 1", "limit": -1, "host": "127.0.0.1", "port": 1}); + let resp: Value = read_rows(json!(1), ¶ms).await; + assert_eq!(resp["error"]["code"], -32602, "{resp}"); } +// --- classify_column / text_projection (#225) --- + #[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'" - ); +fn native_columns_are_the_json_native_and_encoded_types() { + for ty in [ + Type::BOOL, + Type::INT2, + Type::INT4, + Type::INT8, + Type::OID, + Type::FLOAT4, + Type::FLOAT8, + Type::BYTEA, + Type::TEXT, + Type::VARCHAR, + Type::BPCHAR, + Type::NAME, + Type::UUID, + ] { + assert_eq!(classify_column(&ty), ColumnRead::Native, "{ty}"); + } + assert_eq!(classify_column(&Type::MONEY), ColumnRead::MoneyAsNumeric); + for ty in [ + Type::NUMERIC, + Type::DATE, + Type::TIMESTAMPTZ, + Type::INTERVAL, + Type::JSONB, + Type::INT4_ARRAY, + Type::TSTZ_RANGE, + Type::BIT, + Type::INET, + Type::RECORD, + ] { + assert_eq!(classify_column(&ty), ColumnRead::Text, "{ty}"); + } } #[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. +fn an_all_native_query_runs_unchanged() { assert_eq!( - strip_trailing_line_comment("SELECT 'a''b--c'"), - "SELECT 'a''b--c'" + text_projection("SELECT 1", &[ColumnRead::Native, ColumnRead::Native]), + None ); } #[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;"); +fn projection_casts_by_position_and_keeps_the_query_on_its_own_lines() { + let sql = text_projection( + "SELECT 1, 1, now(), 1::money", + &[ + ColumnRead::Native, + ColumnRead::Native, + ColumnRead::Text, + ColumnRead::MoneyAsNumeric, + ], + ) + .unwrap(); + assert_eq!( + sql, + "SELECT c1, c2, c3::text, c4::numeric::text FROM (\n\ + SELECT 1, 1, now(), 1::money\n\ + ) AS tabularis_q(c1, c2, c3, c4)" + ); } diff --git a/src/handlers/crud.rs b/src/handlers/crud.rs index 4585480..5d987ee 100644 --- a/src/handlers/crud.rs +++ b/src/handlers/crud.rs @@ -83,6 +83,9 @@ async fn exec_insert( allow_default: false, hstore_oid, char_max_len: column_types.get(&col_name).and_then(|i| i.char_max_len), + cast_type: column_types + .get(&col_name) + .and_then(|i| i.qualified_type.as_deref()), }; let bound = bind_pg_value(val, placeholder_idx, &options)?; sql_fragments.push(bound.sql); @@ -166,6 +169,9 @@ async fn exec_update( None }, char_max_len: column_types.get(col_name).and_then(|i| i.char_max_len), + cast_type: column_types + .get(col_name) + .and_then(|i| i.qualified_type.as_deref()), }; let bound = bind_pg_value(new_val, 1, &options)?; diff --git a/src/utils/pagination.rs b/src/utils/pagination.rs index de2a716..d641a99 100644 --- a/src/utils/pagination.rs +++ b/src/utils/pagination.rs @@ -194,6 +194,26 @@ fn lex(sql: &str) -> (Vec, bool) { (toks, reliable) } +/// `sql` without its trailing comments, `;`s and whitespace, so it can be +/// embedded in `DECLARE … FOR (…)` or a subquery (#222, #225). Uses the same +/// lexer as pagination, so `--` inside a string, `E''` escapes and +/// dollar-quoted bodies are not mistaken for a comment. If nothing but comments +/// and `;` is left, returns the empty string. +pub(crate) fn trim_statement_end(sql: &str) -> &str { + let (toks, _) = lex(sql); + let end = toks + .iter() + .rev() + .find(|t| { + !matches!( + t.kind, + Kind::LineComment | Kind::BlockComment | Kind::Semicolon + ) + }) + .map_or(0, |t| t.end); + &sql[..end] +} + /// Page a WITH statement only when each CTE body and the final command are queries. pub(crate) fn can_page_cte(sql: &str) -> bool { let (tokens, reliable) = lex(sql); diff --git a/src/utils/pagination_tests.rs b/src/utils/pagination_tests.rs index e12d512..a56ea4e 100644 --- a/src/utils/pagination_tests.rs +++ b/src/utils/pagination_tests.rs @@ -1,7 +1,9 @@ //! Unit tests for `pagination.rs`. Sibling test file per repo convention //! (`.rules/rust.md` #4/#5) — loaded via `#[cfg(test)] mod pagination_tests;`. -use crate::utils::pagination::{build_paginated_query, can_page_cte, limit_offset}; +use crate::utils::pagination::{ + build_paginated_query, can_page_cte, limit_offset, trim_statement_end, +}; #[test] fn cte_pagination_distinguishes_into_labels_from_select_into() { @@ -476,3 +478,49 @@ fn a_run_of_dollar_signs_inside_a_name_never_opens_a_dollar_quote() { let sql = build_paginated_query("SELECT a$$$ -- x", 10, 1); assert_eq!(sql, "SELECT a$$$ LIMIT 11 OFFSET 0 -- x"); } + +// --- trim_statement_end (#222, #225) --- + +#[test] +fn trim_statement_end_drops_trailing_comments_semicolons_and_whitespace() { + for (sql, want) in [ + ("select 1", "select 1"), + ("select 1 -- c", "select 1"), + // #225: a pasted statement ends with a newline after the comment. + ("select 1 -- c\n", "select 1"), + ("select 1;\n-- trailing\n", "select 1"), + ("select 1; -- c", "select 1"), + ("select 1 /* c */ ; ", "select 1"), + ("select 1 -- a\n/* b */ -- c\r\n", "select 1"), + // A comment before the end is kept: only the tail is trimmed. + ( + "select 1 -- first\nfrom t -- last", + "select 1 -- first\nfrom t", + ), + ] { + assert_eq!(trim_statement_end(sql), want, "{sql:?}"); + } +} + +#[test] +fn trim_statement_end_leaves_dashes_inside_literals_alone() { + for sql in [ + "select 'a--b'", + "select 'it''s -- here'", + "select E'\\'--'", + "select $$ -- $$", + "select $t$ ; -- $t$", + r#"select 1 as "a--b""#, + ] { + assert_eq!(trim_statement_end(sql), sql, "{sql:?}"); + } + assert_eq!( + trim_statement_end("select 'it''s' -- c\n"), + "select 'it''s'" + ); +} + +#[test] +fn trim_statement_end_of_only_comments_is_empty() { + assert_eq!(trim_statement_end("-- nothing\n;"), ""); +} From a96889022722442c585460fd60a8f1679de910e7 Mon Sep 17 00:00:00 2001 From: Adam J Esslinger Date: Thu, 3 Dec 2026 10:38:17 -0500 Subject: [PATCH 2/3] fix: keep JSON-array-shaped text as is in text columns (#225) insert_records turned a text value like '[1,2,3]' into the array literal {1,2,3} whatever the target column, so a copied text cell holding a JSON array arrived changed. Skip the array guess when the column is a known text-family type; array and unknown columns keep it. Co-Authored-By: Adam J Esslinger --- src/binding.rs | 7 +++-- src/binding_tests.rs | 20 ++++++++++++++ src/client_live_tests.rs | 57 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 82 insertions(+), 2 deletions(-) diff --git a/src/binding.rs b/src/binding.rs index 4f997ab..9a32262 100644 --- a/src/binding.rs +++ b/src/binding.rs @@ -470,9 +470,12 @@ fn bind_pg_string( }); } - // 11. PG array literal (JSON array embedded in a string, e.g. "[1,2,3]") + // 11. PG array literal (JSON array embedded in a string, e.g. "[1,2,3]"). + // Not for a known text column: there `[1,2,3]` is the value itself, and + // the literal would store it as `{1,2,3}`. let trimmed = s.trim(); - if trimmed.starts_with('[') && trimmed.ends_with(']') { + let text_column = base_type.is_some() && is_text_like(base_type); + if !text_column && trimmed.starts_with('[') && trimmed.ends_with(']') { if let Ok(Value::Array(arr)) = serde_json::from_str::(trimmed) { let literal = json_array_to_pg_literal(&arr)?; return Ok(BoundValue { diff --git a/src/binding_tests.rs b/src/binding_tests.rs index 1eeffda..635a5cd 100644 --- a/src/binding_tests.rs +++ b/src/binding_tests.rs @@ -1371,6 +1371,26 @@ mod cast_type_fallback_tests { } } + #[test] + fn json_array_shaped_text_into_a_text_column_is_stored_as_is() { + // A text cell holding `[1,2,3]` must not be rewritten to the array + // literal `{1,2,3}` on its way into a text column (#225 retest). + for ty in ["text", "character varying", "character", "citext"] { + for s in ["[1,2,3]", "[]", r#"["a","b"]"#, "[1, 2]"] { + let bound = bind_pg_value(json!(s), 1, &opts(ty, "pg_catalog.text")).unwrap(); + assert_eq!(bound.sql, "$1", "{ty} {s}"); + } + } + } + + #[test] + fn json_array_shaped_text_still_becomes_an_array_for_array_or_unknown_columns() { + let bound = bind_pg_value(json!("[1,2,3]"), 1, &opts("_int4", "pg_catalog._int4")).unwrap(); + assert_eq!(bound.sql, "ARRAY[1, 2, 3]"); + let bound = bind_pg_value(json!("[1,2,3]"), 1, &BindOptions::default()).unwrap(); + assert_eq!(bound.sql, "ARRAY[1, 2, 3]"); + } + #[test] fn earlier_cascade_steps_win_over_the_fallback() { // A typed step that already handles the column type is unchanged. diff --git a/src/client_live_tests.rs b/src/client_live_tests.rs index 2b59ff5..18c68eb 100644 --- a/src/client_live_tests.rs +++ b/src/client_live_tests.rs @@ -1469,6 +1469,63 @@ async fn read_rows_session_cursor_full_batch_budget_cut_no_dupes() { /// NOTHING`: rows that conflict with an existing PK are skipped (not errored), /// and the response reports `affected_rows` (inserted) and `skipped` (#214 /// item 3). A `fail`-mode insert into the same conflicting state errors. +/// A JSON-array-shaped string copied into a text-family column is stored as +/// is, not rewritten to the array literal `{1,2,3}` (#225 retest). +#[tokio::test] +#[ignore = "needs a live PostgreSQL (PG_PLUGIN_TEST_HOST=127.0.0.1 ... podman 54320)"] +async fn insert_records_keeps_json_array_shaped_text_in_text_columns() { + use crate::client; + use crate::handlers::copy::insert_records; + use serde_json::json; + + let _guard = POOLS_TEST_LOCK.lock().await; + let params = live_params(&correct_password()) + .expect("PG_PLUGIN_TEST_HOST not set — set PG_PLUGIN_TEST_HOST=127.0.0.1 (and optionally PG_PLUGIN_TEST_PORT/USER/DB) to run live tests"); + + let table = format!("plugin_test_225_arrtext_{}", uuid::Uuid::new_v4().simple()); + client::execute_typed( + ¶ms, + &format!( + "CREATE TABLE {table} (id int primary key, t text, v varchar(20), c char(9), a int[])" + ), + &[], + ) + .await + .unwrap(); + + let values = ["[1,2,3]", "[]", r#"["a","b"]"#, "[1, 2]"]; + let rows: Vec<_> = values + .iter() + .enumerate() + .map(|(i, s)| json!({"id": i, "t": s, "v": s, "c": s, "a": "[1,2,3]"})) + .collect(); + let mut req = json!({ + "driver": "postgresql", + "host": params.host, "port": params.port, + "database": params.database, "username": params.username, "password": params.password, + }); + req["table"] = json!(table.clone()); + req["rows"] = json!(rows); + let resp = insert_records(json!(1), &req).await; + assert!(resp.get("error").is_none(), "{resp}"); + + let got = client::query_rows( + ¶ms, + &format!("SELECT t, v, rtrim(c), a::text FROM {table} ORDER BY id"), + &[], + ) + .await + .unwrap(); + for (row, s) in got.iter().zip(values) { + for col in 0..3 { + assert_eq!(row.get::<_, String>(col), s, "column {col}"); + } + // An array column still takes the JSON array form. + assert_eq!(row.get::<_, String>(3), "{1,2,3}"); + } + let _ = client::execute_typed(¶ms, &format!("DROP TABLE {table}"), &[]).await; +} + #[tokio::test] #[ignore = "needs a live PostgreSQL (PG_PLUGIN_TEST_HOST=127.0.0.1 ... podman 54320)"] async fn insert_records_on_conflict_skip_reports_inserted_and_skipped() { From ac19204c0dd96b7261a8d9b0c5226e9eacddd640 Mon Sep 17 00:00:00 2001 From: Adam J Esslinger Date: Thu, 3 Dec 2026 12:32:29 -0500 Subject: [PATCH 3/3] fix: close the copy gaps found in review (#225) - a bytea column takes only the BLOB wire format; any other string (an unresolved BLOB_FILE_REF, corrupt base64) is an error again instead of being cast to bytea and stored as its own text - behind a transaction pooler read_rows runs on a one-shot connection and starts with DEALLOCATE ALL, so its prepare can't collide with statement names another client left on the backend (42P05) - hstore text from read_rows casts to the column's hstore type - the JSON-array guess applies only to array or unknown columns, so a user-defined range's [a,b] text reaches the cast to its type - the read also pins bytea_output = 'hex' and TimeZone = 'UTC' - raw SQL, WKT and UUID shape guesses no longer apply to text columns, so an md5 hash in a text column is copied as is - stale docs, a split doc comment, and tests for the settings, session columns on later pages, a trailing ';', a failed first page, row editing of a composite and the pooler collision Co-Authored-By: Adam J Esslinger --- CLAUDE.md | 7 +- README.md | 35 +++--- src/binding.rs | 55 +++++--- src/binding_tests.rs | 70 ++++++++++- src/client_live_tests.rs | 265 ++++++++++++++++++++++++++++++++++++++- src/handlers/copy.rs | 54 ++++++-- 6 files changed, 440 insertions(+), 46 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 2a0839b..a2c9ef0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -57,9 +57,10 @@ migration, now applied across the repo boundary. `ssl_mode`/`ssl_ca`/`ssl_cert`/`ssl_key`). - Value binding for INSERT/UPDATE lives in `src/binding.rs` — a strict ordered cascade (DEFAULT sentinel, BLOB wire format, enum CAST, boolean, - numeric, temporal, UUID shape, PG array literal, TEXT fallback). Order - matters; do not reorder without understanding why each earlier step must - run first. + numeric, temporal, UUID shape, PG array literal, CAST to the column's + qualified type, TEXT fallback). Shape-based guesses (raw SQL, WKT, UUID, + array literal) never apply to a known text column. Order matters; do not + reorder without understanding why each earlier step must run first. - Never write to `stdout` outside the JSON-RPC response loop in `main.rs` — any stray write corrupts the protocol stream. Use `log`/stderr for diagnostics. diff --git a/README.md b/README.md index 5d32070..251cfa5 100644 --- a/README.md +++ b/README.md @@ -391,8 +391,8 @@ the value is exactly what the server's own output function prints: not the 10 KB preview) - `money` as `::numeric::text` (`"123.45"`, not a locale-formatted amount) - everything else as `::text`: `numeric`, dates and times (full fractional - seconds, BC values as `"0043-03-15 BC"`, `infinity`), `timestamptz` with the - session offset (`"2026-11-29 13:45:30.345678+00"`), `interval`, `json`/`jsonb` + seconds, BC values as `"0043-03-15 BC"`, `infinity`), `timestamptz` in UTC + (`"2026-11-29 13:45:30.345678+00"`), `interval`, `json`/`jsonb` (exact text, so `1e400`, wide numbers and `json` duplicate keys survive), enums, `inet`, and arrays, ranges, multiranges and composites as PostgreSQL text (`"{{1,2},{3,4}}"`, `"[2:3]={1,2}"`, `"[1,5)"`, `"(1,2)"`) — not JSON @@ -401,10 +401,13 @@ the value is exactly what the server's own output function prints: conversion; also returned for a result with zero rows The read transaction sets `DateStyle = 'ISO, MDY'`, `IntervalStyle = -'postgres'` and `extra_float_digits = 3` with `SET LOCAL`, so the text does not -depend on the connection's startup script, and always ends with `ROLLBACK`, so -a query that changes a setting with `set_config(…, false)` cannot leak it into -the pooled connection. +'postgres'`, `extra_float_digits = 3`, `bytea_output = 'hex'` and `TimeZone = +'UTC'` with `SET LOCAL`, so the text does not depend on the connection's +startup script (`lc_monetary` is not pinned: `money[]` keeps the server's +locale form), and always ends with `ROLLBACK`, so a query that changes a +setting with `set_config(…, false)` cannot leak it into the pooled connection. +Behind a transaction pooler (`pooler_mode = "transaction"`) the read runs on a +one-shot connection and starts with `DEALLOCATE ALL`, like `execute_query`. With a `session_id`, the first page opens a `BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY` transaction on a pinned connection; subsequent pages reuse @@ -416,9 +419,10 @@ and is clamped to 1..`MAX_PAGE_SIZE`; a negative or non-integer `limit` is rejected with `-32602` instead of falling back to the default. With a `session_id`, a single response is bounded by a 16 MB byte budget -(`MAX_RESPONSE_BYTES`): rows are fetched one at a time from the cursor and -accumulated until adding the next would exceed the budget, at which point -the over-budget row is rewound (`MOVE BACKWARD`) for the next page and +(`MAX_RESPONSE_BYTES`): a page is fetched from the cursor in one `FETCH +FORWARD` and rows are accumulated until adding the next would exceed the +budget, at which point the over-budget row and the rest are rewound (`MOVE +BACKWARD`) for the next page and `has_more` reports `true`. A single row larger than the budget still goes out as its own response — at least one row is always returned. The budget keeps a page of large `bytea` values from producing a response larger than @@ -440,11 +444,14 @@ the same keys (a row missing a column is an error, not a silent NULL). The value — `bytea`, full-precision timestamps, `numeric`, etc. A value that no earlier step of the cascade recognizes (an array with explicit -lower bounds, a composite, a range, …) is bound as text and cast to the -column's schema-qualified type, `CAST($N AS public.point2d)`, so the text -`read_rows` returns for it is parsed by the target's own input function. Text -columns are never cast. A `jsonb[]` array may contain JSON objects; each one -is written as its JSON text. +lower bounds, a composite, a range, hstore text, …) is bound as text and cast +to the column's schema-qualified type, `CAST($N AS public.point2d)`, so the +text `read_rows` returns for it is parsed by the target's own input function. +A known text column takes its value as is: no shape-based guess (a UUID-shaped +hash, a JSON-array-shaped string, `POINT(…)`, `ST_…(…)`) applies to it. A +`bytea` column takes only the `BLOB:` wire format; any other string is an +error. A `jsonb[]` array may contain JSON objects; each one is written as its +JSON text. ## Building from Source diff --git a/src/binding.rs b/src/binding.rs index 9a32262..9dbb169 100644 --- a/src/binding.rs +++ b/src/binding.rs @@ -1,6 +1,8 @@ //! Value binding for INSERT/UPDATE — converts JSON values into SQL fragments -//! and typed bind parameters, matching the built-in driver's binding cascade -//! exactly (`src-tauri/src/drivers/postgres/binding.rs`). +//! and typed bind parameters. Ported from the built-in driver's binding +//! cascade (`src-tauri/src/drivers/postgres/binding.rs`); since #225 it also +//! casts unrecognized values to the column's own type and keeps text columns' +//! values as is, where the built-in guessed from the value's shape. //! //! Why the explicit `Type` matters: `tokio-postgres`'s `prepare_typed` lets //! the caller pin a placeholder's wire type instead of letting the server @@ -175,7 +177,7 @@ pub fn bind_pg_value( // hstore column — bind before the JSON/JSONB check below, since a JSON // object destined for hstore must NOT go through the JSON ToSql path. if options.column_type == Some("hstore") { - return bind_pg_hstore(value, placeholder_idx, options.hstore_oid); + return bind_pg_hstore(value, placeholder_idx, options); } // JSON/JSONB columns receiving a native JSON value (object/array/number/bool) @@ -229,10 +231,14 @@ pub fn bind_pg_value( /// Requires the real OID of the `hstore` type in this database (extension-defined, /// not a well-known Postgres OID) so the placeholder's `Type` pins it correctly. /// Ported from `tabularis#427`'s `bind_pg_hstore`. +/// +/// A string that is not a JSON object is hstore's own text form (`"a"=>"1"`, +/// what `read_rows` returns): it is cast to the column's type when that is +/// known (#225). fn bind_pg_hstore( value: Value, placeholder_idx: usize, - hstore_oid: Option, + options: &BindOptions, ) -> Result { let map = match value { Value::Null => { @@ -246,8 +252,14 @@ fn bind_pg_hstore( // The grid's plain-text cell editor doesn't yet know about hstore, so it // may round-trip the value as a JSON-encoded string rather than an // object. Accept that shape here so editing still works. - Value::String(s) => match serde_json::from_str::(&s) { - Ok(Value::Object(map)) => map, + Value::String(s) => match (serde_json::from_str::(&s), options.cast_type) { + (Ok(Value::Object(map)), _) => map, + (_, Some(cast_type)) => { + return Ok(BoundValue { + sql: format!("CAST(${placeholder_idx} AS {cast_type})"), + param: Some((Box::new(s), Type::TEXT)), + }); + } _ => { return Err( "hstore column requires a JSON object value, got a string that is not valid JSON" @@ -263,7 +275,7 @@ fn bind_pg_hstore( } }; - let oid = hstore_oid.ok_or_else(|| { + let oid = options.hstore_oid.ok_or_else(|| { "Could not resolve the hstore type OID; is the hstore extension installed?".to_string() })?; let hmap = hstore_map_from_json_object(map)?; @@ -369,7 +381,7 @@ fn bind_pg_string( // 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 + // (step 13) — both would bind as TEXT, which PostgreSQL rejects for // these types. The placeholder is pinned to TEXT so tokio-postgres // doesn't fight the CAST (#220 item 4). if let Some(bt) = base_type { @@ -406,6 +418,13 @@ fn bind_pg_string( }); } } + // A bytea column takes only the wire format above. Anything else (a + // `BLOB_FILE_REF:` the plugin can't resolve, corrupt base64) must fail, + // not reach step 12's `CAST(.. AS bytea)`, which would store the string's + // own bytes (#225). + if base_type == Some("BYTEA") { + return Err("bytea column requires a BLOB::: value".to_string()); + } // 4. Enum column — always coerces through its own type. Any of the later // shape-based heuristics (uuid-shaped, array-shaped strings) would @@ -442,10 +461,15 @@ fn bind_pg_string( } } + // Steps 8-10 guess the target from the value's shape. In a known text + // column the value is the text itself: an md5 hash must not become a + // uuid, nor `ST_Name (x)` raw SQL (#225). + let text_column = base_type.is_some() && is_text_like(base_type); + // 8. Raw SQL function passthrough (e.g. `ST_GeomFromText('POINT(1 2)', 4326)`) // — inlined verbatim, no bound parameter, so the function actually // executes server-side instead of being stored as its literal text. - if is_raw_sql_function(s) { + if !text_column && is_raw_sql_function(s) { return Ok(BoundValue { sql: s.to_string(), param: None, @@ -455,7 +479,7 @@ fn bind_pg_string( // 9. WKT geometry literal (e.g. `POINT(1 2)`) — wrapped in // `ST_GeomFromText($N)` so PostGIS parses it into a geometry instead of // storing the raw WKT text. - if is_wkt_geometry(s) { + if !text_column && is_wkt_geometry(s) { return Ok(BoundValue { sql: format!("ST_GeomFromText(${})", placeholder_idx), param: Some((Box::new(s.to_string()), Type::TEXT)), @@ -463,7 +487,7 @@ fn bind_pg_string( } // 10. UUID shape (value-based fallback, independent of column type) - if s.parse::().is_ok() { + if !text_column && s.parse::().is_ok() { return Ok(BoundValue { sql: format!("CAST(${} AS uuid)", placeholder_idx), param: Some((Box::new(s.to_string()), Type::TEXT)), @@ -471,11 +495,12 @@ fn bind_pg_string( } // 11. PG array literal (JSON array embedded in a string, e.g. "[1,2,3]"). - // Not for a known text column: there `[1,2,3]` is the value itself, and - // the literal would store it as `{1,2,3}`. + // Only for an array column or an unknown type: in a text column `[1,2,3]` + // is the value itself, and a user-defined range's text `[1.5,2.5]` is + // parsed by step 12's cast to the range type (#225). let trimmed = s.trim(); - let text_column = base_type.is_some() && is_text_like(base_type); - if !text_column && trimmed.starts_with('[') && trimmed.ends_with(']') { + let array_or_unknown = base_type.is_none_or(|bt| bt.starts_with('_')); + if array_or_unknown && trimmed.starts_with('[') && trimmed.ends_with(']') { if let Ok(Value::Array(arr)) = serde_json::from_str::(trimmed) { let literal = json_array_to_pg_literal(&arr)?; return Ok(BoundValue { diff --git a/src/binding_tests.rs b/src/binding_tests.rs index 635a5cd..fb61d1f 100644 --- a/src/binding_tests.rs +++ b/src/binding_tests.rs @@ -302,7 +302,7 @@ mod bind_pg_value_tests { /// `NaN` (which `Decimal` cannot represent) binds through the TEXT+CAST /// path; `CAST('NaN' AS numeric)` is the round-trip pair of `read_rows`' - /// `PgNumeric` `NaN` output. + /// `numeric::text` `NaN` output. #[test] fn numeric_column_binds_nan_string() { let options = BindOptions { @@ -1391,6 +1391,74 @@ mod cast_type_fallback_tests { assert_eq!(bound.sql, "ARRAY[1, 2, 3]"); } + #[test] + fn shape_guesses_do_not_apply_to_text_columns() { + // An md5 hash is not a uuid, `POINT(1 2)` is not WKT and `ST_Pete (x)` + // is not SQL in a text column: each is stored as is (#225 review). + for s in [ + "5d41402abc4b2a76b9719d911017c592", + "POINT(1 2)", + "ST_Petersburg (Russia)", + ] { + let bound = bind_pg_value(json!(s), 1, &opts("text", "pg_catalog.text")).unwrap(); + assert_eq!(bound.sql, "$1", "{s}"); + } + } + + #[test] + fn shape_guesses_still_apply_to_unknown_column_types() { + let none = BindOptions::default(); + let uuid = bind_pg_value(json!("5d41402abc4b2a76b9719d911017c592"), 1, &none).unwrap(); + assert_eq!(uuid.sql, "CAST($1 AS uuid)"); + let wkt = bind_pg_value(json!("POINT(1 2)"), 1, &none).unwrap(); + assert_eq!(wkt.sql, "ST_GeomFromText($1)"); + } + + #[test] + fn a_user_defined_range_with_array_shaped_text_casts_to_the_range() { + // `[1.5,2.5]` parses as JSON, but it is a range's text, not an array. + let bound = bind_pg_value( + json!("[1.5,2.5]"), + 1, + &opts("floatrange", "public.floatrange"), + ) + .unwrap(); + assert_eq!(bound.sql, "CAST($1 AS public.floatrange)"); + } + + #[test] + fn a_bytea_column_rejects_strings_that_are_not_the_blob_wire_format() { + // Cast to bytea, these would store the string's own bytes (#225 review). + for s in [ + "BLOB_FILE_REF:10:application/octet-stream:/tmp/x.bin", + "BLOB:3:application/octet-stream:@@@notbase64@@@", + "plain text", + ] { + let err = bind_pg_value(json!(s), 1, &opts("bytea", "pg_catalog.bytea")).unwrap_err(); + assert!(err.contains("bytea column"), "{s}: {err}"); + } + let ok = bind_pg_value( + json!("BLOB:3:application/octet-stream:AAEC"), + 1, + &opts("bytea", "pg_catalog.bytea"), + ) + .unwrap(); + assert_eq!(ok.param.unwrap().1, tokio_postgres::types::Type::BYTEA); + } + + #[test] + fn hstore_text_casts_to_the_hstore_type() { + let options = BindOptions { + column_type: Some("hstore"), + cast_type: Some("public.hstore"), + hstore_oid: Some(16_500), + ..BindOptions::default() + }; + let bound = bind_pg_value(json!(r#""a"=>"1", "b"=>NULL"#), 1, &options).unwrap(); + assert_eq!(bound.sql, "CAST($1 AS public.hstore)"); + assert_eq!(bound.param.unwrap().1, tokio_postgres::types::Type::TEXT); + } + #[test] fn earlier_cascade_steps_win_over_the_fallback() { // A typed step that already handles the column type is unchanged. diff --git a/src/client_live_tests.rs b/src/client_live_tests.rs index 18c68eb..b26bb60 100644 --- a/src/client_live_tests.rs +++ b/src/client_live_tests.rs @@ -1465,10 +1465,6 @@ async fn read_rows_session_cursor_full_batch_budget_cut_no_dupes() { POOLS.lock().unwrap().remove(&key); } -/// `insert_records` with `on_conflict: "skip"` appends `ON CONFLICT DO -/// NOTHING`: rows that conflict with an existing PK are skipped (not errored), -/// and the response reports `affected_rows` (inserted) and `skipped` (#214 -/// item 3). A `fail`-mode insert into the same conflicting state errors. /// A JSON-array-shaped string copied into a text-family column is stored as /// is, not rewritten to the array literal `{1,2,3}` (#225 retest). #[tokio::test] @@ -1526,6 +1522,227 @@ async fn insert_records_keeps_json_array_shaped_text_in_text_columns() { let _ = client::execute_typed(¶ms, &format!("DROP TABLE {table}"), &[]).await; } +/// The session path keeps reporting `columns` on every page, including for an +/// empty result, accepts a statement ending in `;`, and recovers after a first +/// page that fails (#225 review). +#[tokio::test] +#[ignore = "needs a live PostgreSQL (PG_PLUGIN_TEST_HOST=127.0.0.1 ... podman 54320)"] +async fn read_rows_session_reports_columns_on_every_page_and_recovers_from_errors() { + use crate::handlers::copy::read_rows; + use crate::handlers::query::release_session; + use serde_json::json; + + let _guard = POOLS_TEST_LOCK.lock().await; + let params = live_params(&correct_password()).expect("PG_PLUGIN_TEST_HOST not set"); + let conn = json!({ + "driver": "postgresql", + "host": params.host, "port": params.port, + "database": params.database, "username": params.username, "password": params.password, + }); + let tag = uuid::Uuid::new_v4().simple().to_string(); + let want = json!([{"name": "g", "type": "int4", "oid": 23}, {"name": "d", "type": "date", "oid": 1082}]); + let read = |sid: String, query: &str, page: u64| { + let mut r = conn.clone(); + r["query"] = json!(query); + r["session_id"] = json!(sid); + r["page"] = json!(page); + r["limit"] = json!(2); + async move { read_rows(json!(1), &r).await } + }; + let release = |sid: String| { + let conn = conn.clone(); + async move { release_session(json!(2), &json!({"session_id": sid, "params": conn})).await } + }; + + // Three pages; the statement ends in `;` and a comment. + let sid = format!("cols225_{tag}"); + let q = "SELECT g, date '2024-01-01' + g AS d FROM generate_series(1, 5) g; -- end"; + for page in 1..=3 { + let resp = read(sid.clone(), q, page).await; + assert_eq!(resp["result"]["columns"], want, "page {page}: {resp}"); + } + release(sid.clone()).await; + + // Empty result. + let sid = format!("empty225_{tag}"); + let empty = "SELECT g, date '2024-01-01' + g AS d FROM generate_series(1, 5) g WHERE false"; + for page in 1..=2 { + let resp = read(sid.clone(), empty, page).await; + assert_eq!(resp["result"]["columns"], want, "empty page {page}: {resp}"); + assert_eq!(resp["result"]["rows"], json!([]), "{resp}"); + } + release(sid.clone()).await; + + // A first page that fails leaves nothing pinned: the same session id then + // starts cleanly instead of finding an aborted transaction (25P02). + let sid = format!("fail225_{tag}"); + let resp = read( + sid.clone(), + "SELECT * FROM plugin_test_225_missing_table", + 1, + ) + .await; + assert!(resp.get("error").is_some(), "{resp}"); + let resp = read(sid.clone(), q, 1).await; + assert_eq!( + resp["result"]["columns"], want, + "after a failed first page: {resp}" + ); + release(sid).await; + POOLS.lock().unwrap().remove(&connection_key(¶ms)); +} + +/// Fixes from the #225 review, on the paths the host reaches: a bytea cell +/// edit with an unresolved `BLOB_FILE_REF:` errors instead of storing the +/// reference text, a hash-shaped string stays as is in a text column, hstore +/// and a user-defined range round-trip through `read_rows` → `insert_records`, +/// and the read ignores a startup script's `bytea_output`/`TimeZone`. +#[tokio::test] +#[ignore = "needs a live PostgreSQL (PG_PLUGIN_TEST_HOST=127.0.0.1 ... podman 54320)"] +async fn copy_review_fixes_hold_on_a_live_server() { + use crate::client; + use crate::handlers::copy::{insert_records, read_rows}; + use crate::handlers::crud::insert_record; + use serde_json::json; + + let _guard = POOLS_TEST_LOCK.lock().await; + let params = live_params(&correct_password()).expect("PG_PLUGIN_TEST_HOST not set"); + let tag = uuid::Uuid::new_v4().simple().to_string(); + let (src, dst, rng) = ( + format!("plugin_test_225r_src_{tag}"), + format!("plugin_test_225r_dst_{tag}"), + format!("plugin_test_225r_fr_{tag}"), + ); + let comp = format!("plugin_test_225r_pt_{tag}"); + let cols = format!( + "id int primary key, t text, h hstore, r {rng}, by bytea, ba bytea[], tz timestamptz, \ + d date, iv interval, c {comp}" + ); + for stmt in [ + "CREATE EXTENSION IF NOT EXISTS hstore".to_string(), + format!("CREATE TYPE {rng} AS RANGE (subtype = float8)"), + format!("CREATE TYPE {comp} AS (x int, y text)"), + format!("CREATE TABLE {src} ({cols})"), + format!("CREATE TABLE {dst} ({cols})"), + format!( + "INSERT INTO {src} VALUES (1, '5d41402abc4b2a76b9719d911017c592', \ + 'a=>1, b=>NULL', '[1.5,2.5]', '\\x00ff', ARRAY['\\x01ff'::bytea], \ + '2024-06-01 12:00:00+00', '2024-06-01', '14 months', '(1,a)')" + ), + ] { + client::execute_typed(¶ms, &stmt, &[]) + .await + .unwrap_or_else(|e| panic!("setup failed ({stmt}): {e}")); + } + let conn = json!({ + "driver": "postgresql", + "host": params.host, "port": params.port, + "database": params.database, "username": params.username, "password": params.password, + // Not the read's own settings: the read must not depend on them. + "startup_script": "SET bytea_output = 'escape'; SET TimeZone = 'America/New_York'; \ + SET DateStyle = 'German, DMY'; SET IntervalStyle = 'sql_standard'", + }); + + let mut req = conn.clone(); + req["query"] = json!(format!("SELECT * FROM {src}")); + let resp = read_rows(json!(1), &req).await; + let result = resp + .get("result") + .unwrap_or_else(|| panic!("read_rows: {resp}")); + let names: Vec<&str> = result["columns"] + .as_array() + .unwrap() + .iter() + .map(|c| c["name"].as_str().unwrap()) + .collect(); + let row = result["rows"][0].as_array().unwrap(); + let at = |n: &str| &row[names.iter().position(|c| *c == n).unwrap()]; + assert_eq!( + *at("ba"), + json!("{\"\\\\x01ff\"}"), + "bytea_output is pinned to hex" + ); + assert_eq!( + *at("tz"), + json!("2024-06-01 12:00:00+00"), + "TimeZone is pinned to UTC" + ); + assert_eq!(*at("d"), json!("2024-06-01"), "DateStyle is pinned to ISO"); + assert_eq!( + *at("iv"), + json!("1 year 2 mons"), + "IntervalStyle is pinned to postgres" + ); + + let obj: serde_json::Map = names + .iter() + .zip(row) + .map(|(c, v)| (c.to_string(), v.clone())) + .collect(); + let mut ins = conn.clone(); + ins["table"] = json!(dst); + ins["schema"] = json!("public"); + ins["rows"] = json!([obj]); + let resp = insert_records(json!(2), &ins).await; + assert!(resp.get("error").is_none(), "insert_records: {resp}"); + let diff = client::query_rows( + ¶ms, + &format!( + "SELECT count(*) FROM ((SELECT t::text FROM {src} t) EXCEPT (SELECT t::text FROM {dst} t)) d" + ), + &[], + ) + .await + .unwrap(); + assert_eq!( + diff[0].get::<_, i64>(0), + 0, + "copied row differs from source" + ); + + // A file reference the plugin can't resolve is an error, not stored text. + let mut edit = conn.clone(); + edit["table"] = json!(dst); + edit["schema"] = json!("public"); + edit["data"] = json!({"id": 2, "by": "BLOB_FILE_REF:10:application/octet-stream:/tmp/x.bin"}); + let resp = insert_record(json!(3), &edit).await; + assert!( + resp.get("error").is_some(), + "BLOB_FILE_REF was accepted: {resp}" + ); + let stored = client::query_rows( + ¶ms, + &format!("SELECT count(*) FROM {dst} WHERE id = 2"), + &[], + ) + .await + .unwrap(); + assert_eq!(stored[0].get::<_, i64>(0), 0); + + // Row editing passes the column's type too: a composite cell's text is + // cast to it instead of failing as text. + edit["data"] = json!({"id": 3, "c": "(2,b)"}); + let resp = insert_record(json!(4), &edit).await; + assert!( + resp.get("error").is_none(), + "insert_record composite: {resp}" + ); + + for stmt in [ + format!("DROP TABLE IF EXISTS {src}"), + format!("DROP TABLE IF EXISTS {dst}"), + format!("DROP TYPE IF EXISTS {rng}"), + format!("DROP TYPE IF EXISTS {comp}"), + ] { + let _ = client::execute_typed(¶ms, &stmt, &[]).await; + } + POOLS.lock().unwrap().clear(); +} + +/// `insert_records` with `on_conflict: "skip"` appends `ON CONFLICT DO +/// NOTHING`: rows that conflict with an existing PK are skipped (not errored), +/// and the response reports `affected_rows` (inserted) and `skipped` (#214 +/// item 3). A `fail`-mode insert into the same conflicting state errors. #[tokio::test] #[ignore = "needs a live PostgreSQL (PG_PLUGIN_TEST_HOST=127.0.0.1 ... podman 54320)"] async fn insert_records_on_conflict_skip_reports_inserted_and_skipped() { @@ -6264,6 +6481,46 @@ mod podman { exercise_transport(&t, None).await; } + /// `read_rows` prepares the query to describe its columns. Behind a + /// transaction pooler another client may have left statements with the + /// same `s{N}` names on the backend; the read must not collide with them + /// (`42P05`, #225 review). Pool size 1, so the read lands on that backend. + #[tokio::test] + #[ignore = "needs the podman PgBouncers (tests/podman/env.sh up: PG_PLUGIN_TEST_POOLER_PORT)"] + async fn behind_a_real_transaction_pgbouncer_read_rows_ignores_stale_statement_names() { + let _guard = POOLS_TEST_LOCK.lock().await; + let t = pooler_transport(env_var("PG_PLUGIN_TEST_POOLER_PORT").parse().unwrap()); + let mut raw = t.params.clone(); + raw.pooler_mode = None; + let other = crate::client::oneshot_pool_client(&raw).await.unwrap(); + other + .batch_execute( + "DEALLOCATE ALL; DO $$ BEGIN FOR i IN 0..50000 LOOP \ + EXECUTE 'PREPARE s' || i || ' AS SELECT 1'; END LOOP; END $$", + ) + .await + .unwrap(); + let p = &t.params; + let mut conn = serde_json::json!({ + "driver": "postgresql", "host": p.host, "port": p.port, "database": p.database, + "username": p.username, "password": p.password, "ssl_mode": p.ssl_mode, + "pooler_mode": "transaction", + }); + conn["query"] = serde_json::json!("SELECT 1 AS a, now() AS b"); + let mut session = conn.clone(); + session["session_id"] = serde_json::json!(format!("pgb225_{}", std::process::id())); + for (label, req) in [("one-shot", &conn), ("session", &session)] { + let resp = crate::handlers::copy::read_rows(serde_json::json!(1), req).await; + assert!(resp.get("error").is_none(), "{label}: {resp}"); + } + crate::handlers::query::release_session( + serde_json::json!(2), + &serde_json::json!({"session_id": session["session_id"], "params": conn}), + ) + .await; + let _ = other.batch_execute("DEALLOCATE ALL").await; + } + #[tokio::test] #[ignore = "needs the podman PgBouncers (tests/podman/env.sh up: PG_PLUGIN_TEST_POOLER_PORT)"] async fn behind_a_real_transaction_pgbouncer_a_protected_call_leaves_nothing_on_the_backend() { diff --git a/src/handlers/copy.rs b/src/handlers/copy.rs index 93bda98..6964180 100644 --- a/src/handlers/copy.rs +++ b/src/handlers/copy.rs @@ -59,11 +59,45 @@ pub fn clear_copy_session_query(session_id: &str) { /// Pins the server's text output format for the read, so values don't depend /// on the connection's startup script: ISO dates, `postgres` intervals, -/// shortest-exact floats, hex bytea. `SET LOCAL` — reverted when the read -/// transaction ends. +/// shortest-exact floats (PostgreSQL 12+), hex bytea, UTC offsets. `SET LOCAL` +/// — reverted when the read transaction ends. `lc_monetary` is not pinned: +/// scalar `money` is read as `::numeric::text`, but `money[]` and money inside +/// a composite keep the server's locale form. const TEXT_OUTPUT_SETTINGS: &str = "SET LOCAL DateStyle = 'ISO, MDY'; \ SET LOCAL IntervalStyle = 'postgres'; \ - SET LOCAL extra_float_digits = 3"; + SET LOCAL extra_float_digits = 3; \ + SET LOCAL bytea_output = 'hex'; \ + SET LOCAL TimeZone = 'UTC'"; + +/// The connection a read runs on. Behind a transaction pooler it is a one-shot +/// connection, and the read transaction starts with `DEALLOCATE ALL` +/// ([`clear_pooler_statements`]): `describe_columns` creates a named statement, +/// whose name can collide with one another client left on the pooler's backend +/// (`42P05`, #160/#163). A fresh client also has no cached type-lookup +/// statement for `DEALLOCATE ALL` to invalidate — the same pairing as +/// `query.rs`'s `pin_pooled_txn` (#225). +async fn read_client(conn_params: &ConnectionParams) -> Result { + if conn_params.is_transaction_pooler() { + client::oneshot_pool_client(conn_params).await + } else { + client::get_pool_client(conn_params).await + } +} + +/// `DEALLOCATE ALL` inside the open read transaction behind a transaction +/// pooler (see [`read_client`]); a no-op otherwise. +async fn clear_pooler_statements( + pg_client: &PgClient, + conn_params: &ConnectionParams, +) -> Result<(), String> { + if conn_params.is_transaction_pooler() { + pg_client + .batch_execute("DEALLOCATE ALL") + .await + .map_err(|e| format!("read_rows: setup failed: {}", client::format_pg_error(&e)))?; + } + Ok(()) +} /// How `read_rows` returns one column of the source query. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -284,9 +318,9 @@ async fn run_read_rows( /// the table changes between pages. The host uses `session_id` when it needs /// a stable snapshot. /// -/// The read runs inside a `BEGIN READ ONLY`/`COMMIT` wrapper so the optional -/// `schema` filter (`SET LOCAL search_path`) takes effect — `SET LOCAL` -/// outside a transaction is a no-op. +/// The read runs inside a `BEGIN READ ONLY`/`ROLLBACK` wrapper so the optional +/// `schema` filter and the output settings (`SET LOCAL`) take effect — `SET +/// LOCAL` outside a transaction is a no-op. async fn run_one_shot( conn_params: &ConnectionParams, query: &str, @@ -296,7 +330,7 @@ async fn run_one_shot( id: &Value, ) -> Result { let cancel_guard = crate::cancel::CancelGuard::reserve(id.as_u64()); - let pg_client = client::get_pool_client(conn_params).await?; + let pg_client = read_client(conn_params).await?; cancel_guard.attach(&pg_client, conn_params.clone()); pg_client @@ -305,6 +339,7 @@ async fn run_one_shot( .map_err(|e| format!("read_rows: BEGIN failed: {}", client::format_pg_error(&e)))?; let result = async { + clear_pooler_statements(&pg_client, conn_params).await?; pg_client .batch_execute(TEXT_OUTPUT_SETTINGS) .await @@ -341,7 +376,7 @@ async fn run_one_shot( /// Session-pinned snapshot read: the first call for a session (no connection /// was already pinned) opens a `REPEATABLE READ READ ONLY` transaction on a /// pinned connection and `DECLARE`s a `SCROLL` server-side cursor from the -/// host's `query`, then `FETCH FORWARD 1`s per row (bounded by a byte +/// host's `query`, then `FETCH FORWARD`s a page at a time (bounded by a byte /// budget). Subsequent pages — and retried `page=1` calls — reuse the pinned /// connection and `FETCH FORWARD` from the same cursor. The cursor lives and /// dies with the pinned transaction, so `release_session` (ROLLBACK) drops it @@ -378,7 +413,7 @@ async fn run_snapshot( client } None => { - let client = client::get_pool_client(conn_params).await?; + let client = read_client(conn_params).await?; cancel_guard.attach(&client, conn_params.clone()); client.batch_execute(BEGIN_SNAPSHOT).await.map_err(|e| { // The connection is not yet pinned; on error it returns to the @@ -424,6 +459,7 @@ async fn run_snapshot( // resolves names under it. Skip on later pages — already in effect. if needs_declare { let declared = async { + clear_pooler_statements(&pg_client, conn_params).await?; pg_client .batch_execute(TEXT_OUTPUT_SETTINGS) .await