Skip to main content

fraiseql_db/
traits.rs

1//! Database adapter trait definitions.
2//!
3//! The main [`DatabaseAdapter`] trait lives in this file. Supporting types
4//! (`RelayPageResult`, enums, type aliases) are in
5//! the `adapter_types` submodule.
6
7mod adapter_types;
8mod composed_read;
9mod mutations;
10mod relay;
11
12use std::sync::Arc;
13
14pub use adapter_types::*;
15use async_trait::async_trait;
16pub use composed_read::{
17    COMPOSED_DOCUMENT_KEY, COMPOSED_EMBEDS_KEY, ComposedEmbed, ComposedKeyset, ComposedLevel,
18    EmbedShape, EmbedSource, LevelKeys, NativeCorrelation, composed_read_unsupported,
19};
20use fraiseql_error::{FraiseQLError, Result};
21pub use mutations::{
22    CHANGED_ROWS_KEY, ChangedCollections, ChangedRows, DERIVED_CASCADE_KEY, DerivedCascade,
23    WriteMode, WriteRequest, Writer,
24};
25pub use relay::RelayDatabaseAdapter;
26
27/// A violated constraint as the catalog describes it (#1531): see
28/// [`DatabaseAdapter::describe_constraint`].
29#[derive(Debug, Clone, PartialEq, Eq, Default)]
30pub struct ConstraintDescription {
31    /// The constraint's (or unique index's) name; `None` when nothing names it.
32    pub name:    Option<String>,
33    /// Its key columns in order; `None` when they cannot be read without guessing.
34    pub columns: Option<Vec<String>>,
35}
36
37use crate::{
38    types::{
39        DatabaseType, JsonbValue, PoolMetrics, ReadRouting,
40        sql_hints::{OrderByClause, SqlProjectionHint},
41    },
42    where_clause::WhereClause,
43};
44
45/// Adjudicates the rows a mutation function returned, from **inside** the
46/// transaction that produced them and before it commits.
47///
48/// `Ok(())` commits the transaction; `Err(e)` rolls it back and `e` reaches the
49/// caller. See [`Writer::execute_write`] for why a write needs a decision seam this late
50/// (#1353).
51///
52/// Synchronous by construction: the only decision taken here today is the field
53/// authorizer's, whose `authorize_field` is itself synchronous, and holding an open
54/// transaction across an arbitrary `await` would pin a pooled connection for as long
55/// as app-supplied policy code chose to take.
56pub type MutationRowGate<'a> = &'a (
57        dyn Fn(&[std::collections::HashMap<String, serde_json::Value>]) -> Result<()> + Send + Sync
58    );
59
60/// A [`MutationRowGate`] over a batch: adjudicates the rows the call at `index` returned,
61/// for every call of [`Writer::execute_writes`], in order, before the one transaction ends.
62pub type BatchRowGate<'a> = &'a (
63        dyn Fn(usize, &[std::collections::HashMap<String, serde_json::Value>]) -> Result<()>
64            + Send
65            + Sync
66    );
67
68/// The framework-owned change-log row the mutation executor writes in-txn.
69///
70/// Carries only the fields the adapter cannot derive from the
71/// `app.mutation_response` row it already holds: the DML verb and a NOT-NULL
72/// `object_type` fallback. The changed-entity identity + payload (`object_id`,
73/// `object_data`, `updated_fields`, `cascade`) are read from the function's own
74/// returned row inside the same transaction (see [`Writer::execute_write`]).
75///
76/// This is the Change Spine transactional-outbox contract. Beyond the
77/// `object_type`/`modification_type` + changed-entity columns, it stamps the
78/// envelope: `tenant_id` (carried here, from `SecurityContext`),
79/// `trace_id` (the W3C trace id of the originating request), `schema_version`
80/// (the compiled schema's content hash — a per-deployment constant),
81/// `trace_context` (the full W3C trace context as JSON), `actor_type` /
82/// `acting_for` (the request's actor classification and, for a delegated agent,
83/// the underlying human — #390), `commit_time` (`clock_timestamp()` at INSERT),
84/// and `seq` (the table's `SEQUENCE` default).
85#[derive(Debug, Clone, Copy)]
86pub struct ChangeLogWrite<'a> {
87    /// NOT-NULL fallback for `object_type` when the row's `entity_type` is NULL.
88    /// Sourced from `MutationDefinition.return_type` (always present).
89    pub object_type:       &'a str,
90    /// The DML verb written to `modification_type` (e.g. `"INSERT"`,
91    /// `"UPDATE"`, `"DELETE"`, `"CUSTOM"`), from `MutationOperation`.
92    pub modification_type: &'a str,
93    /// The tenant partition stamp written to the `tenant_id UUID` column — the
94    /// Trinity public-facing identifier, read from `SecurityContext.tenant_id`
95    /// at write time and **never** reconstructed from connection / RLS state
96    /// (RLS is PG-only; out-of-session spine consumers bypass it, so the row
97    /// must carry tenant identity explicitly). `None` (→ SQL NULL) for an
98    /// unauthenticated request, a request with no tenant, or a tenant
99    /// identifier that is not a UUID.
100    pub tenant_id:         Option<uuid::Uuid>,
101    /// The W3C trace id of the originating request, written to the `trace_id`
102    /// column so an outbox row links back to its distributed trace (the #392
103    /// perf tooling surfaces it as the investigation handle). Read from the
104    /// request's `traceparent` header at write time; `None` (→ SQL NULL) for a
105    /// request without a trace context — e.g. an unauthenticated mutation, which
106    /// carries no `SecurityContext` to stamp.
107    pub trace_id:          Option<&'a str>,
108    /// The compiled schema's version written to the `schema_version` column so an
109    /// outbox row records which deployment produced it — the replay /
110    /// zero-downtime correctness handle for #378 (reject a row replayed under a
111    /// different schema). A per-deployment constant derived from the compiled
112    /// schema (`CompiledSchema::content_hash()`), **not** from the request, so it
113    /// changes on any schema change. `None` (→ SQL NULL) for producers with no
114    /// compiled schema in scope — cooperative external producers (ETL) and the
115    /// non-PostgreSQL no-op path.
116    pub schema_version:    Option<&'a str>,
117    /// The originating request's **full W3C trace context** as a JSON object
118    /// (`{version, trace_id, parent_id, trace_flags, tracestate?}`), written to the
119    /// `trace_context` JSONB column so a row carries enough to re-propagate /
120    /// reconstruct the distributed trace — not just the scalar `trace_id`. Carried
121    /// here as pre-serialized JSON **text** (the adapter binds it to the JSONB
122    /// column). Built from the request's `traceparent` / `tracestate` headers at
123    /// write time; `None` (→ SQL NULL) for a request without a valid trace context,
124    /// consistent with `trace_id`.
125    pub trace_context:     Option<&'a str>,
126    /// The request's actor classification written to the `actor_type` column (the
127    /// `snake_case` `ActorType` token: `"human_user"`, `"service_account"`,
128    /// `"ai_agent"`, `"system_job"`), from `SecurityContext.actor_type()` at write
129    /// time (#390). `None` (→ SQL NULL) for a request with no `SecurityContext` to
130    /// stamp (an unauthenticated mutation), or a cooperative external producer.
131    pub actor_type:        Option<&'a str>,
132    /// For a delegated agent request, the **underlying human** the agent acts for
133    /// — the public-facing UUID, written to the `acting_for UUID` column from
134    /// `SecurityContext.acting_for()` (#390). Mirrors `tenant_id`'s UUID shape so
135    /// it is stamped without a DB lookup. `None` (→ SQL NULL) for a non-delegated
136    /// request, an unauthenticated mutation, or a subject that is not UUID-shaped.
137    pub acting_for:        Option<uuid::Uuid>,
138    /// The ingress transport the originating request declared (#376), e.g.
139    /// `"mcp"` — merged into the row's `extra_metadata` JSONB as
140    /// `{"transport": …}` so MCP-originated (and, later, other
141    /// transport-tagged) writes are queryable
142    /// (`extra_metadata->>'transport' = 'mcp'`). From
143    /// `SecurityContext.transport()` at write time; `None` omits the key —
144    /// for the HTTP GraphQL path (which does not stamp one today), an
145    /// unauthenticated mutation, or a cooperative producer.
146    pub transport:         Option<&'a str>,
147    /// Whether this outbox write also records the changed entity's **pre-image**
148    /// (before-state) into the `object_data_before JSONB` column, sourced from the
149    /// function's own `entity_before` (the after-image comes from `entity`). Set
150    /// from `MutationDefinition.changelog_pre_image`; `false` (the default) leaves
151    /// `object_data_before` out of the INSERT entirely (NULL), byte-for-byte
152    /// today's behavior. The changed-entity payload itself is read from the
153    /// returned row inside the outbox CTE, so this flag only selects which SQL
154    /// form the adapter emits.
155    pub pre_image:         bool,
156}
157
158impl<'a> ChangeLogWrite<'a> {
159    /// Build a change-log write descriptor with no envelope stamps (`tenant_id`,
160    /// `trace_id`, `schema_version`, `trace_context`, `actor_type` and
161    /// `acting_for` NULL). Chain [`with_tenant_id`](Self::with_tenant_id) /
162    /// [`with_trace_id`](Self::with_trace_id) /
163    /// [`with_schema_version`](Self::with_schema_version) /
164    /// [`with_trace_context`](Self::with_trace_context) /
165    /// [`with_actor_type`](Self::with_actor_type) /
166    /// [`with_acting_for`](Self::with_acting_for) to stamp them.
167    #[must_use]
168    pub const fn new(object_type: &'a str, modification_type: &'a str) -> Self {
169        Self {
170            object_type,
171            modification_type,
172            tenant_id: None,
173            trace_id: None,
174            schema_version: None,
175            trace_context: None,
176            actor_type: None,
177            acting_for: None,
178            transport: None,
179            pre_image: false,
180        }
181    }
182
183    /// Stamp the tenant partition id (the Trinity public-facing UUID) onto the
184    /// outbox row. `None` leaves `tenant_id` NULL — for system / unauthenticated
185    /// rows, or a tenant identifier that is not UUID-shaped.
186    #[must_use]
187    pub const fn with_tenant_id(mut self, tenant_id: Option<uuid::Uuid>) -> Self {
188        self.tenant_id = tenant_id;
189        self
190    }
191
192    /// Stamp the originating request's W3C trace id onto the outbox row. `None`
193    /// leaves `trace_id` NULL — for a request with no trace context.
194    #[must_use]
195    pub const fn with_trace_id(mut self, trace_id: Option<&'a str>) -> Self {
196        self.trace_id = trace_id;
197        self
198    }
199
200    /// Stamp the compiled schema's version (its content hash) onto the outbox
201    /// row. `None` leaves `schema_version` NULL — for producers with no compiled
202    /// schema in scope (cooperative external producers, the non-PostgreSQL no-op
203    /// path).
204    #[must_use]
205    pub const fn with_schema_version(mut self, schema_version: Option<&'a str>) -> Self {
206        self.schema_version = schema_version;
207        self
208    }
209
210    /// Stamp the originating request's full W3C trace context (pre-serialized JSON
211    /// text) onto the outbox row's `trace_context` JSONB column. `None` leaves it
212    /// NULL — for a request with no valid trace context, or a non-PostgreSQL
213    /// no-op / cooperative producer.
214    #[must_use]
215    pub const fn with_trace_context(mut self, trace_context: Option<&'a str>) -> Self {
216        self.trace_context = trace_context;
217        self
218    }
219
220    /// Stamp the request's actor classification (the `snake_case` `ActorType`
221    /// token) onto the outbox row's `actor_type` column (#390). `None` leaves it
222    /// NULL — for an unauthenticated mutation or a cooperative producer.
223    #[must_use]
224    pub const fn with_actor_type(mut self, actor_type: Option<&'a str>) -> Self {
225        self.actor_type = actor_type;
226        self
227    }
228
229    /// Stamp the delegated user's UUID (the human a delegated agent acts for) onto
230    /// the outbox row's `acting_for` column (#390). `None` leaves it NULL — for a
231    /// non-delegated request, an unauthenticated mutation, or a non-UUID subject.
232    #[must_use]
233    pub const fn with_acting_for(mut self, acting_for: Option<uuid::Uuid>) -> Self {
234        self.acting_for = acting_for;
235        self
236    }
237
238    /// Stamp the ingress transport (e.g. `"mcp"`) onto the outbox row's
239    /// `extra_metadata.transport` key (#376). `None` omits the key — for a
240    /// transport that does not declare itself, an unauthenticated mutation, or
241    /// a cooperative producer.
242    #[must_use]
243    pub const fn with_transport(mut self, transport: Option<&'a str>) -> Self {
244        self.transport = transport;
245        self
246    }
247
248    /// Opt this outbox write into recording the changed entity's pre-image into
249    /// the `object_data_before` column (from the function's `entity_before`). When
250    /// `false` (the default), `object_data_before` is omitted from the INSERT
251    /// entirely, byte-for-byte today's behavior. Set from
252    /// `MutationDefinition.changelog_pre_image`.
253    #[must_use]
254    pub const fn with_pre_image(mut self, pre_image: bool) -> Self {
255        self.pre_image = pre_image;
256        self
257    }
258}
259
260/// Database adapter for executing queries against views.
261///
262/// This trait abstracts over different database backends (PostgreSQL, MySQL, SQLite, SQL Server).
263/// All implementations must support:
264/// - Executing parameterized WHERE queries against views
265/// - Returning JSONB data from the `data` column
266/// - Connection pooling and health checks
267/// - Row-level security (RLS) WHERE clauses
268///
269/// # Architecture
270///
271/// The adapter is the runtime interface to the database. It receives:
272/// - View/table name (e.g., "v_user", "tf_sales")
273/// - Parameterized WHERE clauses (AST form, not strings)
274/// - Projection hints (for performance optimization)
275/// - Pagination parameters (LIMIT/OFFSET)
276///
277/// And returns:
278/// - JSONB rows from the `data` column (most operations)
279/// - Arbitrary rows as HashMap (for aggregation queries)
280/// - Mutation results from stored procedures
281///
282/// # Implementing a New Adapter
283///
284/// To add support for a new database (e.g., Oracle, Snowflake):
285///
286/// 1. **Create a new module** in `src/db/your_database/`
287/// 2. **Implement the trait**:
288///
289///    ```rust,ignore
290///    pub struct YourDatabaseAdapter { /* fields */ }
291///
292///    #[async_trait]
293///    impl DatabaseAdapter for YourDatabaseAdapter {
294///        async fn execute_where_query(&self, ...) -> Result<Vec<JsonbValue>> {
295///            // 1. Build parameterized SQL from WhereClause AST
296///            // 2. Execute with bound parameters (NO string concatenation)
297///            // 3. Return JSONB from data column
298///        }
299///        // Implement other required methods...
300///    }
301///    ```
302/// 3. **Add feature flag** to `Cargo.toml` (e.g., `feature = "your-database"`)
303/// 4. **Copy structure from PostgreSQL adapter** — see `src/db/postgres/adapter.rs`
304/// 5. **Add tests** in `tests/integration/your_database_test.rs`
305///
306/// # Security Requirements
307///
308/// All implementations MUST:
309/// - **Never concatenate user input into SQL strings**
310/// - **Always use parameterized queries** with bind parameters
311/// - **Validate parameter types** before binding
312/// - **Preserve RLS WHERE clauses** (never filter them out)
313/// - **Return errors, not silently fail** (e.g., connection loss)
314///
315/// # Connection Management
316///
317/// - Use a connection pool (recommended: 20 connections default)
318/// - Implement `health_check()` for ping-based monitoring
319/// - Provide `pool_metrics()` for observability
320/// - Handle stale connections gracefully
321///
322/// # Performance Characteristics
323///
324/// Expected throughput when properly implemented:
325/// - **Simple queries** (single table, no WHERE): 250+ Kelem/s
326/// - **Complex queries** (JOINs, multiple conditions): 50+ Kelem/s
327/// - **Mutations** (stored procedures): 1-10 RPS (depends on procedure)
328/// - **Relay pagination** (keyset cursors): 15-30ms latency
329///
330/// # Example: PostgreSQL Implementation
331///
332/// ```rust,ignore
333/// use sqlx::postgres::PgPool;
334/// use async_trait::async_trait;
335///
336/// pub struct PostgresAdapter {
337///     pool: PgPool,
338/// }
339///
340/// #[async_trait]
341/// impl DatabaseAdapter for PostgresAdapter {
342///     async fn execute_where_query(
343///         &self,
344///         view: &str,
345///         where_clause: Option<&WhereClause>,
346///         limit: Option<u32>,
347///         offset: Option<u32>,
348///     ) -> Result<Vec<JsonbValue>> {
349///         // 1. Build SQL: SELECT data FROM {view} WHERE {where_clause} LIMIT {limit}
350///         let mut sql = format!(r#"SELECT data FROM "{}""#, view);
351///
352///         // 2. Add WHERE clause (converts AST to parameterized SQL)
353///         let params = if let Some(where_clause) = where_clause {
354///             sql.push_str(" WHERE ");
355///             let (where_sql, params) = build_where_sql(where_clause)?;
356///             sql.push_str(&where_sql);
357///             params
358///         } else {
359///             vec![]
360///         };
361///
362///         // 3. Add LIMIT and OFFSET
363///         if let Some(limit) = limit {
364///             sql.push_str(" LIMIT ");
365///             sql.push_str(&limit.to_string());
366///         }
367///         if let Some(offset) = offset {
368///             sql.push_str(" OFFSET ");
369///             sql.push_str(&offset.to_string());
370///         }
371///
372///         // 4. Execute with bound parameters (NO string interpolation)
373///         let rows: Vec<(serde_json::Value,)> = sqlx::query_as(&sql)
374///             .bind(&params[0])
375///             .bind(&params[1])
376///             // ... bind all parameters
377///             .fetch_all(&self.pool)
378///             .await?;
379///
380///         // 5. Extract JSONB and return
381///         Ok(rows.into_iter().map(|(data,)| data).collect())
382///     }
383///
384///     // Implement other required methods...
385/// }
386/// ```
387///
388/// # Example: Basic Usage
389///
390/// ```rust,no_run
391/// use fraiseql_db::{DatabaseAdapter, WhereClause, WhereOperator};
392/// use serde_json::json;
393///
394/// # async fn example(adapter: impl DatabaseAdapter) -> Result<(), Box<dyn std::error::Error>> {
395/// // Build WHERE clause (AST, not string)
396/// let where_clause = WhereClause::Field {
397///     path: vec!["email".to_string()],
398///     operator: WhereOperator::Icontains,
399///     value: json!("example.com"),
400/// };
401///
402/// // Execute query with parameters
403/// let results = adapter
404///     .execute_where_query("v_user", Some(&where_clause), Some(10), None, None)
405///     .await?;
406///
407/// println!("Found {} users matching filter", results.len());
408/// # Ok(())
409/// # }
410/// ```
411///
412/// # See Also
413///
414/// - `WhereClause` — AST for parameterized WHERE clauses
415/// - `RelayDatabaseAdapter` — Optional trait for keyset pagination
416/// - [Performance Guide](https://docs.fraiseql.rs/performance/database-adapters.md)
417// POLICY: `#[async_trait]` placement for `DatabaseAdapter`
418//
419// `DatabaseAdapter` is used both generically (`Server<A: DatabaseAdapter>` in axum
420// handlers, zero overhead via static dispatch) and dynamically (`Arc<dyn
421// DatabaseAdapter + Send + Sync>` in federation, heap-boxed future per call).
422//
423// `#[async_trait]` is required on:
424// - The trait definition (generates `Pin<Box<dyn Future + Send>>` return types)
425// - Every `impl DatabaseAdapter for ConcreteType` block (generates the boxing)
426// NOT required on callers (they see `Pin<Box<dyn Future + Send>>` from macro output).
427//
428// Why not native `async fn in trait` (Rust 1.75+)?
429// Native dyn async trait does NOT propagate `+ Send` on generated futures. Tokio
430// requires futures spawned with `tokio::spawn` to be `Send`. Until Return Type
431// Notation (RFC 3425, tracking: github.com/rust-lang/rust/issues/109417) stabilises,
432// `async_trait` is the only ergonomic path to `dyn DatabaseAdapter + Send + Sync`.
433// Re-evaluate when Rust 1.90+ ships or when RTN is stabilised.
434//
435// MIGRATION TRACKING: async-trait → native async fn in trait
436//
437// Current status: BLOCKED on RFC 3425 (Return Type Notation)
438// See: https://github.com/rust-lang/rfcs/pull/3425
439//      https://github.com/rust-lang/rust/issues/109417
440//
441// Migration is safe when ALL of the following are true:
442// 1. RTN with `+ Send` bounds is stable on rustc (e.g. `fn foo() -> impl Future + Send`)
443// 2. FraiseQL MSRV is updated to that stabilising version
444// 3. tokio::spawn() works with native dyn async trait objects (futures must be Send)
445//
446// Scope when criteria are met: 68 files (grep -rn "#\[async_trait\]" crates/)
447// Effort: Medium (mostly mechanical — remove macro from impls, adjust trait defs)
448// dynosaur was evaluated and rejected: does not propagate + Send (incompatible with Tokio)
449#[async_trait]
450pub trait DatabaseAdapter: Send + Sync + 'static {
451    /// Execute a WHERE query against a view and return JSONB rows.
452    ///
453    /// # Arguments
454    ///
455    /// * `view` - View name (e.g., "v_user", "v_post")
456    /// * `where_clause` - Optional WHERE clause AST
457    /// * `limit` - Optional row limit (for pagination)
458    /// * `offset` - Optional row offset (for pagination)
459    /// * `security_context` - Optional security context for RLS and caching decisions
460    ///
461    /// # Returns
462    ///
463    /// Vec of JSONB values from the `data` column.
464    ///
465    /// # Errors
466    ///
467    /// Returns `FraiseQLError::Database` on query execution failure.
468    /// Returns `FraiseQLError::ConnectionPool` if connection pool is exhausted.
469    ///
470    /// # Example
471    ///
472    /// ```rust,no_run
473    /// # use fraiseql_db::DatabaseAdapter;
474    /// # async fn example(adapter: impl DatabaseAdapter) -> Result<(), Box<dyn std::error::Error>> {
475    /// // Simple query without WHERE clause
476    /// let all_users = adapter
477    ///     .execute_where_query("v_user", None, Some(10), Some(0), None)
478    ///     .await?;
479    /// # Ok(())
480    /// # }
481    /// ```
482    async fn execute_where_query(
483        &self,
484        view: &str,
485        where_clause: Option<&WhereClause>,
486        limit: Option<u32>,
487        offset: Option<u32>,
488        order_by: Option<&[OrderByClause]>,
489    ) -> Result<Vec<JsonbValue>>;
490
491    /// Execute a WHERE query with SQL field projection optimization.
492    ///
493    /// Projects only the requested fields at the database level, reducing network payload
494    /// and JSON deserialization overhead by **40-55%** based on production measurements.
495    ///
496    /// This is the primary query execution method for optimized GraphQL queries.
497    /// It automatically selects only the fields requested in the GraphQL query, avoiding
498    /// unnecessary network transfer and deserialization of unused fields.
499    ///
500    /// # Automatic Projection
501    ///
502    /// In most cases, you don't call this directly. The `Executor` automatically:
503    /// 1. Determines which fields the GraphQL query requests
504    /// 2. Generates a `SqlProjectionHint` using database-specific SQL
505    /// 3. Calls this method with the projection hint
506    ///
507    /// # Arguments
508    ///
509    /// * `view` - View name (e.g., "v_user", "v_post")
510    /// * `projection` - Optional SQL projection hint with field list
511    ///   - `Some(hint)`: Use projection to select only requested fields
512    ///   - `None`: Falls back to standard query (full JSONB column)
513    /// * `where_clause` - Optional WHERE clause AST for filtering
514    /// * `limit` - Optional row limit (for pagination)
515    ///
516    /// # Returns
517    ///
518    /// Vec of JSONB values, either:
519    /// - Full objects (when projection is None)
520    /// - Projected objects with only requested fields (when projection is Some)
521    ///
522    /// # Errors
523    ///
524    /// Returns `FraiseQLError::Database` on query execution failure, including:
525    /// - Connection pool exhaustion
526    /// - SQL execution errors
527    /// - Type mismatches
528    ///
529    /// # Performance Characteristics
530    ///
531    /// When projection is provided (recommended):
532    /// - **Latency**: 40-55% reduction vs full object fetch
533    /// - **Network**: 40-55% smaller payload (proportional to unused fields)
534    /// - **Throughput**: Maintains 250+ Kelem/s (elements per second)
535    /// - **Memory**: Proportional to projected fields only
536    ///
537    /// Improvement scales with:
538    /// - Percentage of unused fields (more unused = more improvement)
539    /// - Size of result set (larger sets benefit more)
540    /// - Network latency (network-bound queries benefit most)
541    ///
542    /// When projection is None:
543    /// - Behavior identical to `execute_where_query()`
544    /// - Returns full JSONB column
545    /// - Used for compatibility/debugging
546    ///
547    /// # Database Support
548    ///
549    /// | Database | Status | Implementation |
550    /// |----------|--------|-----------------|
551    /// | PostgreSQL | ✅ Optimized | `jsonb_build_object()` |
552    /// | MySQL | ⏳ Fallback | Server-side filtering (planned) |
553    /// | SQLite | ⏳ Fallback | Server-side filtering (planned) |
554    /// | SQL Server | ⏳ Fallback | Server-side filtering (planned) |
555    ///
556    /// # Example: Direct Usage (Advanced)
557    ///
558    /// ```no_run
559    /// // Requires: running PostgreSQL database and a DatabaseAdapter implementation.
560    /// use fraiseql_db::types::SqlProjectionHint;
561    /// use fraiseql_db::traits::DatabaseAdapter;
562    /// use fraiseql_db::DatabaseType;
563    ///
564    /// # async fn example(adapter: &impl DatabaseAdapter) -> Result<(), Box<dyn std::error::Error>> {
565    /// let projection = SqlProjectionHint::new(
566    ///     DatabaseType::PostgreSQL,
567    ///     "jsonb_build_object(\
568    ///         'id', data->>'id', \
569    ///         'name', data->>'name', \
570    ///         'email', data->>'email'\
571    ///     )".to_string(),
572    ///     75,
573    /// );
574    ///
575    /// let results = adapter
576    ///     .execute_with_projection("v_user", Some(&projection), None, Some(100), None, None)
577    ///     .await?;
578    ///
579    /// // results only contain id, name, email fields
580    /// // 75% smaller than fetching all fields
581    /// # Ok(())
582    /// # }
583    /// ```
584    ///
585    /// # Example: Fallback (No Projection)
586    ///
587    /// ```no_run
588    /// // Requires: running PostgreSQL database and a DatabaseAdapter implementation.
589    /// # use fraiseql_db::traits::DatabaseAdapter;
590    /// # async fn example(adapter: &impl DatabaseAdapter) -> Result<(), Box<dyn std::error::Error>> {
591    /// // For debugging or when projection not available
592    /// let results = adapter
593    ///     .execute_with_projection("v_user", None, None, Some(100), None, None)
594    ///     .await?;
595    ///
596    /// // Equivalent to execute_where_query() - returns full objects
597    /// # Ok(())
598    /// # }
599    /// ```
600    ///
601    /// # See Also
602    ///
603    /// - `execute_where_query()` - Standard query without projection
604    /// - `SqlProjectionHint` - Structure defining field projection
605    /// - [Projection Optimization Guide](https://docs.fraiseql.rs/performance/projection-optimization.md)
606    async fn execute_with_projection(
607        &self,
608        view: &str,
609        projection: Option<&SqlProjectionHint>,
610        where_clause: Option<&WhereClause>,
611        limit: Option<u32>,
612        offset: Option<u32>,
613        order_by: Option<&[OrderByClause]>,
614    ) -> Result<Vec<JsonbValue>>;
615
616    /// Like `execute_where_query` but returns the result wrapped in an `Arc`.
617    ///
618    /// The default implementation wraps the result of `execute_where_query` in a
619    /// fresh `Arc`. `CachedDatabaseAdapter` overrides this to return the cached `Arc`
620    /// directly — eliminating the full `Vec<JsonbValue>` clone that the non-`Arc`
621    /// path requires on every cache hit.
622    ///
623    /// Callers on the hot query path should prefer this variant and borrow from the
624    /// `Arc` via `&**arc` rather than taking ownership.
625    ///
626    /// # Errors
627    ///
628    /// Same errors as `execute_where_query`.
629    async fn execute_where_query_arc(
630        &self,
631        view: &str,
632        where_clause: Option<&WhereClause>,
633        limit: Option<u32>,
634        offset: Option<u32>,
635        order_by: Option<&[OrderByClause]>,
636    ) -> Result<Arc<Vec<JsonbValue>>> {
637        self.execute_where_query(view, where_clause, limit, offset, order_by)
638            .await
639            .map(Arc::new)
640    }
641
642    /// Like `execute_with_projection` but returns the result wrapped in an `Arc`.
643    ///
644    /// The default implementation wraps the result of `execute_with_projection` in a
645    /// fresh `Arc`. `CachedDatabaseAdapter` overrides this to return the cached `Arc`
646    /// directly — eliminating the full `Vec<JsonbValue>` clone that the non-`Arc`
647    /// path requires on every cache hit.
648    ///
649    /// Parameters are passed in a `ProjectionRequest` struct (F043) so adapters
650    /// and callers cannot misorder them.
651    ///
652    /// # Errors
653    ///
654    /// Same errors as `execute_with_projection`.
655    async fn execute_with_projection_arc(
656        &self,
657        request: &ProjectionRequest<'_>,
658    ) -> Result<Arc<Vec<JsonbValue>>> {
659        self.execute_with_projection(
660            request.view,
661            request.projection,
662            request.where_clause,
663            request.limit,
664            request.offset,
665            request.order_by,
666        )
667        .await
668        .map(Arc::new)
669    }
670
671    /// Get database type (for logging/metrics).
672    ///
673    /// Used to identify which database backend is in use.
674    fn database_type(&self) -> DatabaseType;
675
676    /// Whether this adapter applies session variables to the reads that carry them (#1115).
677    ///
678    /// The `*_with_session` defaults cannot: they delegate to the session-free read. Rather
679    /// than drop the variables, which would read unscoped where an RLS policy reads
680    /// `current_setting`, they refuse a non-empty set unless the adapter declares it applies
681    /// them, by overriding them (the PostgreSQL adapter) or by being a test double. The
682    /// server refuses at boot a schema that needs them (`[locale]`, session variables) on an
683    /// adapter that does not.
684    fn applies_session_variables(&self) -> bool {
685        false
686    }
687
688    /// Whether reads may be served by a hot standby — read replicas are configured (#1390).
689    ///
690    /// A standby cannot read an UNLOGGED or temporary relation, so a server whose reads go
691    /// to replicas checks at boot that none of its sources depends on one. A wrapper
692    /// adapter must forward this to the adapter it wraps: inheriting the default would
693    /// switch that check off.
694    fn serves_reads_from_standbys(&self) -> bool {
695        false
696    }
697
698    /// Health check - verify database connectivity.
699    ///
700    /// Executes a simple query (e.g., `SELECT 1`) to verify the database is reachable.
701    ///
702    /// # Errors
703    ///
704    /// Returns `FraiseQLError::Database` if health check fails.
705    async fn health_check(&self) -> Result<()>;
706
707    /// Get connection pool metrics.
708    ///
709    /// Returns current statistics about the connection pool:
710    /// - Total connections
711    /// - Idle connections
712    /// - Active connections
713    /// - Waiting requests
714    fn pool_metrics(&self) -> PoolMetrics;
715
716    /// Execute raw SQL query and return rows as JSON objects.
717    ///
718    /// Used for aggregation queries where we need full row data, not just JSONB column.
719    ///
720    /// # Security Warning
721    ///
722    /// This method executes arbitrary SQL. **NEVER** pass untrusted input directly to this method.
723    /// Always:
724    /// - Use parameterized queries with bound parameters
725    /// - Validate and sanitize SQL templates before execution
726    /// - Only execute SQL generated by the FraiseQL compiler
727    /// - Log SQL execution for audit trails
728    ///
729    /// # Arguments
730    ///
731    /// * `sql` - Raw SQL query to execute (must be safe/trusted)
732    ///
733    /// # Returns
734    ///
735    /// Vec of rows, where each row is a HashMap of column name to JSON value.
736    ///
737    /// # Errors
738    ///
739    /// Returns `FraiseQLError::Database` on query execution failure.
740    ///
741    /// # Example
742    ///
743    /// ```rust,no_run
744    /// # use fraiseql_db::DatabaseAdapter;
745    /// # async fn example(adapter: impl DatabaseAdapter) -> Result<(), Box<dyn std::error::Error>> {
746    /// // Safe: SQL generated by FraiseQL compiler
747    /// let sql = "SELECT category, SUM(revenue) as total FROM tf_sales GROUP BY category";
748    /// let rows = adapter.execute_raw_query(sql).await?;
749    /// for row in rows {
750    ///     println!("Category: {}, Total: {}", row["category"], row["total"]);
751    /// }
752    /// # Ok(())
753    /// # }
754    /// ```
755    async fn execute_raw_query(
756        &self,
757        sql: &str,
758    ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>>;
759
760    /// Execute a row-shaped query against a view, returning typed column values.
761    ///
762    /// Used by the gRPC transport for protobuf encoding of query results.
763    /// The default implementation delegates to `execute_raw_query` and converts
764    /// JSON results to `ColumnValue` vectors.
765    ///
766    /// # Errors
767    ///
768    /// Returns `FraiseQLError::Database` if the adapter returns an error.
769    async fn execute_row_query(
770        &self,
771        view_name: &str,
772        columns: &[crate::types::ColumnSpec],
773        where_sql: Option<&str>,
774        order_by: Option<&str>,
775        limit: Option<u32>,
776        offset: Option<u32>,
777    ) -> Result<Vec<Vec<crate::types::ColumnValue>>> {
778        let sql = build_row_query_sql(view_name, where_sql, order_by, limit, offset);
779        let results = self.execute_raw_query(&sql).await?;
780
781        Ok(results.iter().map(|row| row_to_column_values(row, columns)).collect())
782    }
783
784    /// Connection-affine variant of [`execute_row_query`](Self::execute_row_query).
785    ///
786    /// See
787    /// [`execute_where_query_arc_with_session`](Self::execute_where_query_arc_with_session)
788    /// for the rationale: an RLS policy backed by `current_setting()` (#329) only sees
789    /// the variables if they are applied transaction-locally on the **same** connection
790    /// as the read.
791    ///
792    /// # Why the row shape needs its own pair
793    ///
794    /// The row-shaped read is the gRPC transport's source. Until #1351 it resolved its
795    /// own predicate and never reached the engine, so it had no session variables to
796    /// pin and none of these methods existed. Routing it through the direct-read
797    /// chokepoint gives it `session_variables` like every other read — and a resolved
798    /// value the read cannot apply is the failure mode the chokepoint exists to
799    /// prevent, so it travels rather than being dropped.
800    ///
801    /// # Errors
802    ///
803    /// Same errors as [`execute_row_query`](Self::execute_row_query); additionally
804    /// returns `FraiseQLError::Database` if `set_config` fails on any pair.
805    async fn execute_row_query_with_session(
806        &self,
807        view_name: &str,
808        columns: &[crate::types::ColumnSpec],
809        where_sql: Option<&str>,
810        order_by: Option<&str>,
811        limit: Option<u32>,
812        offset: Option<u32>,
813        session_vars: &[(&str, &str)],
814    ) -> Result<Vec<Vec<crate::types::ColumnValue>>> {
815        refuse_session_variables(self, session_vars)?;
816        self.execute_row_query(view_name, columns, where_sql, order_by, limit, offset)
817            .await
818    }
819
820    /// Execute a parameterized aggregate SQL query (GROUP BY / HAVING / window).
821    ///
822    /// `sql` contains `$N` (PostgreSQL), `?` (MySQL / SQLite), or `@P1` (SQL Server)
823    /// placeholders for string and array values; numeric and NULL values may be inlined.
824    /// `params` are the corresponding values in placeholder order.
825    ///
826    /// Unlike `execute_raw_query`, this method accepts bind parameters so that
827    /// user-supplied filter values never appear as string literals in the SQL text,
828    /// eliminating the injection risk that `escape_sql_string` mitigated previously.
829    ///
830    /// # Arguments
831    ///
832    /// * `sql` - SQL with placeholders generated by
833    ///   `AggregationSqlGenerator::generate_parameterized`
834    /// * `params` - Bind parameters in placeholder order
835    ///
836    /// # Returns
837    ///
838    /// Vec of rows, where each row is a `HashMap` of column name to JSON value.
839    ///
840    /// # Errors
841    ///
842    /// Returns `FraiseQLError::Database` on execution failure.
843    /// Returns `FraiseQLError::Database` on adapters that do not support raw SQL
844    /// (e.g., `FraiseWireAdapter`).
845    async fn execute_parameterized_aggregate(
846        &self,
847        sql: &str,
848        params: &[serde_json::Value],
849    ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>>;
850
851    /// Connection-affine variant of
852    /// [`execute_parameterized_aggregate`](Self::execute_parameterized_aggregate).
853    ///
854    /// Applies `session_vars` transaction-locally on the same connection that
855    /// runs the aggregate, so aggregate views backed by `current_setting()` RLS
856    /// observe the configured values (fixes #329 for the aggregate path). The default
857    /// ignores `session_vars`: a backend without transaction-local settings has none to
858    /// apply.
859    ///
860    /// # Errors
861    ///
862    /// Same errors as [`execute_parameterized_aggregate`](Self::execute_parameterized_aggregate);
863    /// additionally returns `FraiseQLError::Database` if `set_config` fails.
864    async fn execute_parameterized_aggregate_with_session(
865        &self,
866        sql: &str,
867        params: &[serde_json::Value],
868        session_vars: &[(&str, &str)],
869        _routing: ReadRouting,
870    ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
871        refuse_session_variables(self, session_vars)?;
872        self.execute_parameterized_aggregate(sql, params).await
873    }
874
875    /// Whether this adapter implements
876    /// [`execute_composed_with_session`](Self::execute_composed_with_session) — whether a
877    /// read can have related resources composed into it (the REST `?select=` embed).
878    ///
879    /// Asked twice, of one answer: when the REST transport is mounted, so a deployment
880    /// whose adapter cannot serve embeds is told at boot rather than by its first embed;
881    /// and by the engine before a composed read is sent, so the `501` a request gets is
882    /// that same fact rather than a second one.
883    ///
884    /// **Implementing `execute_composed_with_session` obliges you to override this too**,
885    /// and a wrapping adapter must forward both. Defaults to `false`: a capability is not
886    /// something a backend should acquire by omission.
887    fn supports_composed_reads(&self) -> bool {
888        false
889    }
890
891    /// What a constraint violation's typed error reports about its constraint (#1531),
892    /// resolved from the catalog where the error itself does not say.
893    ///
894    /// A not-null violation names its column only; its catalogued not-null constraint is
895    /// found from that column. `columns` is the constraint's (or unique index's) key columns,
896    /// in order, and `None` when they cannot be read off the catalog without guessing (an
897    /// expression index). Read on the failure path, on a connection of its own: the
898    /// mutation's transaction has already rolled back.
899    ///
900    /// The default reports the violation as the error gave it: its name, no columns. **A
901    /// wrapping adapter must forward this**, or a deployment configured for full metadata
902    /// loses the columns in silence.
903    ///
904    /// # Errors
905    ///
906    /// The database errors of the catalog read.
907    async fn describe_constraint(
908        &self,
909        violation: &fraiseql_error::ConstraintViolation,
910    ) -> Result<ConstraintDescription> {
911        Ok(ConstraintDescription {
912            name:    violation.name.clone(),
913            columns: None,
914        })
915    }
916
917    /// The physical health of every TVIEW one of `sources` reads (#1392), from
918    /// `tviews.pg_tviews_profile()`; empty when there is none, or no `pg_tviews`.
919    ///
920    /// The default reports none. **A wrapping adapter must forward this**, or `/metrics`
921    /// loses the TVIEW health in silence.
922    ///
923    /// # Errors
924    ///
925    /// The database errors of the catalog read.
926    async fn tview_profiles(&self, _sources: &[String]) -> Result<Vec<TviewProfile>> {
927        Ok(Vec::new())
928    }
929
930    /// The bytes schema `schema` occupies (#633): every table and materialized view in it,
931    /// their indexes and TOAST included. `None` from an adapter that cannot measure it.
932    ///
933    /// The default measures nothing. **A wrapping adapter must forward this**, or a
934    /// tenant's storage quota is never measured, and so never enforced.
935    ///
936    /// # Errors
937    ///
938    /// The database errors of the catalog read.
939    async fn schema_storage_bytes(&self, _schema: &str) -> Result<Option<u64>> {
940        Ok(None)
941    }
942
943    /// Invalidate cached query results for the specified views.
944    ///
945    /// Called by the executor after a mutation succeeds, so that stale cache
946    /// entries reading from modified views are evicted. The default
947    /// implementation is a no-op; `CachedDatabaseAdapter` overrides this.
948    ///
949    /// View names are passed as `&[ViewName]` so the wrapper's `Arc<str>`
950    /// backing is preserved across the call. Callers that hold a `String`
951    /// can convert in place with `ViewName::from(...)`.
952    ///
953    /// # Returns
954    ///
955    /// The number of cache entries evicted.
956    async fn invalidate_views(&self, _views: &[crate::ViewName]) -> Result<u64> {
957        Ok(0)
958    }
959
960    /// Whether a write should report the rows it changed ([`ChangedRows`], #1576), for
961    /// [`invalidate_written`](Self::invalidate_written). A wrapper adapter must forward this
962    /// to the adapter it wraps.
963    fn reports_changed_rows(&self) -> bool {
964        false
965    }
966
967    /// [`invalidate_views`](Self::invalidate_views), after a write whose changed rows are
968    /// all in `changed`: an adapter may evict reads of single rows by those rows rather than
969    /// by the views. Provided: `invalidate_views`. A wrapper adapter must forward this to the
970    /// adapter it wraps.
971    ///
972    /// # Returns
973    ///
974    /// The number of cache entries evicted.
975    async fn invalidate_written(
976        &self,
977        views: &[crate::ViewName],
978        _changed: &ChangedRows,
979    ) -> Result<u64> {
980        self.invalidate_views(views).await
981    }
982
983    /// Evict cache entries that contain the given entity UUID.
984    ///
985    /// Called by the executor after a successful UPDATE or DELETE mutation when
986    /// the `mutation_response` includes an `entity_id`. Only cache entries whose
987    /// entity-ID index contains the given UUID are removed; unrelated entries
988    /// remain warm.
989    ///
990    /// The default implementation is a no-op. `CachedDatabaseAdapter` overrides
991    /// this to perform the selective eviction.
992    ///
993    /// # Returns
994    ///
995    /// The number of cache entries evicted.
996    async fn invalidate_by_entity(&self, _entity_type: &str, _entity_id: &str) -> Result<u64> {
997        Ok(0)
998    }
999
1000    /// A snapshot of this adapter's query-result cache, or `None` if it has none.
1001    ///
1002    /// The operator surface for the cache that actually serves GraphQL queries.
1003    /// `None` means "this adapter does not cache" — distinct from `Some(stats)` with
1004    /// zero entries, which means "the cache is there and currently empty". The admin
1005    /// API reported the second as the first for every non-Arrow deployment (#941).
1006    ///
1007    /// The default implementation returns `None`; `CachedDatabaseAdapter` overrides it.
1008    fn result_cache_stats(&self) -> Option<crate::ResultCacheStats> {
1009        None
1010    }
1011
1012    /// Drop every entry in this adapter's query-result cache.
1013    ///
1014    /// Returns the number of entries dropped, or `None` if this adapter has no cache
1015    /// — again so the caller can say "there is no such cache" rather than reporting a
1016    /// successful clear of nothing.
1017    ///
1018    /// The default implementation returns `Ok(None)`; `CachedDatabaseAdapter` overrides it.
1019    ///
1020    /// # Errors
1021    ///
1022    /// Returns `FraiseQLError` if the underlying cache cannot be cleared.
1023    async fn clear_result_cache(&self) -> Result<Option<usize>> {
1024        Ok(None)
1025    }
1026
1027    /// Run the database's `EXPLAIN` on a SQL statement without executing it.
1028    ///
1029    /// Returns a JSON representation of the query plan. The format is
1030    /// database-specific (e.g. PostgreSQL returns JSON, SQLite returns rows).
1031    ///
1032    /// The default implementation returns `Unsupported`.
1033    async fn explain_query(
1034        &self,
1035        _sql: &str,
1036        _params: &[serde_json::Value],
1037    ) -> Result<serde_json::Value> {
1038        Err(fraiseql_error::FraiseQLError::Unsupported {
1039            message: "EXPLAIN not available for this database adapter".to_string(),
1040        })
1041    }
1042
1043    /// Run `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)` against a view with the
1044    /// same parameterized WHERE clause that `execute_where_query` would use.
1045    ///
1046    /// Unlike `explain_query`, this method uses **real bound parameters** and
1047    /// **actually executes the query** (ANALYZE mode), so the plan reflects
1048    /// PostgreSQL's runtime statistics for the given filter values.
1049    ///
1050    /// Only PostgreSQL supports this; other adapters return
1051    /// `FraiseQLError::Unsupported` by default.
1052    ///
1053    /// # Arguments
1054    ///
1055    /// * `view` - View name (e.g., "v_user")
1056    /// * `where_clause` - Optional filter (same as `execute_where_query`)
1057    /// * `limit` - Optional row limit
1058    /// * `offset` - Optional row offset
1059    ///
1060    /// # Errors
1061    ///
1062    /// Returns `FraiseQLError::Database` on execution failure.
1063    /// Returns `FraiseQLError::Unsupported` for non-PostgreSQL adapters.
1064    async fn explain_where_query(
1065        &self,
1066        _view: &str,
1067        _where_clause: Option<&WhereClause>,
1068        _limit: Option<u32>,
1069        _offset: Option<u32>,
1070    ) -> Result<serde_json::Value> {
1071        Err(fraiseql_error::FraiseQLError::Unsupported {
1072            message: "EXPLAIN ANALYZE is not available for this database adapter. \
1073                      Only PostgreSQL supports explain_where_query."
1074                .to_string(),
1075        })
1076    }
1077
1078    /// Connection-affine variant of [`execute_where_query_arc`](Self::execute_where_query_arc).
1079    ///
1080    /// Applies `session_vars` transaction-locally on the same connection that
1081    /// runs the read, so PostgreSQL Row-Level-Security policies backed by
1082    /// `current_setting()` see the configured values (fixes #329). The default ignores
1083    /// `session_vars`: a backend without transaction-local settings has none to apply.
1084    ///
1085    /// # Errors
1086    ///
1087    /// Same errors as [`execute_where_query_arc`](Self::execute_where_query_arc); additionally
1088    /// returns `FraiseQLError::Database` if `set_config` fails on any pair.
1089    async fn execute_where_query_arc_with_session(
1090        &self,
1091        view: &str,
1092        where_clause: Option<&WhereClause>,
1093        limit: Option<u32>,
1094        offset: Option<u32>,
1095        order_by: Option<&[OrderByClause]>,
1096        session_vars: &[(&str, &str)],
1097        _routing: ReadRouting,
1098    ) -> Result<Arc<Vec<JsonbValue>>> {
1099        refuse_session_variables(self, session_vars)?;
1100        self.execute_where_query_arc(view, where_clause, limit, offset, order_by).await
1101    }
1102
1103    /// Count the rows of `view` matching `where_clause`, without materialising them.
1104    ///
1105    /// Backs both the GraphQL `<name>Count` sibling (#938) and the REST
1106    /// `Prefer: count=exact` header, so the two cannot answer the same question
1107    /// differently.
1108    ///
1109    /// `session_vars` are applied transaction-locally on the connection that
1110    /// runs the count, exactly as for the read it describes (#329). This is
1111    /// load-bearing rather than symmetric-for-neatness: under RLS, a count that
1112    /// ran without the session variables would report the *unfiltered* total
1113    /// beside a filtered page — a row-count oracle over rows the caller cannot
1114    /// read.
1115    ///
1116    /// # Default implementation
1117    ///
1118    /// The default fetches the matching rows and counts them. That is *correct*
1119    /// — same view, same predicate, same session — but it is O(rows) in memory,
1120    /// so an adapter that can push the count into the database should override
1121    /// it. `PostgresAdapter` does, with `SELECT COUNT(*)`.
1122    ///
1123    /// # Errors
1124    ///
1125    /// Returns `FraiseQLError::Database` if the query fails.
1126    async fn count_where_query(
1127        &self,
1128        view: &str,
1129        where_clause: Option<&WhereClause>,
1130        session_vars: &[(&str, &str)],
1131        routing: ReadRouting,
1132    ) -> Result<u64> {
1133        let rows = self
1134            .execute_where_query_arc_with_session(
1135                view,
1136                where_clause,
1137                None,
1138                None,
1139                None,
1140                session_vars,
1141                routing,
1142            )
1143            .await?;
1144        Ok(rows.len() as u64)
1145    }
1146
1147    /// Connection-affine variant of
1148    /// [`execute_with_projection_arc`](Self::execute_with_projection_arc).
1149    ///
1150    /// See [`execute_where_query_arc_with_session`](Self::execute_where_query_arc_with_session) for
1151    /// the rationale.
1152    ///
1153    /// # Errors
1154    ///
1155    /// Same errors as [`execute_with_projection_arc`](Self::execute_with_projection_arc);
1156    /// additionally returns `FraiseQLError::Database` if `set_config` fails on any pair.
1157    async fn execute_with_projection_arc_with_session(
1158        &self,
1159        request: &ProjectionRequest<'_>,
1160        session_vars: &[(&str, &str)],
1161        _routing: ReadRouting,
1162    ) -> Result<Arc<Vec<JsonbValue>>> {
1163        refuse_session_variables(self, session_vars)?;
1164        self.execute_with_projection_arc(request).await
1165    }
1166
1167    /// The same read as
1168    /// [`execute_with_projection_arc_with_session`](Self::execute_with_projection_arc_with_session),
1169    /// delivered row by row instead of as a materialised `Vec` (#958).
1170    ///
1171    /// Same view, same predicate, same session variables, same routing. The only
1172    /// difference is *when* the rows arrive and how much memory the caller needs
1173    /// to hold them: a streamed read is `O(1)` in the number of rows, so an export
1174    /// of a table larger than memory is possible where the collecting method would
1175    /// have to fail.
1176    ///
1177    /// # Why this exists as its own method
1178    ///
1179    /// A paginated re-execution loop (`LIMIT n OFFSET k`, `k += n`) delivers the
1180    /// same rows in bounded memory and needs no new trait method, and that is what
1181    /// the export surfaces did. It has two properties a stream does not:
1182    ///
1183    /// - it is `O(offset)` per batch, so exporting `N` rows costs `O(N²)` row scans;
1184    /// - each batch is its own snapshot, so a concurrent insert or delete between batches shifts
1185    ///   rows across the page boundary — silently duplicating a row into two batches, or skipping
1186    ///   one entirely.
1187    ///
1188    /// One statement over one portal has neither problem.
1189    ///
1190    /// # Default implementation
1191    ///
1192    /// Collects the read and replays it. That is *correct* — same rows, same order —
1193    /// but it holds the whole result set, so an adapter that can stream should
1194    /// override it. `PostgresAdapter` does.
1195    ///
1196    /// ⚠ A wrapping adapter (caching, instrumentation) that inherits this default
1197    /// converts every streaming caller back into a buffering one **without failing**:
1198    /// the rows are right and the memory bound is gone. A wrapper must forward this
1199    /// method explicitly.
1200    ///
1201    /// # Errors
1202    ///
1203    /// Returns the same errors as
1204    /// [`execute_with_projection_arc_with_session`](Self::execute_with_projection_arc_with_session).
1205    /// Note that an implementation that truly streams can only report the errors it
1206    /// has seen *so far* when this returns: a failure raised after the first row —
1207    /// a lost connection, a runtime cast error on a later row — surfaces as an `Err`
1208    /// item inside the stream, not from this call.
1209    async fn stream_with_projection(
1210        &self,
1211        request: &ProjectionRequest<'_>,
1212        session_vars: &[(&str, &str)],
1213        routing: ReadRouting,
1214    ) -> Result<JsonbRowStream> {
1215        let rows = self
1216            .execute_with_projection_arc_with_session(request, session_vars, routing)
1217            .await?;
1218        // Unwrap when this call owns the only reference (the usual case, since the
1219        // read above just built it) so replaying the buffer costs no deep clone.
1220        let rows = Arc::try_unwrap(rows).unwrap_or_else(|shared| (*shared).clone());
1221        Ok(Box::pin(futures::stream::iter(rows.into_iter().map(Ok))))
1222    }
1223
1224    /// Execute a read that composes its embedded levels into **one** statement.
1225    ///
1226    /// The REST `?select=` embed used to be a parent read plus one sub-read per parent
1227    /// row per level; this is the same answer in one round trip, one snapshot and one
1228    /// pooled connection. See [`ComposedLevel`] for the call shape and for the
1229    /// `{"d": …, "e": …}` rows it returns.
1230    ///
1231    /// Session variables and routing mean what they mean for
1232    /// [`execute_with_projection_arc_with_session`](Self::execute_with_projection_arc_with_session).
1233    ///
1234    /// # Default implementation
1235    ///
1236    /// Refuses. Composing needs correlated `LATERAL` subqueries and JSON aggregation,
1237    /// which an adapter has to render for its own dialect; answering with anything
1238    /// else — the root rows without their embeds, say — would be a partial response
1239    /// indistinguishable from a parent with no related rows. A wrapping adapter must
1240    /// forward this method explicitly.
1241    ///
1242    /// # Errors
1243    ///
1244    /// `FraiseQLError::Unsupported` from the default; otherwise the errors of
1245    /// [`execute_with_projection_arc_with_session`](Self::execute_with_projection_arc_with_session).
1246    async fn execute_composed_with_session(
1247        &self,
1248        read: &ComposedLevel,
1249        _session_vars: &[(&str, &str)],
1250        _routing: ReadRouting,
1251    ) -> Result<Arc<Vec<JsonbValue>>> {
1252        Err(composed_read_unsupported(&read.view))
1253    }
1254
1255    /// The same read as [`execute_row_query`](Self::execute_row_query), delivered
1256    /// row by row (#958).
1257    ///
1258    /// The column-shaped counterpart of
1259    /// [`stream_with_projection`](Self::stream_with_projection); see that method for
1260    /// why streaming and paginated re-execution are not interchangeable. This is the
1261    /// gRPC transport's source, which encodes one protobuf message per row and has
1262    /// no use for a `Vec` of them.
1263    ///
1264    /// # Default implementation
1265    ///
1266    /// Collects and replays, with the same caveat about wrapping adapters.
1267    ///
1268    /// # Errors
1269    ///
1270    /// Returns the same errors as [`execute_row_query`](Self::execute_row_query);
1271    /// see [`stream_with_projection`](Self::stream_with_projection) for which of
1272    /// them can still arrive after this call has returned `Ok`.
1273    async fn stream_row_query(
1274        &self,
1275        view_name: &str,
1276        columns: &[crate::types::ColumnSpec],
1277        where_sql: Option<&str>,
1278        order_by: Option<&str>,
1279        limit: Option<u32>,
1280        offset: Option<u32>,
1281    ) -> Result<ColumnRowStream> {
1282        let rows = self
1283            .execute_row_query(view_name, columns, where_sql, order_by, limit, offset)
1284            .await?;
1285        Ok(Box::pin(futures::stream::iter(rows.into_iter().map(Ok))))
1286    }
1287
1288    /// Connection-affine variant of [`stream_row_query`](Self::stream_row_query).
1289    ///
1290    /// The streaming twin of
1291    /// [`execute_row_query_with_session`](Self::execute_row_query_with_session); see
1292    /// that method for why the row shape carries session variables at all. The
1293    /// streaming arm is where dropping them costs the most, because it is the arm
1294    /// that delivers an unbounded number of rows.
1295    ///
1296    /// # Errors
1297    ///
1298    /// Same errors as [`stream_row_query`](Self::stream_row_query); additionally
1299    /// returns `FraiseQLError::Database` if `set_config` fails on any pair.
1300    async fn stream_row_query_with_session(
1301        &self,
1302        view_name: &str,
1303        columns: &[crate::types::ColumnSpec],
1304        where_sql: Option<&str>,
1305        order_by: Option<&str>,
1306        limit: Option<u32>,
1307        offset: Option<u32>,
1308        session_vars: &[(&str, &str)],
1309    ) -> Result<ColumnRowStream> {
1310        refuse_session_variables(self, session_vars)?;
1311        self.stream_row_query(view_name, columns, where_sql, order_by, limit, offset)
1312            .await
1313    }
1314
1315    /// Retrieve query performance statistics from the database.
1316    ///
1317    /// Returns the top-N queries ordered by total execution time (descending).
1318    /// The exact data source depends on the backend:
1319    /// - PostgreSQL: `pg_stat_statements` (requires extension)
1320    /// - MySQL: `performance_schema.events_statements_summary_by_digest`
1321    /// - SQL Server: `sys.dm_exec_query_stats`
1322    /// - SQLite / Wire: empty (no stats available)
1323    ///
1324    /// # Arguments
1325    ///
1326    /// * `limit` - Maximum number of entries to return.
1327    ///
1328    /// # Errors
1329    ///
1330    /// Returns `FraiseQLError::Database` if the stats query fails.
1331    async fn query_stats(&self, _limit: u32) -> Result<Vec<crate::types::QueryStatEntry>> {
1332        Ok(vec![])
1333    }
1334
1335    /// Retrieve statistics for a single query by its ID.
1336    ///
1337    /// The default implementation fetches up to 1000 entries via
1338    /// [`query_stats`](Self::query_stats) and filters client-side.
1339    /// Backends with efficient single-query lookup (PostgreSQL, SQL Server)
1340    /// should override with a `WHERE` clause.
1341    ///
1342    /// # Errors
1343    ///
1344    /// Returns `FraiseQLError::Database` if the underlying query fails.
1345    async fn query_stats_by_id(&self, id: &str) -> Result<Option<crate::types::QueryStatEntry>> {
1346        let stats = self.query_stats(1000).await?;
1347        Ok(stats.into_iter().find(|e| e.query_id == id))
1348    }
1349
1350    /// Reset query performance statistics.
1351    ///
1352    /// Only PostgreSQL supports this (via `pg_stat_statements_reset()`).
1353    /// All other adapters return `Unsupported`.
1354    ///
1355    /// # Errors
1356    ///
1357    /// Returns `FraiseQLError::Unsupported` for adapters that cannot reset stats.
1358    /// Returns `FraiseQLError::Database` if the reset command fails.
1359    async fn reset_query_stats(&self) -> Result<()> {
1360        Err(FraiseQLError::Unsupported {
1361            message: "Query stats reset is not supported by this database adapter".to_string(),
1362        })
1363    }
1364
1365    /// Notify the adapter that the schema has changed.
1366    ///
1367    /// Called during hot-reload after the new schema has been validated.
1368    /// Adapters that maintain schema-dependent state (e.g. cache keyed by schema
1369    /// version) should clear or rebuild that state here.
1370    ///
1371    /// The default implementation is a no-op.
1372    fn on_schema_reload(&self) {}
1373
1374    /// Run one operator-supplied statement under the bounds in `request` (#962).
1375    ///
1376    /// This is the only method on this trait whose SQL FraiseQL did not generate.
1377    /// It exists for the Studio SQL console, and it is deliberately the *narrowest*
1378    /// possible shape for that: a single statement, in a transaction whose mode,
1379    /// timeout, row budget and session identity are all decided by the caller and
1380    /// enforced by the database. See [`AdminSqlRequest`] for what each bound buys.
1381    ///
1382    /// # Default implementation
1383    ///
1384    /// **Refuses.** An adapter that has not implemented containment does not get
1385    /// to run arbitrary SQL by inheriting a default that "just works" — the
1386    /// convenient default here would be `execute_raw_query`, which has no
1387    /// transaction, no timeout, no row cap and no way to roll back. Every
1388    /// adapter that should serve this endpoint says so by overriding, and the
1389    /// endpoint answers "unsupported" for the rest.
1390    ///
1391    /// A wrapping adapter must forward explicitly for the same reason it forwards
1392    /// [`stream_with_projection`](Self::stream_with_projection): inheriting the
1393    /// default here turns a capable adapter into an incapable one, and the only
1394    /// symptom is a refusal nobody asked for.
1395    ///
1396    /// # Errors
1397    ///
1398    /// Returns `FraiseQLError::Unsupported` by default. Implementations return
1399    /// `FraiseQLError::Database` for anything PostgreSQL rejects — which
1400    /// includes the write refused by a `READ ONLY` transaction (SQLSTATE
1401    /// `25006`) and the statement cancelled by the timeout (`57014`).
1402    async fn execute_admin_sql(&self, _request: &AdminSqlRequest) -> Result<AdminSqlOutcome> {
1403        Err(FraiseQLError::Unsupported {
1404            message: "Operator-supplied SQL execution is not supported by this database adapter."
1405                .to_string(),
1406        })
1407    }
1408}
1409
1410/// The `SELECT` behind [`DatabaseAdapter::execute_row_query`] and its streaming
1411/// sibling.
1412///
1413/// Shared rather than written twice: the two methods answer the same question and
1414/// a transport that got a different row set depending on whether it streamed would
1415/// be the hardest kind of bug to see. `where_sql` and `order_by` are compiler-
1416/// generated SQL fragments, as the method contract requires.
1417#[must_use]
1418pub fn build_row_query_sql(
1419    view_name: &str,
1420    where_sql: Option<&str>,
1421    order_by: Option<&str>,
1422    limit: Option<u32>,
1423    offset: Option<u32>,
1424) -> String {
1425    use std::fmt::Write as _;
1426
1427    let mut sql = format!("SELECT * FROM \"{view_name}\"");
1428    if let Some(w) = where_sql {
1429        sql.push_str(" WHERE ");
1430        sql.push_str(w);
1431    }
1432    if let Some(ob) = order_by {
1433        sql.push_str(" ORDER BY ");
1434        sql.push_str(ob);
1435    }
1436    if let Some(l) = limit {
1437        let _ = write!(sql, " LIMIT {l}");
1438    }
1439    if let Some(o) = offset {
1440        let _ = write!(sql, " OFFSET {o}");
1441    }
1442    sql
1443}
1444
1445/// Decode one JSON-shaped row into the declared column order.
1446///
1447/// A column the row does not carry decodes to [`crate::types::ColumnValue::Null`]
1448/// rather than shortening the row: the transport encodes positionally against
1449/// `columns`.
1450#[must_use]
1451pub fn row_to_column_values<S: std::hash::BuildHasher>(
1452    row: &std::collections::HashMap<String, serde_json::Value, S>,
1453    columns: &[crate::types::ColumnSpec],
1454) -> Vec<crate::types::ColumnValue> {
1455    use crate::types::ColumnValue;
1456
1457    columns
1458        .iter()
1459        .map(|col| {
1460            row.get(&col.name).map_or(ColumnValue::Null, |v| match v {
1461                serde_json::Value::Null => ColumnValue::Null,
1462                serde_json::Value::Bool(b) => ColumnValue::Boolean(*b),
1463                serde_json::Value::Number(n) => {
1464                    if let Some(i) = n.as_i64() {
1465                        ColumnValue::Int64(i)
1466                    } else if let Some(f) = n.as_f64() {
1467                        ColumnValue::Float64(f)
1468                    } else {
1469                        ColumnValue::Text(n.to_string())
1470                    }
1471                },
1472                serde_json::Value::String(s) => ColumnValue::Text(s.clone()),
1473                other => ColumnValue::Json(other.to_string()),
1474            })
1475        })
1476        .collect()
1477}
1478
1479#[cfg(test)]
1480mod tests;
1481
1482/// Refuse `session_vars` on an adapter that cannot apply them (#1115): reading without
1483/// them would read unscoped.
1484pub(crate) fn refuse_session_variables<A: DatabaseAdapter + ?Sized>(
1485    adapter: &A,
1486    session_vars: &[(&str, &str)],
1487) -> Result<()> {
1488    if session_vars.is_empty() || adapter.applies_session_variables() {
1489        return Ok(());
1490    }
1491    Err(fraiseql_error::FraiseQLError::Unsupported {
1492        message: format!(
1493            "the {} adapter ({}) cannot apply session variables, and a read without them \
1494             would ignore every policy that reads them; refused rather than read unscoped",
1495            std::any::type_name::<A>(),
1496            adapter.database_type()
1497        ),
1498    })
1499}
1500
1501/// One TVIEW's physical health, from `tviews.pg_tviews_profile()` (#1392).
1502///
1503/// The columns `fraiseql doctor` and `/metrics` read (`pg_tviews` `docs/reference/profile.md`).
1504/// The profile names a TVIEW by its `schema` and `name` columns, which `tview` joins.
1505#[derive(Debug, Clone, PartialEq)]
1506pub struct TviewProfile {
1507    /// The TVIEW entity (`book` for `tv_book`).
1508    pub entity:        String,
1509    /// The schema-qualified `tv_*` table, each part quoted where it needs to be.
1510    pub tview:         String,
1511    /// HOT updates / updates since the statistics reset; `None` without updates.
1512    pub hot_ratio:     Option<f64>,
1513    /// Dead tuples, from `pg_stat_all_tables`.
1514    pub n_dead_tup:    Option<i64>,
1515    /// Updates since the statistics reset.
1516    pub n_tup_upd:     Option<i64>,
1517    /// HOT updates since the statistics reset.
1518    pub n_tup_hot_upd: Option<i64>,
1519    /// `pg_tviews`' advice for it; empty when it has none.
1520    pub warnings:      Vec<String>,
1521}