Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
83 changes: 47 additions & 36 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)) |
Expand Down Expand Up @@ -377,46 +377,52 @@ 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` 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
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'`, `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
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
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
Expand All @@ -437,10 +443,15 @@ 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, 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

Expand Down
100 changes: 84 additions & 16 deletions src/binding.rs
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -54,6 +56,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<i64>,
/// 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 <cast_type>)` so the type's input function parses it (#225).
pub cast_type: Option<&'a str>,
}

const USE_DEFAULT_SENTINEL: &str = "__USE_DEFAULT__";
Expand Down Expand Up @@ -169,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)
Expand Down Expand Up @@ -223,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<u32>,
options: &BindOptions,
) -> Result<BoundValue, String> {
let map = match value {
Value::Null => {
Expand All @@ -240,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::<Value>(&s) {
Ok(Value::Object(map)) => map,
Value::String(s) => match (serde_json::from_str::<Value>(&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"
Expand All @@ -257,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)?;
Expand Down Expand Up @@ -363,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 {
Expand Down Expand Up @@ -400,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:<size>:<mime>:<base64> 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
Expand Down Expand Up @@ -436,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,
Expand All @@ -449,24 +479,28 @@ 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)),
});
}

// 10. UUID shape (value-based fallback, independent of column type)
if s.parse::<Uuid>().is_ok() {
if !text_column && s.parse::<Uuid>().is_ok() {
return Ok(BoundValue {
sql: format!("CAST(${} AS uuid)", placeholder_idx),
param: Some((Box::new(s.to_string()), Type::TEXT)),
});
}

// 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]").
// 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();
if 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::<Value>(trimmed) {
let literal = json_array_to_pg_literal(&arr)?;
return Ok(BoundValue {
Expand All @@ -476,13 +510,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 <qualified_enum>)`.
/// The placeholder is pinned to `TEXT` so tokio-postgres does not reject the
/// bound `String` client-side before the CAST resolves it server-side.
Expand Down Expand Up @@ -613,7 +679,9 @@ fn json_array_to_pg_literal(arr: &[Value]) -> Result<String, String> {
}
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);
}
Expand Down Expand Up @@ -711,7 +779,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.
Expand Down
Loading
Loading