Skip to main content

fraiseql_db/
traits.rs

1//! Database adapter trait definitions.
2
3use std::future::Future;
4
5use async_trait::async_trait;
6use fraiseql_error::{FraiseQLError, Result};
7
8use super::{
9    types::{DatabaseType, JsonbValue, PoolMetrics},
10    where_clause::WhereClause,
11};
12use crate::types::sql_hints::{OrderByClause, SqlProjectionHint};
13
14/// Result from a relay pagination query, containing rows and an optional total count.
15#[derive(Debug, Clone)]
16pub struct RelayPageResult {
17    /// The page of JSONB rows (already trimmed to the requested page size).
18    pub rows:        Vec<JsonbValue>,
19    /// Total count of matching rows (only populated when requested via `include_total_count`).
20    pub total_count: Option<u64>,
21}
22
23/// Database adapter for executing queries against views.
24///
25/// This trait abstracts over different database backends (PostgreSQL, MySQL, SQLite, SQL Server).
26/// All implementations must support:
27/// - Executing parameterized WHERE queries against views
28/// - Returning JSONB data from the `data` column
29/// - Connection pooling and health checks
30/// - Row-level security (RLS) WHERE clauses
31///
32/// # Architecture
33///
34/// The adapter is the runtime interface to the database. It receives:
35/// - View/table name (e.g., "v_user", "tf_sales")
36/// - Parameterized WHERE clauses (AST form, not strings)
37/// - Projection hints (for performance optimization)
38/// - Pagination parameters (LIMIT/OFFSET)
39///
40/// And returns:
41/// - JSONB rows from the `data` column (most operations)
42/// - Arbitrary rows as HashMap (for aggregation queries)
43/// - Mutation results from stored procedures
44///
45/// # Implementing a New Adapter
46///
47/// To add support for a new database (e.g., Oracle, Snowflake):
48///
49/// 1. **Create a new module** in `src/db/your_database/`
50/// 2. **Implement the trait**:
51///
52///    ```rust,ignore
53///    pub struct YourDatabaseAdapter { /* fields */ }
54///
55///    #[async_trait]
56///    impl DatabaseAdapter for YourDatabaseAdapter {
57///        async fn execute_where_query(&self, ...) -> Result<Vec<JsonbValue>> {
58///            // 1. Build parameterized SQL from WhereClause AST
59///            // 2. Execute with bound parameters (NO string concatenation)
60///            // 3. Return JSONB from data column
61///        }
62///        // Implement other required methods...
63///    }
64///    ```
65/// 3. **Add feature flag** to `Cargo.toml` (e.g., `feature = "your-database"`)
66/// 4. **Copy structure from PostgreSQL adapter** — see `src/db/postgres/adapter.rs`
67/// 5. **Add tests** in `tests/integration/your_database_test.rs`
68///
69/// # Security Requirements
70///
71/// All implementations MUST:
72/// - **Never concatenate user input into SQL strings**
73/// - **Always use parameterized queries** with bind parameters
74/// - **Validate parameter types** before binding
75/// - **Preserve RLS WHERE clauses** (never filter them out)
76/// - **Return errors, not silently fail** (e.g., connection loss)
77///
78/// # Connection Management
79///
80/// - Use a connection pool (recommended: 20 connections default)
81/// - Implement `health_check()` for ping-based monitoring
82/// - Provide `pool_metrics()` for observability
83/// - Handle stale connections gracefully
84///
85/// # Performance Characteristics
86///
87/// Expected throughput when properly implemented:
88/// - **Simple queries** (single table, no WHERE): 250+ Kelem/s
89/// - **Complex queries** (JOINs, multiple conditions): 50+ Kelem/s
90/// - **Mutations** (stored procedures): 1-10 RPS (depends on procedure)
91/// - **Relay pagination** (keyset cursors): 15-30ms latency
92///
93/// # Example: PostgreSQL Implementation
94///
95/// ```rust,ignore
96/// use sqlx::postgres::PgPool;
97/// use async_trait::async_trait;
98///
99/// pub struct PostgresAdapter {
100///     pool: PgPool,
101/// }
102///
103/// #[async_trait]
104/// impl DatabaseAdapter for PostgresAdapter {
105///     async fn execute_where_query(
106///         &self,
107///         view: &str,
108///         where_clause: Option<&WhereClause>,
109///         limit: Option<u32>,
110///         offset: Option<u32>,
111///     ) -> Result<Vec<JsonbValue>> {
112///         // 1. Build SQL: SELECT data FROM {view} WHERE {where_clause} LIMIT {limit}
113///         let mut sql = format!(r#"SELECT data FROM "{}""#, view);
114///
115///         // 2. Add WHERE clause (converts AST to parameterized SQL)
116///         let params = if let Some(where_clause) = where_clause {
117///             sql.push_str(" WHERE ");
118///             let (where_sql, params) = build_where_sql(where_clause)?;
119///             sql.push_str(&where_sql);
120///             params
121///         } else {
122///             vec![]
123///         };
124///
125///         // 3. Add LIMIT and OFFSET
126///         if let Some(limit) = limit {
127///             sql.push_str(" LIMIT ");
128///             sql.push_str(&limit.to_string());
129///         }
130///         if let Some(offset) = offset {
131///             sql.push_str(" OFFSET ");
132///             sql.push_str(&offset.to_string());
133///         }
134///
135///         // 4. Execute with bound parameters (NO string interpolation)
136///         let rows: Vec<(serde_json::Value,)> = sqlx::query_as(&sql)
137///             .bind(&params[0])
138///             .bind(&params[1])
139///             // ... bind all parameters
140///             .fetch_all(&self.pool)
141///             .await?;
142///
143///         // 5. Extract JSONB and return
144///         Ok(rows.into_iter().map(|(data,)| data).collect())
145///     }
146///
147///     // Implement other required methods...
148/// }
149/// ```
150///
151/// # Example: Basic Usage
152///
153/// ```rust,no_run
154/// use fraiseql_db::{DatabaseAdapter, WhereClause, WhereOperator};
155/// use serde_json::json;
156///
157/// # async fn example(adapter: impl DatabaseAdapter) -> Result<(), Box<dyn std::error::Error>> {
158/// // Build WHERE clause (AST, not string)
159/// let where_clause = WhereClause::Field {
160///     path: vec!["email".to_string()],
161///     operator: WhereOperator::Icontains,
162///     value: json!("example.com"),
163/// };
164///
165/// // Execute query with parameters
166/// let results = adapter
167///     .execute_where_query("v_user", Some(&where_clause), Some(10), None, None)
168///     .await?;
169///
170/// println!("Found {} users matching filter", results.len());
171/// # Ok(())
172/// # }
173/// ```
174///
175/// # See Also
176///
177/// - `WhereClause` — AST for parameterized WHERE clauses
178/// - `RelayDatabaseAdapter` — Optional trait for keyset pagination
179/// - `DatabaseCapabilities` — Feature detection for the adapter
180/// - [Performance Guide](https://docs.fraiseql.rs/performance/database-adapters.md)
181// POLICY: `#[async_trait]` placement for `DatabaseAdapter`
182//
183// `DatabaseAdapter` is used both generically (`Server<A: DatabaseAdapter>` in axum
184// handlers, zero overhead via static dispatch) and dynamically (`Arc<dyn
185// DatabaseAdapter + Send + Sync>` in federation, heap-boxed future per call).
186//
187// `#[async_trait]` is required on:
188// - The trait definition (generates `Pin<Box<dyn Future + Send>>` return types)
189// - Every `impl DatabaseAdapter for ConcreteType` block (generates the boxing)
190// NOT required on callers (they see `Pin<Box<dyn Future + Send>>` from macro output).
191//
192// Why not native `async fn in trait` (Rust 1.75+)?
193// Native dyn async trait does NOT propagate `+ Send` on generated futures. Tokio
194// requires futures spawned with `tokio::spawn` to be `Send`. Until Return Type
195// Notation (RFC 3425, tracking: github.com/rust-lang/rust/issues/109417) stabilises,
196// `async_trait` is the only ergonomic path to `dyn DatabaseAdapter + Send + Sync`.
197// Re-evaluate when Rust 1.90+ ships or when RTN is stabilised.
198//
199// MIGRATION TRACKING: async-trait → native async fn in trait
200//
201// Current status: BLOCKED on RFC 3425 (Return Type Notation)
202// See: https://github.com/rust-lang/rfcs/pull/3425
203//      https://github.com/rust-lang/rust/issues/109417
204//
205// Migration is safe when ALL of the following are true:
206// 1. RTN with `+ Send` bounds is stable on rustc (e.g. `fn foo() -> impl Future + Send`)
207// 2. FraiseQL MSRV is updated to that stabilising version
208// 3. tokio::spawn() works with native dyn async trait objects (futures must be Send)
209//
210// Scope when criteria are met: 68 files (grep -rn "#\[async_trait\]" crates/)
211// Effort: Medium (mostly mechanical — remove macro from impls, adjust trait defs)
212// dynosaur was evaluated and rejected: does not propagate + Send (incompatible with Tokio)
213#[async_trait]
214pub trait DatabaseAdapter: Send + Sync {
215    /// Execute a WHERE query against a view and return JSONB rows.
216    ///
217    /// # Arguments
218    ///
219    /// * `view` - View name (e.g., "v_user", "v_post")
220    /// * `where_clause` - Optional WHERE clause AST
221    /// * `limit` - Optional row limit (for pagination)
222    /// * `offset` - Optional row offset (for pagination)
223    ///
224    /// # Returns
225    ///
226    /// Vec of JSONB values from the `data` column.
227    ///
228    /// # Errors
229    ///
230    /// Returns `FraiseQLError::Database` on query execution failure.
231    /// Returns `FraiseQLError::ConnectionPool` if connection pool is exhausted.
232    ///
233    /// # Example
234    ///
235    /// ```rust,no_run
236    /// # use fraiseql_db::DatabaseAdapter;
237    /// # async fn example(adapter: impl DatabaseAdapter) -> Result<(), Box<dyn std::error::Error>> {
238    /// // Simple query without WHERE clause
239    /// let all_users = adapter
240    ///     .execute_where_query("v_user", None, Some(10), Some(0), None)
241    ///     .await?;
242    /// # Ok(())
243    /// # }
244    /// ```
245    async fn execute_where_query(
246        &self,
247        view: &str,
248        where_clause: Option<&WhereClause>,
249        limit: Option<u32>,
250        offset: Option<u32>,
251        order_by: Option<&[OrderByClause]>,
252    ) -> Result<Vec<JsonbValue>>;
253
254    /// Execute a WHERE query with SQL field projection optimization.
255    ///
256    /// Projects only the requested fields at the database level, reducing network payload
257    /// and JSON deserialization overhead by **40-55%** based on production measurements.
258    ///
259    /// This is the primary query execution method for optimized GraphQL queries.
260    /// It automatically selects only the fields requested in the GraphQL query, avoiding
261    /// unnecessary network transfer and deserialization of unused fields.
262    ///
263    /// # Automatic Projection
264    ///
265    /// In most cases, you don't call this directly. The `Executor` automatically:
266    /// 1. Determines which fields the GraphQL query requests
267    /// 2. Generates a `SqlProjectionHint` using database-specific SQL
268    /// 3. Calls this method with the projection hint
269    ///
270    /// # Arguments
271    ///
272    /// * `view` - View name (e.g., "v_user", "v_post")
273    /// * `projection` - Optional SQL projection hint with field list
274    ///   - `Some(hint)`: Use projection to select only requested fields
275    ///   - `None`: Falls back to standard query (full JSONB column)
276    /// * `where_clause` - Optional WHERE clause AST for filtering
277    /// * `limit` - Optional row limit (for pagination)
278    ///
279    /// # Returns
280    ///
281    /// Vec of JSONB values, either:
282    /// - Full objects (when projection is None)
283    /// - Projected objects with only requested fields (when projection is Some)
284    ///
285    /// # Errors
286    ///
287    /// Returns `FraiseQLError::Database` on query execution failure, including:
288    /// - Connection pool exhaustion
289    /// - SQL execution errors
290    /// - Type mismatches
291    ///
292    /// # Performance Characteristics
293    ///
294    /// When projection is provided (recommended):
295    /// - **Latency**: 40-55% reduction vs full object fetch
296    /// - **Network**: 40-55% smaller payload (proportional to unused fields)
297    /// - **Throughput**: Maintains 250+ Kelem/s (elements per second)
298    /// - **Memory**: Proportional to projected fields only
299    ///
300    /// Improvement scales with:
301    /// - Percentage of unused fields (more unused = more improvement)
302    /// - Size of result set (larger sets benefit more)
303    /// - Network latency (network-bound queries benefit most)
304    ///
305    /// When projection is None:
306    /// - Behavior identical to `execute_where_query()`
307    /// - Returns full JSONB column
308    /// - Used for compatibility/debugging
309    ///
310    /// # Database Support
311    ///
312    /// | Database | Status | Implementation |
313    /// |----------|--------|-----------------|
314    /// | PostgreSQL | ✅ Optimized | `jsonb_build_object()` |
315    /// | MySQL | ⏳ Fallback | Server-side filtering (planned) |
316    /// | SQLite | ⏳ Fallback | Server-side filtering (planned) |
317    /// | SQL Server | ⏳ Fallback | Server-side filtering (planned) |
318    ///
319    /// # Example: Direct Usage (Advanced)
320    ///
321    /// ```no_run
322    /// // Requires: running PostgreSQL database and a DatabaseAdapter implementation.
323    /// use fraiseql_db::types::SqlProjectionHint;
324    /// use fraiseql_db::traits::DatabaseAdapter;
325    /// use fraiseql_db::DatabaseType;
326    ///
327    /// # async fn example(adapter: &impl DatabaseAdapter) -> Result<(), Box<dyn std::error::Error>> {
328    /// let projection = SqlProjectionHint {
329    ///     database: DatabaseType::PostgreSQL,
330    ///     projection_template: "jsonb_build_object(\
331    ///         'id', data->>'id', \
332    ///         'name', data->>'name', \
333    ///         'email', data->>'email'\
334    ///     )".to_string(),
335    ///     estimated_reduction_percent: 75,
336    /// };
337    ///
338    /// let results = adapter
339    ///     .execute_with_projection("v_user", Some(&projection), None, Some(100), None, None)
340    ///     .await?;
341    ///
342    /// // results only contain id, name, email fields
343    /// // 75% smaller than fetching all fields
344    /// # Ok(())
345    /// # }
346    /// ```
347    ///
348    /// # Example: Fallback (No Projection)
349    ///
350    /// ```no_run
351    /// // Requires: running PostgreSQL database and a DatabaseAdapter implementation.
352    /// # use fraiseql_db::traits::DatabaseAdapter;
353    /// # async fn example(adapter: &impl DatabaseAdapter) -> Result<(), Box<dyn std::error::Error>> {
354    /// // For debugging or when projection not available
355    /// let results = adapter
356    ///     .execute_with_projection("v_user", None, None, Some(100), None, None)
357    ///     .await?;
358    ///
359    /// // Equivalent to execute_where_query() - returns full objects
360    /// # Ok(())
361    /// # }
362    /// ```
363    ///
364    /// # See Also
365    ///
366    /// - `execute_where_query()` - Standard query without projection
367    /// - `SqlProjectionHint` - Structure defining field projection
368    /// - [Projection Optimization Guide](https://docs.fraiseql.rs/performance/projection-optimization.md)
369    async fn execute_with_projection(
370        &self,
371        view: &str,
372        projection: Option<&SqlProjectionHint>,
373        where_clause: Option<&WhereClause>,
374        limit: Option<u32>,
375        offset: Option<u32>,
376        order_by: Option<&[OrderByClause]>,
377    ) -> Result<Vec<JsonbValue>>;
378
379    /// Get database type (for logging/metrics).
380    ///
381    /// Used to identify which database backend is in use.
382    fn database_type(&self) -> DatabaseType;
383
384    /// Health check - verify database connectivity.
385    ///
386    /// Executes a simple query (e.g., `SELECT 1`) to verify the database is reachable.
387    ///
388    /// # Errors
389    ///
390    /// Returns `FraiseQLError::Database` if health check fails.
391    async fn health_check(&self) -> Result<()>;
392
393    /// Get connection pool metrics.
394    ///
395    /// Returns current statistics about the connection pool:
396    /// - Total connections
397    /// - Idle connections
398    /// - Active connections
399    /// - Waiting requests
400    fn pool_metrics(&self) -> PoolMetrics;
401
402    /// Execute raw SQL query and return rows as JSON objects.
403    ///
404    /// Used for aggregation queries where we need full row data, not just JSONB column.
405    ///
406    /// # Security Warning
407    ///
408    /// This method executes arbitrary SQL. **NEVER** pass untrusted input directly to this method.
409    /// Always:
410    /// - Use parameterized queries with bound parameters
411    /// - Validate and sanitize SQL templates before execution
412    /// - Only execute SQL generated by the FraiseQL compiler
413    /// - Log SQL execution for audit trails
414    ///
415    /// # Arguments
416    ///
417    /// * `sql` - Raw SQL query to execute (must be safe/trusted)
418    ///
419    /// # Returns
420    ///
421    /// Vec of rows, where each row is a HashMap of column name to JSON value.
422    ///
423    /// # Errors
424    ///
425    /// Returns `FraiseQLError::Database` on query execution failure.
426    ///
427    /// # Example
428    ///
429    /// ```rust,no_run
430    /// # use fraiseql_db::DatabaseAdapter;
431    /// # async fn example(adapter: impl DatabaseAdapter) -> Result<(), Box<dyn std::error::Error>> {
432    /// // Safe: SQL generated by FraiseQL compiler
433    /// let sql = "SELECT category, SUM(revenue) as total FROM tf_sales GROUP BY category";
434    /// let rows = adapter.execute_raw_query(sql).await?;
435    /// for row in rows {
436    ///     println!("Category: {}, Total: {}", row["category"], row["total"]);
437    /// }
438    /// # Ok(())
439    /// # }
440    /// ```
441    async fn execute_raw_query(
442        &self,
443        sql: &str,
444    ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>>;
445
446    /// Execute a row-shaped query against a view, returning typed column values.
447    ///
448    /// Used by the gRPC transport for protobuf encoding of query results.
449    /// The default implementation delegates to `execute_raw_query` and converts
450    /// JSON results to `ColumnValue` vectors.
451    ///
452    /// # Errors
453    ///
454    /// Returns `FraiseQLError::Database` if the adapter returns an error.
455    async fn execute_row_query(
456        &self,
457        view_name: &str,
458        columns: &[crate::types::ColumnSpec],
459        where_sql: Option<&str>,
460        order_by: Option<&str>,
461        limit: Option<u32>,
462        offset: Option<u32>,
463    ) -> Result<Vec<Vec<crate::types::ColumnValue>>> {
464        use crate::types::ColumnValue;
465
466        let mut sql = format!("SELECT * FROM \"{view_name}\"");
467        if let Some(w) = where_sql {
468            sql.push_str(" WHERE ");
469            sql.push_str(w);
470        }
471        if let Some(ob) = order_by {
472            sql.push_str(" ORDER BY ");
473            sql.push_str(ob);
474        }
475        if let Some(l) = limit {
476            use std::fmt::Write;
477            let _ = write!(sql, " LIMIT {l}");
478        }
479        if let Some(o) = offset {
480            use std::fmt::Write;
481            let _ = write!(sql, " OFFSET {o}");
482        }
483
484        let results = self.execute_raw_query(&sql).await?;
485
486        Ok(results
487            .iter()
488            .map(|row| {
489                columns
490                    .iter()
491                    .map(|col| {
492                        row.get(&col.name).map_or(ColumnValue::Null, |v| match v {
493                            serde_json::Value::Null => ColumnValue::Null,
494                            serde_json::Value::Bool(b) => ColumnValue::Boolean(*b),
495                            serde_json::Value::Number(n) => {
496                                if let Some(i) = n.as_i64() {
497                                    ColumnValue::Int64(i)
498                                } else if let Some(f) = n.as_f64() {
499                                    ColumnValue::Float64(f)
500                                } else {
501                                    ColumnValue::Text(n.to_string())
502                                }
503                            },
504                            serde_json::Value::String(s) => ColumnValue::Text(s.clone()),
505                            other => ColumnValue::Json(other.to_string()),
506                        })
507                    })
508                    .collect()
509            })
510            .collect())
511    }
512
513    /// Execute a parameterized aggregate SQL query (GROUP BY / HAVING / window).
514    ///
515    /// `sql` contains `$N` (PostgreSQL), `?` (MySQL / SQLite), or `@P1` (SQL Server)
516    /// placeholders for string and array values; numeric and NULL values may be inlined.
517    /// `params` are the corresponding values in placeholder order.
518    ///
519    /// Unlike `execute_raw_query`, this method accepts bind parameters so that
520    /// user-supplied filter values never appear as string literals in the SQL text,
521    /// eliminating the injection risk that `escape_sql_string` mitigated previously.
522    ///
523    /// # Arguments
524    ///
525    /// * `sql` - SQL with placeholders generated by
526    ///   `AggregationSqlGenerator::generate_parameterized`
527    /// * `params` - Bind parameters in placeholder order
528    ///
529    /// # Returns
530    ///
531    /// Vec of rows, where each row is a `HashMap` of column name to JSON value.
532    ///
533    /// # Errors
534    ///
535    /// Returns `FraiseQLError::Database` on execution failure.
536    /// Returns `FraiseQLError::Database` on adapters that do not support raw SQL
537    /// (e.g., `FraiseWireAdapter`).
538    async fn execute_parameterized_aggregate(
539        &self,
540        sql: &str,
541        params: &[serde_json::Value],
542    ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>>;
543
544    /// Execute a database function call and return all columns as rows.
545    ///
546    /// Builds `SELECT * FROM {function_name}($1, $2, ...)` with one positional placeholder per
547    /// argument, executes it with the provided JSON values, and returns each result row as a
548    /// `HashMap<column_name, json_value>`.
549    ///
550    /// Used by the mutation execution pathway to call stored procedures that return the
551    /// `app.mutation_response` composite type
552    /// `(status, message, entity_id, entity_type, entity jsonb, updated_fields text[],
553    ///   cascade jsonb, metadata jsonb)`.
554    ///
555    /// # Arguments
556    ///
557    /// * `function_name` - Fully-qualified function name (e.g. `fn_create_machine`)
558    /// * `args` - Positional JSON arguments passed as `$1, $2, …` bind parameters
559    ///
560    /// # Errors
561    ///
562    /// Returns `FraiseQLError::Database` on query execution failure.
563    /// Returns `FraiseQLError::Unsupported` on adapters that do not support mutations
564    /// (default implementation — see [`SupportsMutations`]).
565    async fn execute_function_call(
566        &self,
567        function_name: &str,
568        _args: &[serde_json::Value],
569    ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
570        Err(FraiseQLError::Unsupported {
571            message: format!(
572                "Mutations via function calls are not supported by this adapter. \
573                 Function '{function_name}' cannot be executed. \
574                 Use PostgreSQL, MySQL, or SQL Server for mutation support."
575            ),
576        })
577    }
578
579    /// Returns `true` if this adapter supports GraphQL mutation operations.
580    ///
581    /// **This is the authoritative mutation gate.** The executor checks this method
582    /// before dispatching any mutation. Adapters that return `false` will cause
583    /// mutations to fail with a clear `FraiseQLError::Validation` diagnostic instead
584    /// of silently calling the unsupported `execute_function_call` default.
585    ///
586    /// Override to return `false` for read-only adapters (e.g., `SqliteAdapter`,
587    /// `FraiseWireAdapter`). The compile-time [`SupportsMutations`] marker trait
588    /// complements this runtime check — see its documentation for the distinction.
589    ///
590    /// # Default
591    ///
592    /// Returns `true`. All adapters are assumed mutation-capable unless they override
593    /// this method.
594    fn supports_mutations(&self) -> bool {
595        true
596    }
597
598    /// Bump fact table version counters after a successful mutation.
599    ///
600    /// Called by the executor when a mutation definition declares
601    /// `invalidates_fact_tables`. For each listed table the version counter is
602    /// incremented so that subsequent aggregation queries miss the cache and
603    /// re-fetch fresh data.
604    ///
605    /// The default implementation is a **no-op**: adapters that are not cache-
606    /// aware (e.g. `PostgresAdapter`, `SqliteAdapter`) simply return `Ok(())`.
607    /// `CachedDatabaseAdapter` overrides this to call `bump_tf_version($1)` for
608    /// every `FactTableVersionStrategy::VersionTable` table and update the
609    /// in-process version cache.
610    ///
611    /// # Arguments
612    ///
613    /// * `tables` - Fact table names declared by the mutation (validated SQL identifiers; originate
614    ///   from `MutationDefinition.invalidates_fact_tables`)
615    ///
616    /// # Errors
617    ///
618    /// Returns `FraiseQLError::Database` if the version-bump SQL function fails.
619    async fn bump_fact_table_versions(&self, _tables: &[String]) -> Result<()> {
620        Ok(())
621    }
622
623    /// Invalidate cached query results for the specified views.
624    ///
625    /// Called by the executor after a mutation succeeds, so that stale cache
626    /// entries reading from modified views are evicted. The default
627    /// implementation is a no-op; `CachedDatabaseAdapter` overrides this.
628    ///
629    /// # Returns
630    ///
631    /// The number of cache entries evicted.
632    async fn invalidate_views(&self, _views: &[String]) -> Result<u64> {
633        Ok(0)
634    }
635
636    /// Evict cache entries that contain the given entity UUID.
637    ///
638    /// Called by the executor after a successful UPDATE or DELETE mutation when
639    /// the `mutation_response` includes an `entity_id`. Only cache entries whose
640    /// entity-ID index contains the given UUID are removed; unrelated entries
641    /// remain warm.
642    ///
643    /// The default implementation is a no-op. `CachedDatabaseAdapter` overrides
644    /// this to perform the selective eviction.
645    ///
646    /// # Returns
647    ///
648    /// The number of cache entries evicted.
649    async fn invalidate_by_entity(&self, _entity_type: &str, _entity_id: &str) -> Result<u64> {
650        Ok(0)
651    }
652
653    /// Get database capabilities.
654    ///
655    /// Returns information about what features this database supports,
656    /// including collation strategies and limitations.
657    ///
658    /// # Returns
659    ///
660    /// `DatabaseCapabilities` describing supported features.
661    fn capabilities(&self) -> DatabaseCapabilities {
662        DatabaseCapabilities::from_database_type(self.database_type())
663    }
664
665    /// Run the database's `EXPLAIN` on a SQL statement without executing it.
666    ///
667    /// Returns a JSON representation of the query plan. The format is
668    /// database-specific (e.g. PostgreSQL returns JSON, SQLite returns rows).
669    ///
670    /// The default implementation returns `Unsupported`.
671    async fn explain_query(
672        &self,
673        _sql: &str,
674        _params: &[serde_json::Value],
675    ) -> Result<serde_json::Value> {
676        Err(fraiseql_error::FraiseQLError::Unsupported {
677            message: "EXPLAIN not available for this database adapter".to_string(),
678        })
679    }
680
681    /// Run `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)` against a view with the
682    /// same parameterized WHERE clause that `execute_where_query` would use.
683    ///
684    /// Unlike `explain_query`, this method uses **real bound parameters** and
685    /// **actually executes the query** (ANALYZE mode), so the plan reflects
686    /// PostgreSQL's runtime statistics for the given filter values.
687    ///
688    /// Only PostgreSQL supports this; other adapters return
689    /// `FraiseQLError::Unsupported` by default.
690    ///
691    /// # Arguments
692    ///
693    /// * `view` - View name (e.g., "v_user")
694    /// * `where_clause` - Optional filter (same as `execute_where_query`)
695    /// * `limit` - Optional row limit
696    /// * `offset` - Optional row offset
697    ///
698    /// # Errors
699    ///
700    /// Returns `FraiseQLError::Database` on execution failure.
701    /// Returns `FraiseQLError::Unsupported` for non-PostgreSQL adapters.
702    async fn explain_where_query(
703        &self,
704        _view: &str,
705        _where_clause: Option<&WhereClause>,
706        _limit: Option<u32>,
707        _offset: Option<u32>,
708    ) -> Result<serde_json::Value> {
709        Err(fraiseql_error::FraiseQLError::Unsupported {
710            message: "EXPLAIN ANALYZE is not available for this database adapter. \
711                      Only PostgreSQL supports explain_where_query."
712                .to_string(),
713        })
714    }
715
716    /// Returns the mutation strategy used by this adapter.
717    ///
718    /// The default is `FunctionCall` (stored procedures). Adapters that generate
719    /// direct SQL (e.g., SQLite) override this to return `DirectSql`.
720    fn mutation_strategy(&self) -> MutationStrategy {
721        MutationStrategy::FunctionCall
722    }
723
724    /// Execute a direct SQL mutation (INSERT/UPDATE/DELETE) and return the
725    /// mutation response rows as JSON objects.
726    ///
727    /// Only adapters using `MutationStrategy::DirectSql` need to override this.
728    /// The default implementation returns `Unsupported`.
729    ///
730    /// # Errors
731    ///
732    /// Returns `FraiseQLError::Unsupported` by default.
733    /// Returns `FraiseQLError::Database` on SQL execution failure.
734    /// Returns `FraiseQLError::Validation` on invalid mutation parameters.
735    async fn execute_direct_mutation(
736        &self,
737        _ctx: &DirectMutationContext<'_>,
738    ) -> Result<Vec<serde_json::Value>> {
739        Err(FraiseQLError::Unsupported {
740            message: "Direct SQL mutations are not supported by this adapter. \
741                      Use execute_function_call for stored-procedure mutations."
742                .to_string(),
743        })
744    }
745}
746
747/// Database capabilities and feature support.
748///
749/// Describes what features a database backend supports, allowing the runtime
750/// to adapt behavior based on database limitations.
751#[derive(Debug, Clone, Copy)]
752pub struct DatabaseCapabilities {
753    /// Database type.
754    pub database_type: DatabaseType,
755
756    /// Supports locale-specific collations.
757    pub supports_locale_collation: bool,
758
759    /// Requires custom collation registration.
760    pub requires_custom_collation: bool,
761
762    /// Recommended collation provider.
763    pub recommended_collation: Option<&'static str>,
764}
765
766impl DatabaseCapabilities {
767    /// Create capabilities from database type.
768    #[must_use]
769    pub const fn from_database_type(db_type: DatabaseType) -> Self {
770        match db_type {
771            DatabaseType::PostgreSQL => Self {
772                database_type:             db_type,
773                supports_locale_collation: true,
774                requires_custom_collation: false,
775                recommended_collation:     Some("icu"),
776            },
777            DatabaseType::MySQL => Self {
778                database_type:             db_type,
779                supports_locale_collation: false,
780                requires_custom_collation: false,
781                recommended_collation:     Some("utf8mb4_unicode_ci"),
782            },
783            DatabaseType::SQLite => Self {
784                database_type:             db_type,
785                supports_locale_collation: false,
786                requires_custom_collation: true,
787                recommended_collation:     Some("NOCASE"),
788            },
789            DatabaseType::SQLServer => Self {
790                database_type:             db_type,
791                supports_locale_collation: true,
792                requires_custom_collation: false,
793                recommended_collation:     Some("Latin1_General_100_CI_AI_SC_UTF8"),
794            },
795        }
796    }
797
798    /// Get collation strategy description.
799    #[must_use]
800    pub const fn collation_strategy(&self) -> &'static str {
801        match self.database_type {
802            DatabaseType::PostgreSQL => "ICU collations (locale-specific)",
803            DatabaseType::MySQL => "UTF8MB4 collations (general)",
804            DatabaseType::SQLite => "NOCASE (limited)",
805            DatabaseType::SQLServer => "Language-specific collations",
806        }
807    }
808}
809
810/// Strategy used by an adapter for executing mutations.
811///
812/// Adapters that use stored database functions (PostgreSQL, MySQL, SQL Server) use
813/// `FunctionCall`. Adapters that generate INSERT/UPDATE/DELETE SQL directly (SQLite)
814/// use `DirectSql`.
815#[derive(Debug, Clone, Copy, PartialEq, Eq)]
816#[non_exhaustive]
817pub enum MutationStrategy {
818    /// Mutations execute via stored database functions (`SELECT * FROM fn_create_user($1, $2)`).
819    FunctionCall,
820    /// Mutations execute via direct SQL (`INSERT INTO ... RETURNING *`).
821    DirectSql,
822}
823
824/// The kind of direct mutation operation.
825#[derive(Debug, Clone, Copy, PartialEq, Eq)]
826#[non_exhaustive]
827pub enum DirectMutationOp {
828    /// `INSERT INTO ... RETURNING *`
829    Insert,
830    /// `UPDATE ... SET ... WHERE pk = ? RETURNING *`
831    Update,
832    /// `DELETE FROM ... WHERE pk = ? RETURNING *`
833    Delete,
834}
835
836/// Context for a direct SQL mutation (used by `DirectSql` strategy adapters).
837///
838/// All field references are borrowed from the caller to avoid allocation.
839#[derive(Debug)]
840pub struct DirectMutationContext<'a> {
841    /// The mutation operation to perform.
842    pub operation:      DirectMutationOp,
843    /// Target table name (e.g., `"users"`).
844    pub table:          &'a str,
845    /// Client-supplied column names (in bind order).
846    pub columns:        &'a [String],
847    /// All bind values: client values first, then injected values.
848    pub values:         &'a [serde_json::Value],
849    /// Server-injected column names (e.g., RLS tenant columns), appended after client columns.
850    pub inject_columns: &'a [String],
851    /// GraphQL return type name (e.g., `"User"`), used in the mutation response envelope.
852    pub return_type:    &'a str,
853}
854
855/// A typed cursor value for keyset (relay) pagination.
856///
857/// The cursor type is determined at compile time by `QueryDefinition::relay_cursor_type`
858/// and used at runtime to choose the correct SQL comparison and cursor
859/// encoding/decoding path.
860#[derive(Debug, Clone, PartialEq, Eq)]
861#[non_exhaustive]
862pub enum CursorValue {
863    /// BIGINT primary key cursor (default, backward-compatible).
864    Int64(i64),
865    /// UUID cursor — bound as text and cast to `uuid` in SQL.
866    Uuid(String),
867}
868
869/// Database adapter supertrait for adapters that implement Relay cursor pagination.
870///
871/// Only adapters that genuinely support keyset pagination need to implement this trait.
872/// Non-implementing adapters carry no relay code at all — no stubs, no flags.
873///
874/// # Implementors
875///
876/// - `PostgresAdapter` — full keyset pagination
877/// - `MySqlAdapter` — keyset pagination with `?` params
878/// - `CachedDatabaseAdapter<A>` — delegates to inner `A`
879///
880/// # Usage
881///
882/// Construct an `Executor` with `Executor::new_with_relay` to enable relay
883/// query execution. The bound `A: RelayDatabaseAdapter` is enforced at that call site.
884pub trait RelayDatabaseAdapter: DatabaseAdapter {
885    /// Execute keyset (cursor-based) pagination against a JSONB view.
886    ///
887    /// # Arguments
888    ///
889    /// * `view`                — SQL view name (will be quoted before use)
890    /// * `cursor_column`       — column used as the pagination key (e.g. `pk_user`, `id`)
891    /// * `after`               — forward cursor: return rows where `cursor_column > after`
892    /// * `before`              — backward cursor: return rows where `cursor_column < before`
893    /// * `limit`               — row fetch count (pass `page_size + 1` to detect `hasNextPage`)
894    /// * `forward`             — `true` → ASC order; `false` → DESC (re-sorted ASC via subquery)
895    /// * `where_clause`        — optional user-supplied filter applied after the cursor condition
896    /// * `order_by`            — optional custom sort; cursor column appended as tiebreaker
897    /// * `include_total_count` — when `true`, compute the matching row count before LIMIT
898    ///
899    /// # Errors
900    ///
901    /// Returns `FraiseQLError::Database` on SQL execution failure.
902    fn execute_relay_page<'a>(
903        &'a self,
904        view: &'a str,
905        cursor_column: &'a str,
906        after: Option<CursorValue>,
907        before: Option<CursorValue>,
908        limit: u32,
909        forward: bool,
910        where_clause: Option<&'a WhereClause>,
911        order_by: Option<&'a [OrderByClause]>,
912        include_total_count: bool,
913    ) -> impl Future<Output = Result<RelayPageResult>> + Send + 'a;
914}
915
916/// Marker trait for database adapters that support write operations via stored functions.
917///
918/// Adapters that implement this trait signal that they can execute GraphQL mutations by
919/// calling stored database functions (e.g. `fn_create_user`, `fn_update_order`).
920///
921/// Marker trait for database adapters that support stored-procedure mutations.
922///
923/// # Role: documentation, generic bound, and compile-time enforcement
924///
925/// This trait serves three purposes:
926/// 1. **Documentation**: it makes write-capable adapters self-describing at the type level.
927/// 2. **Generic bounds**: code that only accepts write-capable adapters can constrain on `A:
928///    SupportsMutations` (e.g., `CachedDatabaseAdapter<A: SupportsMutations>`).
929/// 3. **Compile-time enforcement**: `Executor<A>::execute_mutation()` is only available when `A:
930///    SupportsMutations`. Attempting to call it with `SqliteAdapter` produces a compiler error
931///    (`error[E0277]: SqliteAdapter does not implement SupportsMutations`).
932///
933/// The `execute()` method (which accepts raw GraphQL strings) still performs a runtime
934/// `supports_mutations()` check because it cannot know the operation type at compile time.
935/// For direct mutation dispatch, prefer `execute_mutation()` to get compile-time safety.
936///
937/// # Which adapters implement this?
938///
939/// | Adapter | Implements |
940/// |---------|-----------|
941/// | `PostgresAdapter` | ✅ Yes |
942/// | `MySqlAdapter` | ✅ Yes |
943/// | `SqlServerAdapter` | ✅ Yes |
944/// | `SqliteAdapter` | ❌ No — SQLite does not support stored-function mutations |
945/// | `FraiseWireAdapter` | ❌ No — read-only wire protocol |
946/// | `CachedDatabaseAdapter<A>` | ✅ When `A: SupportsMutations` |
947pub trait SupportsMutations: DatabaseAdapter {}
948
949/// Type alias for boxed dynamic database adapters.
950///
951/// Used to store database adapters without generic type parameters in collections
952/// or struct fields. The adapter type is determined at runtime.
953///
954/// # Example
955///
956/// ```ignore
957/// let adapter: BoxDatabaseAdapter = Box::new(postgres_adapter);
958/// ```
959pub type BoxDatabaseAdapter = Box<dyn DatabaseAdapter>;
960
961/// Type alias for arc-wrapped dynamic database adapters.
962///
963/// Used for thread-safe, reference-counted storage of adapters in shared state.
964///
965/// # Example
966///
967/// ```ignore
968/// let adapter: ArcDatabaseAdapter = Arc::new(postgres_adapter);
969/// ```
970pub type ArcDatabaseAdapter = std::sync::Arc<dyn DatabaseAdapter>;
971
972#[cfg(test)]
973mod tests {
974    #[allow(clippy::unwrap_used)] // Reason: test code
975    #[test]
976    fn database_adapter_is_send_sync() {
977        // Static assertion: `dyn DatabaseAdapter` must be `Send + Sync`.
978        // This test exists to catch accidental removal of `Send + Sync` bounds.
979        // It only needs to compile — no runtime assertion required.
980        fn assert_send_sync<T: Send + Sync + ?Sized>() {}
981        assert_send_sync::<dyn super::DatabaseAdapter>();
982    }
983}