pub trait Database: sqlx::Database {
const SYSTEM: &'static str;
fn connection_attributes(
pool: &sqlx::Pool<Self>,
) -> (Option<String>, Option<u16>, Option<String>);
fn rows_affected(result: &<Self as sqlx::Database>::QueryResult) -> u64;
}
#[cfg(any(feature = "postgres", feature = "mysql"))]
fn url_based_connection_attributes<O: sqlx::ConnectOptions>(
options: &O,
) -> (Option<String>, Option<u16>, Option<String>) {
let url = options.to_url_lossy();
let host = url.host_str().map(String::from);
let port = url.port();
let namespace = url
.path_segments()
.and_then(|mut segments| segments.next().map(String::from));
(host, port, namespace)
}
#[cfg(feature = "sqlite")]
impl Database for sqlx::Sqlite {
const SYSTEM: &'static str = "sqlite";
fn connection_attributes(
pool: &sqlx::Pool<Self>,
) -> (Option<String>, Option<u16>, Option<String>) {
let namespace = pool
.connect_options()
.get_filename()
.to_str()
.map(String::from);
(None, None, namespace)
}
fn rows_affected(result: &sqlx::sqlite::SqliteQueryResult) -> u64 {
result.rows_affected()
}
}
#[cfg(feature = "postgres")]
impl Database for sqlx::Postgres {
const SYSTEM: &'static str = "postgresql";
fn connection_attributes(
pool: &sqlx::Pool<Self>,
) -> (Option<String>, Option<u16>, Option<String>) {
url_based_connection_attributes(pool.connect_options().as_ref())
}
fn rows_affected(result: &sqlx::postgres::PgQueryResult) -> u64 {
result.rows_affected()
}
}
#[cfg(feature = "mysql")]
impl Database for sqlx::MySql {
const SYSTEM: &'static str = "mysql";
fn connection_attributes(
pool: &sqlx::Pool<Self>,
) -> (Option<String>, Option<u16>, Option<String>) {
url_based_connection_attributes(pool.connect_options().as_ref())
}
fn rows_affected(result: &sqlx::mysql::MySqlQueryResult) -> u64 {
result.rows_affected()
}
}