2021-06-06 01:25:45 +03:00
|
|
|
use crate::config::SupportedDatabaseClient;
|
2021-06-06 15:16:00 +03:00
|
|
|
use crate::Config;
|
2021-06-06 01:25:45 +03:00
|
|
|
#[cfg(feature = "mysql")]
|
|
|
|
use migra::clients::MysqlClient;
|
|
|
|
#[cfg(feature = "postgres")]
|
|
|
|
use migra::clients::PostgresClient;
|
|
|
|
#[cfg(feature = "sqlite")]
|
|
|
|
use migra::clients::SqliteClient;
|
|
|
|
use migra::clients::{AnyClient, OpenDatabaseConnection};
|
|
|
|
|
2021-06-07 23:57:32 +03:00
|
|
|
pub fn create_client(
|
2021-06-06 01:25:45 +03:00
|
|
|
client_kind: &SupportedDatabaseClient,
|
|
|
|
connection_string: &str,
|
2021-06-06 15:16:00 +03:00
|
|
|
migrations_table_name: &str,
|
2021-06-06 01:25:45 +03:00
|
|
|
) -> migra::Result<AnyClient> {
|
|
|
|
let client: AnyClient = match client_kind {
|
|
|
|
#[cfg(feature = "postgres")]
|
2021-06-06 15:16:00 +03:00
|
|
|
SupportedDatabaseClient::Postgres => Box::new(PostgresClient::manual(
|
|
|
|
connection_string,
|
|
|
|
migrations_table_name,
|
|
|
|
)?),
|
2021-06-06 01:25:45 +03:00
|
|
|
#[cfg(feature = "mysql")]
|
2021-06-06 15:16:00 +03:00
|
|
|
SupportedDatabaseClient::Mysql => Box::new(MysqlClient::manual(
|
|
|
|
connection_string,
|
|
|
|
migrations_table_name,
|
|
|
|
)?),
|
2021-06-06 01:25:45 +03:00
|
|
|
#[cfg(feature = "sqlite")]
|
2021-06-06 15:16:00 +03:00
|
|
|
SupportedDatabaseClient::Sqlite => Box::new(SqliteClient::manual(
|
|
|
|
connection_string,
|
|
|
|
migrations_table_name,
|
|
|
|
)?),
|
2021-06-06 01:25:45 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
Ok(client)
|
|
|
|
}
|
|
|
|
|
2021-06-07 23:57:32 +03:00
|
|
|
pub fn create_client_from_config(config: &Config) -> migra::StdResult<AnyClient> {
|
|
|
|
create_client(
|
2021-06-06 15:16:00 +03:00
|
|
|
&config.database.client(),
|
|
|
|
&config.database.connection_string()?,
|
|
|
|
&config.migrations.table_name(),
|
|
|
|
)
|
|
|
|
.map_err(From::from)
|
|
|
|
}
|
|
|
|
|
2021-06-06 01:25:45 +03:00
|
|
|
pub fn with_transaction<TrxFnMut, Res>(
|
|
|
|
client: &mut AnyClient,
|
|
|
|
trx_fn: &mut TrxFnMut,
|
|
|
|
) -> migra::Result<Res>
|
|
|
|
where
|
|
|
|
TrxFnMut: FnMut(&mut AnyClient) -> migra::Result<Res>,
|
|
|
|
{
|
|
|
|
client
|
|
|
|
.begin_transaction()
|
|
|
|
.and_then(|_| trx_fn(client))
|
|
|
|
.and_then(|res| client.commit_transaction().and(Ok(res)))
|
|
|
|
.or_else(|err| client.rollback_transaction().and(Err(err)))
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn maybe_with_transaction<TrxFnMut, Res>(
|
|
|
|
is_needed: bool,
|
|
|
|
client: &mut AnyClient,
|
|
|
|
trx_fn: &mut TrxFnMut,
|
|
|
|
) -> migra::Result<Res>
|
|
|
|
where
|
|
|
|
TrxFnMut: FnMut(&mut AnyClient) -> migra::Result<Res>,
|
|
|
|
{
|
|
|
|
if is_needed {
|
|
|
|
with_transaction(client, trx_fn)
|
|
|
|
} else {
|
|
|
|
trx_fn(client)
|
|
|
|
}
|
|
|
|
}
|