♻️ [global] Despivota acceso a base de datos

This commit is contained in:
Manuel Cillero 2022-11-10 22:41:44 +01:00
parent e143ee57ac
commit 19b4c251b0
6 changed files with 105 additions and 102 deletions

View file

@ -51,7 +51,7 @@ impl MigrationTrait for Migration {
.await?;
// Built-in roles.
app::db::exec::<InsertStatement>(
db::exec::<InsertStatement>(
Query::insert()
.into_table(Role::Table)
.columns(vec![Role::Name, Role::Weight])

View file

@ -6,9 +6,6 @@ pub use actix_web_static_files::ResourceFiles;
mod banner;
#[cfg(feature = "database")]
pub mod db;
pub mod application;
pub mod fatal_error;

View file

@ -27,7 +27,7 @@ impl Application {
#[cfg(feature = "database")]
// Conecta con la base de datos.
LazyStatic::force(&super::db::DBCONN);
LazyStatic::force(&crate::db::DBCONN);
// Registra los módulos de la aplicación.
module::all::register_modules(app);

View file

@ -1,95 +0,0 @@
use crate::db::*;
use crate::{global, run_now, trace, LazyStatic};
use sea_orm::{ConnectOptions, ConnectionTrait, Database, DatabaseBackend, Statement};
use tracing_unwrap::ResultExt;
pub static DBCONN: LazyStatic<DbConn> = LazyStatic::new(|| {
trace::info!(
"Connecting to database \"{}\" using a pool of {} connections",
&global::SETTINGS.database.db_name,
&global::SETTINGS.database.max_pool_size
);
let db_uri = match global::SETTINGS.database.db_type.as_str() {
"mysql" | "postgres" => {
let mut tmp_uri = DbUri::parse(
format!(
"{}://{}/{}",
&global::SETTINGS.database.db_type,
&global::SETTINGS.database.db_host,
&global::SETTINGS.database.db_name
)
.as_str(),
)
.unwrap();
tmp_uri
.set_username(global::SETTINGS.database.db_user.as_str())
.unwrap();
// https://github.com/launchbadge/sqlx/issues/1624
tmp_uri
.set_password(Some(global::SETTINGS.database.db_pass.as_str()))
.unwrap();
if global::SETTINGS.database.db_port != 0 {
tmp_uri.set_port(Some(global::SETTINGS.database.db_port)).unwrap();
}
tmp_uri
}
"sqlite" => DbUri::parse(
format!(
"{}://{}",
&global::SETTINGS.database.db_type, &global::SETTINGS.database.db_name
)
.as_str(),
)
.unwrap(),
_ => {
trace::error!(
"Unrecognized database type \"{}\"",
&global::SETTINGS.database.db_type
);
DbUri::parse("").unwrap()
}
};
run_now(Database::connect::<ConnectOptions>({
let mut db_opt = ConnectOptions::new(db_uri.to_string());
db_opt.max_connections(global::SETTINGS.database.max_pool_size);
db_opt
}))
.expect_or_log("Failed to connect to database")
});
static DBBACKEND: LazyStatic<DatabaseBackend> = LazyStatic::new(|| DBCONN.get_database_backend());
pub async fn query<Q: QueryStatementWriter>(stmt: &mut Q) -> Result<Vec<QueryResult>, DbErr> {
DBCONN
.query_all(Statement::from_string(
*DBBACKEND,
match *DBBACKEND {
DatabaseBackend::MySql => stmt.to_string(MysqlQueryBuilder),
DatabaseBackend::Postgres => stmt.to_string(PostgresQueryBuilder),
DatabaseBackend::Sqlite => stmt.to_string(SqliteQueryBuilder),
},
))
.await
}
pub async fn exec<Q: QueryStatementWriter>(stmt: &mut Q) -> Result<Option<QueryResult>, DbErr> {
DBCONN
.query_one(Statement::from_string(
*DBBACKEND,
match *DBBACKEND {
DatabaseBackend::MySql => stmt.to_string(MysqlQueryBuilder),
DatabaseBackend::Postgres => stmt.to_string(PostgresQueryBuilder),
DatabaseBackend::Sqlite => stmt.to_string(SqliteQueryBuilder),
},
))
.await
}
pub async fn exec_raw(stmt: String) -> Result<ExecResult, DbErr> {
DBCONN
.execute(Statement::from_string(*DBBACKEND, stmt))
.await
}

View file

@ -1,4 +1,5 @@
use super::ModuleStaticRef;
use crate::core::hook::add_action;
use crate::core::theme;
use crate::{app, trace, LazyStatic};
@ -109,7 +110,7 @@ pub fn run_migrations() {
migrations
}
}
Migrator::up(&app::db::DBCONN, None)
Migrator::up(&DBCONN, None)
})
.unwrap();
@ -124,7 +125,7 @@ pub fn run_migrations() {
migrations
}
}
Migrator::down(&app::db::DBCONN, None)
Migrator::down(&DBCONN, None)
})
.unwrap();
}

