lib.rs 1.1 KB

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