Skip to content

Commit 7caa7f0

Browse files
authored
Merge pull request #153 from Mintbase/set-schema-for-whole-pool
Set schema for every connection in pool
2 parents 0d70e07 + 8db34fb commit 7caa7f0

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

data-store/src/store.rs

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -60,10 +60,7 @@ impl DataStore {
6060
.parse::<usize>()
6161
.context("parse num_threads")?;
6262

63-
let pool = Self::get_connection_pool(connection, pool_size, num_threads)?;
64-
diesel::sql_query(format!("SET search_path TO {schema};"))
65-
.execute(&mut pool.get()?)
66-
.expect("Error setting search path");
63+
let pool = Self::get_connection_pool(connection, schema, pool_size, num_threads)?;
6764
Ok(Self { pool })
6865
}
6966

@@ -507,6 +504,7 @@ impl DataStore {
507504

508505
fn get_connection_pool(
509506
db_url: &str,
507+
schema: &str,
510508
pool_size: u32,
511509
num_threads: usize,
512510
) -> Result<Pool<ConnectionManager<PgConnection>>> {
@@ -515,11 +513,30 @@ impl DataStore {
515513
.max_size(pool_size) // Should be a configurable env var
516514
.test_on_check_out(true)
517515
.thread_pool(Arc::new(ScheduledThreadPool::new(num_threads)))
516+
.connection_customizer(Box::new(SearchPathCustomizer {
517+
schema: Arc::new(schema.to_string()),
518+
}))
518519
.build(manager)
519520
.context("build connection pool")
520521
}
521522
}
522523

524+
#[derive(Debug)]
525+
struct SearchPathCustomizer {
526+
schema: Arc<String>,
527+
}
528+
529+
// Implement the CustomizeConnection trait for your struct
530+
impl diesel::r2d2::CustomizeConnection<PgConnection, diesel::r2d2::Error> for SearchPathCustomizer {
531+
fn on_acquire(&self, conn: &mut PgConnection) -> Result<(), diesel::r2d2::Error> {
532+
// Use the connection to execute your custom SQL command
533+
diesel::sql_query(format!("SET search_path TO {};", *self.schema))
534+
.execute(conn)
535+
.map_err(diesel::r2d2::Error::QueryError)?;
536+
Ok(())
537+
}
538+
}
539+
523540
#[cfg(test)]
524541
mod tests {
525542
use super::*;

0 commit comments

Comments
 (0)