Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

brokkr-broker::db Rust

Database connection pool management using diesel and r2d2.

For detailed documentation, see the Brokkr Documentation.

Structs

brokkr-broker::db::ConnectionPool

pub

Derives: Clone

Represents a pool of PostgreSQL database connections.

Fields

NameTypeDescription
poolPool < ConnectionManager < PgConnection > >The actual connection pool.
schemaOption < String >Optional schema name for multi-tenant deployments.

Methods

get pub
#![allow(unused)]
fn main() {
fn get (& self ,) -> Result < diesel :: r2d2 :: PooledConnection < ConnectionManager < PgConnection > > , r2d2 :: Error >
}

Gets a connection from the pool with automatic schema search_path configuration.

If a schema is configured, this method automatically executes SET search_path on the connection to ensure all queries execute in the correct schema context.

Returns:

Returns a pooled connection ready for use.

Raises:

ExceptionDescription
PanicThis method will panic if:
PanicUnable to get a connection from the pool
PanicThe schema name is invalid
PanicFailed to set the search path
Source
#![allow(unused)]
fn main() {
    pub fn get(
        &self,
    ) -> Result<diesel::r2d2::PooledConnection<ConnectionManager<PgConnection>>, r2d2::Error> {
        use diesel::prelude::*;

        let mut conn = self.pool.get()?;

        if let Some(ref schema) = self.schema {
            // Validate schema name to prevent SQL injection
            validate_schema_name(schema).expect("Invalid schema name");

            // Set search_path for this connection
            let sql = format!("SET search_path TO {}, public", schema);
            diesel::sql_query(&sql)
                .execute(&mut conn)
                .expect("Failed to set search_path");
        }

        Ok(conn)
    }
}
setup_schema pub
#![allow(unused)]
fn main() {
fn setup_schema (& self , schema : & str) -> Result < () , String >
}

Sets up a PostgreSQL schema for multi-tenant isolation.

This method creates the schema if it doesn’t exist and prepares it for migrations. It should be called during application startup before running migrations.

Parameters:

NameTypeDescription
schema-The schema name to set up

Returns:

Returns Ok(()) on success, or an error if schema setup fails.

Source
#![allow(unused)]
fn main() {
    pub fn setup_schema(&self, schema: &str) -> Result<(), String> {
        use diesel::prelude::*;

        // Validate schema name
        validate_schema_name(schema).map_err(|e| format!("Invalid schema name: {}", e))?;

        let mut conn = self
            .pool
            .get()
            .map_err(|e| format!("Failed to get connection: {}", e))?;

        // Create schema if it doesn't exist
        let create_schema_sql = format!("CREATE SCHEMA IF NOT EXISTS {}", schema);
        diesel::sql_query(&create_schema_sql)
            .execute(&mut conn)
            .map_err(|e| format!("Failed to create schema '{}': {}", schema, e))?;

        // Set search_path for subsequent operations
        let set_search_path_sql = format!("SET search_path TO {}, public", schema);
        diesel::sql_query(&set_search_path_sql)
            .execute(&mut conn)
            .map_err(|e| format!("Failed to set search path: {}", e))?;

        Ok(())
    }
}

Functions

brokkr-broker::db::create_shared_connection_pool

pub

#![allow(unused)]
fn main() {
fn create_shared_connection_pool (base_url : & str , database_name : & str , max_size : u32 , schema : Option < & str > ,) -> ConnectionPool
}

Creates a shared connection pool for PostgreSQL databases.

Parameters:

NameTypeDescription
base_url-The base URL of the database server (e.g., “postgres://username:password@localhost:5432”)
database_name-The name of the database to connect to
max_size-The maximum number of connections the pool should maintain
schema-Optional schema name for multi-tenant isolation

Returns:

Returns a ConnectionPool instance containing the created connection pool.

Raises:

ExceptionDescription
PanicThis function will panic if:
PanicThe base URL is invalid
PanicThe connection pool creation fails
Source
#![allow(unused)]
fn main() {
pub fn create_shared_connection_pool(
    base_url: &str,
    database_name: &str,
    max_size: u32,
    schema: Option<&str>,
) -> ConnectionPool {
    // Parse the base URL and set the database name
    let mut url = Url::parse(base_url).expect("Invalid base URL");
    url.set_path(database_name);

    // Create a connection manager
    let manager = ConnectionManager::<PgConnection>::new(url.as_str());

    // Build the connection pool
    let pool = Pool::builder()
        .max_size(max_size)
        .build(manager)
        .expect("Failed to create connection pool");

    ConnectionPool {
        pool,
        schema: schema.map(String::from),
    }
}
}

brokkr-broker::db::validate_schema_name

pub

#![allow(unused)]
fn main() {
fn validate_schema_name (schema : & str) -> Result < () , String >
}

Validates a PostgreSQL schema name to prevent SQL injection.

Schema names must start with a letter and contain only alphanumeric characters and underscores.

Parameters:

NameTypeDescription
schema-The schema name to validate

Returns:

Returns Ok(()) if valid, or an error message if invalid.

Source
#![allow(unused)]
fn main() {
pub fn validate_schema_name(schema: &str) -> Result<(), String> {
    if schema.is_empty() {
        return Err("Schema name cannot be empty".to_string());
    }

    // Check first character is a letter
    if !schema.chars().next().unwrap().is_ascii_alphabetic() {
        return Err("Schema name must start with a letter".to_string());
    }

    // Check all characters are alphanumeric or underscore
    if !schema
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '_')
    {
        return Err("Schema name can only contain letters, numbers, and underscores".to_string());
    }

    Ok(())
}
}