Skip to main content

fraiseql_db/postgres/adapter/
database.rs

1//! `DatabaseAdapter` and `Writer` implementations for `PostgresAdapter`.
2
3use std::{fmt::Write as _, sync::Arc};
4
5use async_trait::async_trait;
6use bytes::BufMut as _;
7use fraiseql_error::{FraiseQLError, Result};
8use tokio_postgres::{
9    Row,
10    types::{FromSql, Kind, Type},
11};
12
13use super::{
14    PostgresAdapter, build_projection_select_sql, build_where_select_sql,
15    build_where_select_sql_ordered, composed::build_composed_select_sql, jsonb_cell,
16    numeric::PgNumericText,
17};
18use crate::{
19    identifier::quote_postgres_identifier,
20    postgres::pg_detail,
21    traits::{
22        ColumnRowStream, ComposedLevel, DatabaseAdapter, JsonbRowStream, ProjectionRequest, Writer,
23    },
24    types::{
25        DatabaseType, JsonbValue, PoolMetrics, ReadRouting,
26        sql_hints::{OrderByClause, SqlProjectionHint},
27    },
28    where_clause::WhereClause,
29};
30
31/// One row a write function returned, by column.
32type RowMap = std::collections::HashMap<String, serde_json::Value>;
33
34/// One call of a write function, ready to send: its statement, its arguments, and the
35/// configuration it runs under.
36struct PreparedCall<'r> {
37    function_name:  &'r str,
38    sql:            String,
39    args:           Vec<FlexParam>,
40    configuration:  Vec<(&'r str, &'r str)>,
41    /// Names the outbox in an error message when the outbox is what ran. The messages are
42    /// the strings the error sanitizer's corpus is reduced from, and an operator reading a
43    /// failed write wants to know whether the CTE was in it.
44    mechanism:      &'static str,
45    derived:        Option<&'r crate::traits::DerivedCascade<'r>>,
46    /// Report the rows the call changed, at most this many, in the call's own flight
47    /// (#1576). Never with `derived`, whose report already says.
48    report_changes: Option<i32>,
49}
50
51impl<'r> PreparedCall<'r> {
52    fn new(adapter: &'r PostgresAdapter, request: &crate::traits::WriteRequest<'r>) -> Self {
53        let crate::traits::WriteRequest {
54            function: function_name,
55            args,
56            session_vars,
57            changelog,
58            derived_cascade,
59            report_changes,
60            ..
61        } = *request;
62        let quoted_fn = quote_postgres_identifier(function_name);
63
64        // One statement when there is an outbox row: run the function once and INSERT
65        // its outbox row in the same txn, atomically, with no extra connection acquire
66        // (Change Spine). Otherwise the plain call.
67        let sql = if let Some(cl) = changelog {
68            build_changelog_cte_sql(&quoted_fn, args.len(), cl.pre_image)
69        } else {
70            let placeholders: Vec<String> = (1..=args.len()).map(|i| format!("${i}")).collect();
71            format!("SELECT * FROM {quoted_fn}({})", placeholders.join(", "))
72        };
73
74        // Arguments bind as FlexParam: serde_json::Value only accepts JSON/JSONB types, and
75        // Option<String> only text-family types, and a function signature can mix any of
76        // them. FlexParam accepts every PostgreSQL type and sends each value in the format of
77        // the server-resolved parameter type: binary for six, text for the rest (#1547).
78        let mut flex_args: Vec<FlexParam> = args
79            .iter()
80            .map(|v| match v {
81                serde_json::Value::Null => FlexParam::Null,
82                value => FlexParam::Value(value.clone()),
83            })
84            .collect();
85        if let Some(changelog) = changelog {
86            // Function args first; then the threaded change-log envelope params —
87            // object_type fallback ($n+1), modification_type verb ($n+2), the
88            // tenant_id stamp ($n+3, bound against `::uuid`), the trace_id
89            // ($n+4, plain text), the schema_version ($n+5, plain text), the
90            // trace_context ($n+6, bound against `::jsonb`), the actor_type ($n+7,
91            // plain text), the acting_for ($n+8, bound against `::uuid`) and the
92            // transport ($n+9, plain text merged into extra_metadata — #376). Order
93            // matches build_changelog_cte_sql's positional contract; appending the
94            // envelope params keeps the SQL text stable for prepare_cached.
95            flex_args.push(FlexParam::Text(changelog.object_type.to_string()));
96            flex_args.push(FlexParam::Text(changelog.modification_type.to_string()));
97            // tenant_id: bound as text and serialised by FlexParam's UUID branch
98            // (the `::uuid` cast pins the param type); None → SQL NULL.
99            flex_args.push(
100                changelog.tenant_id.map_or(FlexParam::Null, |t| FlexParam::Text(t.to_string())),
101            );
102            // trace_id ($n+4): plain text, None → SQL NULL.
103            flex_args.push(
104                changelog.trace_id.map_or(FlexParam::Null, |t| FlexParam::Text(t.to_string())),
105            );
106            // schema_version ($n+5): plain text, None → SQL NULL.
107            flex_args.push(
108                changelog
109                    .schema_version
110                    .map_or(FlexParam::Null, |s| FlexParam::Text(s.to_string())),
111            );
112            // trace_context ($n+6): JSON text bound against `::jsonb`, None → SQL NULL.
113            flex_args.push(
114                changelog
115                    .trace_context
116                    .map_or(FlexParam::Null, |s| FlexParam::Text(s.to_string())),
117            );
118            // actor_type ($n+7): plain text, None → SQL NULL.
119            flex_args.push(
120                changelog.actor_type.map_or(FlexParam::Null, |s| FlexParam::Text(s.to_string())),
121            );
122            // acting_for ($n+8): bound as text + serialised by FlexParam's UUID branch
123            // (the `::uuid` cast pins the param type); None → SQL NULL.
124            flex_args.push(
125                changelog.acting_for.map_or(FlexParam::Null, |u| FlexParam::Text(u.to_string())),
126            );
127            // transport ($n+9): plain text merged into extra_metadata.transport by the
128            // CTE's deterministic CASE; None → SQL NULL → key omitted (#376).
129            flex_args.push(
130                changelog.transport.map_or(FlexParam::Null, |s| FlexParam::Text(s.to_string())),
131            );
132        }
133
134        // Everything the function and the outbox read of their configuration, in one
135        // statement: the session variables, the #366 marker, the timing stamp, and the
136        // `started_at` the outbox needs. Later pairs win, as when each was its own statement.
137        //
138        // The marker makes the #366 fallback-capture trigger suppress its row: this write is
139        // already logged by the outbox, and on the no-outbox path the opt-out means "no
140        // change-log row", not "let the trigger write a degraded one".
141        let mut configuration: Vec<(&str, &str)> = Vec::with_capacity(session_vars.len() + 3);
142        configuration.extend_from_slice(session_vars);
143        configuration.push((crate::changelog::CDC_MEDIATED_VAR, crate::changelog::CDC_MEDIATED_ON));
144        if adapter.mutation_timing_enabled {
145            configuration.push((
146                adapter.timing_variable_name.as_str(),
147                crate::changelog::CLOCK_TIMESTAMP_DIRECTIVE,
148            ));
149        }
150        // The outbox INSERT reads `fraiseql.started_at` with current_setting() (no
151        // missing_ok), so it must exist on this txn. The mutation runner injects it on the
152        // authenticated path; stamp it on every other one (e.g. an unauthenticated mutation
153        // that resolves no session vars), and never over a value already set. Only the
154        // outbox reads it.
155        if changelog.is_some()
156            && !configuration.iter().any(|(name, _)| *name == crate::changelog::STARTED_AT_VAR)
157        {
158            configuration.push((
159                crate::changelog::STARTED_AT_VAR,
160                crate::changelog::CLOCK_TIMESTAMP_DIRECTIVE,
161            ));
162        }
163
164        Self {
165            function_name,
166            sql,
167            args: flex_args,
168            configuration,
169            mechanism: if changelog.is_some() {
170                " (with change-log outbox)"
171            } else {
172                ""
173            },
174            derived: derived_cascade,
175            report_changes: report_changes.filter(|_| derived_cascade.is_none()),
176        }
177    }
178
179    fn params(&self) -> Vec<&(dyn tokio_postgres::types::ToSql + Sync)> {
180        self.args
181            .iter()
182            .map(|v| v as &(dyn tokio_postgres::types::ToSql + Sync))
183            .collect()
184    }
185
186    fn configuration_failed(&self, e: &tokio_postgres::Error) -> FraiseQLError {
187        let names: Vec<&str> = self.configuration.iter().map(|(name, _)| *name).collect();
188        crate::postgres::database_error(
189            format!("set_config({names:?}) failed: {}", pg_detail(e)),
190            e,
191        )
192    }
193
194    fn call_failed(&self, e: &tokio_postgres::Error) -> FraiseQLError {
195        crate::postgres::database_error(
196            format!(
197                "Function call {}{} failed: {}",
198                self.function_name,
199                self.mechanism,
200                pg_detail(e)
201            ),
202            e,
203        )
204    }
205}
206
207/// The one write (ruling AA 6): run write functions inside one explicit transaction, each
208/// with its change-log outbox row in the same statement when its request carries one, and
209/// let the gate decide the transaction's end.
210///
211/// `gate` runs on each call's rows, in order, after the call and before the transaction
212/// ends. An `Err` from it rolls back and is returned to the caller verbatim, so a refusal
213/// that could only be decided from a written row still refuses the write — every call of a
214/// batch with it (#1574). In [`WriteMode::DryRun`] everything else happens exactly as in a
215/// commit — session variables, CDC marking, the timing stamp, the outbox row, the gate — and
216/// the transaction then rolls back: a dry run exercises the write it stands in for, and
217/// nothing persists.
218///
219/// `numbered`: a database error says which call of the batch raised it.
220async fn run_functions_in_txn(
221    adapter: &PostgresAdapter,
222    requests: &[crate::traits::WriteRequest<'_>],
223    gate: crate::traits::BatchRowGate<'_>,
224    numbered: bool,
225) -> Result<Vec<Vec<RowMap>>> {
226    let Some(mode) = requests.first().map(|request| request.mode) else {
227        return Ok(Vec::new());
228    };
229    if requests.iter().any(|request| request.mode != mode) {
230        return Err(FraiseQLError::Validation {
231            message: "a batch of writes commits all of its calls or none: they must share one \
232                      write mode"
233                .to_string(),
234            path:    None,
235        });
236    }
237    let count = requests.len();
238    let at = |index: usize, error: FraiseQLError| {
239        if numbered {
240            error.in_batch_item(index, count)
241        } else {
242            error
243        }
244    };
245    let commit = matches!(mode, crate::traits::WriteMode::Commit);
246    // Arm the read-your-writes pin (entry + post-commit) — #407. A dry run writes nothing
247    // for a later read to miss.
248    if commit {
249        adapter.mark_write();
250    }
251    let calls: Vec<PreparedCall<'_>> =
252        requests.iter().map(|request| PreparedCall::new(adapter, request)).collect();
253    let configurations: Vec<_> =
254        calls.iter().map(|call| set_config_batch(&call.configuration)).collect();
255
256    let mut client = adapter.acquire_connection_with_retry().await?;
257    // Parse/plan each statement once per connection (statement cache): the call (with the
258    // outbox, a complex CTE) and the configuration, whose text depends only on how many
259    // pairs it sets and which carry the clock directive. A batch of one function prepares
260    // each text once.
261    let mut statements = Vec::with_capacity(count);
262    for (index, (call, (configure_sql, _))) in calls.iter().zip(&configurations).enumerate() {
263        let stmt = prepare_cached_stmt(&client, call.sql.as_str())
264            .await
265            .map_err(|e| at(index, e))?;
266        let configure = client
267            .prepare_cached(configure_sql)
268            .await
269            .map_err(|e| at(index, call.configuration_failed(&e)))?;
270        let report = match call.report_changes {
271            Some(_) => Some(
272                client
273                    .prepare_cached(CHANGED_ROWS_SQL)
274                    .await
275                    .map_err(|e| at(index, changes_report_failed(&e)))?,
276            ),
277            None => None,
278        };
279        statements.push((stmt, configure, report));
280    }
281    let mechanism = calls
282        .iter()
283        .find(|call| !call.mechanism.is_empty())
284        .map_or("", |call| call.mechanism);
285    let txn = client.build_transaction().start().await.map_err(|e| {
286        crate::postgres::database_error(
287            format!("Failed to start mutation{mechanism} transaction: {}", pg_detail(&e)),
288            &e,
289        )
290    })?;
291
292    // The configuration and the call in one flight (#1572): the driver sends both before
293    // reading either answer, and PostgreSQL runs them in order, so the function sees the
294    // configuration. Only once `BEGIN` is confirmed, so neither can run outside the txn.
295    // A failed configuration aborts the txn and the call with it; its own error is the one
296    // reported, not the call's "current transaction is aborted".
297    //
298    // A call that reports what it changed (#1576) sends the report in the same flight, after
299    // it: no round trip of its own.
300    let flight = |index: usize| {
301        let (call, (stmt, configure, report)) = (&calls[index], &statements[index]);
302        let configure_params = &configurations[index].1;
303        let txn = &txn;
304        async move {
305            let params = call.params();
306            let max_entities = call.report_changes.unwrap_or_default();
307            futures::join!(
308                txn.execute(configure, configure_params),
309                txn.query(stmt, params.as_slice()),
310                async {
311                    match report {
312                        Some(report) => Some(txn.query_one(report, &[&max_entities]).await),
313                        None => None,
314                    }
315                }
316            )
317        }
318    };
319    // What a flight answered, as the call's rows: its errors, then (#1391) the rows pg_tviews
320    // reports this transaction changed, read on this connection before the gate adjudicates
321    // the row they are attached to.
322    let settle = |index: usize,
323                  (configured, called, reported): (
324        std::result::Result<u64, tokio_postgres::Error>,
325        std::result::Result<Vec<Row>, tokio_postgres::Error>,
326        Option<std::result::Result<Row, tokio_postgres::Error>>,
327    )| {
328        let call = &calls[index];
329        let txn = &txn;
330        async move {
331            configured.map_err(|e| call.configuration_failed(&e))?;
332            let rows = called.map_err(|e| call.call_failed(&e))?;
333            let mut results: Vec<RowMap> = rows.iter().map(row_to_map).collect();
334            if let Some(reported) = reported {
335                let report: serde_json::Value =
336                    reported.map_err(|e| changes_report_failed(&e))?.get("report");
337                if let Some(first) = results.first_mut() {
338                    first.insert(crate::traits::CHANGED_ROWS_KEY.to_string(), report);
339                }
340            }
341            if let Some(derived) = call.derived {
342                if let Some(first) = results.first_mut() {
343                    if first.get("succeeded").and_then(serde_json::Value::as_bool) == Some(true) {
344                        let report = derived_cascade_report(txn, derived).await?;
345                        first.insert(crate::traits::DERIVED_CASCADE_KEY.to_string(), report);
346                    }
347                }
348            }
349            Ok::<_, FraiseQLError>(results)
350        }
351    };
352
353    // Every flight at once (#1574), unless a call reports a derived cascade: its report is
354    // read after its own call and before the next, so those calls go one flight at a time.
355    let answers: Vec<Option<_>> = if calls.iter().all(|call| call.derived.is_none()) {
356        in_order((0..count).map(flight).collect()).await.into_iter().map(Some).collect()
357    } else {
358        std::iter::repeat_with(|| None).take(count).collect()
359    };
360    let mut results = Vec::with_capacity(count);
361    for (index, answer) in answers.into_iter().enumerate() {
362        let answer = match answer {
363            Some(answer) => answer,
364            None => flight(index).await,
365        };
366        let rows = settle(index, answer).await.map_err(|e| at(index, e))?;
367
368        // The gate decides the commit. It sees the rows the function returned — the
369        // only thing a per-row decision can be keyed on — while they are still
370        // uncommitted, so a refusal takes the write with it rather than leaving the
371        // caller refused and the side effect standing (#1353).
372        if let Err(refusal) = gate(index, &rows) {
373            txn.rollback().await.map_err(|e| {
374                crate::postgres::database_error(
375                    format!("Failed to roll back refused mutation transaction: {}", pg_detail(&e)),
376                    &e,
377                )
378            })?;
379            return Err(refusal);
380        }
381        results.push(rows);
382    }
383
384    if !commit {
385        // The whole point of a dry run: discard every write, the outbox row included.
386        txn.rollback().await.map_err(|e| {
387            crate::postgres::database_error(
388                format!("Failed to roll back dry-run transaction: {}", pg_detail(&e)),
389                &e,
390            )
391        })?;
392        return Ok(results);
393    }
394
395    txn.commit().await.map_err(|e| {
396        crate::postgres::database_error(
397            format!("Failed to commit mutation{mechanism} transaction: {}", pg_detail(&e)),
398            &e,
399        )
400    })?;
401    adapter.mark_write();
402
403    Ok(results)
404}
405
406/// Await `futures` together, polling each for the first time in order: what one sends
407/// reaches the connection before what the next sends, so PostgreSQL runs them in that order.
408async fn in_order<F: std::future::Future>(futures: Vec<F>) -> Vec<F::Output> {
409    let mut pending: Vec<_> =
410        futures.into_iter().map(|f| Box::pin(futures::future::maybe_done(f))).collect();
411    std::future::poll_fn(|cx| {
412        let mut done = true;
413        for future in &mut pending {
414            done &= std::future::Future::poll(future.as_mut(), cx).is_ready();
415        }
416        if done {
417            std::task::Poll::Ready(())
418        } else {
419            std::task::Poll::Pending
420        }
421    })
422    .await;
423    pending.iter_mut().filter_map(|future| future.as_mut().take_output()).collect()
424}
425
426/// The report of the rows a call changed (#1576): `pg_tviews`' ids only, no row read.
427const CHANGED_ROWS_SQL: &str =
428    "SELECT tviews.pg_tviews_flush_and_report($1, false, true) AS report";
429
430fn changes_report_failed(e: &tokio_postgres::Error) -> FraiseQLError {
431    crate::postgres::database_error(
432        format!(
433            "tviews.pg_tviews_flush_and_report() failed, asked for the rows this write changed \
434             to evict the cached reads of exactly those (is pg_tviews installed and \
435             preloaded?): {}",
436            pg_detail(e)
437        ),
438        e,
439    )
440}
441
442/// Flush `pg_tviews`' queue and report the rows this transaction changed, each reported
443/// updated row read from its type's view on this connection (see
444/// [`crate::traits::DerivedCascade`]).
445///
446/// The rows of a type are read by one prepared statement, `WHERE id = ANY($1)`, and every
447/// type's read is sent in one flight (#1573): the cost does not grow with the fan-out.
448async fn derived_cascade_report(
449    txn: &deadpool_postgres::Transaction<'_>,
450    derived: &crate::traits::DerivedCascade<'_>,
451) -> Result<serde_json::Value> {
452    let report_failed = |e: &tokio_postgres::Error| {
453        crate::postgres::database_error(
454            format!(
455                "cascade_source = \"pg_tviews\": tviews.pg_tviews_flush_and_report() \
456                 failed (is pg_tviews installed and preloaded?): {}",
457                pg_detail(e)
458            ),
459            e,
460        )
461    };
462    let flush = txn
463        .prepare_cached(
464            "SELECT tviews.pg_tviews_flush_and_report($1, false, true) AS report, \
465             to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS at",
466        )
467        .await
468        .map_err(|e| report_failed(&e))?;
469    let row = txn
470        .query_one(&flush, &[&derived.max_entities])
471        .await
472        .map_err(|e| report_failed(&e))?;
473    let mut report: serde_json::Value = row.get("report");
474    let at: String = row.get("at");
475    let reported_id = |entry: &serde_json::Value| match &entry["id"] {
476        serde_json::Value::String(s) => s.clone(),
477        other => other.to_string(),
478    };
479
480    if let Some(updated) = report.get_mut("updated").and_then(serde_json::Value::as_array_mut) {
481        // The reported ids of each type a view serves, in report order.
482        let mut ids_by_view: Vec<(&str, &str, Vec<FlexParam>)> = Vec::new();
483        for entry in updated.iter() {
484            let typename = entry["__typename"].as_str().unwrap_or_default();
485            let Some((name, view)) = derived.views.iter().find(|(name, _)| *name == typename)
486            else {
487                continue;
488            };
489            let id = FlexParam::Text(reported_id(entry));
490            match ids_by_view.iter_mut().find(|(n, ..)| n == name) {
491                Some((.., ids)) => ids.push(id),
492                None => ids_by_view.push((name, view, vec![id])),
493            }
494        }
495        let reads = ids_by_view.iter().map(|(typename, view, ids)| async move {
496            let read_failed = |e: &tokio_postgres::Error| {
497                crate::postgres::database_error(
498                    format!(
499                        "cascade_source = \"pg_tviews\": reading {typename} from {view} \
500                         failed: {}",
501                        pg_detail(e)
502                    ),
503                    e,
504                )
505            };
506            // Prepared once per connection: one text per view a schema names.
507            let sql = format!(
508                "SELECT id::text AS id, data FROM {} WHERE id = ANY($1)",
509                quote_postgres_identifier(view)
510            );
511            let statement = txn.prepare_cached(&sql).await.map_err(|e| read_failed(&e))?;
512            let rows = txn.query(&statement, &[ids]).await.map_err(|e| read_failed(&e))?;
513            let by_id: std::collections::HashMap<String, serde_json::Value> =
514                rows.iter().map(|r| (r.get("id"), r.get("data"))).collect();
515            Ok::<_, FraiseQLError>((*typename, by_id))
516        });
517        let read: Vec<(&str, std::collections::HashMap<String, serde_json::Value>)> =
518            futures::future::try_join_all(reads).await?;
519
520        // A row its view did not return (not visible to this caller), or of a type no view
521        // serves, is `null`.
522        for entry in updated.iter_mut() {
523            let typename = entry["__typename"].as_str().unwrap_or_default();
524            let entity = read
525                .iter()
526                .find(|(name, _)| *name == typename)
527                .and_then(|(_, by_id)| by_id.get(&reported_id(entry)))
528                .cloned()
529                .unwrap_or(serde_json::Value::Null);
530            entry["entity"] = entity;
531        }
532    }
533    if let Some(deleted) = report.get_mut("deleted").and_then(serde_json::Value::as_array_mut) {
534        for entry in deleted.iter_mut() {
535            entry["deletedAt"] = serde_json::Value::String(at.clone());
536        }
537    }
538    Ok(report)
539}
540
541/// PostgreSQL SQLSTATE 42703: undefined column.
542const PG_UNDEFINED_COLUMN: &str = "42703";
543
544/// A flexible SQL parameter that binds to any PostgreSQL type.
545///
546/// Solves the impedance mismatch between `serde_json::Value` (only accepts JSON/JSONB)
547/// and `Option<String>` (only accepts text-family types) when binding function-call
548/// arguments whose types are resolved at runtime from the function signature.
549///
550/// Serialisation strategy:
551/// - `JSONB`: binary, a 1-byte version header (1) + UTF-8 JSON bytes
552/// - `JSON`: binary, UTF-8 JSON bytes
553/// - `UUID`: binary, 16-byte big-endian UUID
554/// - `INT4`: binary, 4-byte big-endian i32
555/// - `INT8`: binary, 8-byte big-endian i64
556/// - `BOOL`: binary, 1 byte (0 or 1)
557/// - Every other type: the **text** format, the value's UTF-8 bytes, which PostgreSQL parses with
558///   the type's own input function (#1547). A `float8`, `numeric`, `date`, `timestamp`, `interval`,
559///   an array, an enum or a domain reads its text form; the binary form of most of them is not
560///   their text (a `float8` is 8 bytes, a `date` 4), so sending the text as binary failed with
561///   `insufficient data left in message`.
562///
563/// A write function's argument is the JSON value the request carries, written for the
564/// parameter's type: a `json`/`jsonb` parameter takes it as the JSON it is (a string stays a
565/// string), an array parameter a JSON array in PostgreSQL's array syntax, `{"a","b"}`, each
566/// item parsed by the element type's input function, and any other parameter its text (a
567/// string's own characters, any other value's JSON).
568///
569/// Inside an array (`id = ANY($1)`) each element is written by [`ToSql::to_sql`] in the binary
570/// format whatever [`ToSql::encode_format`] says, so the six binary encodings stay.
571#[derive(Debug)]
572enum FlexParam {
573    /// SQL NULL — accepted by any PostgreSQL type.
574    Null,
575    /// A text-encoded value; binary-serialised according to the server-resolved type. A
576    /// `json`/`jsonb` parameter takes the text as JSON text.
577    Text(String),
578    /// A request's JSON value, written for the server-resolved type.
579    Value(serde_json::Value),
580}
581
582/// An aggregate's parameters, each written for the type the server resolves it to, as a
583/// write function's arguments are (#1620): a string compared with `data->>'region'` is text,
584/// a number compared with `SUM(qty)` (a `numeric`) its text in the text format. They were
585/// bound as `QueryParam`, whose number is text bytes sent under the binary format, which a
586/// `numeric` parameter cannot read (`insufficient data left in message`).
587fn aggregate_params(params: &[serde_json::Value]) -> Vec<FlexParam> {
588    params
589        .iter()
590        .map(|v| match v {
591            serde_json::Value::Null => FlexParam::Null,
592            value => FlexParam::Value(value.clone()),
593        })
594        .collect()
595}
596
597/// Write `text`, the text form of a value, for the parameter type `ty`: the binary form of
598/// the six types `encode_format` sends in binary, the UTF-8 bytes otherwise.
599fn write_text(
600    text: &str,
601    ty: &tokio_postgres::types::Type,
602    out: &mut bytes::BytesMut,
603) -> std::result::Result<(), Box<dyn std::error::Error + Sync + Send>> {
604    use tokio_postgres::types::Type;
605    if *ty == Type::JSONB {
606        // JSONB binary wire format: 1-byte version (1) + JSON bytes
607        out.put_u8(1);
608        out.extend_from_slice(text.as_bytes());
609    } else if *ty == Type::UUID {
610        let uuid = uuid::Uuid::parse_str(text)?;
611        out.extend_from_slice(uuid.as_bytes());
612    } else if *ty == Type::INT4 {
613        let n: i32 = text.parse()?;
614        out.put_i32(n);
615    } else if *ty == Type::INT8 {
616        let n: i64 = text.parse()?;
617        out.put_i64(n);
618    } else if *ty == Type::BOOL {
619        let b: bool = text.parse()?;
620        out.put_u8(u8::from(b));
621    } else {
622        // Sent in the text format (`encode_format`): the UTF-8 bytes, parsed by the type's
623        // input function. Also the binary form of `json` and of the text family.
624        out.extend_from_slice(text.as_bytes());
625    }
626    Ok(())
627}
628
629/// Write `items` in PostgreSQL's array syntax: every item quoted (an element type's input
630/// function reads `"1"` as it reads `1`), `NULL` for a JSON `null`, and a nested JSON array as
631/// a sub-array, unless the elements are `json`/`jsonb`, where every item is one JSON value
632/// written as its JSON text.
633fn write_array_literal(items: &[serde_json::Value], json_elements: bool, out: &mut String) {
634    out.push('{');
635    for (i, item) in items.iter().enumerate() {
636        if i > 0 {
637            out.push(',');
638        }
639        match item {
640            serde_json::Value::Null => out.push_str("NULL"),
641            serde_json::Value::Array(inner) if !json_elements => {
642                write_array_literal(inner, json_elements, out);
643            },
644            serde_json::Value::String(s) if !json_elements => quote_array_item(s, out),
645            other => quote_array_item(&other.to_string(), out),
646        }
647    }
648    out.push('}');
649}
650
651fn quote_array_item(item: &str, out: &mut String) {
652    out.push('"');
653    for c in item.chars() {
654        if c == '"' || c == '\\' {
655            out.push('\\');
656        }
657        out.push(c);
658    }
659    out.push('"');
660}
661
662/// The element type of `ty`, seen through any domains over it, when it is an array type.
663fn array_element(ty: &tokio_postgres::types::Type) -> Option<&tokio_postgres::types::Type> {
664    use tokio_postgres::types::Kind;
665    match ty.kind() {
666        Kind::Array(element) => Some(element),
667        Kind::Domain(base) => array_element(base),
668        _ => None,
669    }
670}
671
672impl tokio_postgres::types::ToSql for FlexParam {
673    fn to_sql(
674        &self,
675        ty: &tokio_postgres::types::Type,
676        out: &mut bytes::BytesMut,
677    ) -> std::result::Result<tokio_postgres::types::IsNull, Box<dyn std::error::Error + Sync + Send>>
678    {
679        use tokio_postgres::types::{IsNull, Type};
680        match self {
681            Self::Null => Ok(IsNull::Yes),
682            Self::Text(s) => {
683                write_text(s, ty, out)?;
684                Ok(IsNull::No)
685            },
686            Self::Value(value) => {
687                if *ty == Type::JSONB {
688                    out.put_u8(1);
689                    serde_json::to_writer((&mut *out).writer(), value)?;
690                } else if *ty == Type::JSON {
691                    serde_json::to_writer((&mut *out).writer(), value)?;
692                } else if let (Some(element), serde_json::Value::Array(items)) =
693                    (array_element(ty), value)
694                {
695                    let json_elements = [Type::JSONB, Type::JSON].contains(element);
696                    let mut literal = String::new();
697                    write_array_literal(items, json_elements, &mut literal);
698                    out.extend_from_slice(literal.as_bytes());
699                } else if let serde_json::Value::String(s) = value {
700                    write_text(s, ty, out)?;
701                } else {
702                    // Another type reads the JSON text with its own input function, which
703                    // accepts it (`9.5` for a `float8`) or refuses it with its own message.
704                    write_text(&value.to_string(), ty, out)?;
705                }
706                Ok(IsNull::No)
707            },
708        }
709    }
710
711    fn accepts(_ty: &tokio_postgres::types::Type) -> bool {
712        // Accepts all types; per-type serialisation is handled in `to_sql`.
713        true
714    }
715
716    fn encode_format(&self, ty: &tokio_postgres::types::Type) -> tokio_postgres::types::Format {
717        use tokio_postgres::types::{Format, Type};
718        if [
719            Type::JSONB,
720            Type::JSON,
721            Type::UUID,
722            Type::INT4,
723            Type::INT8,
724            Type::BOOL,
725        ]
726        .contains(ty)
727        {
728            Format::Binary
729        } else {
730            Format::Text
731        }
732    }
733
734    fn to_sql_checked(
735        &self,
736        ty: &tokio_postgres::types::Type,
737        out: &mut bytes::BytesMut,
738    ) -> std::result::Result<tokio_postgres::types::IsNull, Box<dyn std::error::Error + Sync + Send>>
739    {
740        // `accepts()` returns true for all types, so the standard WrongType check is
741        // unnecessary.  Delegate directly to `to_sql`.
742        self.to_sql(ty, out)
743    }
744}
745
746/// Enrich a `FraiseQLError::Database` error for PostgreSQL SQLSTATE 42703 (undefined column)
747/// when the WHERE clause contains `NativeField` conditions.
748///
749/// Native columns may be inferred automatically at compile time from `ID`/`UUID`-typed
750/// arguments.  If the column does not exist on the target table at runtime, the raw
751/// PostgreSQL error is replaced with a diagnostic message that names the native columns
752/// involved and explains how to fix the schema.
753fn enrich_undefined_column_error(
754    err: FraiseQLError,
755    view: &str,
756    where_clause: Option<&WhereClause>,
757) -> FraiseQLError {
758    let FraiseQLError::Database { ref sql_state, .. } = err else {
759        return err;
760    };
761    if sql_state.as_deref() != Some(PG_UNDEFINED_COLUMN) {
762        return err;
763    }
764    let native_cols: Vec<&str> =
765        where_clause.map(|wc| wc.native_column_names()).unwrap_or_default();
766    if native_cols.is_empty() {
767        return err;
768    }
769    FraiseQLError::Database {
770        message:    format!(
771            "Column(s) {:?} referenced as native column(s) on `{view}` do not exist. \
772             These columns were auto-inferred from ID/UUID-typed query arguments. \
773             Either add the column(s) to the table/view, or set \
774             `native_columns = {{}}` explicitly in your schema to disable inference.",
775            native_cols,
776        ),
777        sql_state:  Some(PG_UNDEFINED_COLUMN.to_string()),
778        constraint: None,
779    }
780}
781
782/// Decodes any PostgreSQL `ENUM` value as its text label.
783///
784/// `String`'s `FromSql` accepts only the text family (TEXT/VARCHAR/BPCHAR/NAME), not
785/// a custom enum OID, so an enum column otherwise falls through [`row_to_map`]'s
786/// decode ladder to `Null`. An enum's binary wire representation *is* its label as
787/// UTF-8 text, so this reads it directly (#472).
788struct PgEnumLabel(String);
789
790impl<'a> FromSql<'a> for PgEnumLabel {
791    fn from_sql(
792        _ty: &Type,
793        raw: &'a [u8],
794    ) -> std::result::Result<Self, Box<dyn std::error::Error + Sync + Send>> {
795        Ok(Self(std::str::from_utf8(raw)?.to_owned()))
796    }
797
798    fn accepts(ty: &Type) -> bool {
799        matches!(ty.kind(), Kind::Enum(_))
800    }
801}
802
803/// Accepts every PostgreSQL type and decodes none of it.
804///
805/// Read as `Option<AnyCell>`, it answers one question: is this cell SQL `NULL`. Each branch
806/// of [`decode_cell`]'s ladder refuses a `NULL` with `WasNull`, so without this a `NULL` of any
807/// type fell through to the "not representable" warning (#1514).
808struct AnyCell;
809
810impl<'a> FromSql<'a> for AnyCell {
811    fn from_sql(
812        _ty: &Type,
813        _raw: &'a [u8],
814    ) -> std::result::Result<Self, Box<dyn std::error::Error + Sync + Send>> {
815        Ok(Self)
816    }
817
818    fn accepts(_ty: &Type) -> bool {
819        true
820    }
821}
822
823/// Convert a single `tokio_postgres::Row` into a `HashMap<String, serde_json::Value>`.
824///
825/// Tries each PostgreSQL type in priority order; falls back to `Null` for
826/// types that cannot be represented as JSON.
827fn row_to_map(row: &Row) -> std::collections::HashMap<String, serde_json::Value> {
828    let mut map = std::collections::HashMap::new();
829    for (idx, column) in row.columns().iter().enumerate() {
830        map.insert(column.name().to_string(), decode_cell(row, idx));
831    }
832    map
833}
834
835/// Decode one cell of a `tokio_postgres::Row` to JSON.
836///
837/// The decode ladder itself, extracted from [`row_to_map`] so the positional
838/// reader the admin SQL console needs (#962) and the name-keyed map every other
839/// caller wants cannot disagree about what a `numeric`, an enum or a `timestamptz`
840/// becomes. A console keyed by column *name* would also collapse `SELECT 1 AS a,
841/// 2 AS a` to one column and silently drop the other.
842///
843/// Tries each PostgreSQL type in priority order; falls back to `Null` for types
844/// that cannot be represented as JSON.
845pub(super) fn decode_cell(row: &Row, idx: usize) -> serde_json::Value {
846    let column = &row.columns()[idx];
847    if matches!(row.try_get::<_, Option<AnyCell>>(idx), Ok(None)) {
848        // SQL NULL, whatever the column's type: decided once, before the ladder (#1514).
849        serde_json::Value::Null
850    } else if let Ok(v) = row.try_get::<_, i16>(idx) {
851        // SMALLINT/int2 columns (e.g. `app.mutation_response.http_status`).
852        // Without this branch a non-null int2 fell through to `Null` because
853        // `FromSql for i32` rejects int2 — which dropped `MutationError`'s
854        // `httpStatus` to absent. Order among i16/i32/i64 is correctness-
855        // neutral (each `FromSql` accepts only its own PG int width), so this
856        // sits first for readability.
857        serde_json::json!(v)
858    } else if let Ok(v) = row.try_get::<_, i32>(idx) {
859        serde_json::json!(v)
860    } else if let Ok(v) = row.try_get::<_, i64>(idx) {
861        serde_json::json!(v)
862    } else if let Ok(v) = row.try_get::<_, f64>(idx) {
863        serde_json::json!(v)
864    } else if let Ok(v) = row.try_get::<_, String>(idx) {
865        serde_json::json!(v)
866    } else if let Ok(v) = row.try_get::<_, bool>(idx) {
867        serde_json::json!(v)
868    } else if let Ok(v) = row.try_get::<_, PgNumericText>(idx) {
869        // NUMERIC/DECIMAL — decoded to PostgreSQL's exact text rendering
870        // (#980), then re-parsed as a JSON number so the value isn't forced
871        // through f64 at construction. Without this branch a `SUM(revenue)`
872        // aggregate (and every raw NUMERIC column) fell through to `Null`
873        // (H35). Falls back to a JSON string for the values whose text is
874        // not JSON numeric syntax: NaN, Infinity and -Infinity.
875        let s = v.0;
876        serde_json::from_str::<serde_json::Value>(&s).unwrap_or(serde_json::Value::String(s))
877    } else if let Ok(v) = row.try_get::<_, uuid::Uuid>(idx) {
878        // UUID columns (e.g. `app.mutation_response.entity_id`) render as the
879        // canonical hyphenated string instead of silently nulling (H35).
880        serde_json::json!(v.to_string())
881    } else if let Ok(v) = row.try_get::<_, chrono::DateTime<chrono::Utc>>(idx) {
882        // `timestamptz` → RFC 3339 / ISO 8601 text (H35).
883        serde_json::json!(v.to_rfc3339())
884    } else if let Ok(v) = row.try_get::<_, chrono::NaiveDateTime>(idx) {
885        // `timestamp` (no tz) → ISO 8601 text (H35).
886        serde_json::json!(v.to_string())
887    } else if let Ok(v) = row.try_get::<_, chrono::NaiveDate>(idx) {
888        // `date` → ISO 8601 date text (H35).
889        serde_json::json!(v.to_string())
890    } else if let Ok(v) = row.try_get::<_, Vec<String>>(idx) {
891        // TEXT[] columns (e.g. `app.mutation_response.updated_fields`) — without
892        // this branch a non-null text array falls through to Null and a parser
893        // expecting a sequence fails. Must precede the jsonb branch (a jsonb
894        // column never deserializes as Vec<String>, so ordering is safe).
895        serde_json::json!(v)
896    } else if let Ok(v) = row.try_get::<_, PgEnumLabel>(idx) {
897        // ENUM columns (e.g. `app.mutation_response.error_class`, the
898        // `app.mutation_error_class` enum) render as their text label. Without
899        // this branch a non-null enum fell through to `Null` (`String: FromSql`
900        // rejects a custom enum OID), which dropped `error_class` to absent on a
901        // failed mutation — and the parser then rejected the row with
902        // "succeeded=false requires error_class", so the typed error arm was
903        // never reached (#472). `PgEnumLabel` accepts only `Kind::Enum`, so this
904        // never shadows another branch regardless of position.
905        serde_json::json!(v.0)
906    } else if let Ok(v) = row.try_get::<_, serde_json::Value>(idx) {
907        v
908    } else {
909        // A column whose PostgreSQL type none of the branches above can
910        // decode. Name the column and its type so the next drift is visible
911        // in logs instead of a silent null (H35).
912        tracing::warn!(
913            column = %column.name(),
914            pg_type = %column.type_(),
915            "decode_cell: column type not representable as JSON; returning null"
916        );
917        serde_json::Value::Null
918    }
919}
920
921/// Apply transaction-local session variables on an in-progress transaction.
922///
923/// Every `(name, value)` pair is set with `set_config(name, value, true)`, all of them in one
924/// `SELECT`, so the values are scoped to `txn` and visible to every statement run on it (fixes
925/// #329), for one round trip whatever their number. The caller is responsible for committing or
926/// rolling back.
927pub(super) async fn apply_session_vars(
928    txn: &deadpool_postgres::Transaction<'_>,
929    session_vars: &[(&str, &str)],
930) -> Result<()> {
931    if session_vars.is_empty() {
932        return Ok(());
933    }
934    let (sql, params) = set_config_batch(session_vars);
935    // Prepared once per connection. Names and values are parameters, so the text depends only
936    // on how many variables are set and which carry the clock directive: a handful of texts per
937    // schema, none a client can mint, so unlike a read's it needs no cap.
938    let applied = match txn.prepare_cached(&sql).await {
939        Ok(statement) => txn.execute(&statement, &params).await,
940        Err(e) => Err(e),
941    };
942    applied.map_err(|e| {
943        let names: Vec<&str> = session_vars.iter().map(|(name, _)| *name).collect();
944        crate::postgres::database_error(
945            format!("set_config({names:?}) failed: {}", pg_detail(&e)),
946            &e,
947        )
948    })?;
949    Ok(())
950}
951
952/// One `SELECT set_config(…), set_config(…), …` setting every pair transaction-locally, and its
953/// parameters. Names and values are always parameters, never SQL text.
954///
955/// A var carrying the clock-timestamp directive (e.g. `fraiseql.started_at`) is stamped with the
956/// DB clock at apply time, on this very transaction, so the start timestamp and the
957/// close-of-interval at the outbox write share one clock (no app↔DB skew).
958fn set_config_batch<'a>(
959    session_vars: &'a [(&'a str, &'a str)],
960) -> (String, Vec<&'a (dyn tokio_postgres::types::ToSql + Sync)>) {
961    let mut sql = String::from("SELECT ");
962    let mut params: Vec<&(dyn tokio_postgres::types::ToSql + Sync)> =
963        Vec::with_capacity(session_vars.len() * 2);
964    for (index, (name, value)) in session_vars.iter().enumerate() {
965        if index > 0 {
966            sql.push_str(", ");
967        }
968        params.push(name);
969        let name_param = params.len();
970        if *value == crate::changelog::CLOCK_TIMESTAMP_DIRECTIVE {
971            let _ = write!(sql, "set_config(${name_param}, clock_timestamp()::text, true)");
972        } else {
973            params.push(value);
974            let _ = write!(sql, "set_config(${name_param}, ${}, true)", name_param + 1);
975        }
976    }
977    (sql, params)
978}
979
980/// Build the single statement that runs a mutation function and writes its
981/// `core.tb_entity_change_log` outbox row in the same transaction (the Change
982/// Spine transactional outbox).
983///
984/// The function call is materialised once (`WITH r AS MATERIALIZED`, so a
985/// volatile mutation function executes **exactly once** even though two CTEs
986/// read it), a data-modifying CTE INSERTs the change-log row for an effective
987/// change (`succeeded AND state_changed`), and the primary `SELECT * FROM r`
988/// returns the function's row unchanged to the caller. The changed-entity
989/// columns (`object_id`, `object_data`, `updated_fields`, `cascade`) come from
990/// the function's own `app.mutation_response` row; `$<n+1>` is the NOT-NULL
991/// `object_type` fallback, `$<n+2>` is the `modification_type` verb,
992/// `$<n+3>` is the envelope `tenant_id` (the Trinity public-facing UUID, NULL
993/// for system / unauthenticated / non-UUID-tenant rows), `$<n+4>` is the
994/// `trace_id` (the request's W3C trace id, plain text), `$<n+5>` is the
995/// `schema_version` (the compiled schema's content hash, plain text), `$<n+6>`
996/// is the `trace_context` (the full W3C trace context, cast `::jsonb`), and
997/// `$<n+9>` is the ingress `transport` (#376), merged into `extra_metadata` as
998/// `{"transport": …}` by a deterministic `CASE` (NULL omits the key, so the SQL
999/// text never depends on the value), where `n` = `n_args` (the number of
1000/// function arguments). The envelope params are
1001/// appended **after** the function args so the SQL text stays deterministic per
1002/// `(function, n_args)` — `prepare_cached` keys the statement by text, so the
1003/// column list and placeholder positions must never depend on the param *values*.
1004///
1005/// `started_at`/`duration_ms` read `fraiseql.started_at` (set txn-locally by the
1006/// caller) on the DB clock — the canonical computation from
1007/// [`crate::changelog::duration_ms_sql`], stamped with
1008/// [`crate::changelog::DURATION_CALC_VERSION`]. `commit_time` is the DB clock at
1009/// INSERT; `seq` is omitted so the column's `SEQUENCE` default fires (so any
1010/// INSERTer, incl. cooperative external producers, gets a monotonic value).
1011pub(super) fn build_changelog_cte_sql(quoted_fn: &str, n_args: usize, pre_image: bool) -> String {
1012    let placeholders: Vec<String> = (1..=n_args).map(|i| format!("${i}")).collect();
1013    let object_type_idx = n_args + 1;
1014    let modification_type_idx = n_args + 2;
1015    let tenant_id_idx = n_args + 3;
1016    let trace_id_idx = n_args + 4;
1017    let schema_version_idx = n_args + 5;
1018    let trace_context_idx = n_args + 6;
1019    let actor_type_idx = n_args + 7;
1020    let acting_for_idx = n_args + 8;
1021    let transport_idx = n_args + 9;
1022    let started_var = crate::changelog::STARTED_AT_VAR;
1023    let duration = crate::changelog::duration_ms_sql(started_var);
1024    let calc_version = crate::changelog::DURATION_CALC_VERSION;
1025    // Pre-image (opt-in, #changelog_pre_image): also record the changed entity's
1026    // before-state from the function's own `entity_before` column, alongside the
1027    // after-image `entity`. Adds `object_data_before` to the INSERT and
1028    // `r.entity_before` to the SELECT ONLY when requested — `object_data` stays
1029    // the after-image for every consumer; an absent flag emits today's SQL
1030    // byte-for-byte. No new placeholder: the before-image is a column on `r`, like
1031    // `r.entity`. The two SQL forms differ in text, so `prepare_cached` keys them
1032    // as separate statements automatically (no extra cache discriminator needed).
1033    let after_before_cols = if pre_image {
1034        "object_data, object_data_before"
1035    } else {
1036        "object_data"
1037    };
1038    let after_before_vals = if pre_image {
1039        "r.entity, r.entity_before"
1040    } else {
1041        "r.entity"
1042    };
1043    format!(
1044        "WITH r AS MATERIALIZED (SELECT * FROM {quoted_fn}({args})), \
1045         _changelog AS ( \
1046           INSERT INTO core.tb_entity_change_log \
1047             (object_type, modification_type, object_id, {after_before_cols}, \
1048              updated_fields, cascade, started_at, duration_ms, extra_metadata, \
1049              tenant_id, trace_id, schema_version, trace_context, \
1050              actor_type, acting_for, commit_time) \
1051           SELECT \
1052             COALESCE(r.entity_type, ${object_type_idx}), \
1053             ${modification_type_idx}, \
1054             r.entity_id, {after_before_vals}, r.updated_fields, r.cascade, \
1055             current_setting('{started_var}')::timestamptz, \
1056             {duration}, \
1057             jsonb_build_object('duration_calc_version', {calc_version}::int) \
1058               || CASE WHEN ${transport_idx}::text IS NULL THEN '{{}}'::jsonb \
1059                       ELSE jsonb_build_object('transport', ${transport_idx}::text) END, \
1060             ${tenant_id_idx}::uuid, \
1061             ${trace_id_idx}, \
1062             ${schema_version_idx}, \
1063             ${trace_context_idx}::jsonb, \
1064             ${actor_type_idx}, \
1065             ${acting_for_idx}::uuid, \
1066             clock_timestamp() \
1067           FROM r \
1068           WHERE r.succeeded AND r.state_changed \
1069           RETURNING 1 \
1070         ) \
1071         SELECT * FROM r",
1072        args = placeholders.join(", "),
1073    )
1074}
1075
1076/// Prepare `sql` on `client` using deadpool's **per-connection statement cache**.
1077///
1078/// The mutation function-call path sends the same statement (a fixed
1079/// `SELECT * FROM fn(...)` or the change-log CTE) on every call, so without
1080/// caching PostgreSQL re-parses and re-plans it for each mutation — the dominant
1081/// hot-path cost (the complex outbox CTE in particular). `prepare_cached` keys
1082/// the parsed/planned [`tokio_postgres::Statement`] by SQL text per connection
1083/// and reuses it across calls, so the parse/plan happens once per connection.
1084///
1085/// Returns an owned `Statement` (releasing the `&client` borrow), so it can be
1086/// prepared before `client.build_transaction()` and used inside that transaction.
1087async fn prepare_cached_stmt(
1088    client: &deadpool_postgres::Client,
1089    sql: &str,
1090) -> Result<tokio_postgres::Statement> {
1091    client.prepare_cached(sql).await.map_err(|e| {
1092        // Surface the underlying PostgreSQL diagnostic (SQLSTATE message, e.g.
1093        // `function "foo" does not exist`) rather than the opaque `db error` the
1094        // top-level `Display` renders (#451, generalised to every query path by #888).
1095        let detail = pg_detail(&e);
1096        let hint = changelog_prepare_hint(&detail);
1097        crate::postgres::database_error(format!("Failed to prepare statement: {detail}{hint}"), &e)
1098    })
1099}
1100
1101/// Actionable operator guidance for the two prepare failures every freshly
1102/// authored stack hits (#569). The bare PostgreSQL diagnostics — `relation
1103/// "core.tb_entity_change_log" does not exist` and `column r.entity_type does
1104/// not exist` — point at neither of the actual requirements: the change-log
1105/// outbox table must be installed (`fraiseql setup`), and every mutation
1106/// function must return the 13-column v2.2 `mutation_response` row the outbox
1107/// CTE reads (`r.` is that CTE's alias for the function result, so a missing
1108/// `r.*` column means the function returns some other shape — classically
1109/// `RETURNS SETOF v_*`).
1110fn changelog_prepare_hint(detail: &str) -> &'static str {
1111    if detail.contains("core.tb_entity_change_log") {
1112        "\nhint: the mutation change-log outbox table is not installed in this database — \
1113         run `fraiseql setup` (or apply the fraiseql-observers change-log contract \
1114         migration) before executing mutations"
1115    } else if detail.contains("column r.") {
1116        "\nhint: the mutation function does not return the v2.2 mutation_response row \
1117         (13 columns: succeeded, state_changed, …) that the change-log outbox reads. \
1118         `RETURNS SETOF v_*` and bare scalar returns are not supported — build the row \
1119         with fraiseql.mutation_ok()/fraiseql.mutation_err() (installed by `fraiseql \
1120         setup`); see docs/architecture/mutation-response.md"
1121    } else {
1122        ""
1123    }
1124}
1125
1126// Reason: DatabaseAdapter is defined with #[async_trait]; all implementations must match
1127// its transformed method signatures to satisfy the trait contract
1128// async_trait: dyn-dispatch required; remove when RTN + Send is stable (RFC 3425)
1129#[async_trait]
1130impl DatabaseAdapter for PostgresAdapter {
1131    // Every `*_with_session` read is overridden to apply its variables (#1115).
1132    fn applies_session_variables(&self) -> bool {
1133        true
1134    }
1135
1136    fn serves_reads_from_standbys(&self) -> bool {
1137        self.read_replicas.is_some()
1138    }
1139
1140    async fn execute_with_projection(
1141        &self,
1142        view: &str,
1143        projection: Option<&SqlProjectionHint>,
1144        where_clause: Option<&WhereClause>,
1145        limit: Option<u32>,
1146        offset: Option<u32>,
1147        order_by: Option<&[OrderByClause]>,
1148    ) -> Result<Vec<JsonbValue>> {
1149        self.execute_with_projection_impl(view, projection, where_clause, limit, offset, order_by)
1150            .await
1151    }
1152
1153    async fn execute_where_query(
1154        &self,
1155        view: &str,
1156        where_clause: Option<&WhereClause>,
1157        limit: Option<u32>,
1158        offset: Option<u32>,
1159        order_by: Option<&[OrderByClause]>,
1160    ) -> Result<Vec<JsonbValue>> {
1161        let (sql, typed_params) =
1162            build_where_select_sql_ordered(view, where_clause, limit, offset, order_by)?;
1163
1164        let param_refs = crate::types::as_sql_param_refs(&typed_params);
1165
1166        self.execute_raw(&sql, &param_refs, ReadRouting::Any)
1167            .await
1168            .map_err(|e| enrich_undefined_column_error(e, view, where_clause))
1169    }
1170
1171    async fn explain_where_query(
1172        &self,
1173        view: &str,
1174        where_clause: Option<&WhereClause>,
1175        limit: Option<u32>,
1176        offset: Option<u32>,
1177    ) -> Result<serde_json::Value> {
1178        let (select_sql, typed_params) = build_where_select_sql(view, where_clause, limit, offset)?;
1179        // Defense-in-depth: compiler-generated SQL should never contain a
1180        // semicolon, but guard against it to prevent statement injection.
1181        if select_sql.contains(';') {
1182            return Err(FraiseQLError::Validation {
1183                message: "EXPLAIN SQL must be a single statement".into(),
1184                path:    None,
1185            });
1186        }
1187        let explain_sql = format!("EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) {select_sql}");
1188
1189        let param_refs = crate::types::as_sql_param_refs(&typed_params);
1190
1191        // EXPLAIN ANALYZE of a compiled SELECT: read-only, and most truthful when
1192        // it runs where the reads it describes run — the replica route (#407).
1193        let client = self.acquire_read_connection_with_retry(ReadRouting::Any).await?;
1194        let rows = client.query(explain_sql.as_str(), &param_refs).await.map_err(|e| {
1195            crate::postgres::database_error(
1196                format!("EXPLAIN ANALYZE failed: {}", pg_detail(&e)),
1197                &e,
1198            )
1199        })?;
1200
1201        if let Some(row) = rows.first() {
1202            let plan: serde_json::Value = row.try_get(0).map_err(|e| FraiseQLError::Database {
1203                message:    format!("Failed to parse EXPLAIN output: {e}"),
1204                sql_state:  None,
1205                constraint: None,
1206            })?;
1207            Ok(plan)
1208        } else {
1209            Ok(serde_json::Value::Null)
1210        }
1211    }
1212
1213    fn database_type(&self) -> DatabaseType {
1214        DatabaseType::PostgreSQL
1215    }
1216
1217    /// `execute_composed_with_session` is implemented below.
1218    fn supports_composed_reads(&self) -> bool {
1219        true
1220    }
1221
1222    async fn tview_profiles(&self, sources: &[String]) -> Result<Vec<crate::traits::TviewProfile>> {
1223        let client = self.acquire_connection_with_retry().await?;
1224        crate::postgres::introspector::query_tview_profiles(&client, sources).await
1225    }
1226
1227    async fn schema_storage_bytes(&self, schema: &str) -> Result<Option<u64>> {
1228        let client = self.acquire_connection_with_retry().await?;
1229        // Tables and materialized views only: `pg_total_relation_size` already counts a
1230        // relation's indexes and TOAST, so listing those too would count them twice. The
1231        // schema is a bound parameter, never interpolated.
1232        let row = client
1233            .query_one(
1234                "SELECT COALESCE(sum(pg_total_relation_size(c.oid)), 0)::bigint FROM pg_class c \
1235                 JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = $1 \
1236                 AND c.relkind IN ('r', 'm')",
1237                &[&schema],
1238            )
1239            .await
1240            .map_err(|e| {
1241                crate::postgres::database_error(
1242                    format!("measuring schema {schema:?}: {}", pg_detail(&e)),
1243                    &e,
1244                )
1245            })?;
1246        let bytes: i64 = row.get(0);
1247        Ok(Some(u64::try_from(bytes).unwrap_or(0)))
1248    }
1249
1250    async fn describe_constraint(
1251        &self,
1252        violation: &fraiseql_error::ConstraintViolation,
1253    ) -> Result<crate::traits::ConstraintDescription> {
1254        // The catalog is keyed by the relation the error names; without it there is nothing
1255        // to read, and the violation is reported as given.
1256        let (Some(schema), Some(table)) = (&violation.schema, &violation.table) else {
1257            return Ok(crate::traits::ConstraintDescription {
1258                name:    violation.name.clone(),
1259                columns: None,
1260            });
1261        };
1262        let client = self.acquire_connection_with_retry().await?;
1263        // A not-null violation names its column, not its constraint: PostgreSQL 18
1264        // catalogues the not-null constraint (`contype = 'n'`), so it is found from it.
1265        let name = match (&violation.name, &violation.column) {
1266            (Some(name), _) => Some(name.clone()),
1267            (None, Some(column)) => client
1268                .query_opt(
1269                    "SELECT c.conname::text FROM pg_constraint c JOIN pg_attribute a ON \
1270                     a.attrelid = c.conrelid WHERE c.conrelid = to_regclass(format('%I.%I', \
1271                     $1::text, $2::text)) AND c.contype = 'n' AND a.attname = $3 AND c.conkey = \
1272                     ARRAY[a.attnum]",
1273                    &[schema, table, column],
1274                )
1275                .await
1276                .map_err(|e| {
1277                    crate::postgres::database_error(
1278                        format!("Failed to resolve a not-null constraint: {}", pg_detail(&e)),
1279                        &e,
1280                    )
1281                })?
1282                .map(|row| row.get(0)),
1283            (None, None) => None,
1284        };
1285        let Some(name) = name else {
1286            return Ok(crate::traits::ConstraintDescription::default());
1287        };
1288        // The key columns of the constraint, or of the unique index of that name (a partial
1289        // unique index has no `pg_constraint` row), in order. An expression column
1290        // (`attnum = 0`) makes the answer `NULL`: never guessed. `INCLUDE` columns are not
1291        // key columns.
1292        let columns: Option<Vec<String>> = client
1293            .query_one(
1294                "WITH k AS ( \
1295                   SELECT u.attnum, u.ord FROM pg_constraint c, \
1296                          unnest(c.conkey) WITH ORDINALITY u(attnum, ord) \
1297                    WHERE c.conrelid = to_regclass(format('%I.%I', $1::text, $2::text)) \
1298                      AND c.conname = $3 \
1299                   UNION ALL \
1300                   SELECT u.attnum, u.ord FROM pg_index i, \
1301                          unnest(i.indkey) WITH ORDINALITY u(attnum, ord) \
1302                    WHERE i.indexrelid = to_regclass(format('%I.%I', $1::text, $3::text)) \
1303                      AND i.indrelid = to_regclass(format('%I.%I', $1::text, $2::text)) \
1304                      AND u.ord <= i.indnkeyatts \
1305                      AND NOT EXISTS (SELECT 1 FROM pg_constraint c2 \
1306                                       WHERE c2.conrelid = i.indrelid AND c2.conname = $3)) \
1307                 SELECT CASE WHEN count(*) = 0 OR bool_or(k.attnum = 0) THEN NULL \
1308                             ELSE array_agg(a.attname::text ORDER BY k.ord) END \
1309                   FROM k LEFT JOIN pg_attribute a \
1310                     ON a.attrelid = to_regclass(format('%I.%I', $1::text, $2::text)) \
1311                    AND a.attnum = k.attnum",
1312                &[schema, table, &name],
1313            )
1314            .await
1315            .map_err(|e| {
1316                crate::postgres::database_error(
1317                    format!("Failed to resolve a constraint's columns: {}", pg_detail(&e)),
1318                    &e,
1319                )
1320            })?
1321            .get(0);
1322        Ok(crate::traits::ConstraintDescription {
1323            name: Some(name),
1324            columns,
1325        })
1326    }
1327
1328    async fn health_check(&self) -> Result<()> {
1329        // Use retry logic for health check to avoid false negatives during pool exhaustion
1330        let client = self.acquire_connection_with_retry().await?;
1331
1332        client.query("SELECT 1", &[]).await.map_err(|e| {
1333            crate::postgres::database_error(format!("Health check failed: {}", pg_detail(&e)), &e)
1334        })?;
1335
1336        Ok(())
1337    }
1338
1339    #[allow(clippy::cast_possible_truncation)] // Reason: value is bounded; truncation cannot occur in practice
1340    fn pool_metrics(&self) -> PoolMetrics {
1341        let status = self.pool.status();
1342
1343        PoolMetrics {
1344            total_connections:  status.size as u32,
1345            idle_connections:   status.available as u32,
1346            active_connections: (status.size - status.available) as u32,
1347            waiting_requests:   status.waiting as u32,
1348        }
1349    }
1350
1351    /// # Security
1352    ///
1353    /// `sql` **must** be compiler-generated. Never pass user-supplied strings
1354    /// directly — doing so would open SQL-injection vulnerabilities.
1355    async fn execute_raw_query(
1356        &self,
1357        sql: &str,
1358    ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
1359        // Use retry logic for connection acquisition
1360        let client = self.acquire_connection_with_retry().await?;
1361
1362        let rows: Vec<Row> = client.query(sql, &[]).await.map_err(|e| {
1363            crate::postgres::database_error(
1364                format!("Query execution failed: {}", pg_detail(&e)),
1365                &e,
1366            )
1367        })?;
1368
1369        // Convert each row to HashMap<String, Value>
1370        let results: Vec<std::collections::HashMap<String, serde_json::Value>> =
1371            rows.iter().map(row_to_map).collect();
1372
1373        Ok(results)
1374    }
1375
1376    async fn execute_parameterized_aggregate(
1377        &self,
1378        sql: &str,
1379        params: &[serde_json::Value],
1380    ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
1381        let typed = aggregate_params(params);
1382        let param_refs: Vec<&(dyn tokio_postgres::types::ToSql + Sync)> =
1383            typed.iter().map(|v| v as &(dyn tokio_postgres::types::ToSql + Sync)).collect();
1384
1385        // Compiled aggregate SELECT: read-only, replica-eligible (#407).
1386        let client = self.acquire_read_connection_with_retry(ReadRouting::Any).await?;
1387        let rows: Vec<Row> = client.query(sql, &param_refs).await.map_err(|e| {
1388            crate::postgres::database_error(
1389                format!("Parameterized aggregate query failed: {}", pg_detail(&e)),
1390                &e,
1391            )
1392        })?;
1393
1394        let results: Vec<std::collections::HashMap<String, serde_json::Value>> =
1395            rows.iter().map(row_to_map).collect();
1396
1397        Ok(results)
1398    }
1399
1400    async fn execute_parameterized_aggregate_with_session(
1401        &self,
1402        sql: &str,
1403        params: &[serde_json::Value],
1404        session_vars: &[(&str, &str)],
1405        routing: ReadRouting,
1406    ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
1407        if session_vars.is_empty() {
1408            return self.execute_parameterized_aggregate(sql, params).await;
1409        }
1410
1411        let typed = aggregate_params(params);
1412        let param_refs: Vec<&(dyn tokio_postgres::types::ToSql + Sync)> =
1413            typed.iter().map(|v| v as &(dyn tokio_postgres::types::ToSql + Sync)).collect();
1414
1415        // Read-only aggregate with session vars; standby-safe → replica-eligible.
1416        let mut client = self.acquire_read_connection_with_retry(routing).await?;
1417        let txn = client.build_transaction().start().await.map_err(|e| {
1418            crate::postgres::database_error(
1419                format!("Failed to start session-var transaction: {}", pg_detail(&e)),
1420                &e,
1421            )
1422        })?;
1423        apply_session_vars(&txn, session_vars).await?;
1424        let rows: Vec<Row> = txn.query(sql, &param_refs).await.map_err(|e| {
1425            crate::postgres::database_error(
1426                format!("Parameterized aggregate query failed: {}", pg_detail(&e)),
1427                &e,
1428            )
1429        })?;
1430        txn.commit().await.map_err(|e| {
1431            crate::postgres::database_error(
1432                format!("Failed to commit session-var transaction: {}", pg_detail(&e)),
1433                &e,
1434            )
1435        })?;
1436
1437        Ok(rows.iter().map(row_to_map).collect())
1438    }
1439
1440    // PostgreSQL session variables are applied connection-affinely by the
1441    // `*_with_session` methods below: `set_config(..., true)` and the operation
1442    // share one transaction on one connection, so transaction-local GUCs are
1443    // visible to the function / view (fixes #329).
1444
1445    async fn execute_where_query_arc_with_session(
1446        &self,
1447        view: &str,
1448        where_clause: Option<&WhereClause>,
1449        limit: Option<u32>,
1450        offset: Option<u32>,
1451        order_by: Option<&[OrderByClause]>,
1452        session_vars: &[(&str, &str)],
1453        routing: ReadRouting,
1454    ) -> Result<Arc<Vec<JsonbValue>>> {
1455        let (sql, typed_params) =
1456            build_where_select_sql_ordered(view, where_clause, limit, offset, order_by)?;
1457        let param_refs = crate::types::as_sql_param_refs(&typed_params);
1458
1459        // No session variables => no transaction wrapper, but still this query's
1460        // routing. The fast path used to delegate to `execute_where_query_arc`,
1461        // which has no routing parameter, so every read that happened not to carry
1462        // session variables silently reverted to server policy — `read_routing`
1463        // accepted and dropped on the most common shape there is.
1464        if session_vars.is_empty() {
1465            return self
1466                .execute_raw(&sql, &param_refs, routing)
1467                .await
1468                .map(Arc::new)
1469                .map_err(|e| enrich_undefined_column_error(e, view, where_clause));
1470        }
1471
1472        self.execute_raw_with_session(&sql, &param_refs, session_vars, routing)
1473            .await
1474            .map(Arc::new)
1475            .map_err(|e| enrich_undefined_column_error(e, view, where_clause))
1476    }
1477
1478    /// `SELECT COUNT(*)`, pushed into the database rather than counted in Rust.
1479    ///
1480    /// The trait's default fetches every matching row and takes `.len()`, which
1481    /// is correct but materialises the whole filtered set — on an unfiltered
1482    /// list that is the entire table in memory to answer a single integer.
1483    async fn count_where_query(
1484        &self,
1485        view: &str,
1486        where_clause: Option<&WhereClause>,
1487        session_vars: &[(&str, &str)],
1488        routing: ReadRouting,
1489    ) -> Result<u64> {
1490        let (sql, typed_params) = super::build_count_sql(view, where_clause)?;
1491        let param_refs = crate::types::as_sql_param_refs(&typed_params);
1492
1493        // Structurally read-only: replica-eligible, and `set_config` + SELECT are
1494        // both fine inside a hot-standby read-only transaction (#407).
1495        let row = if session_vars.is_empty() {
1496            let client = self.acquire_read_connection_with_retry(routing).await?;
1497            client.query_one(&sql, &param_refs).await.map_err(|e| {
1498                crate::postgres::database_error(
1499                    format!("Count query failed: {}", pg_detail(&e)),
1500                    &e,
1501                )
1502            })?
1503        } else {
1504            // Session variables must land on the *same* connection as the count,
1505            // or an RLS-filtered page gets an unfiltered total beside it (#329).
1506            let mut client = self.acquire_read_connection_with_retry(routing).await?;
1507            let txn = client.build_transaction().start().await.map_err(|e| {
1508                crate::postgres::database_error(
1509                    format!("Failed to start count session-var transaction: {}", pg_detail(&e)),
1510                    &e,
1511                )
1512            })?;
1513            super::database::apply_session_vars(&txn, session_vars).await?;
1514            let row = txn.query_one(&sql, &param_refs).await.map_err(|e| {
1515                crate::postgres::database_error(
1516                    format!("Count query failed: {}", pg_detail(&e)),
1517                    &e,
1518                )
1519            })?;
1520            txn.commit().await.map_err(|e| {
1521                crate::postgres::database_error(
1522                    format!("Failed to commit count session-var transaction: {}", pg_detail(&e)),
1523                    &e,
1524                )
1525            })?;
1526            row
1527        };
1528
1529        let total: i64 = row.get(0);
1530        // COUNT(*) is never negative, so the bit pattern is the value; `cast_unsigned`
1531        // states that intent where `as u64` would only imply it.
1532        Ok(total.cast_unsigned())
1533    }
1534
1535    async fn execute_with_projection_arc_with_session(
1536        &self,
1537        request: &ProjectionRequest<'_>,
1538        session_vars: &[(&str, &str)],
1539        routing: ReadRouting,
1540    ) -> Result<Arc<Vec<JsonbValue>>> {
1541        // #1314: a page that also counts what its filter matches, in one statement so the
1542        // count and the page see the same snapshot.
1543        if let Some(bound) = request.matched_up_to {
1544            let (page, params) = match request.projection {
1545                Some(projection) => build_projection_select_sql(
1546                    projection,
1547                    request.view,
1548                    request.where_clause,
1549                    request.limit,
1550                    request.offset,
1551                    request.order_by,
1552                )?,
1553                None => super::build_where_select_sql_ordered(
1554                    request.view,
1555                    request.where_clause,
1556                    request.limit,
1557                    request.offset,
1558                    request.order_by,
1559                )?,
1560            };
1561            let (sql, typed_params) = super::with_matched_count(
1562                &page,
1563                params,
1564                request.view,
1565                request.where_clause,
1566                bound,
1567            )?;
1568            let param_refs = crate::types::as_sql_param_refs(&typed_params);
1569            if session_vars.is_empty() {
1570                return self.execute_raw(&sql, &param_refs, routing).await.map(Arc::new);
1571            }
1572            return self
1573                .execute_raw_with_session(&sql, &param_refs, session_vars, routing)
1574                .await
1575                .map(Arc::new);
1576        }
1577
1578        // No projection => behave like a plain WHERE query, matching
1579        // execute_with_projection_impl's fallback.
1580        let Some(projection) = request.projection else {
1581            return self
1582                .execute_where_query_arc_with_session(
1583                    request.view,
1584                    request.where_clause,
1585                    request.limit,
1586                    request.offset,
1587                    request.order_by,
1588                    session_vars,
1589                    routing,
1590                )
1591                .await;
1592        };
1593
1594        let (sql, typed_params) = build_projection_select_sql(
1595            projection,
1596            request.view,
1597            request.where_clause,
1598            request.limit,
1599            request.offset,
1600            request.order_by,
1601        )?;
1602        tracing::debug!("SQL with projection = {}", sql);
1603        let param_refs = crate::types::as_sql_param_refs(&typed_params);
1604
1605        // See `execute_where_query_arc_with_session`: the session-free path has to
1606        // carry the routing too.
1607        if session_vars.is_empty() {
1608            return self.execute_raw(&sql, &param_refs, routing).await.map(Arc::new);
1609        }
1610
1611        self.execute_raw_with_session(&sql, &param_refs, session_vars, routing)
1612            .await
1613            .map(Arc::new)
1614    }
1615
1616    /// One statement, one snapshot, one connection held for the delivery (#958).
1617    ///
1618    /// The SQL is built by the same two builders the collecting read uses, so a
1619    /// streamed export and a buffered read of the same query cannot select
1620    /// different rows — the drift that made `execute_query_direct` disagree with
1621    /// `count_rows` about a tenant filter (#739).
1622    async fn execute_composed_with_session(
1623        &self,
1624        read: &ComposedLevel,
1625        session_vars: &[(&str, &str)],
1626        routing: ReadRouting,
1627    ) -> Result<Arc<Vec<JsonbValue>>> {
1628        let (sql, typed_params) = build_composed_select_sql(read)?;
1629        let param_refs = crate::types::as_sql_param_refs(&typed_params);
1630
1631        // See `execute_where_query_arc_with_session`: the session-free path has to
1632        // carry the routing too.
1633        if session_vars.is_empty() {
1634            return self.execute_raw(&sql, &param_refs, routing).await.map(Arc::new);
1635        }
1636
1637        self.execute_raw_with_session(&sql, &param_refs, session_vars, routing)
1638            .await
1639            .map(Arc::new)
1640    }
1641
1642    async fn stream_with_projection(
1643        &self,
1644        request: &ProjectionRequest<'_>,
1645        session_vars: &[(&str, &str)],
1646        routing: ReadRouting,
1647    ) -> Result<JsonbRowStream> {
1648        let (sql, typed_params) = match request.projection {
1649            Some(projection) => build_projection_select_sql(
1650                projection,
1651                request.view,
1652                request.where_clause,
1653                request.limit,
1654                request.offset,
1655                request.order_by,
1656            )?,
1657            None => build_where_select_sql_ordered(
1658                request.view,
1659                request.where_clause,
1660                request.limit,
1661                request.offset,
1662                request.order_by,
1663            )?,
1664        };
1665
1666        super::streaming::stream_rows(self, sql, typed_params, session_vars, routing, |row, sql| {
1667            jsonb_cell(row, 0, sql)
1668        })
1669        .await
1670        .map_err(|e| enrich_undefined_column_error(e, request.view, request.where_clause))
1671    }
1672
1673    /// The column-shaped streaming read behind gRPC server-streaming (#958).
1674    ///
1675    /// Routed to the primary like its collecting sibling: `execute_row_query`
1676    /// reaches `execute_raw_query`, and a surface that executes composed SQL is
1677    /// never sent to a replica.
1678    async fn stream_row_query(
1679        &self,
1680        view_name: &str,
1681        columns: &[crate::types::ColumnSpec],
1682        where_sql: Option<&str>,
1683        order_by: Option<&str>,
1684        limit: Option<u32>,
1685        offset: Option<u32>,
1686    ) -> Result<ColumnRowStream> {
1687        let sql = crate::traits::build_row_query_sql(view_name, where_sql, order_by, limit, offset);
1688        let columns = columns.to_vec();
1689
1690        super::streaming::stream_rows(
1691            self,
1692            sql,
1693            Vec::new(),
1694            &[],
1695            ReadRouting::Primary,
1696            move |row, _sql| Ok(crate::traits::row_to_column_values(&row_to_map(row), &columns)),
1697        )
1698        .await
1699    }
1700
1701    /// The session-pinned collecting row read (#1351).
1702    ///
1703    /// Same shape as [`count_where_query`](Self::count_where_query): with no session
1704    /// variables it is a plain read; with them it is one transaction, so `set_config`
1705    /// and the SELECT land on the same connection and an RLS policy backed by
1706    /// `current_setting()` sees them (#329).
1707    async fn execute_row_query_with_session(
1708        &self,
1709        view_name: &str,
1710        columns: &[crate::types::ColumnSpec],
1711        where_sql: Option<&str>,
1712        order_by: Option<&str>,
1713        limit: Option<u32>,
1714        offset: Option<u32>,
1715        session_vars: &[(&str, &str)],
1716    ) -> Result<Vec<Vec<crate::types::ColumnValue>>> {
1717        if session_vars.is_empty() {
1718            return self
1719                .execute_row_query(view_name, columns, where_sql, order_by, limit, offset)
1720                .await;
1721        }
1722
1723        let sql = crate::traits::build_row_query_sql(view_name, where_sql, order_by, limit, offset);
1724
1725        let mut client = self.acquire_connection_with_retry().await?;
1726        let txn = client.build_transaction().start().await.map_err(|e| {
1727            crate::postgres::database_error(
1728                format!("Failed to start row-read session-var transaction: {}", pg_detail(&e)),
1729                &e,
1730            )
1731        })?;
1732        apply_session_vars(&txn, session_vars).await?;
1733        let rows: Vec<Row> = txn.query(sql.as_str(), &[]).await.map_err(|e| {
1734            crate::postgres::database_error(
1735                format!("Row query execution failed: {}", pg_detail(&e)),
1736                &e,
1737            )
1738        })?;
1739        txn.commit().await.map_err(|e| {
1740            crate::postgres::database_error(
1741                format!("Failed to commit row-read session-var transaction: {}", pg_detail(&e)),
1742                &e,
1743            )
1744        })?;
1745
1746        Ok(rows
1747            .iter()
1748            .map(|row| crate::traits::row_to_column_values(&row_to_map(row), columns))
1749            .collect())
1750    }
1751
1752    /// The session-pinned streaming row read (#1351).
1753    ///
1754    /// `stream_rows` already pins session variables for the life of the portal —
1755    /// the non-session arm above passes `&[]` to the very same call.
1756    async fn stream_row_query_with_session(
1757        &self,
1758        view_name: &str,
1759        columns: &[crate::types::ColumnSpec],
1760        where_sql: Option<&str>,
1761        order_by: Option<&str>,
1762        limit: Option<u32>,
1763        offset: Option<u32>,
1764        session_vars: &[(&str, &str)],
1765    ) -> Result<ColumnRowStream> {
1766        let sql = crate::traits::build_row_query_sql(view_name, where_sql, order_by, limit, offset);
1767        let columns = columns.to_vec();
1768
1769        super::streaming::stream_rows(
1770            self,
1771            sql,
1772            Vec::new(),
1773            session_vars,
1774            ReadRouting::Primary,
1775            move |row, _sql| Ok(crate::traits::row_to_column_values(&row_to_map(row), &columns)),
1776        )
1777        .await
1778    }
1779
1780    async fn explain_query(
1781        &self,
1782        sql: &str,
1783        _params: &[serde_json::Value],
1784    ) -> Result<serde_json::Value> {
1785        // Defense-in-depth: reject multi-statement input even though this SQL is
1786        // compiler-generated. A semicolon would allow a second statement to be
1787        // appended to the EXPLAIN prefix.
1788        if sql.contains(';') {
1789            return Err(FraiseQLError::Validation {
1790                message: "EXPLAIN SQL must be a single statement".into(),
1791                path:    None,
1792            });
1793        }
1794        let explain_sql = format!("EXPLAIN (ANALYZE false, FORMAT JSON) {sql}");
1795        // Read-only (plan only, ANALYZE false): replica-eligible (#407).
1796        let client = self.acquire_read_connection_with_retry(ReadRouting::Any).await?;
1797        let rows: Vec<Row> = client.query(explain_sql.as_str(), &[]).await.map_err(|e| {
1798            crate::postgres::database_error(format!("EXPLAIN failed: {}", pg_detail(&e)), &e)
1799        })?;
1800
1801        if let Some(row) = rows.first() {
1802            let plan: serde_json::Value = row.try_get(0).map_err(|e| FraiseQLError::Database {
1803                message:    format!("Failed to parse EXPLAIN output: {e}"),
1804                sql_state:  None,
1805                constraint: None,
1806            })?;
1807            Ok(plan)
1808        } else {
1809            Ok(serde_json::Value::Null)
1810        }
1811    }
1812
1813    async fn query_stats(&self, limit: u32) -> Result<Vec<crate::types::QueryStatEntry>> {
1814        self.pg_query_stats(limit).await
1815    }
1816
1817    async fn query_stats_by_id(&self, id: &str) -> Result<Option<crate::types::QueryStatEntry>> {
1818        self.pg_query_stats_by_id(id).await
1819    }
1820
1821    async fn reset_query_stats(&self) -> Result<()> {
1822        self.pg_reset_query_stats().await
1823    }
1824
1825    /// The operator SQL console (#962). The containment lives in the private
1826    /// `postgres::adapter::admin_sql` module; see [`AdminSqlRequest`] for what
1827    /// each bound is and how PostgreSQL — not a parse of the statement text —
1828    /// enforces it.
1829    ///
1830    /// [`AdminSqlRequest`]: crate::traits::AdminSqlRequest
1831    async fn execute_admin_sql(
1832        &self,
1833        request: &crate::traits::AdminSqlRequest,
1834    ) -> Result<crate::traits::AdminSqlOutcome> {
1835        super::admin_sql::execute_admin_sql_impl(self, request).await
1836    }
1837}
1838
1839// async_trait: dyn-dispatch required; remove when RTN + Send is stable (RFC 3425)
1840#[async_trait]
1841impl Writer for PostgresAdapter {
1842    async fn execute_write(
1843        &self,
1844        request: &crate::traits::WriteRequest<'_>,
1845        gate: crate::traits::MutationRowGate<'_>,
1846    ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
1847        let mut rows =
1848            run_functions_in_txn(self, std::slice::from_ref(request), &|_, rows| gate(rows), false)
1849                .await?;
1850        Ok(rows.pop().unwrap_or_default())
1851    }
1852
1853    async fn execute_writes(
1854        &self,
1855        requests: &[crate::traits::WriteRequest<'_>],
1856        gate: crate::traits::BatchRowGate<'_>,
1857    ) -> Result<Vec<Vec<std::collections::HashMap<String, serde_json::Value>>>> {
1858        run_functions_in_txn(self, requests, gate, true).await
1859    }
1860}