Skip to main content

rustlavel_db/
lib.rs

1//! rustlavel-db: the database package.
2//!
3//! A PostgreSQL driver written directly on the version 3 wire protocol, a
4//! connection pool, a query builder, schema migrations, and seeding. Enabled
5//! with `cargo add rustlavel-db` — an application that never adds it never
6//! compiles a line of this.
7
8pub mod base64;
9pub mod builder;
10pub mod config;
11pub mod connections;
12pub mod credentials;
13pub mod dialect;
14pub mod driver;
15pub mod migration;
16pub mod model;
17pub mod mysql;
18pub mod pagination;
19pub mod pool;
20pub mod postgres;
21pub mod random;
22pub mod row;
23pub mod schema;
24pub mod sqlserver;
25pub mod tls;
26pub mod value;
27
28pub use builder::{Direction, QueryBuilder};
29pub use config::DatabaseConfig;
30pub use dialect::{ColumnType, Dialect, ReturningStyle};
31pub use driver::{Driver, DriverConnection, QueryResult};
32pub use connections::{Connections, DEFAULT_BUDGET};
33pub use migration::{Faker, Migration, Migrator, Seeder};
34pub use model::{Model, ModelExt, belongs_to, has_many};
35pub use mysql::{MySqlConnection, MySqlDriver};
36pub use pagination::{CursorPage, Page};
37pub use postgres::connection::{log_bindings, set_log_bindings};
38pub use pool::{Pool, PooledConnection};
39pub use schema::{Schema, Table};
40pub use sqlserver::{SqlServerConnection, SqlServerDriver};
41pub use row::{Row, rows_to_json};
42pub use value::{FromValue, Value};
43
44pub use rustlavel_core::{Error, Result};
45use std::sync::Arc;
46
47/// Build the driver a configuration asks for.
48///
49/// A driver that is not compiled into this build says so by name, rather than
50/// failing later with something about a connection.
51fn driver_for(config: DatabaseConfig) -> Result<Arc<dyn Driver>> {
52    match config.driver.as_str() {
53        "postgres" => Ok(Arc::new(postgres::PostgresDriver::new(config))),
54        "mysql" => Ok(Arc::new(mysql::MySqlDriver::new(config))),
55        "sqlserver" => Ok(Arc::new(sqlserver::SqlServerDriver::new(config))),
56        other => Err(Error::msg(format!(
57            "the `{other}` driver is not available in this build. \
58             Point DATABASE_URL at a database this build supports."
59        ))),
60    }
61}
62
63/// `#[derive(Model)]`.
64pub use rustlavel_macros::Model;
65
66/// What a migration, seeder, or model file imports.
67pub mod prelude {
68    pub use crate::migration::{Faker, Migrator, Seeder};
69    pub use crate::model::{ModelExt, belongs_to, has_many};
70    pub use crate::schema::{Schema, Table};
71    pub use crate::{CursorPage, Database, Model, Page, QueryBuilder, Row, Value};
72    pub use rustlavel_core::{Error, Json, Result};
73}
74
75/// The application's handle on the database.
76///
77/// Registered as application state, so a handler reaches it with
78/// `req.state::<Database>()`.
79#[derive(Clone)]
80pub struct Database {
81    pool: Pool,
82    dialect: Arc<dyn Dialect>,
83}
84
85impl Database {
86    /// Connect using a URL: `postgres://user:password@host:port/database`.
87    pub async fn connect(url: &str) -> Result<Database> {
88        Database::with_config(DatabaseConfig::from_url(url)?).await
89    }
90
91    /// Connect using explicit settings, verifying the connection works.
92    pub async fn with_config(config: DatabaseConfig) -> Result<Database> {
93        let database = Database::lazy(config)?;
94        database.pool.verify().await?;
95        Ok(database)
96    }
97
98    /// Build a handle without touching the network. Useful when the process
99    /// should start even if the database is briefly down.
100    pub fn lazy(config: DatabaseConfig) -> Result<Database> {
101        Ok(Database::with_driver(driver_for(config)?))
102    }
103
104    /// Use a driver directly — how a database this crate does not know about
105    /// would be plugged in.
106    pub fn with_driver(driver: Arc<dyn Driver>) -> Database {
107        let dialect = driver.dialect();
108        Database { pool: Pool::new(driver), dialect }
109    }
110
111    /// What SQL this connection speaks.
112    ///
113    /// The query and schema builders take it, which is how one builder produces
114    /// correct SQL for three different databases.
115    pub fn dialect(&self) -> &dyn Dialect {
116        self.dialect.as_ref()
117    }
118
119    pub fn pool(&self) -> &Pool {
120        &self.pool
121    }
122
123    /// Start a query: `db.table("users").filter("active", true).get(&db).await`.
124    pub fn table(&self, name: &str) -> QueryBuilder {
125        QueryBuilder::new(name)
126    }
127
128    /// Run a query and return every row.
129    pub async fn select(&self, sql: &str, params: &[Value]) -> Result<Vec<Row>> {
130        let mut connection = self.pool.acquire().await?;
131        Ok(connection.query(sql, params).await?.rows)
132    }
133
134    /// Run a query expecting at most one row.
135    pub async fn select_one(&self, sql: &str, params: &[Value]) -> Result<Option<Row>> {
136        Ok(self.select(sql, params).await?.into_iter().next())
137    }
138
139    /// Run a statement and return the number of rows it affected.
140    pub async fn execute(&self, sql: &str, params: &[Value]) -> Result<u64> {
141        let mut connection = self.pool.acquire().await?;
142        Ok(connection.query(sql, params).await?.affected)
143    }
144
145    /// Run one or more statements with no parameters — DDL, mostly.
146    pub async fn run(&self, sql: &str) -> Result<u64> {
147        let mut connection = self.pool.acquire().await?;
148        Ok(connection.simple_query(sql).await?.affected)
149    }
150
151    /// Run an insert and hand back the key the database generated.
152    ///
153    /// Three mechanisms, one method: PostgreSQL returns a row from `RETURNING`,
154    /// SQL Server from `OUTPUT`, and MySQL reports the id in the packet that
155    /// acknowledges the insert, with no row at all.
156    pub async fn insert_returning_key(
157        &self,
158        sql: &str,
159        params: &[Value],
160        column: &str,
161    ) -> Result<Option<Value>> {
162        let mut connection = self.pool.acquire().await?;
163        let result = connection.query(sql, params).await?;
164
165        if let Some(row) = result.rows.first() {
166            // Named lookup where the database labelled the column, positional
167            // where it did not.
168            return Ok(Some(row.value(column).or_else(|_| row.value_at(0))?.clone()));
169        }
170        Ok(result.last_insert_id.map(Value::Int))
171    }
172
173    /// Read a single value from the first column of the first row.
174    pub async fn scalar<T: FromValue>(&self, sql: &str, params: &[Value]) -> Result<Option<T>> {
175        match self.select_one(sql, params).await? {
176            Some(row) => row.get_at::<T>(0).map(Some),
177            None => Ok(None),
178        }
179    }
180
181    /// Begin a transaction.
182    ///
183    /// Rust's borrow rules make Laravel's `DB::transaction(closure)` shape
184    /// awkward — the closure's future would have to borrow the connection it
185    /// was handed — so the transaction is a value you hold instead:
186    ///
187    /// ```ignore
188    /// let mut tx = db.begin().await?;
189    /// tx.execute("update accounts set balance = balance - $1", &[amount]).await?;
190    /// tx.commit().await?;
191    /// ```
192    ///
193    /// Dropping it without committing rolls back, so an early `?` cannot leave
194    /// a half-finished transaction behind.
195    pub async fn begin(&self) -> Result<Transaction> {
196        let mut connection = self.pool.acquire().await?;
197        connection.simple_query(self.dialect.begin_sql()).await?;
198        Ok(Transaction {
199            connection: Some(connection),
200            dialect: Arc::clone(&self.dialect),
201            finished: false,
202        })
203    }
204
205    /// Close every pooled connection.
206    pub async fn close(&self) {
207        self.pool.close().await;
208    }
209}
210
211/// An open transaction, holding its connection until it ends.
212pub struct Transaction {
213    connection: Option<PooledConnection>,
214    /// Kept so committing and rolling back use this database's own words.
215    dialect: Arc<dyn Dialect>,
216    finished: bool,
217}
218
219impl Transaction {
220    fn connection(&mut self) -> Result<&mut PooledConnection> {
221        self.connection
222            .as_mut()
223            .ok_or_else(|| Error::msg("this transaction has already finished"))
224    }
225
226    pub async fn select(&mut self, sql: &str, params: &[Value]) -> Result<Vec<Row>> {
227        Ok(self.connection()?.query(sql, params).await?.rows)
228    }
229
230    pub async fn select_one(&mut self, sql: &str, params: &[Value]) -> Result<Option<Row>> {
231        Ok(self.select(sql, params).await?.into_iter().next())
232    }
233
234    pub async fn execute(&mut self, sql: &str, params: &[Value]) -> Result<u64> {
235        Ok(self.connection()?.query(sql, params).await?.affected)
236    }
237
238    pub async fn run(&mut self, sql: &str) -> Result<u64> {
239        Ok(self.connection()?.simple_query(sql).await?.affected)
240    }
241
242    pub async fn scalar<T: FromValue>(&mut self, sql: &str, params: &[Value]) -> Result<Option<T>> {
243        match self.select_one(sql, params).await? {
244            Some(row) => row.get_at::<T>(0).map(Some),
245            None => Ok(None),
246        }
247    }
248
249    /// A named savepoint, so part of a transaction can be undone on its own.
250    pub async fn savepoint(&mut self, name: &str) -> Result<()> {
251        validate_identifier(name)?;
252        let sql = self.dialect.savepoint_sql(name);
253        self.connection()?.simple_query(&sql).await?;
254        Ok(())
255    }
256
257    pub async fn rollback_to(&mut self, name: &str) -> Result<()> {
258        validate_identifier(name)?;
259        let sql = self.dialect.rollback_to_savepoint_sql(name);
260        self.connection()?.simple_query(&sql).await?;
261        Ok(())
262    }
263
264    /// Commit and release the connection.
265    pub async fn commit(mut self) -> Result<()> {
266        let sql = self.dialect.commit_sql();
267        self.connection()?.simple_query(sql).await?;
268        self.finished = true;
269        Ok(())
270    }
271
272    /// Roll back and release the connection.
273    pub async fn rollback(mut self) -> Result<()> {
274        let sql = self.dialect.rollback_sql();
275        self.connection()?.simple_query(sql).await?;
276        self.finished = true;
277        Ok(())
278    }
279}
280
281impl Drop for Transaction {
282    fn drop(&mut self) {
283        if self.finished {
284            return;
285        }
286        // Nothing committed it, so undo it. The pool would discard a connection
287        // left in a transaction anyway; rolling back explicitly returns it to
288        // service instead of throwing it away.
289        if let Some(mut connection) = self.connection.take() {
290            let sql = self.dialect.rollback_sql();
291            tokio::spawn(async move {
292                let _ = connection.simple_query(sql).await;
293            });
294        }
295    }
296}
297
298/// Reject anything that is not a plain identifier.
299///
300/// Identifiers cannot be sent as parameters, so every place the framework
301/// interpolates one into SQL passes through here first.
302pub fn validate_identifier(name: &str) -> Result<()> {
303    let valid = !name.is_empty()
304        && name.len() <= 63
305        && name.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
306        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
307
308    if valid {
309        Ok(())
310    } else {
311        Err(Error::msg(format!(
312            "`{name}` is not a valid SQL identifier. Identifiers may contain letters, digits and \
313             underscores, and must not start with a digit."
314        )))
315    }
316}
317
318/// Quote an identifier after validating it.
319pub fn quote_identifier(name: &str) -> Result<String> {
320    // A qualified name (`schema.table`) is validated one part at a time.
321    let quoted: Result<Vec<String>> = name
322        .split('.')
323        .map(|part| validate_identifier(part).map(|_| format!("\"{part}\"")))
324        .collect();
325    Ok(quoted?.join("."))
326}
327
328#[cfg(test)]
329mod tests {
330    use super::*;
331
332    #[test]
333    fn accepts_ordinary_identifiers() {
334        for name in ["users", "user_profiles", "_private", "t1"] {
335            assert!(validate_identifier(name).is_ok(), "{name} should be valid");
336        }
337    }
338
339    #[test]
340    fn rejects_anything_that_could_alter_a_statement() {
341        for name in ["users; drop table users", "user\"s", "1abc", "", "a b", "users--"] {
342            assert!(validate_identifier(name).is_err(), "{name:?} should be rejected");
343        }
344    }
345
346    #[test]
347    fn quotes_qualified_names_part_by_part() {
348        assert_eq!(quote_identifier("public.users").unwrap(), "\"public\".\"users\"");
349        assert!(quote_identifier("public.users; drop table x").is_err());
350    }
351}