AppFlowy/rust-lib/flowy-database/src/lib.rs

54 lines
1.4 KiB
Rust
Raw Normal View History

pub mod schema;
2021-07-09 15:31:44 +00:00
#[macro_use]
pub mod macros;
2021-07-09 15:31:44 +00:00
#[macro_use]
extern crate diesel;
pub use diesel::*;
2021-07-09 15:31:44 +00:00
#[macro_use]
extern crate diesel_derives;
pub use diesel_derives::*;
2021-07-09 15:31:44 +00:00
#[macro_use]
extern crate diesel_migrations;
pub use flowy_sqlite::{ConnectionPool, DBConnection, Database};
pub type Error = diesel::result::Error;
2021-07-09 15:31:44 +00:00
use diesel_migrations::*;
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
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-09 15:31:44 +00:00
embed_migrations!("../flowy-database/migrations/");
pub const DB_NAME: &str = "flowy-database.db";
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();
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-11 09:38:03 +00:00
fn as_io_error<E>(e: E) -> io::Error
where
E: Into<flowy_sqlite::Error> + Debug,
2021-07-11 09:38:03 +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>;
}