cooklang_sync_client/
connection.rs

1use diesel::r2d2::{ConnectionManager, Pool, PooledConnection};
2use diesel::SqliteConnection;
3use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
4
5use crate::errors::SyncError;
6
7pub type Connection = PooledConnection<ConnectionManager<SqliteConnection>>;
8pub type ConnectionPool = Pool<ConnectionManager<SqliteConnection>>;
9
10pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations");
11
12pub fn get_connection_pool(db_path: &str) -> Result<ConnectionPool, SyncError> {
13    let manager = ConnectionManager::<SqliteConnection>::new(db_path);
14
15    let pool = match Pool::builder().test_on_check_out(true).build(manager) {
16        Ok(p) => p,
17        Err(e) => return Err(SyncError::ConnectionInitError(e.to_string())),
18    };
19
20    let conn = &mut get_connection(&pool)?;
21
22    if let Err(e) = conn.run_pending_migrations(MIGRATIONS) {
23        return Err(SyncError::ConnectionInitError(e.to_string()));
24    };
25
26    Ok(pool)
27}
28
29pub fn get_connection(pool: &ConnectionPool) -> Result<Connection, SyncError> {
30    let conn = match pool.get() {
31        Ok(c) => c,
32        Err(e) => return Err(SyncError::ConnectionInitError(e.to_string())),
33    };
34
35    Ok(conn)
36}