Skip to content

Instantly share code, notes, and snippets.

@dertin
Last active July 23, 2023 20:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dertin/d5e6b031cb86fbe71c6d2272c764dedd to your computer and use it in GitHub Desktop.
Save dertin/d5e6b031cb86fbe71c6d2272c764dedd to your computer and use it in GitHub Desktop.
Efficient Connection Pooling in ODBC-MSSQL (odbc-api) - unixODBC 2.3.12pre
[package]
name = "rust-pooldb"
version = "0.1.0"
edition = "2021"
[dependencies]
tokio = { version = "1.29.1", features = ["full"] }
odbc-sys = "0.21.4"
odbc-api = "0.57.0"
[ODBC]
Trace=Yes
Trace File=/tmp/sql.log
Pooling=Yes
PoolMaxSize=15
PoolWaitTimeout=30
[ODBC_Driver_18_for_SQL_Server_Pool]
Description=Microsoft ODBC Driver 18 for SQL Server - POOL
Driver=/opt/microsoft/msodbcsql18/lib64/libmsodbcsql-18.2.so.2.1
UsageCount=1
CPTimeout=180
[ODBC_Driver_18_for_SQL_Server]
Description=Microsoft ODBC Driver 18 for SQL Server
Driver=/opt/microsoft/msodbcsql18/lib64/libmsodbcsql-18.2.so.2.1
UsageCount=1
CPTimeout=0
use odbc_api::{Connection, ConnectionOptions, Environment, IntoParameter, sys::{AttrConnectionPooling, AttrCpMatch}};
use std::{sync::OnceLock, time::Duration};
use std::sync::{Arc, Condvar, Mutex};
const NUM_THREADS: u32 = 10; // number of threads to spawn
const CONDVAR_FLAG: bool = false; // wait for all threads to start then connect to ODBC all at the same time.
const CONN_IDLE_PAUSE: u64 = 30; // seconds to stay alive connection within each thread
// Behaviors:
// It's not a sure thing, just a rough reference.
// I have to keep investigating
// if CONDVAR_FLAG == true :
// PoolMaxSize >= NUM_THREADS ==> OK
// PoolMaxSize < NUM_THREADS ==> OK (if the difference is not much) || [[unixODBC][Driver Manager]Connection pool at capacity and the wait has timed out]
// if CONDVAR_FLAG == false and (CONN_IDLE_PAUSE + CPTimeout) > PoolWaitTimeout :
// PoolMaxSize >= NUM_THREADS ==> OK
// PoolMaxSize < NUM_THREADS ==> [[unixODBC][Driver Manager]Connection pool at capacity and the wait has timed out]
fn connection_pooling<'a>(connection_string: &str) -> Connection<'a> {
// Environment initialized only once and safe to share between threads
let env = {
pub static ENV: OnceLock<Environment> = OnceLock::new();
ENV.get_or_init(|| unsafe {
println!("Environment for connection pooling");
Environment::set_connection_pooling(AttrConnectionPooling::DriverAware).unwrap();
let mut env = Environment::new().unwrap();
env.set_connection_pooling_matching(AttrCpMatch::Strict)
.unwrap();
env
})
};
println!("Connection MSSQL pool");
let conn: Connection<'a> = env
.connect_with_connection_string(
connection_string,
ConnectionOptions {
login_timeout_sec: Some(15),
},
)
.unwrap();
conn
}
fn odbc_mssql() -> Result<(), Box<dyn std::error::Error>> {
let counter = Arc::new((Mutex::new(0), Condvar::new()));
let mut handles = Vec::new();
for _ in 0..NUM_THREADS {
let counter_clone = Arc::clone(&counter);
let handle = std::thread::spawn(move || {
if CONDVAR_FLAG {
// Wait for all threads to start then connect to ODBC all at the same time.
println!("Thread {:?} waits for all threads", std::thread::current().id());
let (lock, cvar) = &*counter_clone;
let mut count = lock.lock().unwrap();
*count += 1;
if *count < NUM_THREADS {
count = cvar.wait(count).unwrap();
} else {
cvar.notify_all(); // Notify all threads to start
}
}
// Connection string for MSSQL
let connection_string = "Driver={ODBC_Driver_18_for_SQL_Server_Pool};\
Server=0.0.0.0;\
UID=SA;\
PWD=Pepe1234;TrustServerCertificate=Yes;Database=mydatabase;";
let conn: Connection<'_> = connection_pooling(connection_string);
// let conn = unsafe { conn.promote_to_send() };
let mut prepared = conn.prepare("SELECT * FROM mytable WHERE id=?;").unwrap();
match prepared.execute(&IntoParameter::into_parameter(1)) {
Err(e) => println!("{}", e),
Ok(None) => println!("No result set generated."),
Ok(Some(_cursor)) => {}
};
// Stay alive for 10 seconds
std::thread::sleep(Duration::from_secs(CONN_IDLE_PAUSE));
// Check if connection is dead
assert!(!conn.is_dead().unwrap());
});
handles.push(handle);
}
for handle in handles {
println!("Thread {:?} started", handle.thread().id());
handle.join().unwrap();
}
Ok(())
}
fn main() {
odbc_mssql().unwrap();
}
@abernardo88
Copy link

Hello I'm trying to implement the same logic, can you please share the cargo file? Thanks!

@dertin
Copy link
Author

dertin commented Jul 11, 2023

Hello @abernardo88, yes I'll add it soon. However it's not finished yet, leave some questions in the comments of the code that should be resolved before it can be used.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment