Skip to main content

DatabaseAdapter

Trait DatabaseAdapter 

Source
pub trait DatabaseAdapter: Send + Sync {
    // Required methods
    fn execute_where_query<'life0, 'life1, 'life2, 'async_trait>(
        &'life0 self,
        view: &'life1 str,
        where_clause: Option<&'life2 WhereClause>,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<JsonbValue>>> + Send + 'async_trait>>
       where Self: 'async_trait,
             'life0: 'async_trait,
             'life1: 'async_trait,
             'life2: 'async_trait;
    fn execute_with_projection<'life0, 'life1, 'life2, 'life3, 'async_trait>(
        &'life0 self,
        view: &'life1 str,
        projection: Option<&'life2 SqlProjectionHint>,
        where_clause: Option<&'life3 WhereClause>,
        limit: Option<u32>,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<JsonbValue>>> + Send + 'async_trait>>
       where Self: 'async_trait,
             'life0: 'async_trait,
             'life1: 'async_trait,
             'life2: 'async_trait,
             'life3: 'async_trait;
    fn database_type(&self) -> DatabaseType;
    fn health_check<'life0, 'async_trait>(
        &'life0 self,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>
       where Self: 'async_trait,
             'life0: 'async_trait;
    fn pool_metrics(&self) -> PoolMetrics;
    fn execute_raw_query<'life0, 'life1, 'async_trait>(
        &'life0 self,
        sql: &'life1 str,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<HashMap<String, Value>>>> + Send + 'async_trait>>
       where Self: 'async_trait,
             'life0: 'async_trait,
             'life1: 'async_trait;
    fn execute_function_call<'life0, 'life1, 'life2, 'async_trait>(
        &'life0 self,
        function_name: &'life1 str,
        args: &'life2 [Value],
    ) -> Pin<Box<dyn Future<Output = Result<Vec<HashMap<String, Value>>>> + Send + 'async_trait>>
       where Self: 'async_trait,
             'life0: 'async_trait,
             'life1: 'async_trait,
             'life2: 'async_trait;

    // Provided method
    fn capabilities(&self) -> DatabaseCapabilities { ... }
}
Expand description

Database adapter for executing queries against views.

This trait abstracts over different database backends (PostgreSQL, MySQL, SQLite, SQL Server). All implementations must support:

  • Executing simple WHERE queries against views
  • Returning JSONB data from the data column
  • Connection pooling and health checks

§Example

use fraiseql_core::db::{DatabaseAdapter, WhereClause, WhereOperator};
use serde_json::json;

// Build WHERE clause
let where_clause = WhereClause::Field {
    path: vec!["email".to_string()],
    operator: WhereOperator::Icontains,
    value: json!("example.com"),
};

// Execute query
let results = adapter
    .execute_where_query("v_user", Some(&where_clause), None, None)
    .await?;

println!("Found {} users", results.len());

Required Methods§

Source

fn execute_where_query<'life0, 'life1, 'life2, 'async_trait>( &'life0 self, view: &'life1 str, where_clause: Option<&'life2 WhereClause>, limit: Option<u32>, offset: Option<u32>, ) -> Pin<Box<dyn Future<Output = Result<Vec<JsonbValue>>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait,

Execute a WHERE query against a view and return JSONB rows.

§Arguments
  • view - View name (e.g., “v_user”, “v_post”)
  • where_clause - Optional WHERE clause AST
  • limit - Optional row limit (for pagination)
  • offset - Optional row offset (for pagination)
§Returns

Vec of JSONB values from the data column.

§Errors

Returns FraiseQLError::Database on query execution failure. Returns FraiseQLError::ConnectionPool if connection pool is exhausted.

§Example
// Simple query without WHERE clause
let all_users = adapter
    .execute_where_query("v_user", None, Some(10), Some(0))
    .await?;
Source

fn execute_with_projection<'life0, 'life1, 'life2, 'life3, 'async_trait>( &'life0 self, view: &'life1 str, projection: Option<&'life2 SqlProjectionHint>, where_clause: Option<&'life3 WhereClause>, limit: Option<u32>, ) -> Pin<Box<dyn Future<Output = Result<Vec<JsonbValue>>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait, 'life3: 'async_trait,

Execute a WHERE query with SQL field projection optimization.

Projects only the requested fields at the database level, reducing network payload and JSON deserialization overhead by 40-55% based on production measurements.

This is the primary query execution method for optimized GraphQL queries. It automatically selects only the fields requested in the GraphQL query, avoiding unnecessary network transfer and deserialization of unused fields.

§Automatic Projection

In most cases, you don’t call this directly. The Executor automatically:

  1. Determines which fields the GraphQL query requests
  2. Generates a SqlProjectionHint using database-specific SQL
  3. Calls this method with the projection hint
§Arguments
  • view - View name (e.g., “v_user”, “v_post”)
  • projection - Optional SQL projection hint with field list
    • Some(hint): Use projection to select only requested fields
    • None: Falls back to standard query (full JSONB column)
  • where_clause - Optional WHERE clause AST for filtering
  • limit - Optional row limit (for pagination)
§Returns

Vec of JSONB values, either:

  • Full objects (when projection is None)
  • Projected objects with only requested fields (when projection is Some)
§Errors

Returns FraiseQLError::Database on query execution failure, including:

  • Connection pool exhaustion
  • SQL execution errors
  • Type mismatches
§Performance Characteristics

When projection is provided (recommended):

  • Latency: 40-55% reduction vs full object fetch
  • Network: 40-55% smaller payload (proportional to unused fields)
  • Throughput: Maintains 250+ Kelem/s (elements per second)
  • Memory: Proportional to projected fields only

Improvement scales with:

  • Percentage of unused fields (more unused = more improvement)
  • Size of result set (larger sets benefit more)
  • Network latency (network-bound queries benefit most)

When projection is None:

  • Behavior identical to execute_where_query()
  • Returns full JSONB column
  • Used for compatibility/debugging
§Database Support
DatabaseStatusImplementation
PostgreSQL✅ Optimizedjsonb_build_object()
MySQL⏳ FallbackServer-side filtering (planned)
SQLite⏳ FallbackServer-side filtering (planned)
SQL Server⏳ FallbackServer-side filtering (planned)
§Example: Direct Usage (Advanced)
use fraiseql_core::schema::SqlProjectionHint;
use fraiseql_core::db::DatabaseAdapter;

let projection = SqlProjectionHint {
    database: "postgresql".to_string(),
    projection_template: "jsonb_build_object(\
        'id', data->>'id', \
        'name', data->>'name', \
        'email', data->>'email'\
    )".to_string(),
    estimated_reduction_percent: 75,
};

let results = adapter
    .execute_with_projection("v_user", Some(&projection), None, Some(100))
    .await?;

// results only contain id, name, email fields
// 75% smaller than fetching all fields
§Example: Fallback (No Projection)
// For debugging or when projection not available
let results = adapter
    .execute_with_projection("v_user", None, None, Some(100))
    .await?;

// Equivalent to execute_where_query() - returns full objects
§See Also
  • execute_where_query() - Standard query without projection
  • SqlProjectionHint - Structure defining field projection
  • Projection Optimization Guide
Source

fn database_type(&self) -> DatabaseType

Get database type (for logging/metrics).

Used to identify which database backend is in use.

Source

fn health_check<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Health check - verify database connectivity.

Executes a simple query (e.g., SELECT 1) to verify the database is reachable.

§Errors

Returns FraiseQLError::Database if health check fails.

Source

fn pool_metrics(&self) -> PoolMetrics

Get connection pool metrics.

Returns current statistics about the connection pool:

  • Total connections
  • Idle connections
  • Active connections
  • Waiting requests
Source

fn execute_raw_query<'life0, 'life1, 'async_trait>( &'life0 self, sql: &'life1 str, ) -> Pin<Box<dyn Future<Output = Result<Vec<HashMap<String, Value>>>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Execute raw SQL query and return rows as JSON objects.

Used for aggregation queries where we need full row data, not just JSONB column.

§Security Warning

This method executes arbitrary SQL. NEVER pass untrusted input directly to this method. Always:

  • Use parameterized queries with bound parameters
  • Validate and sanitize SQL templates before execution
  • Only execute SQL generated by the FraiseQL compiler
  • Log SQL execution for audit trails
§Arguments
  • sql - Raw SQL query to execute (must be safe/trusted)
§Returns

Vec of rows, where each row is a HashMap of column name to JSON value.

§Errors

Returns FraiseQLError::Database on query execution failure.

§Example
// Safe: SQL generated by FraiseQL compiler
let sql = "SELECT category, SUM(revenue) as total FROM tf_sales GROUP BY category";
let rows = adapter.execute_raw_query(sql).await?;
for row in rows {
    println!("Category: {}, Total: {}", row["category"], row["total"]);
}
Source

fn execute_function_call<'life0, 'life1, 'life2, 'async_trait>( &'life0 self, function_name: &'life1 str, args: &'life2 [Value], ) -> Pin<Box<dyn Future<Output = Result<Vec<HashMap<String, Value>>>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait,

Execute a PostgreSQL function call and return all columns as rows.

Builds SELECT * FROM {function_name}($1, $2, ...) with one positional placeholder per argument, executes it with the provided JSON values, and returns each result row as a HashMap<column_name, json_value>.

Used by the mutation execution pathway to call stored procedures that return the app.mutation_response composite type (status, message, entity_id, entity_type, entity jsonb, updated_fields text[], cascade jsonb, metadata jsonb).

§Arguments
  • function_name - Fully-qualified PostgreSQL function name (e.g. fn_create_machine)
  • args - Positional JSON arguments passed as $1, $2, … bind parameters
§Errors

Returns FraiseQLError::Database on query execution failure.

Provided Methods§

Source

fn capabilities(&self) -> DatabaseCapabilities

Get database capabilities.

Returns information about what features this database supports, including collation strategies and limitations.

§Returns

DatabaseCapabilities describing supported features.

Implementors§