diff --git a/src/binding.rs b/src/binding.rs index 8750ff2..727af95 100644 --- a/src/binding.rs +++ b/src/binding.rs @@ -11,7 +11,6 @@ //! in the SQL text and pin the placeholder's `Type` to `TEXT` so tokio-postgres //! doesn't fight the CAST. -use rust_decimal::Decimal; use serde_json::Value; use std::collections::HashMap; use tokio_postgres::types::{Kind, ToSql, Type}; @@ -467,6 +466,60 @@ fn json_array_to_pg_literal(arr: &[Value]) -> Result { Ok(format!("ARRAY[{}]", parts.join(", "))) } +/// Quick shape check for a numeric literal: an optional sign, then digits with +/// at most one `.`, and an optional exponent (`e`/`E` + optional sign + digits). +/// Used by [`bind_pg_numeric_string`]'s `NUMERIC`/`DECIMAL` fallback to tell a +/// wide valid numeric (which `rust_decimal::Decimal` rejected only for being +/// too wide) from a non-numeric string (which must be rejected client-side). +/// Conservative — rejects edge forms PostgreSQL also rejects, never accepts +/// garbage: it must have at least one digit, and `.`/`e` cannot be the only +/// content. Specials (`NaN`/`Infinity`/`-Infinity`) are handled separately by +/// the caller before this is reached. +fn looks_like_numeric_literal(s: &str) -> bool { + let s = s.trim(); + if s.is_empty() { + return false; + } + let bytes = s.as_bytes(); + let mut i = 0; + // Optional leading sign. + if bytes[i] == b'+' || bytes[i] == b'-' { + i += 1; + } + let mut saw_digit = false; + // Integer digits (at least one, unless a fraction follows). + while i < bytes.len() && bytes[i].is_ascii_digit() { + saw_digit = true; + i += 1; + } + // Optional fraction. + if i < bytes.len() && bytes[i] == b'.' { + i += 1; + while i < bytes.len() && bytes[i].is_ascii_digit() { + saw_digit = true; + i += 1; + } + } + if !saw_digit { + return false; + } + // Optional exponent. + if i < bytes.len() && (bytes[i] == b'e' || bytes[i] == b'E') { + i += 1; + if i < bytes.len() && (bytes[i] == b'+' || bytes[i] == b'-') { + i += 1; + } + let exp_start = i; + while i < bytes.len() && bytes[i].is_ascii_digit() { + i += 1; + } + if i == exp_start { + return false; // exponent with no digits + } + } + i == bytes.len() +} + /// Coerce a string value into a numeric PostgreSQL column (`smallint` /// through `bigint`, `numeric`/`decimal`, `real`/`double precision`). /// Returns `None` if the column is not numeric, so callers can fall through @@ -495,20 +548,37 @@ fn bind_pg_numeric_string( }, )) } - "NUMERIC" | "DECIMAL" => Some(s.parse::().map_or_else( - |_| { - Err(format!( + // NUMERIC/DECIMAL: always bind the exact string as TEXT and let the + // server cast it with `CAST($N AS numeric)`. `rust_decimal::Decimal` + // (the old path, `s.parse::()`) holds a 96-bit mantissa + // (~28-29 significant digits) and cannot represent `NaN`/`Infinity` — + // AND, critically, it silently *rounds* (not errors) on values with + // more than ~28 significant *fractional* digits, returning `Ok` with a + // truncated value that would then bind as `Type::NUMERIC` and corrupt + // 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 + // + 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. + "NUMERIC" | "DECIMAL" => { + if s.eq_ignore_ascii_case("NaN") + || s.eq_ignore_ascii_case("Infinity") + || s.eq_ignore_ascii_case("-Infinity") + || looks_like_numeric_literal(s) + { + Some(Ok(BoundValue { + sql: format!("CAST(${} AS numeric)", placeholder_idx), + param: Some((Box::new(s.to_string()), Type::TEXT)), + })) + } else { + Some(Err(format!( "Cannot bind '{}' as numeric for target type {}", s, base_type - )) - }, - |d| { - Ok(BoundValue { - sql: format!("CAST(${} AS numeric)", placeholder_idx), - param: Some((Box::new(d), Type::NUMERIC)), - }) - }, - )), + ))) + } + } "REAL" | "DOUBLE PRECISION" | "FLOAT4" | "FLOAT8" => Some(s.parse::().map_or_else( |_| { Err(format!( diff --git a/src/binding_tests.rs b/src/binding_tests.rs index 5489f64..ed345f6 100644 --- a/src/binding_tests.rs +++ b/src/binding_tests.rs @@ -236,6 +236,93 @@ mod bind_pg_value_tests { assert_eq!(bound.sql, "CAST($1 AS numeric)"); } + /// A 38-digit numeric value that `rust_decimal::Decimal` cannot hold (the + /// old `s.parse::()` path rejected it) must still bind for the + /// table-copy write side (#214 item 1). The TEXT+CAST path has no such + /// ceiling — PostgreSQL parses the full-precision decimal text. + #[test] + fn numeric_column_binds_a_38_digit_string_via_text_cast() { + let options = BindOptions { + column_type: Some("numeric"), + enum_type: None, + allow_default: false, + hstore_oid: None, + }; + let wide = "12345678901234567890123456789012345678.1234567890"; + let bound = bind_pg_value(json!(wide), 1, &options).unwrap(); + assert_eq!(bound.sql, "CAST($1 AS numeric)"); + let (_, pg_type) = bound.param.unwrap(); + assert_eq!(pg_type, tokio_postgres::types::Type::TEXT); + } + + /// `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. + #[test] + fn numeric_column_binds_nan_string() { + let options = BindOptions { + column_type: Some("numeric"), + enum_type: None, + allow_default: false, + hstore_oid: None, + }; + let bound = bind_pg_value(json!("NaN"), 1, &options).unwrap(); + assert_eq!(bound.sql, "CAST($1 AS numeric)"); + let (_, pg_type) = bound.param.unwrap(); + assert_eq!(pg_type, tokio_postgres::types::Type::TEXT); + } + + /// `DECIMAL` is an alias for `NUMERIC` and takes the same TEXT+CAST path. + #[test] + fn decimal_column_binds_a_wide_string_via_text_cast() { + let options = BindOptions { + column_type: Some("decimal"), + enum_type: None, + allow_default: false, + hstore_oid: None, + }; + let bound = + bind_pg_value(json!("99999999999999999999999999999999999999"), 1, &options).unwrap(); + assert_eq!(bound.sql, "CAST($1 AS numeric)"); + let (_, pg_type) = bound.param.unwrap(); + assert_eq!(pg_type, tokio_postgres::types::Type::TEXT); + } + + /// `looks_like_numeric_literal` must reject non-numeric garbage for a + /// NUMERIC column (the guard's whole purpose — keeps the PK-path's + /// client-side rejection) (#214 review finding: this was untested). + #[test] + fn numeric_column_rejects_non_numeric_garbage() { + let options = BindOptions { + column_type: Some("numeric"), + enum_type: None, + allow_default: false, + hstore_oid: None, + }; + assert!(bind_pg_value(json!("abc"), 1, &options).is_err()); + assert!(bind_pg_value(json!("1.2.3"), 1, &options).is_err()); + assert!(bind_pg_value(json!("1e"), 1, &options).is_err()); + } + + /// `looks_like_numeric_literal` edge forms that ARE valid numeric + /// literals and must bind (not be rejected) (#214 review finding). + #[test] + fn numeric_column_accepts_edge_form_numeric_literals() { + let options = BindOptions { + column_type: Some("numeric"), + enum_type: None, + allow_default: false, + hstore_oid: None, + }; + // Exponent form. + assert!(bind_pg_value(json!("1e10"), 1, &options).is_ok()); + assert!(bind_pg_value(json!("1.5e-3"), 1, &options).is_ok()); + // Leading + sign. + assert!(bind_pg_value(json!("+5"), 1, &options).is_ok()); + // Fraction-only, no integer digits (.5 → valid PostgreSQL numeric). + assert!(bind_pg_value(json!(".5"), 1, &options).is_ok()); + } + #[test] fn timestamp_column_string_binds_with_timestamp_cast() { let options = BindOptions { @@ -627,10 +714,13 @@ mod bind_pk_value_tests { #[test] fn numeric_column_string_value_casts_to_numeric() { + // After the always-TEXT+CAST fix (#214 review), small numerics bind the + // exact string as Type::TEXT (not Type::NUMERIC via Decimal) — avoiding + // Decimal's silent rounding on high-scale values. The SQL is the same. let bound = bind_pk_value(&json!("1500.00"), 2, Some("numeric")).unwrap(); assert_eq!(bound.sql, "CAST($2 AS numeric)"); let (_, pg_type) = bound.param.unwrap(); - assert_eq!(pg_type, tokio_postgres::types::Type::NUMERIC); + assert_eq!(pg_type, tokio_postgres::types::Type::TEXT); } #[test] diff --git a/src/client_live_tests.rs b/src/client_live_tests.rs index 7614f3c..688e052 100644 --- a/src/client_live_tests.rs +++ b/src/client_live_tests.rs @@ -373,13 +373,15 @@ async fn read_rows_returns_lossless_values_for_table_copy() { format!( "CREATE TABLE {table} (\ id int8 primary key, ts6 timestamp(6), tstz timestamptz, \ - blob bytea, n numeric(38,10), f float8, b bool, t text, u uuid\ + blob bytea, n numeric(38,10), wide numeric(48,10), nan numeric, \ + f float8, b bool, t text, u uuid\ )" ), format!( - "INSERT INTO {table} (id, ts6, tstz, blob, n, f, b, t, u) VALUES \ + "INSERT INTO {table} (id, ts6, tstz, blob, n, wide, nan, f, b, t, u) VALUES \ (1, '2026-11-29 13:45:30.345678', '2026-11-29 13:45:30.345678+00', \ - {big_blob}, 12345678901234567890.1234567890, 2.5, true, \ + {big_blob}, 12345678901234567890.1234567890, \ + 12345678901234567890123456789012345678.1234567890, 'NaN', 2.5, true, \ 'hello', '550e8400-e29b-41d4-a716-446655440000')" ), ] { @@ -392,7 +394,7 @@ async fn read_rows_returns_lossless_values_for_table_copy() { "driver": "postgresql", "host": params.host, "port": params.port, "database": params.database, "username": params.username, "password": params.password, - "query": format!("SELECT id, ts6, tstz, blob, n, f, b, t, u FROM {table}"), + "query": format!("SELECT id, ts6, tstz, blob, n, wide, nan, f, b, t, u FROM {table}"), "limit": 100, "page": 1, }); let resp = tokio::time::timeout( @@ -420,6 +422,8 @@ async fn read_rows_returns_lossless_values_for_table_copy() { assert_eq!(col_types["tstz"], "timestamptz"); assert_eq!(col_types["blob"], "bytea"); assert_eq!(col_types["n"], "numeric"); + assert_eq!(col_types["wide"], "numeric"); + assert_eq!(col_types["nan"], "numeric"); let rows = result .get("rows") @@ -455,22 +459,33 @@ 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. + // numeric(38,10) — exact decimal string, full scale (PgNumeric keeps the + // trailing scale-10 zero that the old rust_decimal path trimmed). assert_eq!( row[4], - // rust_decimal::Decimal::to_string() trims the trailing scale-10 zero. - json!("12345678901234567890.123456789"), - "numeric: {row:?}" + json!("12345678901234567890.1234567890"), + "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 + // full-precision string (#214 item 1). + assert_eq!( + row[5], + json!("12345678901234567890123456789012345678.1234567890"), + "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). + assert_eq!(row[6], json!("NaN"), "numeric NaN: {row:?}"); // float8 — native number. - assert_eq!(row[5], json!(2.5), "float8: {row:?}"); + assert_eq!(row[7], json!(2.5), "float8: {row:?}"); // bool. - assert_eq!(row[6], json!(true), "bool: {row:?}"); + assert_eq!(row[8], json!(true), "bool: {row:?}"); // text. - assert_eq!(row[7], json!("hello"), "text: {row:?}"); + assert_eq!(row[9], json!("hello"), "text: {row:?}"); // uuid. assert_eq!( - row[8], + row[10], json!("550e8400-e29b-41d4-a716-446655440000"), "uuid: {row:?}" ); @@ -480,10 +495,13 @@ async fn read_rows_returns_lossless_values_for_table_copy() { POOLS.lock().unwrap().remove(&key); } -/// A `read_rows` with a `session_id` holds a `REPEATABLE READ` snapshot across -/// pages: a row inserted between page 1 and page 2 is NOT visible to page 2. -/// This is the snapshot guarantee the table-copy feature needs so rows are not -/// skipped or repeated when the source table changes mid-copy. +/// 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 batch; page 2 FETCHes the next batch from the same cursor +/// (linear, one stable order — no `LIMIT/OFFSET` re-read). A row inserted +/// between page 1 and page 2 is NOT visible to page 2 (the snapshot was taken +/// at page 1's BEGIN), so rows are not skipped or repeated when the source +/// changes mid-copy. #[tokio::test] #[ignore = "needs a live PostgreSQL (PG_PLUGIN_TEST_HOST=127.0.0.1 ... podman 54320)"] async fn read_rows_session_holds_a_repeatable_read_snapshot_across_pages() { @@ -499,10 +517,13 @@ async fn read_rows_session_holds_a_repeatable_read_snapshot_across_pages() { let table = format!("plugin_test_207_snap_{}", uuid::Uuid::new_v4().simple()); let session = format!("copy_{}", uuid::Uuid::new_v4().simple()); + // Seed 3 rows; page 1 (limit 2) reads rows 1-2, then a 4th row is inserted + // outside the snapshot before page 2 reads row 3 — proving page 2 advances + // the cursor (not re-reads from page 1) AND the snapshot hides row 4. for stmt in [ format!("DROP TABLE IF EXISTS {table}"), format!("CREATE TABLE {table} (id int primary key, val int)"), - format!("INSERT INTO {table} (id, val) VALUES (1, 10), (2, 20)"), + format!("INSERT INTO {table} (id, val) VALUES (1, 10), (2, 20), (3, 30)"), ] { client::execute_typed(¶ms, &stmt, &[]) .await @@ -516,12 +537,12 @@ async fn read_rows_session_holds_a_repeatable_read_snapshot_across_pages() { "session_id": session, }); - // Page 1: read the 2 existing rows (limit 100 so both fit on page 1, and - // has_more is false). The snapshot is taken at this BEGIN. + // Page 1: DECLARE the cursor (page 1) and FETCH the first 2 rows. The + // snapshot is taken at this BEGIN. let req1 = { let mut r = base_req.clone(); r["query"] = json!(format!("SELECT id, val FROM {table} ORDER BY id")); - r["limit"] = json!(100); + r["limit"] = json!(2); r["page"] = json!(1); r }; @@ -534,24 +555,36 @@ async fn read_rows_session_holds_a_repeatable_read_snapshot_across_pages() { assert!(resp1.get("error").is_none(), "page 1: {resp1}"); let rows1 = resp1["result"]["rows"].as_array().unwrap(); assert_eq!(rows1.len(), 2, "page 1 sees 2 rows: {rows1:?}"); + assert_eq!(rows1[0][0], json!(1), "page 1 first row is id 1: {rows1:?}"); + assert_eq!( + rows1[1][0], + json!(2), + "page 1 second row is id 2: {rows1:?}" + ); + assert_eq!( + resp1["result"]["has_more"], + json!(true), + "page 1 is full (2/2) so has_more is true: {resp1}" + ); - // Insert a 3rd row OUTSIDE the snapshot. + // Insert a 4th row OUTSIDE the snapshot. client::execute_typed( ¶ms, - &format!("INSERT INTO {table} (id, val) VALUES (3, 30)"), + &format!("INSERT INTO {table} (id, val) VALUES (4, 40)"), &[], ) .await .unwrap(); - // Page 2: same session_id → reuses the pinned connection + its snapshot. - // The new row 3 is NOT visible (REPEATABLE READ). A non-snapshot read would - // see 3 rows. + // Page 2: same session_id → FETCHes the next batch from the same cursor + // (page 2 advances past rows 1-2). Row 3 IS visible (it was in the table + // before page 1's BEGIN); row 4 is NOT (inserted after the snapshot). A + // non-snapshot read would see row 4. let req2 = { let mut r = base_req.clone(); r["query"] = json!(format!("SELECT id, val FROM {table} ORDER BY id")); - r["limit"] = json!(100); - r["page"] = json!(1); + r["limit"] = json!(2); + r["page"] = json!(2); r }; let resp2 = tokio::time::timeout( @@ -564,11 +597,17 @@ async fn read_rows_session_holds_a_repeatable_read_snapshot_across_pages() { let rows2 = resp2["result"]["rows"].as_array().unwrap(); assert_eq!( rows2.len(), - 2, - "snapshot: page 2 still sees 2 rows (row 3 not visible): {rows2:?}" + 1, + "snapshot: page 2 sees 1 row (row 3; row 4 not visible): {rows2:?}" + ); + assert_eq!(rows2[0][0], json!(3), "page 2's row is id 3: {rows2:?}"); + assert_eq!( + resp2["result"]["has_more"], + json!(false), + "page 2 is short (1 < 2) so the cursor is exhausted: {resp2}" ); - // Release the session (ROLLBACK ends the snapshot). + // Release the session (ROLLBACK ends the snapshot and drops the cursor). let release_req = json!({ "driver": "postgresql", "host": params.host, "port": params.port, @@ -620,23 +659,26 @@ async fn read_rows_then_insert_records_copies_a_table_losslessly() { format!( "CREATE TABLE {src} (\ id int8 primary key, ts6 timestamp(6), tstz timestamptz, \ - blob bytea, n numeric(38,10), f float8, b bool, t text, u uuid\ + blob bytea, n numeric(38,10), wide numeric(48,10), nan numeric, \ + f float8, b bool, t text, u uuid\ )" ), // The destination has the same shape (a real copy preserves the schema). format!( "CREATE TABLE {dst} (\ id int8 primary key, ts6 timestamp(6), tstz timestamptz, \ - blob bytea, n numeric(38,10), f float8, b bool, t text, u uuid\ + blob bytea, n numeric(38,10), wide numeric(48,10), nan numeric, \ + f float8, b bool, t text, u uuid\ )" ), format!( - "INSERT INTO {src} (id, ts6, tstz, blob, n, f, b, t, u) VALUES \ + "INSERT INTO {src} (id, ts6, tstz, blob, n, wide, nan, f, b, t, u) VALUES \ (1, '2026-11-29 13:45:30.345678', '2026-11-29 13:45:30.345678+00', \ - {big_blob}, 12345678901234567890.1234567890, 2.5, true, \ + {big_blob}, 12345678901234567890.1234567890, \ + 12345678901234567890123456789012345678.1234567890, 'NaN', 2.5, true, \ 'hello', '550e8400-e29b-41d4-a716-446655440000'), \ (2, '2000-01-01 00:00:00', '2000-01-01 00:00:00+00', \ - decode(repeat('CD', 100), 'hex'), 0, 0, false, '', \ + decode(repeat('CD', 100), 'hex'), 0, 0, NULL, 0, false, '', \ '00000000-0000-0000-0000-000000000000')" ), ] { @@ -649,7 +691,7 @@ async fn read_rows_then_insert_records_copies_a_table_losslessly() { let read_req = { let mut r = conn.clone(); r["query"] = json!(format!( - "SELECT id, ts6, tstz, blob, n, f, b, t, u FROM {src} ORDER BY id" + "SELECT id, ts6, tstz, blob, n, wide, nan, f, b, t, u FROM {src} ORDER BY id" )); r["limit"] = json!(100); r["page"] = json!(1); @@ -704,8 +746,8 @@ async fn read_rows_then_insert_records_copies_a_table_losslessly() { ); assert_eq!( insert_resp["result"], - json!(2), - "inserted 2 rows: {insert_resp}" + json!({ "affected_rows": 2, "skipped": 0 }), + "inserted 2 rows, skipped 0: {insert_resp}" ); // Step 3: read the destination back and assert every value matches the @@ -713,7 +755,7 @@ async fn read_rows_then_insert_records_copies_a_table_losslessly() { let verify_req = { let mut r = conn.clone(); r["query"] = json!(format!( - "SELECT id, ts6, tstz, blob, n, f, b, t, u FROM {dst} ORDER BY id" + "SELECT id, ts6, tstz, blob, n, wide, nan, f, b, t, u FROM {dst} ORDER BY id" )); r["limit"] = json!(100); r["page"] = json!(1); @@ -742,6 +784,213 @@ async fn read_rows_then_insert_records_copies_a_table_losslessly() { POOLS.lock().unwrap().remove(&key); } +/// A session-pinned `read_rows` pages a large table through the server-side +/// cursor linearly (#214 item 4): every row appears exactly once across pages, +/// in stable order, with no `LIMIT/OFFSET` re-read. 2500 rows paged 1000 at a +/// time → 3 pages (1000, 1000, 500) + a confirming empty 4th page. +#[tokio::test] +#[ignore = "needs a live PostgreSQL (PG_PLUGIN_TEST_HOST=127.0.0.1 ... podman 54320)"] +async fn read_rows_session_cursor_pages_a_large_table_linearly() { + use crate::client; + 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 — 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_214_cursor_{}", uuid::Uuid::new_v4().simple()); + let session = format!("copy_{}", uuid::Uuid::new_v4().simple()); + + for stmt in [ + format!("DROP TABLE IF EXISTS {table}"), + format!("CREATE TABLE {table} (id int primary key, val int)"), + // 2500 rows (NOT a multiple of the 1000-row page size, so the last page + // is short — exercising the has_more=false cursor-exhaustion rule). + ] { + client::execute_typed(¶ms, &stmt, &[]) + .await + .unwrap_or_else(|e| panic!("setup failed ({stmt}): {e}")); + } + // Bulk-insert 2500 rows in one statement. + let values: Vec = (1..=2500).map(|i| format!("({i}, {i})")).collect(); + client::execute_typed( + ¶ms, + &format!("INSERT INTO {table} (id, val) VALUES {}", values.join(", ")), + &[], + ) + .await + .unwrap_or_else(|e| panic!("bulk insert failed: {e}")); + + let base_req = json!({ + "driver": "postgresql", + "host": params.host, "port": params.port, + "database": params.database, "username": params.username, "password": params.password, + "session_id": session, + "query": format!("SELECT id, val FROM {table} ORDER BY id"), + "limit": 1000, + }); + + // Page through 4 pages: 1000 + 1000 + 500 + 0. Collect every id and assert + // the full 1..=2500 range appears exactly once (no skips, no repeats). + let mut seen: Vec = Vec::new(); + let mut page = 1u64; + loop { + let mut req = base_req.clone(); + req["page"] = json!(page); + let resp = tokio::time::timeout( + std::time::Duration::from_secs(30), + read_rows(json!(page), &req), + ) + .await + .unwrap_or_else(|_| panic!("read_rows page {page} hung")); + assert!(resp.get("error").is_none(), "page {page}: {resp}"); + let rows = resp["result"]["rows"].as_array().unwrap(); + let has_more = resp["result"]["has_more"].as_bool().unwrap(); + for row in rows { + let arr = row.as_array().unwrap(); + seen.push(arr[0].as_i64().unwrap()); + } + if !has_more { + // The last non-empty page says has_more=true (full 1000 or the 500 + // short page says false). A short page ends the loop. + break; + } + page += 1; + // Guard against a runaway loop if has_more is stuck true. + if page > 10 { + panic!("cursor paging did not terminate; seen {} rows", seen.len()); + } + } + + // Every row exactly once, in order — the cursor's stable forward order. + assert_eq!(seen.len(), 2500, "saw 2500 rows total: {seen:?}"); + assert_eq!(seen[0], 1, "first row is 1"); + assert_eq!(seen[2499], 2500, "last row is 2500"); + for (i, &id) in seen.iter().enumerate() { + assert_eq!( + id, + (i + 1) as i64, + "row {} is id {} (expected {}): out of order", + i, + id, + i + 1 + ); + } + + // Release the session (ROLLBACK drops the cursor). + let release_req = json!({ + "driver": "postgresql", + "host": params.host, "port": params.port, + "database": params.database, "username": params.username, "password": params.password, + "session_id": session, + }); + let _ = tokio::time::timeout( + std::time::Duration::from_secs(10), + release_session(json!(99), &release_req), + ) + .await; + + let _ = client::execute_typed(¶ms, &format!("DROP TABLE IF EXISTS {table}"), &[]).await; + let key = connection_key(¶ms); + 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. +#[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() { + 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_214_skip_{}", uuid::Uuid::new_v4().simple()); + for stmt in [ + format!("DROP TABLE IF EXISTS {table}"), + format!("CREATE TABLE {table} (id int primary key, val int)"), + // Row id=1 already exists — the copy's id=1 will conflict. + format!("INSERT INTO {table} (id, val) VALUES (1, 100)"), + ] { + 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, + }); + // Two rows: id=1 conflicts (skipped), id=2 inserts (affected). + let req = { + let mut r = conn.clone(); + r["table"] = json!(table.clone()); + r["rows"] = json!([{"id": 1, "val": 10}, {"id": 2, "val": 20}]); + r["on_conflict"] = json!("skip"); + r + }; + let resp = tokio::time::timeout( + std::time::Duration::from_secs(30), + insert_records(json!(1), &req), + ) + .await + .expect("insert_records hung"); + assert!(resp.get("error").is_none(), "skip mode: {resp}"); + assert_eq!( + resp["result"], + json!({ "affected_rows": 1, "skipped": 1 }), + "1 inserted (id=2), 1 skipped (id=1 conflicts): {resp}" + ); + + // The existing row 1 was NOT overwritten (val stays 100); row 2 was inserted. + let rows = client::query_rows( + ¶ms, + &format!("SELECT id, val FROM {table} ORDER BY id"), + &[], + ) + .await + .unwrap(); + let r1: (i32, i32) = (rows[0].try_get(0).unwrap(), rows[0].try_get(1).unwrap()); + let r2: (i32, i32) = (rows[1].try_get(0).unwrap(), rows[1].try_get(1).unwrap()); + assert_eq!( + r1, + (1, 100), + "row 1 untouched (skip, not overwrite): {r1:?}" + ); + assert_eq!(r2, (2, 20), "row 2 inserted: {r2:?}"); + + // fail mode into the same conflicting state errors (SQLSTATE 23505). + let fail_req = { + let mut r = conn.clone(); + r["table"] = json!(table.clone()); + r["rows"] = json!([{"id": 1, "val": 999}]); + // omit on_conflict → defaults to "fail" + r + }; + let fail_resp = tokio::time::timeout( + std::time::Duration::from_secs(30), + insert_records(json!(2), &fail_req), + ) + .await + .expect("insert_records fail hung"); + assert!( + fail_resp.get("error").is_some(), + "fail mode should error on conflict: {fail_resp}" + ); + + let _ = client::execute_typed(¶ms, &format!("DROP TABLE IF EXISTS {table}"), &[]).await; + let key = connection_key(¶ms); + POOLS.lock().unwrap().remove(&key); +} + /// Exercises the transaction-pooler pinned path (`exec_query_pooled_txn`) /// against a *direct* Postgres. Setting `pooler_mode: "transaction"` routes /// result-set queries through `BEGIN; DEALLOCATE ALL; prepare; query_typed; diff --git a/src/extract.rs b/src/extract.rs index 074e987..7b61e37 100644 --- a/src/extract.rs +++ b/src/extract.rs @@ -191,15 +191,17 @@ 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 four display-lossy scalar types (TIME, -/// TIMESTAMP, TIMESTAMPTZ, BYTEA) use full-precision decoders: TIME/TIMESTAMP -/// keep fractional seconds, TIMESTAMPTZ keeps the `+00:00` offset, and BYTEA -/// is base64-encoded in full (not the 10 KB preview). All other scalar types -/// delegate to [`extract_simple_kind`] (already lossless: NUMERIC, INT, FLOAT, -/// JSON, UUID, BOOL, TEXT, enum, DATE, TIMETZ, INTERVAL, etc.). Arrays, ranges, -/// composites, and multiranges delegate to [`extract_value`] — temporal values -/// nested in those stay lossy in this PR (documented limitation; the copy -/// acceptance criteria are all scalar columns). +/// [`extract_value`], but the display-lossy scalar types use full-precision +/// decoders: TIME/TIMESTAMP keep fractional seconds, TIMESTAMPTZ keeps the +/// `+00:00` offset, BYTEA is base64-encoded in full (not the 10 KB preview), +/// and 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`). All other scalar types delegate to +/// [`extract_simple_kind`] (already lossless: INT, FLOAT, JSON, UUID, BOOL, +/// TEXT, enum, DATE, TIMETZ, INTERVAL, etc.). Arrays, ranges, composites, and +/// multiranges delegate to [`extract_value`] — temporal values nested in those +/// stay lossy in this PR (documented limitation; the copy acceptance criteria +/// are all scalar columns). pub fn extract_value_lossless(row: &Row, index: usize) -> JsonValue { let col_type = row.columns()[index].type_().clone(); @@ -211,8 +213,9 @@ pub fn extract_value_lossless(row: &Row, index: usize) -> JsonValue { } } -/// The lossless `Kind::Simple` bucket: overrides the four display-lossy arms -/// and delegates the rest to [`extract_simple_kind`]. +/// The lossless `Kind::Simple` bucket: overrides the five display-lossy arms +/// (TIME, TIMESTAMP, TIMESTAMPTZ, BYTEA, NUMERIC) and delegates the rest to +/// [`extract_simple_kind`]. fn extract_simple_kind_lossless(col_type: &Type, row: &Row, index: usize) -> JsonValue { match *col_type { ref t if *t == Type::TIME => try_extract::(row, index, JsonValue::from), @@ -225,6 +228,16 @@ fn extract_simple_kind_lossless(col_type: &Type, row: &Row, index: usize) -> Jso ref t if *t == 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)) + } // All other scalar types are already lossless — reuse the display path. _ => extract_simple_kind(col_type, row, index), } @@ -1103,6 +1116,184 @@ impl From for JsonValue { } } +/// 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), diff --git a/src/extract_tests.rs b/src/extract_tests.rs index 5a0d0ca..e7e3139 100644 --- a/src/extract_tests.rs +++ b/src/extract_tests.rs @@ -12,8 +12,8 @@ use crate::extract::{ ArrayValue, BitOrVarBit, Cid, Circle, CompositeValue, EnumLabel, GtsVector, JsonPath, Line, Lseg, MacAddr8, Money, MultirangeValue, Path, PgBox, PgBrinBloomSummary, PgDependencies, - PgHalfVector, PgLsn, PgMcvList, PgNdistinct, PgNodeTree, PgSparseVector, PgVector, Point, - Polygon, RefCursor, RegClass, RegProc, RegType, Tid, TsQuery, TsVector, + PgHalfVector, PgLsn, PgMcvList, PgNdistinct, PgNodeTree, PgNumeric, PgSparseVector, PgVector, + Point, Polygon, RefCursor, RegClass, RegProc, RegType, Tid, TsQuery, TsVector, TxidSnapshotOrPgSnapshot, Xid, Xid8, Xml, }; use std::collections::HashMap; @@ -87,6 +87,232 @@ 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(), diff --git a/src/handlers/copy.rs b/src/handlers/copy.rs index 9671b43..35118e6 100644 --- a/src/handlers/copy.rs +++ b/src/handlers/copy.rs @@ -66,7 +66,14 @@ pub async fn read_rows(id: Value, params: &Value) -> Value { .get("limit") .and_then(Value::as_u64) .and_then(|n| u32::try_from(n).ok()) - .unwrap_or(DEFAULT_PAGE_SIZE); + .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.len() >= 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). + .max(1); let schema = params .get("schema") .and_then(Value::as_str) @@ -109,14 +116,19 @@ async fn run_read_rows( ); } - let final_query = - build_paginated_query(query, page_size, u32::try_from(page).unwrap_or(u32::MAX)); - + // The session path pages through a server-side cursor (`DECLARE` + `FETCH + // FORWARD`) on the pinned connection — linear in table size and one stable + // row order, unlike `LIMIT/OFFSET` (#214 item 4). The cursor DECLAREs from + // the raw `query` (no pagination clause), so pass it through unwrapped. + // The one-shot path keeps `LIMIT/OFFSET` (it makes no consistency/order + // promise), so it still gets the paginated statement. match session_id { - Some(sid) => { - run_snapshot(conn_params, &final_query, page, page_size, schema, sid, id).await + 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, &final_query, page, page_size, schema, id).await, } } @@ -162,13 +174,28 @@ async fn run_one_shot( result } -/// Session-pinned snapshot read: the first call opens a `REPEATABLE READ READ -/// ONLY` transaction on a pinned connection; subsequent pages reuse that -/// connection and its snapshot. The connection stays pinned until -/// `release_session` (ROLLBACK) or the idle sweep (30 min). +/// 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 `NO SCROLL` server-side cursor from the +/// host's `query`, then `FETCH FORWARD `s. 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 with no explicit `CLOSE`. +/// +/// 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, - final_query: &str, + query: &str, page: u64, page_size: u32, schema: Option, @@ -177,6 +204,7 @@ async fn run_snapshot( ) -> Result { let mut slot = session::lock(&session_id).await; let pinned = slot.take(); + let pinned_was_none = pinned.is_none(); let cancel_guard = crate::cancel::CancelGuard::reserve(id.as_u64()); @@ -202,34 +230,153 @@ async fn run_snapshot( } }; - if let Some(schema) = &schema { - // `SET LOCAL` inside the transaction, scoped to the snapshot. - if let Err(e) = apply_search_path_local(&pg_client, schema).await { - // A failed SET LOCAL aborts the transaction if one is open. + // The cursor is declared once, on the first call for this session (when no + // connection was already pinned). Keying off `pinned.is_none()` — not the + // client-supplied `page` number — means a retried/duplicate `page=1` call + // that finds an already-pinned connection reuses the existing cursor via + // FETCH instead of re-DECLAREing (which would error "cursor already exists" + // and tear down the live snapshot) (#214 review finding). + let needs_declare = pinned_was_none; + // `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 { + // 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). + drop(cancel_guard); + cleanup_on_error(&pg_client, true).await; + return Err(e); + } + } + let cursor = cursor_name(&session_id); + // Trim a trailing ';' 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). + let trimmed_query = query.trim_end_matches(';'); + // `NO SCROLL`: forward-only, so PostgreSQL can pick a linear plan. 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 the + // session path lost when it switched to a cursor DECLARE (#214 review). + let declare = format!("DECLARE {cursor} NO 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(e); + return Err(format!( + "read_rows: DECLARE cursor failed: {}", + client::format_pg_error(&e) + )); } } - match fetch_lossless(&pg_client, final_query, page, page_size).await { + let cursor = cursor_name(&session_id); + match fetch_cursor(&pg_client, &cursor, page, page_size).await { Ok(result) => { - // Keep the connection pinned for the next page. `DROP` of the - // `CancelGuard` detaches the cancel registration. drop(cancel_guard); slot.pin(pg_client); Ok(result) } Err(e) => { - // A transaction is always open on this path: the first page - // opened BEGIN, and subsequent pages reuse a pinned connection - // whose transaction is still open from page 1. - cleanup_on_error(&pg_client, true).await; + // Drop the cancel guard BEFORE cleanup so a re-sent cancel can't + // interrupt the ROLLBACK (#214 review finding). drop(cancel_guard); + cleanup_on_error(&pg_client, true).await; Err(e) } } } +/// Build a deterministic, identifier-safe cursor name for a copy session, so +/// page 2 reuses the cursor page 1 declared. The session_id is host-generated +/// (not user-controlled), but it is sanitized to `[A-Za-z0-9_]` and length- +/// capped anyway, prefixed with a fixed namespace so it cannot collide with a +/// user-declared cursor. Identifiers in PostgreSQL are at most 63 bytes after +/// truncation; keep well under that. +fn cursor_name(session_id: &str) -> String { + const MAX: usize = 50; + let mut name = String::from("tabularis_copy_"); + for c in session_id.chars() { + if c.is_ascii_alphanumeric() || c == '_' { + name.push(c); + } + if name.len() >= MAX { + break; + } + } + name +} + +/// `FETCH FORWARD FROM ` and extract lossless rows + column +/// metadata. A forward-only (`NO SCROLL`) cursor cannot rewind, so `has_more` +/// is `rows.len() == page_size` (a full page may have more behind it; a short +/// page means the cursor is exhausted) — NOT the `+1` row probe the +/// `LIMIT/OFFSET` path uses, which would consume and lose the extra row here. +/// An empty source (or an exhausted cursor's final zero-row `FETCH`) reports +/// `columns: []`: `query_typed` returns `Vec`, and with no rows there is +/// no `rows[0].columns()` to read metadata from. The host falls back to +/// `get_columns` for column metadata on an empty source. +async fn fetch_cursor( + pg_client: &PgClient, + cursor: &str, + page: u64, + page_size: u32, +) -> Result { + let fetch = format!("FETCH FORWARD {page_size} FROM {cursor}"); + let rows = pg_client + .query_typed(&fetch, &[]) + .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 (tokio-postgres does not surface the DECLARE's + // RowDescription on a zero-row `query_typed`), 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() + }; + + // has_more: a forward-only cursor can't probe ahead without consuming the + // row, so a full page means "there may be more" and a short page means + // "exhausted". This costs one extra empty FETCH when the row count is an + // exact multiple of page_size (negligible next to the OFFSET savings). + let has_more = rows.len() >= page_size as usize; + let result_rows: Vec = rows + .iter() + .take(page_size as usize) + .map(|row| { + let values: Vec = (0..row.columns().len()) + .map(|i| extract_value_lossless(row, i)) + .collect(); + Value::Array(values) + }) + .collect(); + + Ok(json!({ + "columns": columns, + "rows": result_rows, + "has_more": has_more, + "page": page, + "page_size": page_size, + })) +} + /// On any error when a transaction is open: ROLLBACK so the connection /// returns to the pool clean (the caller owns the `PgClient` and drops it on /// the `Err` path, which returns the `deadpool::Object` to the pool). Do NOT @@ -319,16 +466,21 @@ const MAX_PLACEHOLDERS_PER_STMT: usize = 32_000; /// `insert_records` — batch typed insert for the table-copy write side. /// /// Request params: `table` (str), `schema` (str, default "public"), `rows` -/// (array of objects `{column: value, ...}`), plus connection params via -/// `inner_params`. The column list is derived from the first row's keys; -/// every row must have the same keys (the host builds them from a `read_rows` -/// result set). A row missing a key present in `rows[0]` is an error, not a -/// silent NULL — a copy must not invent values the source didn't send. +/// (array of objects `{column: value, ...}`), `on_conflict` (str, optional, +/// `"fail"` default or `"skip"` for `ON CONFLICT DO NOTHING`), plus connection +/// params via `inner_params`. The column list is derived from the first row's +/// keys; every row must have the same keys (the host builds them from a +/// `read_rows` result set). A row missing a key present in `rows[0]` is an +/// error, not a silent NULL — a copy must not invent values the source didn't +/// send. /// -/// Response: `u64` (affected rows), matching `insert_record`. The whole batch -/// runs in one transaction on a one-shot connection: `BEGIN` → one or more -/// chunked `INSERT`s → `COMMIT`, `ROLLBACK` on any error, so a batch that fails -/// writes none of its rows. +/// Response: `{ affected_rows, skipped }` — `affected_rows` is the count of +/// rows actually inserted (with `on_conflict: "skip"`, `ON CONFLICT DO +/// NOTHING` counts only the inserted ones); `skipped` is rows the target +/// already had (only nonzero with `"skip"`). The whole batch runs in one +/// transaction on a one-shot connection: `BEGIN` → one or more chunked +/// `INSERT`s → `COMMIT`, `ROLLBACK` on any error, so a batch that fails writes +/// none of its rows. pub async fn insert_records(id: Value, params: &Value) -> Value { let conn_params = ConnectionParams::from_value(inner_params(params)); let table = params.get("table").and_then(Value::as_str).unwrap_or(""); @@ -344,21 +496,86 @@ pub async fn insert_records(id: Value, params: &Value) -> Value { .and_then(Value::as_array) .cloned() .unwrap_or_default(); + // `on_conflict`: a present-but-non-string value (null, number, bool) must + // be rejected, not silently defaulted — `as_str()` returns `None` for those + // just as for an absent key, so distinguish the two (#214 review finding). + let on_conflict = match params.get("on_conflict") { + None | Some(Value::Null) => OnConflict::Fail, + Some(Value::String(s)) => match s.as_str() { + "fail" => OnConflict::Fail, + "skip" => OnConflict::Skip, + other => { + return crate::rpc::error_response( + id, + -32602, + &format!( + "insert_records: 'on_conflict' must be \"fail\" or \"skip\", got {other:?}" + ), + ); + } + }, + Some(other) => { + return crate::rpc::error_response( + id, + -32602, + &format!( + "insert_records: 'on_conflict' must be a string \"fail\" or \"skip\", got {}", + type_of_value(other) + ), + ); + } + }; - match exec_insert_batch(&conn_params, table, &rows, schema).await { - Ok(affected) => crate::rpc::ok_response(id, Value::from(affected)), + match exec_insert_batch(&conn_params, table, &rows, schema, on_conflict).await { + Ok(outcome) => crate::rpc::ok_response(id, json!(outcome)), Err(e) => crate::rpc::error_response(id, -32603, &e), } } +/// One-word JSON type name for a `Value`, used in `on_conflict` validation +/// error messages (#214 review finding). +fn type_of_value(v: &Value) -> &'static str { + match v { + Value::Null => "null", + Value::Bool(_) => "bool", + Value::Number(_) => "number", + Value::String(_) => "string", + Value::Array(_) => "array", + Value::Object(_) => "object", + } +} + +/// Conflict policy for `insert_records`. `"fail"` (default) lets a conflicting +/// row raise SQLSTATE 23505 and abort the batch; `"skip"` appends +/// `ON CONFLICT DO NOTHING` so conflicting rows are skipped, and the response +/// reports how many were skipped (#214 item 3). Mirrors the removed built-in +/// driver's `fail`/`skip` table-copy conflict modes. +#[derive(Clone, Copy, PartialEq, Eq)] +enum OnConflict { + Fail, + Skip, +} + +/// Outcome of an `insert_records` batch — the host's `rows_written` and +/// `rows_skipped` are derived from these two fields (#214 item 3). +#[derive(serde::Serialize)] +struct InsertOutcome { + affected_rows: u64, + skipped: u64, +} + async fn exec_insert_batch( conn_params: &ConnectionParams, table: &str, rows: &[Value], schema: &str, -) -> Result { + on_conflict: OnConflict, +) -> Result { if rows.is_empty() { - return Ok(0); + return Ok(InsertOutcome { + affected_rows: 0, + skipped: 0, + }); } // Derive the column list from the first row's keys. The rows must be @@ -415,17 +632,22 @@ async fn exec_insert_batch( ) })?; - let outcome = build_and_execute_chunks(&pg_client, &qualified, &col_list, rows, &types).await; + let outcome = + build_and_execute_chunks(&pg_client, &qualified, &col_list, rows, &types, on_conflict) + .await; match outcome { - Ok(affected) => { + Ok((affected, skipped)) => { pg_client.batch_execute("COMMIT").await.map_err(|e| { format!( "insert_records: COMMIT failed: {}", client::format_pg_error(&e) ) })?; - Ok(affected) + Ok(InsertOutcome { + affected_rows: affected, + skipped, + }) } Err(e) => { // ROLLBACK is the one command the server still accepts in an @@ -448,20 +670,28 @@ struct ResolvedTypes { /// Build and execute chunked multi-row `INSERT`s. Each chunk's `columns * /// rows` placeholders stay under [`MAX_PLACEHOLDERS_PER_STMT`]. All chunks run -/// inside the caller's transaction. +/// inside the caller's transaction. With [`OnConflict::Skip`], each `INSERT` +/// appends `ON CONFLICT DO NOTHING`; `execute_typed` then counts only the rows +/// actually inserted, so the returned `skipped` is `chunk rows - inserted`. async fn build_and_execute_chunks( pg_client: &PgClient, qualified: &str, col_list: &str, rows: &[Value], types: &ResolvedTypes, -) -> Result { + on_conflict: OnConflict, +) -> Result<(u64, u64), String> { let n_cols = types.columns.len(); if n_cols == 0 { return Err("insert_records: column list is empty".into()); } let rows_per_chunk = (MAX_PLACEHOLDERS_PER_STMT / n_cols).max(1); let mut affected: u64 = 0; + let mut skipped: u64 = 0; + let on_conflict_clause = match on_conflict { + OnConflict::Fail => "", + OnConflict::Skip => " ON CONFLICT DO NOTHING", + }; for chunk in rows.chunks(rows_per_chunk) { // Reset the placeholder index per chunk: each chunk is a standalone @@ -519,20 +749,58 @@ async fn build_and_execute_chunks( } let query = format!( - "INSERT INTO {} ({}) VALUES {}", + "INSERT INTO {} ({}) VALUES {}{}", qualified, col_list, - tuples.join(", ") + tuples.join(", "), + on_conflict_clause, ); let typed_params: Vec<(&(dyn ToSql + Sync), Type)> = owned_params .iter() .map(|(p, t)| (p.as_ref() as &(dyn ToSql + Sync), t.clone())) .collect(); - affected += pg_client + let chunk_inserted = pg_client .execute_typed(&query, &typed_params) .await .map_err(|e| format!("insert_records: {}", client::format_pg_error(&e)))?; + affected += chunk_inserted; + // With `ON CONFLICT DO NOTHING`, `execute_typed` counts only the rows + // actually inserted; the rest of the chunk conflicted and were skipped. + if on_conflict == OnConflict::Skip { + skipped += chunk.len() as u64 - chunk_inserted; + } + } + + Ok((affected, skipped)) +} + +#[cfg(test)] +mod cursor_name_tests { + use super::cursor_name; + + #[test] + fn strips_non_alphanumeric_characters() { + // A session_id with SQL-meaningful chars (`;`, space, `"`) must be + // sanitized to `[A-Za-z0-9_]` so the cursor name is a safe identifier. + let name = cursor_name("a;b c\"d"); + assert_eq!(name, "tabularis_copy_abcd"); } - Ok(affected) + #[test] + fn caps_at_max_length() { + // A very long session_id is truncated to MAX (50) chars. + let long = "x".repeat(200); + let name = cursor_name(&long); + assert!(name.len() <= 50, "cursor name len {} > 50", name.len()); + assert!(name.starts_with("tabularis_copy_")); + } + + #[test] + fn all_special_chars_produce_the_bare_prefix() { + // An all-special session_id sanitizes to the bare prefix — the host + // is expected to send usable session IDs, but the sanitizer degrades + // gracefully rather than producing an invalid identifier. + let name = cursor_name("@@@"); + assert_eq!(name, "tabularis_copy_"); + } } diff --git a/src/handlers/copy_tests.rs b/src/handlers/copy_tests.rs index 40f1643..3550960 100644 --- a/src/handlers/copy_tests.rs +++ b/src/handlers/copy_tests.rs @@ -67,3 +67,116 @@ async fn insert_records_rejects_a_non_object_row() { "non-object row should error: {resp}" ); } + +#[tokio::test] +async fn insert_records_rejects_an_unknown_on_conflict_value() { + // `on_conflict` must be "fail" or "skip"; anything else is a caller error + // surfaced before any DB call (#214 item 3). + let params = json!({ "table": "t", "rows": [{"a": 1}], "on_conflict": "overwrite" }); + let resp = insert_records(json!(1), ¶ms).await; + assert!( + resp.get("error").is_some(), + "unknown on_conflict should error: {resp}" + ); + let msg = resp["error"]["message"].as_str().unwrap_or_default(); + assert!( + msg.contains("on_conflict") && msg.contains("fail") && msg.contains("skip"), + "error should name on_conflict and the allowed values: {resp}" + ); +} + +#[tokio::test] +async fn insert_records_accepts_on_conflict_fail_and_skip() { + // Both "fail" and "skip" pass validation; with bogus connection params the + // call fails at the DB rather than at the param check, but never with the + // on_conflict validation message. Omitting on_conflict defaults to "fail". + for val in [None, Some("fail"), Some("skip")] { + let mut params = + json!({ "table": "t", "rows": [{"a": 1}], "host": "127.0.0.1", "port": 1 }); + if let Some(v) = val { + params["on_conflict"] = json!(v); + } + let resp = insert_records(json!(1), ¶ms).await; + let msg = resp["error"]["message"].as_str().unwrap_or_default(); + assert!( + !msg.contains("on_conflict") || msg.contains("insert_records: query failed"), + "on_conflict={val:?} should not fail on_conflict validation (got: {msg})" + ); + } +} + +#[tokio::test] +async fn insert_records_rejects_a_non_string_on_conflict() { + // A present-but-non-string on_conflict (number, bool, array, object) must + // be rejected, not silently defaulted to "fail" (#214 review finding). + // (JSON `null` is treated as "absent" → default "fail", which is the + // intended contract for an omitted field.) + for val in [json!(1), json!(true), json!([]), json!({})] { + let params = json!({ "table": "t", "rows": [{"a": 1}], "on_conflict": val }); + let resp = insert_records(json!(1), ¶ms).await; + assert!( + resp.get("error").is_some(), + "non-string on_conflict {val} should error: {resp}" + ); + let msg = resp["error"]["message"].as_str().unwrap_or_default(); + assert!( + msg.contains("on_conflict") && msg.contains("string"), + "error should name on_conflict and its expected type: {resp}" + ); + } +} + +#[tokio::test] +async fn insert_records_empty_rows_returns_zero_outcome() { + // An empty rows array short-circuits to InsertOutcome{0,0} before any DB + // call — if the early return were removed, rows[0] would panic (#214 review). + let params = json!({ "table": "t", "rows": [], "host": "127.0.0.1", "port": 1 }); + let resp = insert_records(json!(1), ¶ms).await; + assert!( + resp.get("error").is_none(), + "empty rows should succeed: {resp}" + ); + assert_eq!( + resp["result"], + json!({ "affected_rows": 0, "skipped": 0 }), + "empty batch: {resp}" + ); +} + +#[tokio::test] +async fn read_rows_clamps_limit_zero_to_one() { + // limit:0 is clamped to page_size=1 (not 0) so FETCH FORWARD 0 (which + // would loop forever with has_more=true) can't happen (#214 review). + // With bogus params the call fails at the connection, but the limit + // clamp is applied before the connection — the key assertion is that + // the call does not silently loop; the error is a connection error. + let params = json!({ + "query": "SELECT 1", + "limit": 0, + "page": 1, + "host": "127.0.0.1", + "port": 1, + }); + let resp: Value = read_rows(json!(1), ¶ms).await; + assert!( + resp.get("error").is_some(), + "limit:0 with bogus host should error (not hang): {resp}" + ); +} + +#[tokio::test] +async fn read_rows_rejects_a_non_result_set_query_on_the_session_path() { + // The `returns_result_set` guard fires before any cursor/connection work, + // so a non-result-set statement is rejected on the session path too. + let params = json!({ + "query": "INSERT INTO t VALUES (1)", + "session_id": "copy_guard", + "host": "127.0.0.1", + "port": 1, + }); + let resp: Value = read_rows(json!(1), ¶ms).await; + assert!( + resp.get("error").is_some(), + "non-result-set should error: {resp}" + ); +} diff --git a/src/handlers/metadata.rs b/src/handlers/metadata.rs index 8b3441e..23d35c5 100644 --- a/src/handlers/metadata.rs +++ b/src/handlers/metadata.rs @@ -119,6 +119,8 @@ async fn fetch_table_columns( WHEN c.data_type = 'USER-DEFINED' THEN c.udt_name::text ELSE c.data_type::text END AS data_type, + t.typname AS type_name, + a.atttypid::oid AS oid, c.is_nullable::text, c.column_default::text, c.is_identity::text, @@ -150,6 +152,7 @@ async fn fetch_table_columns( JOIN pg_namespace n ON n.nspname = c.table_schema JOIN pg_class pc ON pc.relnamespace = n.oid AND pc.relname = c.table_name JOIN pg_attribute a ON a.attrelid = pc.oid AND a.attname = c.column_name + JOIN pg_type t ON t.oid = a.atttypid LEFT JOIN pg_description d ON d.objoid = pc.oid AND d.classoid = 'pg_class'::regclass @@ -263,6 +266,13 @@ fn build_table_ddl(schema: &str, table: &str, columns: &[Value]) -> Result Value { let name: String = r.try_get("column_name").unwrap_or_default(); let raw_data_type: String = r.try_get("data_type").unwrap_or_default(); + // The canonical PostgreSQL type name (e.g. `numeric`, `timestamptz`, + // `int8`) from `pg_type.typname` — the same string `read_rows` reports via + // `Type::name()`, so the host has one type vocabulary for both the row data + // and the column metadata (#214 item 2). May be NULL only if the row came + // from a query that didn't select it (e.g. a LEFT JOIN miss). + let type_name: Option = r.try_get("type_name").ok().flatten(); + let oid: Option = r.try_get("oid").ok().flatten(); let enum_values: Option = r.try_get("enum_values").ok().flatten(); let is_nullable_str: String = r.try_get("is_nullable").unwrap_or_default(); let column_default: Option = r.try_get("column_default").ok().flatten(); @@ -301,6 +311,22 @@ fn row_to_table_column(r: &tokio_postgres::Row) -> Value { "is_auto_increment": is_auto_increment, }); + // The canonical type name + OID (from `format_type`/`pg_attribute`), so the + // host can plan a copy from column types with the same vocabulary + // `read_rows` uses (#214 item 2). Added only when the query selected them + // (always present for `get_columns`/`get_table_ddl`; `get_view_columns` and + // `get_materialized_view_columns` add them too). + if let Some(tn) = type_name { + col.as_object_mut() + .unwrap() + .insert("type".to_string(), json!(tn)); + } + if let Some(oid) = oid { + col.as_object_mut() + .unwrap() + .insert("oid".to_string(), json!(oid)); + } + if let Some(dv) = default_value { col.as_object_mut() .unwrap() @@ -610,6 +636,8 @@ pub async fn get_view_columns(id: Value, params: &Value) -> Value { WHEN c.data_type = 'USER-DEFINED' THEN c.udt_name::text ELSE c.data_type::text END AS data_type, + t.typname AS type_name, + a.atttypid::oid AS oid, c.is_nullable::text, c.column_default::text, c.is_identity::text, @@ -637,6 +665,15 @@ pub async fn get_view_columns(id: Value, params: &Value) -> Value { AND pk_att.attname = c.column_name ) AS is_pk FROM information_schema.columns c + JOIN pg_namespace n ON n.nspname = c.table_schema + JOIN pg_class pc ON pc.relnamespace = n.oid AND pc.relname = c.table_name + -- LEFT JOINs: a view column whose pg_attribute row is temporarily absent + -- (foreign-table backing, mid-ALTER edge case) must not silently drop + -- the column from the result — `type`/`oid` come back NULL instead + -- (#214 review finding). The table/batch paths already had this join + -- pre-PR; the view path is new in #216. + LEFT JOIN pg_attribute a ON a.attrelid = pc.oid AND a.attname = c.column_name + LEFT JOIN pg_type t ON t.oid = a.atttypid WHERE c.table_schema = $1 AND c.table_name = $2 ORDER BY c.ordinal_position "#; @@ -766,10 +803,13 @@ pub async fn get_materialized_view_columns(id: Value, params: &Value) -> Value { SELECT a.attname AS column_name, format_type(a.atttypid, a.atttypmod) AS data_type, + t.typname AS type_name, + a.atttypid::oid AS oid, a.attnotnull AS not_null FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid JOIN pg_namespace n ON n.oid = c.relnamespace + JOIN pg_type t ON t.oid = a.atttypid WHERE n.nspname = $1 AND c.relname = $2 AND c.relkind = 'm' AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum @@ -782,14 +822,32 @@ pub async fn get_materialized_view_columns(id: Value, params: &Value) -> Value { .map(|r| { let name: String = r.try_get("column_name").unwrap_or_default(); let data_type: String = r.try_get("data_type").unwrap_or_default(); + let type_name: Option = r.try_get("type_name").ok().flatten(); + let oid: Option = r.try_get("oid").ok().flatten(); let not_null: bool = r.try_get("not_null").unwrap_or(false); - json!({ + let mut col = json!({ "name": name, "data_type": data_type, "is_pk": false, "is_nullable": !not_null, "is_auto_increment": false, - }) + }); + // `type` uses `pg_type.typname` (the short internal name, + // e.g. `numeric`, `int8`) matching `read_rows`' + // `Type::name()` — NOT `data_type` (which is `format_type` + // output, e.g. `numeric(38,10)`). One vocabulary across + // tables/views/matviews (#214 item 2 + review finding). + if let Some(tn) = type_name { + col.as_object_mut() + .unwrap() + .insert("type".to_string(), json!(tn)); + } + if let Some(oid) = oid { + col.as_object_mut() + .unwrap() + .insert("oid".to_string(), json!(oid)); + } + col }) .collect(); ok_response(id, json!(columns)) @@ -1256,6 +1314,8 @@ async fn fetch_all_columns( WHEN c.data_type = 'USER-DEFINED' THEN c.udt_name::text ELSE c.data_type::text END AS data_type, + t.typname AS type_name, + a.atttypid::oid AS oid, c.is_nullable::text, c.column_default::text, c.is_identity::text, @@ -1287,6 +1347,7 @@ async fn fetch_all_columns( JOIN pg_namespace n ON n.nspname = c.table_schema JOIN pg_class pc ON pc.relnamespace = n.oid AND pc.relname = c.table_name JOIN pg_attribute a ON a.attrelid = pc.oid AND a.attname = c.column_name + JOIN pg_type t ON t.oid = a.atttypid LEFT JOIN pg_description d ON d.objoid = pc.oid AND d.classoid = 'pg_class'::regclass