use super::lease::{ClientId, ConnectionLease, LeaseAction};
use super::mode::PoolingMode;
use crate::connection_pool::PooledConnection;
pub struct SessionModeHandler {
track_prepared_statements: bool,
}
impl Default for SessionModeHandler {
fn default() -> Self {
Self::new()
}
}
impl SessionModeHandler {
pub fn new() -> Self {
Self {
track_prepared_statements: false,
}
}
pub fn with_prepared_tracking() -> Self {
Self {
track_prepared_statements: true,
}
}
pub fn create_lease(&self, connection: PooledConnection, client_id: ClientId) -> ConnectionLease {
ConnectionLease::new(connection, PoolingMode::Session, client_id)
}
pub fn on_statement_complete(&self, _lease: &mut ConnectionLease, _sql: &str) -> LeaseAction {
LeaseAction::Hold
}
pub fn on_transaction_end(&self, _lease: &mut ConnectionLease) -> LeaseAction {
LeaseAction::Hold
}
pub fn should_release(&self, _lease: &ConnectionLease) -> bool {
false
}
pub fn on_client_disconnect(&self, _lease: ConnectionLease) -> LeaseAction {
LeaseAction::Reset
}
pub fn mode(&self) -> PoolingMode {
PoolingMode::Session
}
pub fn tracks_prepared_statements(&self) -> bool {
self.track_prepared_statements
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::connection_pool::ConnectionState;
use crate::NodeId;
use uuid::Uuid;
fn create_test_connection() -> PooledConnection {
PooledConnection {
id: Uuid::new_v4(),
node_id: NodeId::new(),
created_at: chrono::Utc::now(),
last_used: chrono::Utc::now(),
state: ConnectionState::InUse,
use_count: 1,
permit: None,
client: None,
}
}
#[test]
fn test_session_mode_always_holds() {
let handler = SessionModeHandler::new();
let conn = create_test_connection();
let mut lease = handler.create_lease(conn, ClientId::new());
assert_eq!(
handler.on_statement_complete(&mut lease, "SELECT 1"),
LeaseAction::Hold
);
assert_eq!(
handler.on_statement_complete(&mut lease, "BEGIN"),
LeaseAction::Hold
);
assert_eq!(
handler.on_statement_complete(&mut lease, "COMMIT"),
LeaseAction::Hold
);
assert_eq!(handler.on_transaction_end(&mut lease), LeaseAction::Hold);
}
#[test]
fn test_session_mode_never_releases() {
let handler = SessionModeHandler::new();
let conn = create_test_connection();
let lease = handler.create_lease(conn, ClientId::new());
assert!(!handler.should_release(&lease));
}
#[test]
fn test_session_mode_disconnect_resets() {
let handler = SessionModeHandler::new();
let conn = create_test_connection();
let lease = handler.create_lease(conn, ClientId::new());
assert_eq!(handler.on_client_disconnect(lease), LeaseAction::Reset);
}
#[test]
fn test_mode() {
let handler = SessionModeHandler::new();
assert_eq!(handler.mode(), PoolingMode::Session);
}
}