2021-07-10 08:27:20 +00:00
|
|
|
pub mod schema;
|
2021-07-09 15:31:44 +00:00
|
|
|
|
2021-07-14 13:12:52 +00:00
|
|
|
#[macro_use]
|
|
|
|
pub mod macros;
|
|
|
|
|
2021-07-09 15:31:44 +00:00
|
|
|
#[macro_use]
|
|
|
|
extern crate diesel;
|
2021-07-10 08:27:20 +00:00
|
|
|
pub use diesel::*;
|
|
|
|
|
2021-07-09 15:31:44 +00:00
|
|
|
#[macro_use]
|
|
|
|
extern crate diesel_derives;
|
2021-07-10 08:27:20 +00:00
|
|
|
pub use diesel_derives::*;
|
|
|
|
|
2021-07-09 15:31:44 +00:00
|
|
|
#[macro_use]
|
|
|
|
extern crate diesel_migrations;
|
|
|
|
|
2021-09-11 12:09:46 +00:00
|
|
|
pub use flowy_sqlite::{ConnectionPool, DBConnection, Database};
|
2021-09-07 13:31:04 +00:00
|
|
|
pub type Error = diesel::result::Error;
|
2021-07-09 15:31:44 +00:00
|
|
|
|
|
|
|
use diesel_migrations::*;
|
2021-09-07 13:31:04 +00:00
|
|
|
use flowy_sqlite::PoolConfig;
|
2021-07-11 09:38:03 +00:00
|
|
|
use std::{fmt::Debug, io, path::Path};
|
2021-07-09 15:31:44 +00:00
|
|
|
|
2021-07-14 13:12:52 +00:00
|
|
|
pub mod prelude {
|
|
|
|
pub use super::UserDatabaseConnection;
|
2021-07-20 06:03:21 +00:00
|
|
|
pub use diesel::{query_dsl::*, BelongingToDsl, ExpressionMethods, RunQueryDsl};
|
2021-07-14 13:12:52 +00:00
|
|
|
}
|
|
|
|
|
2021-07-09 15:31:44 +00:00
|
|
|
embed_migrations!("../flowy-database/migrations/");
|
|
|
|
pub const DB_NAME: &str = "flowy-database.db";
|
|
|
|
|
2021-07-10 08:27:20 +00:00
|
|
|
pub fn init(storage_path: &str) -> Result<Database, io::Error> {
|
2021-07-09 15:31:44 +00:00
|
|
|
if !Path::new(storage_path).exists() {
|
|
|
|
std::fs::create_dir_all(storage_path)?;
|
|
|
|
}
|
|
|
|
let pool_config = PoolConfig::default();
|
2021-07-10 08:27:20 +00:00
|
|
|
let database = Database::new(storage_path, DB_NAME, pool_config).map_err(as_io_error)?;
|
|
|
|
let conn = database.get_connection().map_err(as_io_error)?;
|
2021-07-11 09:38:03 +00:00
|
|
|
let _ = embedded_migrations::run(&*conn).map_err(as_io_error)?;
|
2021-07-09 15:31:44 +00:00
|
|
|
Ok(database)
|
|
|
|
}
|
2021-07-10 08:27:20 +00:00
|
|
|
|
2021-07-11 09:38:03 +00:00
|
|
|
fn as_io_error<E>(e: E) -> io::Error
|
|
|
|
where
|
2021-09-07 13:31:04 +00:00
|
|
|
E: Into<flowy_sqlite::Error> + Debug,
|
2021-07-11 09:38:03 +00:00
|
|
|
{
|
2021-07-10 08:27:20 +00:00
|
|
|
let msg = format!("{:?}", e);
|
|
|
|
io::Error::new(io::ErrorKind::NotConnected, msg)
|
|
|
|
}
|
2021-07-13 15:08:20 +00:00
|
|
|
|
2021-07-14 00:07:25 +00:00
|
|
|
pub trait UserDatabaseConnection: Send + Sync {
|
2021-07-13 15:08:20 +00:00
|
|
|
fn get_connection(&self) -> Result<DBConnection, String>;
|
|
|
|
}
|