Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Database connection init #2440

Merged
merged 3 commits into from
May 11, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .env.template
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,17 @@
## Define the size of the connection pool used for connecting to the database.
# DATABASE_MAX_CONNS=10

## Database connection initialization
## Allows SQL statements to be run whenever a new database connection is created.
## For example, this can be used to run connection-scoped pragma statements.
##
## Statements to run when creating a new SQLite connection
# SQLITE_CONN_INIT="PRAGMA busy_timeout = 5000; PRAGMA synchronous = NORMAL;"
## Statements to run when creating a new MySQL connection
# MYSQL_CONN_INIT=""
## Statements to run when creating a new PostgreSQL connection
# POSTGRESQL_CONN_INIT=""

## Individual folders, these override %DATA_FOLDER%
# RSA_KEY_FILENAME=data/rsa_key
# ICON_CACHE_FOLDER=data/icon_cache
Expand Down
11 changes: 10 additions & 1 deletion src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -515,11 +515,20 @@ make_config! {
db_connection_retries: u32, false, def, 15;

/// Timeout when aquiring database connection
database_timeout: u64, false, def, 30;
database_timeout: u64, false, def, 30;

/// Database connection pool size
database_max_conns: u32, false, def, 10;

/// SQLite connection init |> Statements to run when creating a new SQLite connection
sqlite_conn_init: String, false, def, "PRAGMA busy_timeout = 5000; PRAGMA synchronous = NORMAL;".to_string();
BlackDex marked this conversation as resolved.
Show resolved Hide resolved

/// MySQL connection init |> Statements to run when creating a new MySQL connection
mysql_conn_init: String, false, def, "".to_string();

/// PostgreSQL connection init |> Statements to run when creating a new PostgreSQL connection
postgresql_conn_init: String, false, def, "".to_string();

/// Bypass admin page security (Know the risks!) |> Disables the Admin Token for the admin page so you may use your own auth in-front
disable_admin_token: bool, true, def, false;

Expand Down
29 changes: 27 additions & 2 deletions src/db/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
use std::{sync::Arc, time::Duration};

use diesel::r2d2::{ConnectionManager, Pool, PooledConnection};
use diesel::{
connection::SimpleConnection,
r2d2::{ConnectionManager, CustomizeConnection, Pool, PooledConnection},
};

use rocket::{
http::Status,
outcome::IntoOutcome,
Expand Down Expand Up @@ -62,6 +66,23 @@ macro_rules! generate_connections {
#[allow(non_camel_case_types)]
pub enum DbConnInner { $( #[cfg($name)] $name(PooledConnection<ConnectionManager< $ty >>), )+ }

#[derive(Debug)]
pub struct DbConnOptions {
pub init_stmts: String,
}

$( // Based on <https://stackoverflow.com/a/57717533>.
#[cfg($name)]
impl CustomizeConnection<$ty, diesel::r2d2::Error> for DbConnOptions {
fn on_acquire(&self, conn: &mut $ty) -> Result<(), diesel::r2d2::Error> {
(|| {
if !self.init_stmts.is_empty() {
conn.batch_execute(&self.init_stmts)?;
}
Ok(())
})().map_err(diesel::r2d2::Error::QueryError)
}
})+

#[derive(Clone)]
pub struct DbPool {
Expand Down Expand Up @@ -103,7 +124,8 @@ macro_rules! generate_connections {
}

impl DbPool {
// For the given database URL, guess it's type, run migrations create pool and return it
// For the given database URL, guess its type, run migrations, create pool, and return it
#[allow(clippy::diverging_sub_expression)]
pub fn from_config() -> Result<Self, Error> {
let url = CONFIG.database_url();
let conn_type = DbConnType::from_url(&url)?;
Expand All @@ -117,6 +139,9 @@ macro_rules! generate_connections {
let pool = Pool::builder()
.max_size(CONFIG.database_max_conns())
.connection_timeout(Duration::from_secs(CONFIG.database_timeout()))
.connection_customizer(Box::new(DbConnOptions{
init_stmts: paste::paste!{ CONFIG. [< $name _conn_init >] () }
}))
.build(manager)
.map_res("Failed to create pool")?;
return Ok(DbPool {
Expand Down