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