lib.rs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. pub mod schema;
  2. #[macro_use]
  3. pub mod macros;
  4. #[macro_use]
  5. extern crate diesel;
  6. pub use diesel::*;
  7. #[macro_use]
  8. extern crate diesel_derives;
  9. pub use diesel_derives::*;
  10. #[macro_use]
  11. extern crate diesel_migrations;
  12. pub use flowy_sqlite::{DBConnection, Database};
  13. use diesel_migrations::*;
  14. use flowy_sqlite::{Error, PoolConfig};
  15. use std::{fmt::Debug, io, path::Path};
  16. pub mod prelude {
  17. pub use super::UserDatabaseConnection;
  18. pub use diesel::{query_dsl::*, BelongingToDsl, ExpressionMethods, RunQueryDsl};
  19. }
  20. embed_migrations!("../flowy-database/migrations/");
  21. pub const DB_NAME: &str = "flowy-database.db";
  22. pub fn init(storage_path: &str) -> Result<Database, io::Error> {
  23. if !Path::new(storage_path).exists() {
  24. std::fs::create_dir_all(storage_path)?;
  25. }
  26. let pool_config = PoolConfig::default();
  27. let database = Database::new(storage_path, DB_NAME, pool_config).map_err(as_io_error)?;
  28. let conn = database.get_connection().map_err(as_io_error)?;
  29. let _ = embedded_migrations::run(&*conn).map_err(as_io_error)?;
  30. Ok(database)
  31. }
  32. fn as_io_error<E>(e: E) -> io::Error
  33. where
  34. E: Into<Error> + Debug,
  35. {
  36. let msg = format!("{:?}", e);
  37. io::Error::new(io::ErrorKind::NotConnected, msg)
  38. }
  39. pub trait UserDatabaseConnection: Send + Sync {
  40. fn get_connection(&self) -> Result<DBConnection, String>;
  41. }