Skip to main content

toasty_core/
driver.rs

1//! Database driver interface for Toasty.
2//!
3//! This module defines the traits and types that database drivers must implement
4//! to integrate with the Toasty query engine. The two core traits are [`Driver`]
5//! (factory for connections and schema operations) and [`Connection`] (executes
6//! operations against a live database session).
7//!
8//! The query planner inspects [`Capability`] to decide which [`Operation`]
9//! variants to emit. SQL-based drivers receive [`Operation::QuerySql`],
10//! [`Operation::RawSql`], and [`Operation::Insert`], while key-value drivers
11//! (e.g., DynamoDB) receive [`Operation::GetByKey`], [`Operation::QueryPk`], etc.
12//! SQL drivers receive upserts through `Operation::QuerySql`. Non-SQL drivers
13//! receive `Operation::Upsert` with an already-lowered conflict target and
14//! return projection. The
15//! [`SchemaMutations`] sub-struct (`Capability::schema_mutations`) describes
16//! what the database can do to its own schema — for example, whether
17//! `ALTER COLUMN` can change a column's type — and the migration generator
18//! consults it to decide between an in-place alter and a table rebuild.
19//! [`SqlPlaceholder`] describes the bind placeholder syntax used by SQL
20//! operations and raw SQL.
21//!
22//! # Architecture
23//!
24//! ```text
25//! Query Engine  ──▶  Operation  ──▶  Connection::exec()  ──▶  ExecResponse
26//!                        ▲
27//!                        │
28//!               Driver::capability()
29//! ```
30//!
31//! # Error classification
32//!
33//! The pool and the engine branch on the error variant returned from
34//! [`Connection::exec`] and [`Connection::ping`]. Drivers MUST cooperate
35//! with those branches:
36//!
37//! - A connection-level fault (closed socket, broken pipe, protocol
38//!   error, end-of-stream during handshake) MUST be classified as
39//!   [`crate::Error::connection_lost`]. The pool uses that signal to
40//!   evict the slot and to wake the background sweep, which then pings
41//!   the remaining idle connections and drops any that also fail. Any
42//!   other error variant for the same condition leaks a dead connection
43//!   back into the pool.
44//!
45//! - A retryable transaction conflict (PostgreSQL SQLSTATE `40001`,
46//!   MySQL error `1213`) SHOULD be classified as
47//!   [`crate::Error::serialization_failure`]. The engine does not retry
48//!   automatically; the classification is propagated to user code so
49//!   the caller can decide.
50//!
51//! - A write attempted against a read-only session (PostgreSQL
52//!   `25006`, MySQL `1792`) SHOULD be classified as
53//!   [`crate::Error::read_only_transaction`].
54//!
55//! Other backend errors are typically wrapped with
56//! [`crate::Error::driver_operation_failed`].
57
58mod capability;
59pub use capability::{Capability, SchemaMutations, SqlPlaceholder, StorageTypes};
60
61mod connection_url;
62pub use connection_url::ConnectionUrl;
63
64mod dialect;
65pub use dialect::Dialect;
66
67pub mod log;
68pub use log::QueryLogConfig;
69
70mod response;
71pub use response::{ExecResponse, Rows};
72
73pub mod operation;
74pub use operation::{IsolationLevel, Operation};
75
76use crate::schema::{
77    Schema,
78    db::{AppliedMigration, Migration},
79};
80
81use async_trait::async_trait;
82
83use std::{borrow::Cow, fmt::Debug, sync::Arc};
84
85/// Per-connection configuration passed to [`Driver::connect`].
86///
87/// The connection pool builds one from the values set on `Db::builder()` and
88/// hands it to the driver every time a new connection is created, so drivers
89/// can apply configuration at construction time rather than through separate
90/// setters. Callers connecting outside a pool use
91/// [`ConnectContext::default()`].
92///
93/// The struct is non-exhaustive: construct it with `default()` and assign the
94/// fields to override.
95#[derive(Debug, Clone, Default)]
96#[non_exhaustive]
97pub struct ConnectContext {
98    /// Configuration for the per-query `toasty::query` tracing event (see
99    /// [`log`]). Drivers that emit the event store this on the connection
100    /// and consult it on every operation.
101    pub query_log: QueryLogConfig,
102}
103
104/// Factory for database connections and provider of driver-level metadata.
105///
106/// Each database backend (SQLite, PostgreSQL, MySQL, DynamoDB) implements this
107/// trait to tell Toasty what the backend supports ([`Capability`]) and to
108/// create [`Connection`] instances on demand.
109///
110/// # Examples
111///
112/// ```ignore
113/// use toasty_core::driver::Driver;
114///
115/// // Drivers are typically constructed from a connection URL:
116/// let driver: Box<dyn Driver> = make_driver("sqlite::memory:").await;
117/// assert!(!driver.url().is_empty());
118///
119/// let capability = driver.capability();
120/// assert!(capability.sql());
121///
122/// let conn = driver.connect(&ConnectContext::default()).await.unwrap();
123/// ```
124#[async_trait]
125pub trait Driver: Debug + Send + Sync + 'static {
126    /// Returns the URL this driver is connecting to.
127    fn url(&self) -> Cow<'_, str>;
128
129    /// Describes the driver's capability, which informs the query planner.
130    fn capability(&self) -> &'static Capability;
131
132    /// Creates a new connection to the database.
133    ///
134    /// This method is called by the [`Pool`] whenever a [`Connection`] is requested while none is
135    /// available and there is room to create a new [`Connection`]. The [`ConnectContext`] carries
136    /// per-connection configuration the driver applies at construction time.
137    async fn connect(&self, cx: &ConnectContext) -> crate::Result<Box<dyn Connection>>;
138
139    /// Returns the maximum number of simultaneous database connections supported. For example,
140    /// this is `Some(1)` for the in-memory SQLite driver which cannot be pooled.
141    fn max_connections(&self) -> Option<usize> {
142        None
143    }
144
145    /// Drops the entire database and recreates an empty one without applying migrations.
146    ///
147    /// Used primarily in tests to start with a clean slate.
148    async fn reset_db(&self) -> crate::Result<()>;
149}
150
151/// A live database session that can execute [`Operation`]s.
152///
153/// Connections are obtained from [`Driver::connect`] and are managed by the
154/// connection pool. All query execution flows through [`Connection::exec`],
155/// which accepts an [`Operation`] and returns an [`ExecResponse`].
156///
157/// # Examples
158///
159/// ```ignore
160/// use toasty_core::driver::{Connection, Operation, ExecResponse};
161/// use toasty_core::driver::operation::Transaction;
162///
163/// // Execute a transaction start operation on a connection:
164/// let response = conn.exec(&schema, Transaction::start().into()).await?;
165/// ```
166#[async_trait]
167pub trait Connection: Debug + Send + 'static {
168    /// Executes a database operation and returns the result.
169    ///
170    /// This is the single entry point for all database interactions. The
171    /// query engine compiles user queries into [`Operation`] values and
172    /// dispatches them here. The driver translates each operation into
173    /// backend-specific calls and returns an [`ExecResponse`].
174    ///
175    /// Drivers use only the database-level half of the schema (`schema.db`:
176    /// tables, columns, indices). The application schema (models, fields,
177    /// mappings) is an engine concept that a driver never consults.
178    /// Everything in the operation is already expressed in database terms:
179    /// `#[document]` values arrive as named `Value::Object`s, document paths
180    /// as resolved `FuncJsonExtract` name paths, and document columns are
181    /// typed by the structural `Type::Object`.
182    async fn exec(&mut self, schema: &Arc<Schema>, plan: Operation) -> crate::Result<ExecResponse>;
183
184    /// Cheap, synchronous, local check that the driver's client object
185    /// still considers the connection open.
186    ///
187    /// Examples: a flag the driver flips when its background reader
188    /// reports a socket close (the MySQL driver does this), an
189    /// `is_closed()` accessor on the underlying client. Implementations
190    /// must not block and must not perform I/O — the check runs on the
191    /// hot path of every recycle and must complete in nanoseconds.
192    /// Drivers that cannot answer cheaply leave this at the default and
193    /// rely on the pool's [`ping`](Self::ping) sweep or the per-acquire
194    /// pre-ping option to catch a dead connection.
195    ///
196    /// The pool consults `is_valid()` whenever a connection is returned
197    /// to the idle set. A `false` result causes the slot to be dropped
198    /// before another caller can pick it up; the pool then returns
199    /// another idle connection or opens a fresh one. A connection is
200    /// also re-checked immediately after every [`Connection::exec`]; if
201    /// the operation flipped the flag (e.g. the driver classified the
202    /// error as connection-lost and updated its state), the worker task
203    /// exits and the slot is evicted.
204    ///
205    /// The default returns `true`. Drivers without a usable passive
206    /// signal stay on this default and rely on the active path: an
207    /// operation surfaces [`crate::Error::connection_lost`], the pool
208    /// drops the slot, and the background sweep eagerly pings the rest
209    /// of the idle pool.
210    fn is_valid(&self) -> bool {
211        true
212    }
213
214    /// Active liveness probe. The pool's background health-check sweep
215    /// calls this on the longest-idle connection on every tick, and on
216    /// every other idle connection when an escalation is triggered.
217    /// When `pool_pre_ping` is enabled, the pool also calls it on every
218    /// acquire.
219    ///
220    /// Drivers MUST classify a failure here as
221    /// [`crate::Error::connection_lost`] rather than a generic operation
222    /// error. The pool branches on that classification to drop the slot
223    /// (vs. returning it to the idle set after a transient query
224    /// error), and a user-observed `connection_lost` is what wakes the
225    /// pool's sweep to eagerly check the rest of the pool. Returning
226    /// any other error variant from `ping` will leak a dead connection
227    /// back into rotation.
228    ///
229    /// Drivers SHOULD make this the cheapest round-trip the backend
230    /// supports (`SELECT 1`, `COM_PING`, etc.). A ping that runs slower
231    /// than the sweep's per-call timeout (5 seconds, internal) is
232    /// treated as failed.
233    ///
234    /// The default returns `Ok(())` without doing any I/O. That is the
235    /// right answer for drivers whose connection layer cannot fail in
236    /// isolation (the in-process SQLite driver) or whose backend
237    /// manages its own pool beneath this surface (DynamoDB, where each
238    /// `exec` is an HTTP call with its own retry policy).
239    async fn ping(&mut self) -> crate::Result<()> {
240        Ok(())
241    }
242
243    /// Creates tables and indices defined in the schema on the database.
244    /// TODO: This will probably use database introspection in the future.
245    async fn push_schema(&mut self, _schema: &Schema) -> crate::Result<()>;
246
247    /// Returns a list of currently applied database migrations.
248    async fn applied_migrations(&mut self) -> crate::Result<Vec<AppliedMigration>>;
249
250    /// Applies a single migration to the database and records it as applied.
251    async fn apply_migration(
252        &mut self,
253        id: u64,
254        name: &str,
255        migration: &Migration,
256    ) -> crate::Result<()>;
257}