1pub 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
47fn 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
63pub use rustlavel_macros::Model;
65
66pub 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#[derive(Clone)]
80pub struct Database {
81 pool: Pool,
82 dialect: Arc<dyn Dialect>,
83}
84
85impl Database {
86 pub async fn connect(url: &str) -> Result<Database> {
88 Database::with_config(DatabaseConfig::from_url(url)?).await
89 }
90
91 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 pub fn lazy(config: DatabaseConfig) -> Result<Database> {
101 Ok(Database::with_driver(driver_for(config)?))
102 }
103
104 pub fn with_driver(driver: Arc<dyn Driver>) -> Database {
107 let dialect = driver.dialect();
108 Database { pool: Pool::new(driver), dialect }
109 }
110
111 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 pub fn table(&self, name: &str) -> QueryBuilder {
125 QueryBuilder::new(name)
126 }
127
128 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 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 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 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 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 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 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 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 pub async fn close(&self) {
207 self.pool.close().await;
208 }
209}
210
211pub struct Transaction {
213 connection: Option<PooledConnection>,
214 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 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 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 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 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
298pub 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
318pub fn quote_identifier(name: &str) -> Result<String> {
320 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}