Skip to main content

rivet/source/postgres/
mod.rs

1//! PostgreSQL `Source` implementation.
2//!
3//! Module layout:
4//!
5//! - `mod.rs` (this file) — `PostgresSource` struct + connect/TLS path, the
6//!   transaction-pooler detector, `PgTxnGuard`, sampling helpers
7//!   (`sample_temp_bytes`, `pg_sample_checkpoints_req`, `pg_fetch_work_mem_bytes`),
8//!   `introspect_pg_table_for_chunking`, the cursor + FETCH export loop
9//!   (`pg_run_export`), the `Source` trait impl, and the catalog-hint
10//!   resolver that bridges parsed FROM clauses to `pg_catalog`.
11//! - [`arrow_convert`] — the entire row → Arrow `RecordBatch` pipeline: type
12//!   mapping (`pg_columns_to_schema`, `rivet_type_for_pg_column`), per-cell
13//!   decoders (INTERVAL, UUID, enum, NUMERIC), and the array builders. Kept
14//!   in a sibling because it is the largest single-purpose cluster in this
15//!   driver (~620 LoC) and has zero reverse dependency back into the
16//!   connection / cursor layer.
17//! - [`from_parse`] — pure `&str`/`&[u8]` parser that extracts the simple
18//!   `<schema>.<table>` literal from a user query so the catalog-hint path
19//!   can cast it to `regclass`.  Zero postgres-crate dependency, fully
20//!   unit-tested in isolation.
21
22mod arrow_convert;
23pub(crate) mod cdc;
24mod from_parse;
25
26use std::collections::HashMap;
27use std::sync::Arc;
28
29use arrow::datatypes::{Schema, SchemaRef};
30use postgres::types::Type;
31use postgres::{Client, NoTls};
32
33use crate::config::{SourceType, TlsConfig};
34use crate::error::Result;
35use crate::source::batch_controller::AdaptiveBatchController;
36use crate::source::query::build_export_query;
37use crate::source::tls::build_native_tls;
38use crate::tuning::SourceTuning;
39use crate::types::{ColumnOverrides, SourceColumn, TypeMapping};
40
41use arrow_convert::{pg_columns_to_schema, rivet_type_for_pg_column, rows_to_record_batch_typed};
42use from_parse::try_parse_pg_simple_from_regclass_literal;
43
44pub struct PostgresSource {
45    client: Client,
46    /// True when two consecutive pg_backend_pid() calls returned different values,
47    /// indicating a transaction-mode connection pooler (pgBouncer, Odyssey, etc.).
48    transaction_pooler: bool,
49}
50
51/// Detect whether the connection is going through a transaction-mode pooler
52/// (pgBouncer, Odyssey, etc.) by comparing backend PIDs across two implicit
53/// transactions. Returns true when PIDs differ — impossible on a direct
54/// connection or session-mode pooler where the same physical backend is kept.
55///
56/// False negatives are possible when pool_size = 1 (the same backend is always
57/// reused), so this is a best-effort warning rather than a hard guarantee.
58fn detect_pg_transaction_pooler(client: &mut Client) -> bool {
59    let pid1: Option<i32> = client
60        .query_one("SELECT pg_backend_pid()", &[])
61        .ok()
62        .and_then(|r| r.try_get(0).ok());
63    let pid2: Option<i32> = client
64        .query_one("SELECT pg_backend_pid()", &[])
65        .ok()
66        .and_then(|r| r.try_get(0).ok());
67    matches!((pid1, pid2), (Some(a), Some(b)) if a != b)
68}
69
70impl PostgresSource {
71    /// Connect with no transport security (legacy path). Prefer [`Self::connect_with_tls`]
72    /// for production workloads so credentials and result sets are not visible on the wire.
73    pub fn connect(url: &str) -> Result<Self> {
74        let mut client = Client::connect(url, NoTls)?;
75        let transaction_pooler = detect_pg_transaction_pooler(&mut client);
76        if transaction_pooler {
77            log::warn!(
78                "transaction-mode connection pooler detected (pgBouncer/Odyssey) — \
79                 SET LOCAL tuning is transaction-scoped; \
80                 LISTEN/NOTIFY and advisory locks are unavailable"
81            );
82        }
83        Ok(Self {
84            client,
85            transaction_pooler,
86        })
87    }
88
89    /// Connect honoring the user's [`TlsConfig`]. When `tls.mode` is
90    /// [`TlsMode::Disable`] this falls back to [`Self::connect`].
91    pub fn connect_with_tls(url: &str, tls: Option<&TlsConfig>) -> Result<Self> {
92        // Refuse remote plaintext (no `tls:` block) before any dial (CWE-319).
93        crate::source::require_tls_or_loopback(url, tls)?;
94        match tls {
95            Some(cfg) if cfg.mode.is_enforced() => {
96                let connector = build_native_tls(cfg)?;
97                let make_tls = postgres_native_tls::MakeTlsConnector::new(connector);
98                let mut client = Client::connect(url, make_tls)?;
99                let transaction_pooler = detect_pg_transaction_pooler(&mut client);
100                if transaction_pooler {
101                    log::warn!(
102                        "transaction-mode connection pooler detected (pgBouncer/Odyssey) — \
103                         SET LOCAL tuning is transaction-scoped; \
104                         LISTEN/NOTIFY and advisory locks are unavailable"
105                    );
106                }
107                Ok(Self {
108                    client,
109                    transaction_pooler,
110                })
111            }
112            _ => Self::connect(url),
113        }
114    }
115}
116
117/// RAII guard for an open `BEGIN ... COMMIT` block.
118///
119/// `commit()` runs `COMMIT` and marks the txn done; if the guard is dropped
120/// before `commit()` (early return, `?`-bubbled error, or panic-driven unwind),
121/// `Drop` issues a best-effort `ROLLBACK`. Postgres releases any open cursors
122/// as part of ROLLBACK, so the cursor declared inside the txn is also cleaned
123/// up. Closes the **G1** gap from the DBA audit (cursor leak on panic).
124struct PgTxnGuard<'a> {
125    client: &'a mut Client,
126    committed: bool,
127}
128
129impl<'a> PgTxnGuard<'a> {
130    fn begin(client: &'a mut Client) -> Result<Self> {
131        client.batch_execute("BEGIN")?;
132        Ok(Self {
133            client,
134            committed: false,
135        })
136    }
137
138    fn client_mut(&mut self) -> &mut Client {
139        self.client
140    }
141
142    fn commit(mut self) -> Result<()> {
143        self.client.batch_execute("COMMIT")?;
144        self.committed = true;
145        Ok(())
146    }
147}
148
149impl Drop for PgTxnGuard<'_> {
150    fn drop(&mut self) {
151        if !self.committed
152            && let Err(e) = self.client.batch_execute("ROLLBACK")
153        {
154            // Drop must not panic. Worst case the connection is poisoned and
155            // the pool recycles it; log so operators see it.
156            log::warn!("PgTxnGuard: ROLLBACK during drop failed: {e:#}");
157        }
158    }
159}
160
161/// Snapshot `pg_stat_database.temp_bytes` for the current database.
162///
163/// Used by the pipeline job to compute per-run cursor / sort spill: we capture
164/// the cluster-wide counter immediately before and after each export and
165/// surface the delta on the run summary card. Failures (connect, query) return
166/// `None` — the metric is informational, not a correctness signal.
167///
168/// Note this is a cluster-level counter: concurrent activity from other
169/// connections during the run inflates the delta. For a single-tenant test
170/// box (the common pilot setup) it is accurate; for shared hosts it is a
171/// noisy upper bound, useful as a "your workload was loud" signal.
172pub(crate) fn sample_temp_bytes(url: &str, tls: Option<&TlsConfig>) -> Option<i64> {
173    let mut client = connect_client(url, tls).ok()?;
174    client
175        .query_one(
176            "SELECT temp_bytes::bigint FROM pg_stat_database WHERE datname = current_database()",
177            &[],
178        )
179        .ok()
180        .and_then(|r| r.try_get::<_, i64>(0).ok())
181}
182
183/// Snapshot the broader source-harm counters from `pg_stat_database` for the
184/// current database — a superset of [`sample_temp_bytes`] (which the run summary
185/// tracks on its own). Returns `(metric, cumulative_value)` pairs; the pipeline
186/// captures these before and after the export and stores the per-metric delta in
187/// `export_harm`.
188///
189/// All counters live in `pg_stat_database` and are readable by **any** role — no
190/// `pg_monitor` membership or superuser needed (unlike `pg_stat_activity`'s view
191/// of other sessions). These are cluster-level cumulative counters, so concurrent
192/// activity inflates the delta; on a single-tenant pilot box it is the run's own
193/// footprint. `None` on connect/query failure — informational, never blocks the
194/// export.
195pub(crate) fn sample_harm_counters(
196    url: &str,
197    tls: Option<&TlsConfig>,
198) -> Option<Vec<(String, i64)>> {
199    let mut client = connect_client(url, tls).ok()?;
200    // `tup_returned` (rows the engine had to scan) is the read-amplification
201    // signal; `blks_read`/`blks_hit` the I/O vs cache split; `temp_files` the
202    // spill count; `deadlocks` contention. temp_bytes is intentionally omitted —
203    // it's already on the run summary (export_metrics.pg_temp_bytes_delta).
204    let row = client
205        .query_one(
206            "SELECT blks_read::bigint, blks_hit::bigint, tup_returned::bigint, \
207             tup_fetched::bigint, temp_files::bigint, deadlocks::bigint \
208             FROM pg_stat_database WHERE datname = current_database()",
209            &[],
210        )
211        .ok()?;
212    let names = [
213        "pg_blks_read",
214        "pg_blks_hit",
215        "pg_tup_returned",
216        "pg_tup_fetched",
217        "pg_temp_files",
218        "pg_deadlocks",
219    ];
220    let mut out = Vec::with_capacity(names.len());
221    for (i, name) in names.iter().enumerate() {
222        if let Ok(v) = row.try_get::<_, i64>(i) {
223            out.push(((*name).to_string(), v));
224        }
225    }
226    Some(out)
227}
228
229/// Probe `SHOW work_mem` and return the value in bytes.
230///
231/// PostgreSQL spills FETCH-cursor output to `pgsql_tmp/` once the in-flight
232/// row set exceeds `work_mem` — on wide rows with the default 4 MB the spill
233/// fires on every chunk and dominates `pg_stat_database.temp_bytes`. Knowing
234/// the value lets the cursor loop cap FETCH N below `work_mem × 0.7`, keeping
235/// the result set in memory.
236///
237/// Returns None on any parse / query failure — the cursor loop falls back to
238/// the configured static batch_size in that case.
239fn pg_fetch_work_mem_bytes(client: &mut Client) -> Option<i64> {
240    let raw: Option<String> = client
241        .query_one("SHOW work_mem", &[])
242        .ok()
243        .and_then(|r| r.try_get::<_, String>(0).ok());
244    raw.as_deref().and_then(parse_work_mem)
245}
246
247/// Parse a `SHOW work_mem` value like `"4MB"`, `"16384kB"`, `"1GB"`, or a bare
248/// number-of-kB string (the older PG default unit) into a byte count. Returns
249/// `None` for anything else so callers can decide whether to fall back.
250fn parse_work_mem(raw: &str) -> Option<i64> {
251    let s = raw.trim();
252    // Split numeric prefix from optional unit.
253    let mut split = 0;
254    for (i, ch) in s.char_indices() {
255        if !ch.is_ascii_digit() && ch != '.' && ch != '-' {
256            split = i;
257            break;
258        }
259        split = i + ch.len_utf8();
260    }
261    if split == 0 {
262        return None;
263    }
264    let (num_str, unit) = s.split_at(split);
265    let num: f64 = num_str.parse().ok()?;
266    let unit = unit.trim().to_ascii_lowercase();
267    let multiplier: f64 = match unit.as_str() {
268        // Postgres always uses 1024-based units, matching the syntax it
269        // accepts in postgresql.conf.
270        "" | "kb" => 1024.0,
271        "mb" => 1024.0 * 1024.0,
272        "gb" => 1024.0 * 1024.0 * 1024.0,
273        "tb" => 1024.0 * 1024.0 * 1024.0 * 1024.0,
274        _ => return None,
275    };
276    let bytes = (num * multiplier) as i64;
277    (bytes > 0).then_some(bytes)
278}
279
280/// Sample `checkpoints_req` from `pg_stat_bgwriter`.
281///
282/// PostgreSQL caches the statistics snapshot at the start of each transaction.
283/// We call `pg_stat_clear_snapshot()` first to discard that cache so every
284/// adaptive sample sees fresh counters rather than the frozen value from BEGIN.
285fn pg_sample_checkpoints_req(client: &mut Client) -> Option<i64> {
286    let _ = client.execute("SELECT pg_stat_clear_snapshot()", &[]);
287    client
288        .query_one("SELECT checkpoints_req FROM pg_stat_bgwriter", &[])
289        .ok()
290        .and_then(|r| r.try_get::<_, i64>(0).ok())
291}
292
293/// Probe `pg_class` and `pg_index` for the stats chunked-mode planning needs.
294///
295/// Returns a [`crate::source::TableIntrospection`] populated from one connection
296/// (two round-trips total: one stats query, one PK query). Failure to connect
297/// or to query bubbles up as `Err`; missing rows or unanalyzed tables are
298/// represented as zero/None in the result so callers can decide policy.
299///
300/// The `qualified_table` argument is `<schema>.<table>` (e.g. `public.users`)
301/// or bare `<table>` (resolved under `public`). It is split internally with
302/// the same strict rules as the `table:` YAML shortcut — anything more
303/// elaborate must use the explicit-column path.
304pub(crate) fn introspect_pg_table_for_chunking(
305    url: &str,
306    tls: Option<&TlsConfig>,
307    qualified_table: &str,
308) -> Result<crate::source::TableIntrospection> {
309    let (schema, table) = match qualified_table.split_once('.') {
310        Some((s, t)) => (s.to_string(), t.to_string()),
311        None => ("public".to_string(), qualified_table.to_string()),
312    };
313    let mut client = connect_client(url, tls)?;
314
315    // ── reltuples + heap size, in one shot ──────────────────────────────
316    let (row_estimate, rel_size_bytes) = match client.query_opt(
317        "SELECT c.reltuples::bigint, pg_relation_size(c.oid)::bigint \
318         FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
319         WHERE n.nspname = $1::text AND c.relname = $2::text",
320        &[&schema, &table],
321    )? {
322        Some(row) => {
323            let rt: i64 = row.try_get(0).unwrap_or(0);
324            let sz: i64 = row.try_get(1).unwrap_or(0);
325            (rt.max(0), sz.max(0))
326        }
327        None => (0, 0),
328    };
329    let avg_row_bytes = if row_estimate > 0 {
330        Some(rel_size_bytes / row_estimate)
331    } else {
332        None
333    };
334
335    // ── single int PK probe ─────────────────────────────────────────────
336    let pk_rows = client.query(
337        "SELECT a.attname::text, t.typname::text \
338         FROM pg_index i \
339         JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey) \
340         JOIN pg_type t ON t.oid = a.atttypid \
341         WHERE i.indrelid = (($1::text || '.' || $2::text)::regclass) \
342           AND i.indisprimary",
343        &[&schema, &table],
344    )?;
345    let single_int_pk = if pk_rows.len() == 1 {
346        let col: String = pk_rows[0].get(0);
347        let pg_type: String = pk_rows[0].get(1);
348        // Only integer-family types are safe for range chunking via min/max →
349        // BETWEEN slicing. Text/UUID/decimal would need different splitting
350        // logic and are excluded from auto-resolution.
351        if matches!(pg_type.as_str(), "int2" | "int4" | "int8") {
352            Some(col)
353        } else {
354            log::debug!(
355                "introspect_pg_table: PK '{col}' on {schema}.{table} has non-int type '{pg_type}' — skipping auto-resolve"
356            );
357            None
358        }
359    } else {
360        None
361    };
362
363    // ── keyset keys (OPT-4): single-column, NOT NULL, UNIQUE indexes ────
364    // `indnkeyatts = 1` keeps single-column indexes; `indkey[0] = a.attnum`
365    // binds to a real column (not an expression index); `attnotnull` removes
366    // NULL-ordering ambiguity. Index-backed + unique ⇒ keyset's `ORDER BY key
367    // LIMIT n` is a range scan and `WHERE key > last` never skips dup keys.
368    let keyset_rows = client.query(
369        "SELECT a.attname::text, i.indisprimary \
370         FROM pg_index i \
371         JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = i.indkey[0] \
372         WHERE i.indrelid = (($1::text || '.' || $2::text)::regclass) \
373           AND i.indisunique AND i.indnkeyatts = 1 AND a.attnotnull",
374        &[&schema, &table],
375    )?;
376    let mut keyset_keys: Vec<String> = Vec::new();
377    for primary in [true, false] {
378        for row in &keyset_rows {
379            let col: String = row.get(0);
380            let is_primary: bool = row.get(1);
381            if is_primary == primary && !keyset_keys.contains(&col) {
382                keyset_keys.push(col);
383            }
384        }
385    }
386
387    Ok(crate::source::TableIntrospection {
388        single_int_pk,
389        keyset_keys,
390        row_estimate,
391        avg_row_bytes,
392    })
393}
394
395/// Open a bare `postgres::Client` honoring the configured TLS policy.
396///
397/// Shared by preflight, doctor, and `rivet init` so every code path that
398/// connects to Postgres applies the same transport-security rules. Preflight
399/// and doctor pass the YAML `tls:` block; init runs before any YAML exists,
400/// so it derives a `TlsConfig` from the URL's `sslmode` parameter (see
401/// `crate::init::postgres::connect`). `tls = None` or `mode: disable` falls
402/// back to the insecure `NoTls` transport — a warning is logged from
403/// `create_source` so operators know TLS is off.
404pub(crate) fn connect_client(url: &str, tls: Option<&TlsConfig>) -> Result<Client> {
405    // Refuse remote plaintext (no `tls:` block) before any dial (CWE-319).
406    crate::source::require_tls_or_loopback(url, tls)?;
407    match tls {
408        Some(cfg) if cfg.mode.is_enforced() => {
409            let connector = build_native_tls(cfg)?;
410            let make_tls = postgres_native_tls::MakeTlsConnector::new(connector);
411            Ok(Client::connect(url, make_tls)?)
412        }
413        _ => Ok(Client::connect(url, NoTls)?),
414    }
415}
416
417/// Run the full export transaction against an open Postgres client.
418///
419/// All session-mutating SET commands use SET LOCAL so they are scoped to
420/// the transaction and reset automatically on COMMIT or ROLLBACK. The caller
421/// is responsible for issuing ROLLBACK if this function returns Err.
422///
423/// Returns (total_rows, had_schema). had_schema is false only when the query
424/// returned zero rows; the caller must emit an empty schema in that case.
425fn pg_run_export(
426    client: &mut Client,
427    built_sql: &str,
428    tuning: &SourceTuning,
429    column_overrides: &ColumnOverrides,
430    sink: &mut dyn super::BatchSink,
431    numeric_hints: Option<&HashMap<String, (u8, i8)>>,
432) -> Result<(usize, bool)> {
433    // Open the txn under guard *first* — if SET LOCAL or DECLARE fails below,
434    // Drop will roll back. Without the guard, a failure between BEGIN and the
435    // explicit ROLLBACK in the caller would leak a half-set-up txn into the pool.
436    let mut guard = PgTxnGuard::begin(client)?;
437    // Pin the read txn's TimeZone to UTC. The row READ is UTC-absolute (the binary
438    // protocol yields instants regardless of session zone), but the incremental /
439    // keyset cursor boundary is re-injected as an OFFSET-LESS naive-UTC literal
440    // into `WHERE col > '<literal>'`; PostgreSQL coerces a naive literal to
441    // `timestamptz` using the SESSION TimeZone, so on any non-UTC session (a common
442    // production default via postgresql.conf or `ALTER ROLE/DATABASE ... SET
443    // timezone`) the boundary shifts by the zone offset and every incremental run
444    // silently SKIPS (west of UTC) or DUPLICATES (east) the offset-wide gap window —
445    // a count-passing data loss invisible under a UTC test session. The MySQL path
446    // pins the equivalent (`SET time_zone='+00:00'`). SET LOCAL is txn-scoped, so it
447    // auto-resets on commit/rollback and never leaks into the pooled connection.
448    guard
449        .client_mut()
450        .batch_execute("SET LOCAL TimeZone = 'UTC'")?;
451    if tuning.statement_timeout_s > 0 {
452        guard.client_mut().batch_execute(&format!(
453            "SET LOCAL statement_timeout = '{}s'",
454            tuning.statement_timeout_s
455        ))?;
456    }
457    if tuning.lock_timeout_s > 0 {
458        guard.client_mut().batch_execute(&format!(
459            "SET LOCAL lock_timeout = '{}s'",
460            tuning.lock_timeout_s
461        ))?;
462    }
463    // Cap FETCH N under `work_mem × 0.7` so the cursor never spills to
464    // `pgsql_tmp/`. Without this, a wide-row chunk with the default
465    // `batch_size: 50000` × ~4 KB/row = ~200 MB easily exceeds the typical
466    // `work_mem: 4 MB` and writes the entire chunk to disk before the first
467    // FETCH returns. Measured cost on the content_items bench: ~3.2 GB of
468    // temp_bytes per export, dominating the DB-side signal report.
469    let work_mem_bytes = pg_fetch_work_mem_bytes(guard.client_mut());
470
471    guard
472        .client_mut()
473        .batch_execute(&format!("DECLARE _rivet NO SCROLL CURSOR FOR {built_sql}"))?;
474
475    // The first FETCH is intentionally a small `PROBE_BATCH_SIZE` row-width
476    // probe (the controller starts there): without it we can't know
477    // `arrow_bytes/row` before the cursor runs, and a single FETCH of
478    // `tuning.batch_size` × wide rows already triggers a `pgsql_tmp/` spill.
479    let configured_batch_size = tuning.batch_size;
480    // Shared batch-size state machine; PG provides the FETCH N row source, the
481    // work_mem (or schema-derived) cap target, and the checkpoint pressure proxy.
482    let mut ctl = AdaptiveBatchController::new(tuning, configured_batch_size);
483    ctl.seed_pressure(if tuning.adaptive {
484        pg_sample_checkpoints_req(guard.client_mut()).map(|v| v as u64)
485    } else {
486        None
487    });
488    let mut schema: Option<SchemaRef> = None;
489    let mut columns_cache: Option<Vec<(String, Type)>> = None;
490    let mut total_rows: usize = 0;
491    let mut cap_applied = false;
492    // Per-value ceiling (MB→bytes; `0`/None disables), enforced pre-allocation
493    // inside the batch builder so an oversized cell bails before Arrow reserves
494    // the buffer. Same source of truth as the sink's backstop guard.
495    let max_value_bytes = tuning.max_value_bytes();
496
497    loop {
498        let requested = ctl.target();
499        let fetch_sql = format!("FETCH {} FROM _rivet", requested);
500        let rows = guard.client_mut().query(&fetch_sql, &[])?;
501        if rows.is_empty() {
502            break;
503        }
504
505        if schema.is_none() {
506            let stmt_cols: Vec<(String, Type)> = rows[0]
507                .columns()
508                .iter()
509                .map(|c| (c.name().to_string(), c.type_().clone()))
510                .collect();
511            let s = Arc::new(pg_columns_to_schema(
512                rows[0].columns(),
513                column_overrides,
514                numeric_hints,
515            )?);
516            sink.on_schema(s.clone())?;
517            // When work_mem can't be read, fall back to the schema-derived
518            // effective batch size as the cap target (controller clamps it).
519            if work_mem_bytes.is_none() {
520                let effective = tuning.effective_batch_size(Some(&s));
521                ctl.apply_memory_cap(effective.max(requested));
522                cap_applied = true;
523            }
524            schema = Some(s);
525            columns_cache = Some(stmt_cols);
526        }
527
528        let row_count = rows.len();
529        total_rows += row_count;
530
531        let s = schema.as_ref().expect("schema set on first iteration");
532        let cols = columns_cache
533            .as_ref()
534            .expect("columns set on first iteration");
535        let batch = rows_to_record_batch_typed(s, cols, &rows, max_value_bytes)?;
536        drop(rows);
537
538        // After the first (probe) batch we know the actual row width. Cap the
539        // FETCH N below `work_mem × 0.7` so the cursor never spills:
540        //   pg_row_bytes ≈ arrow_per_row × 1.2 ; safe = work_mem×0.7 / pg_row_bytes
541        // The controller clamps it to the configured `batch_size`.
542        if !cap_applied
543            && let Some(wm) = work_mem_bytes
544            && row_count > 0
545        {
546            let arrow_bytes = crate::tuning::SourceTuning::batch_memory_bytes(&batch);
547            let arrow_per_row = (arrow_bytes / row_count).max(1);
548            let pg_per_row = ((arrow_per_row * 12) / 10).max(64);
549            let safe = (((wm as f64) * 0.7) as usize / pg_per_row).max(100);
550            let mut target = safe;
551            if let Some(mem_mb) = tuning.batch_size_memory_mb {
552                let arrow_target = (mem_mb * 1024 * 1024) / arrow_per_row;
553                target = target.min(arrow_target.max(100));
554            }
555            if let Some(new) = ctl.apply_memory_cap(target) {
556                log::info!(
557                    "PG work_mem={} B, observed row={} B (arrow), pg≈{} B → FETCH N → {} (configured={})",
558                    wm,
559                    arrow_per_row,
560                    pg_per_row,
561                    new,
562                    configured_batch_size,
563                );
564            }
565            cap_applied = true;
566        }
567
568        sink.on_batch(&batch)?;
569
570        if let Some((new, under_pressure)) =
571            ctl.after_batch(|| pg_sample_checkpoints_req(guard.client_mut()).map(|v| v as u64))
572        {
573            log::info!(
574                "adaptive batch size → {} ({})",
575                new,
576                if under_pressure {
577                    "pressure"
578                } else {
579                    "recovery"
580                }
581            );
582        }
583
584        log::info!("fetched {} rows so far...", total_rows);
585
586        if row_count < requested {
587            break;
588        }
589        ctl.throttle(row_count);
590    }
591
592    // Explicit CLOSE is technically redundant — COMMIT releases the cursor —
593    // but it documents intent and surfaces any close errors before COMMIT.
594    guard.client_mut().batch_execute("CLOSE _rivet")?;
595    guard.commit()?;
596    Ok((total_rows, schema.is_some()))
597}
598
599impl super::Source for PostgresSource {
600    fn export(
601        &mut self,
602        request: &super::ExportRequest<'_>,
603        sink: &mut dyn super::BatchSink,
604    ) -> Result<()> {
605        let built = build_export_query(request, SourceType::Postgres);
606        debug_assert!(
607            built.cursor_param.is_none(),
608            "Postgres path inlines cursor values as E'…' literals — binding is unused"
609        );
610        log::debug!(
611            "executing query (connection={}): {}",
612            if self.transaction_pooler {
613                "transaction-pooler"
614            } else {
615                "direct"
616            },
617            built.sql
618        );
619
620        // Resolve NUMERIC precision from the *unwrapped* base query when the
621        // caller wrapped `query` in a chunk/keyset subquery (which hides the
622        // source table from the catalog parser). Falls back to `query`.
623        let hint_query = request.catalog_hint_query.unwrap_or(request.query);
624        let numeric_hints = pg_numeric_catalog_hints_opt(&mut self.client, hint_query);
625
626        // PgTxnGuard inside pg_run_export rolls the txn back automatically on
627        // any error or panic, so no explicit ROLLBACK is needed here.
628        let (total_rows, had_schema) = pg_run_export(
629            &mut self.client,
630            &built.sql,
631            request.tuning,
632            request.column_overrides,
633            sink,
634            numeric_hints.as_ref(),
635        )?;
636
637        if !had_schema {
638            sink.on_schema(Arc::new(Schema::empty()))?;
639        }
640
641        log::info!("total: {} rows", total_rows);
642        Ok(())
643    }
644
645    fn query_scalar(&mut self, sql: &str) -> Result<Option<String>> {
646        let rows = self.client.query(sql, &[])?;
647        if rows.is_empty() {
648            return Ok(None);
649        }
650        let row = &rows[0];
651        if let Ok(Some(v)) = row.try_get::<_, Option<i64>>(0) {
652            return Ok(Some(v.to_string()));
653        }
654        if let Ok(Some(v)) = row.try_get::<_, Option<i32>>(0) {
655            return Ok(Some(v.to_string()));
656        }
657        if let Ok(Some(v)) = row.try_get::<_, Option<f64>>(0) {
658            return Ok(Some(v.to_string()));
659        }
660        // TIMESTAMP / DATE / TIMESTAMPTZ — required for MIN/MAX on time columns (e.g. chunk_by_days)
661        if let Ok(Some(v)) = row.try_get::<_, Option<chrono::NaiveDateTime>>(0) {
662            return Ok(Some(v.format("%Y-%m-%d %H:%M:%S").to_string()));
663        }
664        if let Ok(Some(v)) = row.try_get::<_, Option<chrono::NaiveDate>>(0) {
665            return Ok(Some(v.format("%Y-%m-%d").to_string()));
666        }
667        if let Ok(Some(v)) = row.try_get::<_, Option<chrono::DateTime<chrono::Utc>>>(0) {
668            return Ok(Some(v.format("%Y-%m-%d %H:%M:%S").to_string()));
669        }
670        if let Ok(Some(v)) = row.try_get::<_, Option<String>>(0) {
671            return Ok(Some(v));
672        }
673        Ok(None)
674    }
675
676    fn type_mappings(
677        &mut self,
678        query: &str,
679        column_overrides: &ColumnOverrides,
680    ) -> Result<Vec<TypeMapping>> {
681        let wrapped = format!("SELECT * FROM ({}) AS _rivet_type_probe LIMIT 0", query);
682        let stmt = self.client.prepare(&wrapped)?;
683        let hints = pg_numeric_catalog_hints_opt(&mut self.client, query);
684        let mappings = stmt
685            .columns()
686            .iter()
687            .map(|col| {
688                let rivet = rivet_type_for_pg_column(col, column_overrides, hints.as_ref());
689                let source = SourceColumn::simple(col.name(), col.type_().name(), true);
690                TypeMapping::from_source(&source, rivet)
691            })
692            .collect();
693        Ok(mappings)
694    }
695
696    /// Governor pressure proxy: `pg_stat_bgwriter.checkpoints_req` — the same
697    /// monotonic counter the adaptive batch loop samples. Rising between samples
698    /// means the source is checkpointing harder under write pressure.
699    fn sample_pressure(&mut self) -> Option<u64> {
700        pg_sample_checkpoints_req(&mut self.client).map(|v| v.max(0) as u64)
701    }
702}
703
704/// When the query is a single-table `SELECT … FROM rel` (no joins, no subquery
705/// in `FROM`), PostgreSQL result metadata does not carry `NUMERIC` typmod, but
706/// `information_schema` / the table DDL does. We resolve the base relation with
707/// a small parser and fetch declared precision/scale so `rivet init`-style
708/// exports work without hand-written `columns:` overrides.
709fn pg_numeric_catalog_hints_opt(
710    client: &mut Client,
711    query: &str,
712) -> Option<HashMap<String, (u8, i8)>> {
713    match pg_fetch_numeric_catalog_hints(client, query) {
714        Ok(m) => m,
715        Err(e) => {
716            // Reaching this arm means the parser identified a single-table query
717            // and we tried catalog lookup, but the lookup itself failed. That is
718            // unexpected (not "this query has a JOIN"), so surface it — otherwise
719            // a downstream NUMERIC mapping failure looks like a config problem
720            // when the real cause is here.
721            log::warn!(
722                "PG numeric catalog lookup failed — NUMERIC columns will require explicit `columns:` overrides: {e}"
723            );
724            None
725        }
726    }
727}
728
729fn pg_fetch_numeric_catalog_hints(
730    client: &mut Client,
731    query: &str,
732) -> crate::error::Result<Option<HashMap<String, (u8, i8)>>> {
733    let Some(regclass_lit) = try_parse_pg_simple_from_regclass_literal(query) else {
734        return Ok(None);
735    };
736    let locate_sql = "SELECT n.nspname::text, c.relname::text \
737         FROM pg_catalog.pg_class c \
738         JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
739         WHERE c.oid = ($1::text)::regclass";
740    let row_opt = match client.query_opt(locate_sql, &[&regclass_lit]) {
741        Ok(r) => r,
742        Err(e) => {
743            log::warn!("PG numeric catalog: '{regclass_lit}' regclass lookup failed: {e}");
744            return Ok(None);
745        }
746    };
747    let Some(row) = row_opt else {
748        return Ok(None);
749    };
750    let schema: String = row.get(0);
751    let table: String = row.get(1);
752    let rows = client.query(
753        "SELECT column_name::text, data_type::text, numeric_precision, numeric_scale \
754             FROM information_schema.columns \
755             WHERE table_schema = $1 AND table_name = $2 \
756             ORDER BY ordinal_position",
757        &[&schema, &table],
758    )?;
759
760    let mut map = HashMap::new();
761    for row in rows {
762        let col: String = row.get(0);
763        let dt: String = row.get(1);
764        if !is_pg_numeric_information_type(&dt) {
765            continue;
766        }
767        let p: Option<i32> = row.get(2);
768        let s: Option<i32> = row.get(3);
769        if let (Some(p), Some(s)) = (p, s)
770            && let Some(pair) = catalog_numeric_to_decimal_params(p, s)
771        {
772            map.insert(col, pair);
773        }
774    }
775
776    if map.is_empty() {
777        Ok(None)
778    } else {
779        log::debug!(
780            "PG numeric catalog: resolved {} DECIMAL/NUMERIC column(s) for relation {regclass_lit}",
781            map.len(),
782        );
783        Ok(Some(map))
784    }
785}
786
787fn is_pg_numeric_information_type(dt: &str) -> bool {
788    let d = dt.trim().to_ascii_lowercase();
789    matches!(d.as_str(), "numeric" | "decimal")
790        || d.starts_with("numeric(")
791        || d.starts_with("decimal(")
792}
793
794/// Match Rivet YAML `decimal(p,s)` / Arrow limits (same bound as overrides).
795fn catalog_numeric_to_decimal_params(precision: i32, scale: i32) -> Option<(u8, i8)> {
796    if precision <= 0 || precision > 76 {
797        return None;
798    }
799    let precision_u = precision as u8;
800    if scale < i32::from(i8::MIN) || scale > i32::from(i8::MAX) {
801        return None;
802    }
803    let scale_i = scale as i8;
804    if scale_i > precision as i8 {
805        return None;
806    }
807    Some((precision_u, scale_i))
808}
809
810#[cfg(test)]
811mod tests {
812    use super::catalog_numeric_to_decimal_params;
813
814    // FROM-clause parser tests live in `from_parse.rs` alongside the parser.
815
816    #[test]
817    fn catalog_decimal_bounds() {
818        assert_eq!(catalog_numeric_to_decimal_params(18, 2), Some((18, 2)));
819        assert!(catalog_numeric_to_decimal_params(0, 2).is_none());
820        assert!(catalog_numeric_to_decimal_params(77, 0).is_none());
821        assert!(catalog_numeric_to_decimal_params(18, 19).is_none());
822        // W4 boundary rows — the mutants lived exactly ON the bounds:
823        // precision 76 is the LAST valid (a `> 76` -> `>= 76` mutant rejects it);
824        assert_eq!(catalog_numeric_to_decimal_params(76, 0), Some((76, 0)));
825        // scale == precision is valid (`>` not `>=` on the third check);
826        assert_eq!(catalog_numeric_to_decimal_params(18, 18), Some((18, 18)));
827        // scale == i8::MIN is the last valid negative;
828        assert_eq!(
829            catalog_numeric_to_decimal_params(10, -128),
830            Some((10, -128))
831        );
832        assert!(catalog_numeric_to_decimal_params(10, -129).is_none());
833        // an `|| -> &&` mutant on the range check lets scale=200 reach the
834        // `as i8` cast, wrapping to -56 and CORRUPTING the params silently.
835        assert!(catalog_numeric_to_decimal_params(76, 200).is_none());
836    }
837
838    #[test]
839    fn parse_work_mem_handles_pg_units() {
840        use super::parse_work_mem;
841        // Postgres SHOW work_mem normally returns "<N>kB", "<N>MB", "<N>GB".
842        // A bare integer is interpreted as kB (matches postgresql.conf parsing).
843        assert_eq!(parse_work_mem("4MB"), Some(4 * 1024 * 1024));
844        assert_eq!(parse_work_mem("16384kB"), Some(16384 * 1024));
845        assert_eq!(parse_work_mem("1GB"), Some(1024 * 1024 * 1024));
846        assert_eq!(parse_work_mem("  4MB  "), Some(4 * 1024 * 1024));
847        assert_eq!(parse_work_mem("4mb"), Some(4 * 1024 * 1024));
848        assert_eq!(parse_work_mem("65536"), Some(65536 * 1024));
849        assert_eq!(parse_work_mem(""), None);
850        assert_eq!(parse_work_mem("garbage"), None);
851        // We don't accept seconds / units PG would never emit for work_mem.
852        assert_eq!(parse_work_mem("4s"), None);
853        // W4: the TB arm and the zero guard had no rows — deleting the "tb"
854        // arm and every `*` in its multiplier survived.
855        assert_eq!(
856            parse_work_mem("2TB"),
857            Some(2 * 1024 * 1024 * 1024 * 1024),
858            "terabytes are 1024^4"
859        );
860        // Fractional values exercise the float multiply exactly.
861        assert_eq!(parse_work_mem("0.5MB"), Some(512 * 1024));
862        // Zero is rejected (`> 0`, not `>= 0`) — callers fall back.
863        assert_eq!(parse_work_mem("0"), None);
864        assert_eq!(parse_work_mem("0MB"), None);
865    }
866}