1#![warn(missing_docs)]
2
3mod pragma;
21use pragma::Pragmas;
22pub use pragma::{AutoVacuum, JournalMode, LockingMode, Synchronous};
23
24mod value;
25pub(crate) use value::Value;
26
27use async_trait::async_trait;
28use rusqlite::Connection as RusqliteConnection;
29use std::{
30 borrow::Cow,
31 path::{Path, PathBuf},
32 sync::Arc,
33 time::Duration,
34};
35use toasty_core::{
36 Result, Schema,
37 driver::{
38 Capability, ConnectContext, ConnectionUrl, Driver, ExecResponse, QueryLogConfig,
39 log::QueryLog,
40 operation::{IsolationLevel, Operation, RawSqlRet, Transaction, TypedValue},
41 },
42 schema::db::{self, Table},
43 stmt,
44};
45use toasty_sql::{self as sql};
46
47enum SqlReturn {
48 Count,
49 Infer,
50 Types(Vec<stmt::Type>),
51}
52
53#[derive(Debug)]
63pub struct Sqlite {
64 source: Source,
65 busy_timeout: Duration,
66 pragmas: Pragmas,
67}
68
69#[derive(Debug)]
71enum Source {
72 File(PathBuf),
74 InMemory,
76}
77
78impl Sqlite {
79 fn from_source(source: Source) -> Self {
80 Self {
81 source,
82 busy_timeout: Duration::from_secs(5),
83 pragmas: Pragmas::default(),
84 }
85 }
86
87 pub fn new(url: impl Into<String>) -> Result<Self> {
89 let url_str = url.into();
90 let url = ConnectionUrl::parse(&url_str)?;
91
92 if !url.has_scheme("sqlite") {
93 return Err(toasty_core::Error::invalid_connection_url(format!(
94 "connection URL does not have a `sqlite` scheme; url={url_str}"
95 )));
96 }
97
98 let path = url.file_path()?;
99 if path == Path::new(":memory:") {
100 return Ok(Self::in_memory());
101 }
102
103 Ok(Self::open(path))
104 }
105
106 pub fn in_memory() -> Self {
108 Self::from_source(Source::InMemory)
109 }
110
111 pub fn open<P: AsRef<Path>>(path: P) -> Self {
113 Self::from_source(Source::File(path.as_ref().to_path_buf()))
114 }
115
116 pub fn foreign_keys(mut self, on: bool) -> Self {
121 self.pragmas
122 .set("foreign_keys", if on { "ON" } else { "OFF" });
123 self
124 }
125
126 pub fn busy_timeout(mut self, timeout: Duration) -> Self {
132 self.busy_timeout = timeout;
133 self
134 }
135
136 pub fn journal_mode(mut self, mode: JournalMode) -> Self {
153 self.pragmas.set("journal_mode", mode);
154 self
155 }
156
157 pub fn synchronous(mut self, synchronous: Synchronous) -> Self {
163 self.pragmas.set("synchronous", synchronous);
164 self
165 }
166
167 pub fn locking_mode(mut self, mode: LockingMode) -> Self {
171 self.pragmas.set("locking_mode", mode);
172 self
173 }
174
175 pub fn auto_vacuum(mut self, auto_vacuum: AutoVacuum) -> Self {
181 self.pragmas.set("auto_vacuum", auto_vacuum);
182 self
183 }
184
185 pub fn page_size(mut self, page_size: u32) -> Self {
192 self.pragmas.set("page_size", page_size.to_string());
193 self
194 }
195
196 #[cfg(feature = "sqlcipher")]
214 pub fn key(mut self, passphrase: impl AsRef<str>) -> Self {
215 let quoted = format!("'{}'", passphrase.as_ref().replace('\'', "''"));
216 self.pragmas.set("key", quoted);
217 self
218 }
219
220 pub fn pragma<K, V>(mut self, key: K, value: V) -> Self
247 where
248 K: Into<Cow<'static, str>>,
249 V: Into<Cow<'static, str>>,
250 {
251 self.pragmas.set(key, value);
252 self
253 }
254}
255
256#[async_trait]
257impl Driver for Sqlite {
258 fn url(&self) -> Cow<'_, str> {
259 match &self.source {
260 Source::InMemory => Cow::Borrowed("sqlite::memory:"),
261 Source::File(path) => Cow::Owned(format!("sqlite:{}", path.display())),
262 }
263 }
264
265 fn capability(&self) -> &'static Capability {
266 &Capability::SQLITE
267 }
268
269 async fn connect(
270 &self,
271 cx: &ConnectContext,
272 ) -> toasty_core::Result<Box<dyn toasty_core::Connection>> {
273 let mut connection = match &self.source {
274 Source::File(path) => Connection::open(path)?,
275 Source::InMemory => Connection::in_memory(),
276 };
277 connection.query_log = cx.query_log;
278 connection
279 .connection
280 .busy_timeout(self.busy_timeout)
281 .map_err(toasty_core::Error::driver_operation_failed)?;
282 self.pragmas.apply(&connection.connection, &cx.query_log)?;
283 Ok(Box::new(connection))
284 }
285
286 fn max_connections(&self) -> Option<usize> {
287 matches!(self.source, Source::InMemory).then_some(1)
288 }
289
290 async fn reset_db(&self) -> toasty_core::Result<()> {
291 match &self.source {
292 Source::File(path) => {
293 if path.exists() {
295 std::fs::remove_file(path)
296 .map_err(toasty_core::Error::driver_operation_failed)?;
297 }
298 }
299 Source::InMemory => {
300 }
302 }
303
304 Ok(())
305 }
306}
307
308#[derive(Debug)]
310pub struct Connection {
311 connection: RusqliteConnection,
312 query_log: QueryLogConfig,
313}
314
315impl Connection {
316 pub fn in_memory() -> Self {
318 let connection = RusqliteConnection::open_in_memory().unwrap();
319
320 Self {
321 connection,
322 query_log: QueryLogConfig::default(),
323 }
324 }
325
326 pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
328 let connection =
329 RusqliteConnection::open(path).map_err(toasty_core::Error::driver_operation_failed)?;
330 let sqlite = Self {
331 connection,
332 query_log: QueryLogConfig::default(),
333 };
334 Ok(sqlite)
335 }
336
337 fn exec_sql(
338 &mut self,
339 sql_str: &str,
340 typed_params: Vec<TypedValue>,
341 ret: SqlReturn,
342 ) -> Result<ExecResponse> {
343 let mut log = QueryLog::sql(
344 &self.query_log,
345 "sqlite",
346 sql_str,
347 typed_params.iter().map(|tv| &tv.value),
348 );
349 let result = self.exec_sql_inner(sql_str, typed_params, ret, &mut log);
350 log.finish(&result);
351 result
352 }
353
354 fn exec_sql_inner(
355 &mut self,
356 sql_str: &str,
357 typed_params: Vec<TypedValue>,
358 ret: SqlReturn,
359 log: &mut QueryLog<'_>,
360 ) -> Result<ExecResponse> {
361 let mut stmt = self
362 .connection
363 .prepare_cached(sql_str)
364 .map_err(toasty_core::Error::driver_operation_failed)?;
365
366 let params = typed_params
367 .into_iter()
368 .map(|tv| Value::from(tv.value))
369 .collect::<Vec<_>>();
370
371 if matches!(ret, SqlReturn::Count) {
372 let count = stmt
373 .execute(rusqlite::params_from_iter(params.iter()))
374 .map_err(toasty_core::Error::driver_operation_failed)?;
375
376 return Ok(ExecResponse::count(count as _));
377 }
378
379 let mut rows = stmt
380 .query(rusqlite::params_from_iter(params.iter()))
381 .map_err(toasty_core::Error::driver_operation_failed)?;
382
383 let mut values = vec![];
384 let column_count = rows.as_ref().map(|stmt| stmt.column_count()).unwrap_or(0);
385
386 loop {
387 match rows.next() {
388 Ok(Some(row)) => {
389 let items = match &ret {
390 SqlReturn::Count => unreachable!(),
391 SqlReturn::Infer => (0..column_count)
392 .map(|index| Value::from_sql_infer(row, index).into_inner())
393 .collect(),
394 SqlReturn::Types(ret_tys) => ret_tys
395 .iter()
396 .enumerate()
397 .map(|(index, ret_ty)| Value::from_sql(row, index, ret_ty).into_inner())
398 .collect(),
399 };
400
401 values.push(stmt::ValueRecord::from_vec(items).into());
402 }
403 Ok(None) => break,
404 Err(err) => {
405 return Err(toasty_core::Error::driver_operation_failed(err));
406 }
407 }
408 }
409
410 log.rows(values.len() as u64);
411 Ok(ExecResponse::value_stream(stmt::ValueStream::from_vec(
412 values,
413 )))
414 }
415}
416
417#[async_trait]
418impl toasty_core::driver::Connection for Connection {
419 async fn exec(&mut self, schema: &Arc<Schema>, op: Operation) -> Result<ExecResponse> {
420 tracing::trace!(driver = "sqlite", op = %op.name(), "driver exec");
421
422 let (sql, typed_params, ret_tys) = match op {
423 Operation::Insert(op) => (sql::Statement::from(op.stmt), op.params, op.ret),
424 Operation::QuerySql(op) => (sql::Statement::from(op.stmt), op.params, op.ret),
425 Operation::RawSql(op) => {
426 let ret = match op.ret {
427 RawSqlRet::None => SqlReturn::Count,
428 RawSqlRet::Infer => SqlReturn::Infer,
429 RawSqlRet::Types(types) => SqlReturn::Types(types),
430 };
431 return self.exec_sql(&op.sql, op.params, ret);
432 }
433 Operation::Transaction(mut op) => {
434 if let Transaction::Start { isolation, .. } = &mut op {
435 if !matches!(isolation, Some(IsolationLevel::Serializable) | None) {
436 return Err(toasty_core::Error::unsupported_feature(
437 "SQLite only supports Serializable isolation",
438 ));
439 }
440 *isolation = None;
441 }
442 let sql = sql::Serializer::sqlite(&schema.db).serialize_transaction(&op);
443 self.connection
444 .execute(&sql, [])
445 .map_err(toasty_core::Error::driver_operation_failed)?;
446 return Ok(ExecResponse::count(0));
447 }
448 _ => todo!("op={:#?}", op),
449 };
450
451 let ret = match &sql {
452 sql::Statement::Query(stmt) => match &stmt.body {
453 stmt::ExprSet::Select(_) => SqlReturn::Types(ret_tys.unwrap()),
454 _ => todo!(),
455 },
456 sql::Statement::Insert(stmt) => stmt
457 .returning
458 .as_ref()
459 .map(|_| SqlReturn::Types(ret_tys.unwrap()))
460 .unwrap_or(SqlReturn::Count),
461 sql::Statement::Delete(stmt) => stmt
462 .returning
463 .as_ref()
464 .map(|_| SqlReturn::Types(ret_tys.unwrap()))
465 .unwrap_or(SqlReturn::Count),
466 sql::Statement::Update(stmt) => {
467 assert!(stmt.condition.is_none(), "stmt={stmt:#?}");
468 stmt.returning
469 .as_ref()
470 .map(|_| SqlReturn::Types(ret_tys.unwrap()))
471 .unwrap_or(SqlReturn::Count)
472 }
473 _ => SqlReturn::Count,
474 };
475
476 let sql_str = sql::Serializer::sqlite(&schema.db).serialize(&sql);
477 self.exec_sql(&sql_str, typed_params, ret)
478 }
479
480 async fn push_schema(&mut self, schema: &Schema) -> Result<()> {
481 for table in &schema.db.tables {
482 tracing::debug!(table = %table.name, "creating table");
483 self.create_table(&schema.db, table)?;
484 }
485
486 Ok(())
487 }
488
489 async fn applied_migrations(
490 &mut self,
491 ) -> Result<Vec<toasty_core::schema::db::AppliedMigration>> {
492 self.connection
494 .execute(
495 "CREATE TABLE IF NOT EXISTS __toasty_migrations (
496 id INTEGER PRIMARY KEY,
497 name TEXT NOT NULL,
498 applied_at TEXT NOT NULL
499 )",
500 [],
501 )
502 .map_err(toasty_core::Error::driver_operation_failed)?;
503
504 let mut stmt = self
506 .connection
507 .prepare("SELECT id FROM __toasty_migrations ORDER BY applied_at")
508 .map_err(toasty_core::Error::driver_operation_failed)?;
509
510 let rows = stmt
511 .query_map([], |row| {
512 let id: i64 = row.get(0)?;
513 Ok(toasty_core::schema::db::AppliedMigration::new(id as u64))
514 })
515 .map_err(toasty_core::Error::driver_operation_failed)?;
516
517 rows.collect::<rusqlite::Result<Vec<_>>>()
518 .map_err(toasty_core::Error::driver_operation_failed)
519 }
520
521 async fn apply_migration(
522 &mut self,
523 id: u64,
524 name: &str,
525 migration: &toasty_core::schema::db::Migration,
526 ) -> Result<()> {
527 tracing::info!(id = id, name = %name, "applying migration");
528 self.connection
530 .execute(
531 "CREATE TABLE IF NOT EXISTS __toasty_migrations (
532 id INTEGER PRIMARY KEY,
533 name TEXT NOT NULL,
534 applied_at TEXT NOT NULL
535 )",
536 [],
537 )
538 .map_err(toasty_core::Error::driver_operation_failed)?;
539
540 self.connection
542 .execute("BEGIN", [])
543 .map_err(toasty_core::Error::driver_operation_failed)?;
544
545 for statement in migration.statements() {
547 if let Err(e) = self
548 .connection
549 .execute(statement, [])
550 .map_err(toasty_core::Error::driver_operation_failed)
551 {
552 self.connection
553 .execute("ROLLBACK", [])
554 .map_err(toasty_core::Error::driver_operation_failed)?;
555 return Err(e);
556 }
557 }
558
559 if let Err(e) = self.connection.execute(
561 "INSERT INTO __toasty_migrations (id, name, applied_at) VALUES (?1, ?2, datetime('now'))",
562 rusqlite::params![id as i64, name],
563 ).map_err(toasty_core::Error::driver_operation_failed) {
564 self.connection.execute("ROLLBACK", []).map_err(toasty_core::Error::driver_operation_failed)?;
565 return Err(e);
566 }
567
568 self.connection
570 .execute("COMMIT", [])
571 .map_err(toasty_core::Error::driver_operation_failed)?;
572 Ok(())
573 }
574}
575
576impl Connection {
577 fn create_table(&mut self, schema: &db::Schema, table: &Table) -> Result<()> {
578 let serializer = sql::Serializer::sqlite(schema);
579
580 let stmt = serializer.serialize(&sql::Statement::create_table(table, &Capability::SQLITE));
581
582 self.connection
583 .execute(&stmt, [])
584 .map_err(toasty_core::Error::driver_operation_failed)?;
585
586 for index in &table.indices {
588 if index.primary_key {
590 continue;
591 }
592
593 let stmt = serializer.serialize(&sql::Statement::create_index(index));
594
595 self.connection
596 .execute(&stmt, [])
597 .map_err(toasty_core::Error::driver_operation_failed)?;
598 }
599 Ok(())
600 }
601}