diff --git a/pagetop-user/src/migration/m20220312_000001_create_table_role.rs b/pagetop-user/src/migration/m20220312_000001_create_table_role.rs index eeb3abed..f1fa802c 100644 --- a/pagetop-user/src/migration/m20220312_000001_create_table_role.rs +++ b/pagetop-user/src/migration/m20220312_000001_create_table_role.rs @@ -51,7 +51,7 @@ impl MigrationTrait for Migration { .await?; // Built-in roles. - app::db::exec::( + db::exec::( Query::insert() .into_table(Role::Table) .columns(vec![Role::Name, Role::Weight]) diff --git a/pagetop/src/app.rs b/pagetop/src/app.rs index 843a32b5..702a5a45 100644 --- a/pagetop/src/app.rs +++ b/pagetop/src/app.rs @@ -10,9 +10,6 @@ mod tracing; pub mod locale; -#[cfg(feature = "database")] -pub mod db; - pub mod application; pub mod fatal_error; diff --git a/pagetop/src/app/application.rs b/pagetop/src/app/application.rs index 2c0b9c4c..7213ddae 100644 --- a/pagetop/src/app/application.rs +++ b/pagetop/src/app/application.rs @@ -4,7 +4,7 @@ use crate::core::module::ModuleStaticRef; use crate::core::{module, theme}; use crate::html::Markup; use crate::response::page::ResultPage; -use crate::{config, LazyStatic}; +use crate::{config, db, LazyStatic}; use actix_web::dev::Server; @@ -27,7 +27,7 @@ impl Application { #[cfg(feature = "database")] // Conecta con la base de datos. - LazyStatic::force(&super::db::DBCONN); + LazyStatic::force(&db::DBCONN); // Registra los módulos de la aplicación. module::all::register_modules(app); diff --git a/pagetop/src/app/db.rs b/pagetop/src/app/db.rs deleted file mode 100644 index 59e73156..00000000 --- a/pagetop/src/app/db.rs +++ /dev/null @@ -1,98 +0,0 @@ -use crate::db::*; -use crate::{config, run_now, trace, LazyStatic}; - -use sea_orm::{ConnectOptions, ConnectionTrait, Database, DatabaseBackend, Statement}; -use tracing_unwrap::ResultExt; - -pub static DBCONN: LazyStatic = LazyStatic::new(|| { - trace::info!( - "Connecting to database \"{}\" using a pool of {} connections", - &config::SETTINGS.database.db_name, - &config::SETTINGS.database.max_pool_size - ); - - let db_uri = match config::SETTINGS.database.db_type.as_str() { - "mysql" | "postgres" => { - let mut tmp_uri = DbUri::parse( - format!( - "{}://{}/{}", - &config::SETTINGS.database.db_type, - &config::SETTINGS.database.db_host, - &config::SETTINGS.database.db_name - ) - .as_str(), - ) - .unwrap(); - tmp_uri - .set_username(config::SETTINGS.database.db_user.as_str()) - .unwrap(); - // https://github.com/launchbadge/sqlx/issues/1624 - tmp_uri - .set_password(Some(config::SETTINGS.database.db_pass.as_str())) - .unwrap(); - if config::SETTINGS.database.db_port != 0 { - tmp_uri - .set_port(Some(config::SETTINGS.database.db_port)) - .unwrap(); - } - tmp_uri - } - "sqlite" => DbUri::parse( - format!( - "{}://{}", - &config::SETTINGS.database.db_type, - &config::SETTINGS.database.db_name - ) - .as_str(), - ) - .unwrap(), - _ => { - trace::error!( - "Unrecognized database type \"{}\"", - &config::SETTINGS.database.db_type - ); - DbUri::parse("").unwrap() - } - }; - - run_now(Database::connect::({ - let mut db_opt = ConnectOptions::new(db_uri.to_string()); - db_opt.max_connections(config::SETTINGS.database.max_pool_size); - db_opt - })) - .expect_or_log("Failed to connect to database") -}); - -static DBBACKEND: LazyStatic = LazyStatic::new(|| DBCONN.get_database_backend()); - -pub async fn query(stmt: &mut Q) -> Result, 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(stmt: &mut Q) -> Result, 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 { - DBCONN - .execute(Statement::from_string(*DBBACKEND, stmt)) - .await -} diff --git a/pagetop/src/core/module/all.rs b/pagetop/src/core/module/all.rs index 2dc3efa1..1023a860 100644 --- a/pagetop/src/core/module/all.rs +++ b/pagetop/src/core/module/all.rs @@ -2,7 +2,7 @@ use super::ModuleStaticRef; use crate::core::hook::add_action; use crate::core::theme; -use crate::{app, trace, LazyStatic}; +use crate::{app, db, trace, LazyStatic}; #[cfg(feature = "database")] use crate::{db::*, run_now}; @@ -110,7 +110,7 @@ pub fn run_migrations() { migrations } } - Migrator::up(&app::db::DBCONN, None) + Migrator::up(&db::DBCONN, None) }) .unwrap(); @@ -125,7 +125,7 @@ pub fn run_migrations() { migrations } } - Migrator::down(&app::db::DBCONN, None) + Migrator::down(&db::DBCONN, None) }) .unwrap(); } diff --git a/pagetop/src/db.rs b/pagetop/src/db.rs index a6639943..c7aeb879 100644 --- a/pagetop/src/db.rs +++ b/pagetop/src/db.rs @@ -1,7 +1,105 @@ +use crate::{config, 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; + +pub(crate) static DBCONN: LazyStatic = LazyStatic::new(|| { + trace::info!( + "Connecting to database \"{}\" using a pool of {} connections", + &config::SETTINGS.database.db_name, + &config::SETTINGS.database.max_pool_size + ); + + let db_uri = match config::SETTINGS.database.db_type.as_str() { + "mysql" | "postgres" => { + let mut tmp_uri = DbUri::parse( + format!( + "{}://{}/{}", + &config::SETTINGS.database.db_type, + &config::SETTINGS.database.db_host, + &config::SETTINGS.database.db_name + ) + .as_str(), + ) + .unwrap(); + tmp_uri + .set_username(config::SETTINGS.database.db_user.as_str()) + .unwrap(); + // https://github.com/launchbadge/sqlx/issues/1624 + tmp_uri + .set_password(Some(config::SETTINGS.database.db_pass.as_str())) + .unwrap(); + if config::SETTINGS.database.db_port != 0 { + tmp_uri + .set_port(Some(config::SETTINGS.database.db_port)) + .unwrap(); + } + tmp_uri + } + "sqlite" => DbUri::parse( + format!( + "{}://{}", + &config::SETTINGS.database.db_type, + &config::SETTINGS.database.db_name + ) + .as_str(), + ) + .unwrap(), + _ => { + trace::error!( + "Unrecognized database type \"{}\"", + &config::SETTINGS.database.db_type + ); + DbUri::parse("").unwrap() + } + }; + + run_now(Database::connect::({ + let mut db_opt = ConnectOptions::new(db_uri.to_string()); + db_opt.max_connections(config::SETTINGS.database.max_pool_size); + db_opt + })) + .expect_or_log("Failed to connect to database") +}); + +static DBBACKEND: LazyStatic = LazyStatic::new(|| DBCONN.get_database_backend()); + +pub async fn query(stmt: &mut Q) -> Result, 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(stmt: &mut Q) -> Result, 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 { + DBCONN + .execute(Statement::from_string(*DBBACKEND, stmt)) + .await +} + // 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: