common.rs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. use std::str::FromStr;
  2. use std::time::Duration;
  3. use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
  4. use sqlx::{Error, Pool, Sqlite};
  5. #[inline(always)]
  6. pub async fn create_sqlite_pool(
  7. path: &str,
  8. #[cfg(feature = "sqlcipher")] password: String,
  9. ) -> Result<Pool<Sqlite>, Error> {
  10. let db_options = SqliteConnectOptions::from_str(path)?
  11. .busy_timeout(Duration::from_secs(10))
  12. .read_only(false)
  13. .pragma("busy_timeout", "5000")
  14. .pragma("journal_mode", "wal")
  15. .pragma("synchronous", "normal")
  16. .pragma("temp_store", "memory")
  17. .pragma("mmap_size", "30000000000")
  18. .shared_cache(true)
  19. .create_if_missing(true);
  20. #[cfg(feature = "sqlcipher")]
  21. let db_options = db_options.pragma("key", password);
  22. let is_memory = path.contains(":memory:");
  23. let options = SqlitePoolOptions::new()
  24. .min_connections(1)
  25. .max_connections(1);
  26. let pool = if is_memory {
  27. // Make sure that the connection is not closed after the first query, or any query, as long
  28. // as the pool is not dropped
  29. options
  30. .idle_timeout(None)
  31. .max_lifetime(None)
  32. .test_before_acquire(false)
  33. } else {
  34. options
  35. }
  36. .connect_with(db_options)
  37. .await?;
  38. Ok(pool)
  39. }