View file

@ -1,7 +1,13 @@
use crate::{global, run_now, trace, LazyStatic};
pub use url::Url as DbUri;
pub use sea_orm::{DatabaseConnection as DbConn, ExecResult, QueryResult};
use sea_orm::{ConnectOptions, ConnectionTrait, Database, DatabaseBackend, Statement};
use tracing_unwrap::ResultExt;
// El siguiente módulo migration es una versión simplificada del módulo sea_orm_migration (v0.9.1)
// https://github.com/SeaQL/sea-orm/tree/0.9.1/sea-orm-migration para evitar los errores generados
// por el paradigma modular de PageTop. Se copian los siguientes archivos del original:
@ -36,3 +42,97 @@ macro_rules! migration_item {
Box::new(migration::$migration_module::Migration)
}};
}
pub static DBCONN: LazyStatic<DbConn> = LazyStatic::new(|| {
trace::info!(
"Connecting to database \"{}\" using a pool of {} connections",
&global::SETTINGS.database.db_name,
&global::SETTINGS.database.max_pool_size
);
let db_uri = match global::SETTINGS.database.db_type.as_str() {
"mysql" | "postgres" => {
let mut tmp_uri = DbUri::parse(
format!(
"{}://{}/{}",
&global::SETTINGS.database.db_type,
&global::SETTINGS.database.db_host,
&global::SETTINGS.database.db_name
)
.as_str(),
)
.unwrap();
tmp_uri
.set_username(global::SETTINGS.database.db_user.as_str())
.unwrap();
// https://github.com/launchbadge/sqlx/issues/1624
tmp_uri
.set_password(Some(global::SETTINGS.database.db_pass.as_str()))
.unwrap();
if global::SETTINGS.database.db_port != 0 {
tmp_uri.set_port(Some(global::SETTINGS.database.db_port)).unwrap();
}
tmp_uri
}
"sqlite" => DbUri::parse(
format!(
"{}://{}",
&global::SETTINGS.database.db_type, &global::SETTINGS.database.db_name
)
.as_str(),
)
.unwrap(),
_ => {
trace::error!(
"Unrecognized database type \"{}\"",
&global::SETTINGS.database.db_type
);
DbUri::parse("").unwrap()
}
};
run_now(Database::connect::<ConnectOptions>({
let mut db_opt = ConnectOptions::new(db_uri.to_string());
db_opt.max_connections(global::SETTINGS.database.max_pool_size);
db_opt
}))
.expect_or_log("Failed to connect to database")
});
static DBBACKEND: LazyStatic<DatabaseBackend> = LazyStatic::new(||
DBCONN.get_database_backend()
);
pub async fn query<Q: QueryStatementWriter>(stmt: &mut Q) -> Result<Vec<QueryResult>, DbErr> {
DBCONN
.query_all(Statement::from_string(
*DBBACKEND,
match *DBBACKEND {
DatabaseBackend::MySql => stmt.to_string(MysqlQueryBuilder),
DatabaseBackend::Postgres => stmt.to_string(PostgresQueryBuilder),
DatabaseBackend::Sqlite => stmt.to_string(SqliteQueryBuilder),
},
))
.await
}
pub async fn exec<Q: QueryStatementWriter>(stmt: &mut Q) -> Result<Option<QueryResult>, DbErr> {
DBCONN
.query_one(Statement::from_string(
*DBBACKEND,
match *DBBACKEND {
DatabaseBackend::MySql => stmt.to_string(MysqlQueryBuilder),
DatabaseBackend::Postgres => stmt.to_string(PostgresQueryBuilder),
DatabaseBackend::Sqlite => stmt.to_string(SqliteQueryBuilder),
},
))
.await
}
pub async fn exec_raw(stmt: String) -> Result<ExecResult, DbErr> {
DBCONN
.execute(Statement::from_string(*DBBACKEND, stmt))
.await
}