// rust/01-connection-pooling.rs/*Database connection pooling patterns and best practices*/usestd::collections::HashMap;usestd::sync::Arc;usestd::time::Duration;useserde::{Deserialize,Serialize};usetokio::sync::{RwLock,Semaphore};usetokio::time::{timeout,Instant};/// Database connection pool configuration.#[derive(Debug, Clone, Serialize, Deserialize)]pubstructPoolConfig{pubmax_connections:u32,pubmin_connections:u32,pubconnection_timeout:Duration,pubidle_timeout:Duration,pubmax_lifetime:Duration,pubacquire_timeout:Duration,}implDefaultforPoolConfig{fndefault()->Self{Self{max_connections:10,min_connections:1,connection_timeout:Duration::from_secs(30),idle_timeout:Duration::from_secs(600),max_lifetime:Duration::from_secs(3600),acquire_timeout:Duration::from_secs(30),}}}/// Database connection.#[derive(Debug, Clone)]pubstructDatabaseConnection{pubid:String,pubcreated_at:Instant,publast_used:Instant,pubis_active:bool,pubconnection_string:String,}implDatabaseConnection{pubfnnew(id:String,connection_string:String)->Self{letnow=Instant::now();Self{id,created_at:now,last_used:now,is_active:true,connection_string,}}/// Check if connection is expired.pubfnis_expired(&self,max_lifetime:Duration)->bool{self.created_at.elapsed()>max_lifetime}/// Check if connection is idle.pubfnis_idle(&self,idle_timeout:Duration)->bool{self.last_used.elapsed()>idle_timeout}/// Mark connection as used.pubfnmark_used(&mutself){self.last_used=Instant::now();}}/// Database connection pool.pubstructConnectionPool{config:PoolConfig,connections:Arc<RwLock<Vec<DatabaseConnection>>>,semaphore:Arc<Semaphore>,connection_string:String,next_connection_id:Arc<RwLock<u32>>,}implConnectionPool{pubfnnew(config:PoolConfig,connection_string:String)->Self{letmax_connections=config.max_connectionsasusize;Self{config,connections:Arc::new(RwLock::new(Vec::new())),semaphore:Arc::new(Semaphore::new(max_connections)),connection_string,next_connection_id:Arc::new(RwLock::new(1)),}}/// Get a connection from the pool.pubasyncfnget_connection(&self)->Result<PooledConnection,String>{// Acquire semaphore permitlet_permit=self.semaphore.acquire().await.map_err(|e|format!("Failed to acquire connection permit: {}",e))?;// Try to get existing connectionifletSome(connection)=self.get_existing_connection().await?{returnOk(PooledConnection{connection,pool:self.clone(),});}// Create new connectionletconnection=self.create_connection().await?;self.add_connection(connection.clone()).await;Ok(PooledConnection{connection,pool:self.clone(),})}/// Get an existing connection from the pool.asyncfnget_existing_connection(&self)->Result<Option<DatabaseConnection>,String>{letmutconnections=self.connections.write().await;// Find a healthy, non-expired connectionfor(index,connection)inconnections.iter().enumerate(){ifconnection.is_active&&!connection.is_expired(self.config.max_lifetime)&&!connection.is_idle(self.config.idle_timeout){letmutconn=connection.clone();conn.mark_used();connections.remove(index);returnOk(Some(conn));}}Ok(None)}/// Create a new database connection.asyncfncreate_connection(&self)->Result<DatabaseConnection,String>{letmutnext_id=self.next_connection_id.write().await;letconnection_id=format!("conn-{}",*next_id);*next_id+=1;// In a real implementation, you would establish a database connection// For this example, we'll simulate the connectiontokio::time::sleep(Duration::from_millis(100)).await;Ok(DatabaseConnection::new(connection_id,self.connection_string.clone()))}/// Add a connection to the pool.asyncfnadd_connection(&self,connection:DatabaseConnection){letmutconnections=self.connections.write().await;connections.push(connection);}/// Return a connection to the pool.pubasyncfnreturn_connection(&self,connection:DatabaseConnection){letmutconnections=self.connections.write().await;// Check if connection is still validifconnection.is_active&&!connection.is_expired(self.config.max_lifetime){connections.push(connection);}}/// Clean up expired connections.pubasyncfncleanup_expired_connections(&self){letmutconnections=self.connections.write().await;connections.retain(|conn|{conn.is_active&&!conn.is_expired(self.config.max_lifetime)});}/// Get pool statistics.pubasyncfnget_stats(&self)->PoolStats{letconnections=self.connections.read().await;lettotal_connections=connections.len();letactive_connections=connections.iter().filter(|c|c.is_active).count();letidle_connections=connections.iter().filter(|c|c.is_idle(self.config.idle_timeout)).count();PoolStats{total_connections,active_connections,idle_connections,max_connections:self.config.max_connectionsasusize,min_connections:self.config.min_connectionsasusize,}}}implCloneforConnectionPool{fnclone(&self)->Self{Self{config:self.config.clone(),connections:Arc::clone(&self.connections),semaphore:Arc::clone(&self.semaphore),connection_string:self.connection_string.clone(),next_connection_id:Arc::clone(&self.next_connection_id),}}}/// Pooled connection wrapper.pubstructPooledConnection{connection:DatabaseConnection,pool:ConnectionPool,}implPooledConnection{/// Execute a query using the connection.pubasyncfnexecute_query(&self,query:&str)->Result<QueryResult,String>{// In a real implementation, you would execute the query// For this example, we'll simulate the query executiontokio::time::sleep(Duration::from_millis(50)).await;Ok(QueryResult{rows_affected:1,rows_returned:1,execution_time:Duration::from_millis(50),})}/// Execute a prepared statement.pubasyncfnexecute_prepared(&self,statement:&str,params:&[serde_json::Value])->Result<QueryResult,String>{// In a real implementation, you would execute the prepared statementtokio::time::sleep(Duration::from_millis(30)).await;Ok(QueryResult{rows_affected:1,rows_returned:1,execution_time:Duration::from_millis(30),})}}implDropforPooledConnection{fndrop(&mutself){letpool=self.pool.clone();letconnection=self.connection.clone();tokio::spawn(asyncmove{pool.return_connection(connection).await;});}}#[derive(Debug, Clone)]pubstructQueryResult{pubrows_affected:u64,pubrows_returned:u64,pubexecution_time:Duration,}#[derive(Debug, Clone)]pubstructPoolStats{pubtotal_connections:usize,pubactive_connections:usize,pubidle_connections:usize,pubmax_connections:usize,pubmin_connections:usize,}#[cfg(test)]modtests{usesuper::*;#[tokio::test]asyncfntest_connection_pool(){letconfig=PoolConfig::default();letpool=ConnectionPool::new(config,"postgresql://localhost/test".to_string());letconnection=pool.get_connection().await.unwrap();letresult=connection.execute_query("SELECT 1").await.unwrap();assert_eq!(result.rows_affected,1);}#[tokio::test]asyncfntest_pool_stats(){letconfig=PoolConfig::default();letpool=ConnectionPool::new(config,"postgresql://localhost/test".to_string());letstats=pool.get_stats().await;assert_eq!(stats.max_connections,10);assert_eq!(stats.min_connections,1);}}
// rust/02-transaction-management.rs/*Transaction management patterns and best practices*/usestd::collections::HashMap;useserde::{Deserialize,Serialize};usestd::time::Duration;/// Transaction isolation levels.#[derive(Debug, Clone, Serialize, Deserialize)]pubenumIsolationLevel{ReadUncommitted,ReadCommitted,RepeatableRead,Serializable,}/// Transaction configuration.#[derive(Debug, Clone, Serialize, Deserialize)]pubstructTransactionConfig{pubisolation_level:IsolationLevel,pubtimeout:Duration,pubread_only:bool,pubdeferrable:bool,}implDefaultforTransactionConfig{fndefault()->Self{Self{isolation_level:IsolationLevel::ReadCommitted,timeout:Duration::from_secs(30),read_only:false,deferrable:false,}}}/// Database transaction.pubstructTransaction{pubid:String,pubconfig:TransactionConfig,pubis_active:bool,pubstart_time:std::time::Instant,puboperations:Vec<TransactionOperation>,}#[derive(Debug, Clone, Serialize, Deserialize)]pubstructTransactionOperation{pubid:String,puboperation_type:OperationType,pubquery:String,pubparameters:HashMap<String,serde_json::Value>,pubtimestamp:std::time::SystemTime,}#[derive(Debug, Clone, Serialize, Deserialize)]pubenumOperationType{Select,Insert,Update,Delete,Create,Drop,Alter,}implTransaction{pubfnnew(id:String,config:TransactionConfig)->Self{Self{id,config,is_active:true,start_time:std::time::Instant::now(),operations:Vec::new(),}}/// Execute a query within the transaction.pubasyncfnexecute_query(&mutself,query:String,parameters:HashMap<String,serde_json::Value>)->Result<QueryResult,String>{if!self.is_active{returnErr("Transaction is not active".to_string());}// Check timeoutifself.start_time.elapsed()>self.config.timeout{returnErr("Transaction timeout".to_string());}// Add operation to transaction logletoperation=TransactionOperation{id:format!("op-{}",self.operations.len()+1),operation_type:self.determine_operation_type(&query),query:query.clone(),parameters:parameters.clone(),timestamp:std::time::SystemTime::now(),};self.operations.push(operation);// Execute the queryletresult=self.execute_query_internal(&query,¶meters).await?;Ok(result)}/// Determine the operation type from the query.fndetermine_operation_type(&self,query:&str)->OperationType{letquery_lower=query.to_lowercase();ifquery_lower.starts_with("select"){OperationType::Select}elseifquery_lower.starts_with("insert"){OperationType::Insert}elseifquery_lower.starts_with("update"){OperationType::Update}elseifquery_lower.starts_with("delete"){OperationType::Delete}elseifquery_lower.starts_with("create"){OperationType::Create}elseifquery_lower.starts_with("drop"){OperationType::Drop}elseifquery_lower.starts_with("alter"){OperationType::Alter}else{OperationType::Select}}/// Execute query internally.asyncfnexecute_query_internal(&self,query:&str,parameters:&HashMap<String,serde_json::Value>)->Result<QueryResult,String>{// In a real implementation, you would execute the query against the database// For this example, we'll simulate the query executiontokio::time::sleep(Duration::from_millis(50)).await;Ok(QueryResult{rows_affected:1,rows_returned:1,execution_time:Duration::from_millis(50),})}/// Commit the transaction.pubasyncfncommit(&mutself)->Result<(),String>{if!self.is_active{returnErr("Transaction is not active".to_string());}// In a real implementation, you would commit the transactionprintln!("Committing transaction {}",self.id);self.is_active=false;Ok(())}/// Rollback the transaction.pubasyncfnrollback(&mutself)->Result<(),String>{if!self.is_active{returnErr("Transaction is not active".to_string());}// In a real implementation, you would rollback the transactionprintln!("Rolling back transaction {}",self.id);self.is_active=false;Ok(())}/// Get transaction status.pubfnget_status(&self)->TransactionStatus{TransactionStatus{id:self.id.clone(),is_active:self.is_active,duration:self.start_time.elapsed(),operation_count:self.operations.len(),}}}#[derive(Debug, Clone)]pubstructTransactionStatus{pubid:String,pubis_active:bool,pubduration:Duration,puboperation_count:usize,}/// Transaction manager.pubstructTransactionManager{active_transactions:HashMap<String,Transaction>,next_transaction_id:u32,}implTransactionManager{pubfnnew()->Self{Self{active_transactions:HashMap::new(),next_transaction_id:1,}}/// Start a new transaction.pubfnstart_transaction(&mutself,config:TransactionConfig)->String{lettransaction_id=format!("txn-{}",self.next_transaction_id);self.next_transaction_id+=1;lettransaction=Transaction::new(transaction_id.clone(),config);self.active_transactions.insert(transaction_id.clone(),transaction);transaction_id}/// Get a transaction by ID.pubfnget_transaction(&mutself,id:&str)->Option<&mutTransaction>{self.active_transactions.get_mut(id)}/// Commit a transaction.pubasyncfncommit_transaction(&mutself,id:&str)->Result<(),String>{ifletSome(transaction)=self.active_transactions.get_mut(id){transaction.commit().await?;self.active_transactions.remove(id);Ok(())}else{Err("Transaction not found".to_string())}}/// Rollback a transaction.pubasyncfnrollback_transaction(&mutself,id:&str)->Result<(),String>{ifletSome(transaction)=self.active_transactions.get_mut(id){transaction.rollback().await?;self.active_transactions.remove(id);Ok(())}else{Err("Transaction not found".to_string())}}/// Get all active transactions.pubfnget_active_transactions(&self)->Vec<&Transaction>{self.active_transactions.values().collect()}/// Clean up expired transactions.pubasyncfncleanup_expired_transactions(&mutself){letmutexpired_transactions=Vec::new();for(id,transaction)in&self.active_transactions{iftransaction.start_time.elapsed()>transaction.config.timeout{expired_transactions.push(id.clone());}}foridinexpired_transactions{ifletSome(transaction)=self.active_transactions.get_mut(&id){let_=transaction.rollback().await;self.active_transactions.remove(&id);}}}}#[cfg(test)]modtests{usesuper::*;#[tokio::test]asyncfntest_transaction(){letconfig=TransactionConfig::default();letmuttransaction=Transaction::new("test-txn".to_string(),config);letmutparams=HashMap::new();params.insert("id".to_string(),serde_json::Value::Number(1.into()));letresult=transaction.execute_query("SELECT * FROM users WHERE id = $1".to_string(),params).await;assert!(result.is_ok());letcommit_result=transaction.commit().await;assert!(commit_result.is_ok());}#[tokio::test]asyncfntest_transaction_rollback(){letconfig=TransactionConfig::default();letmuttransaction=Transaction::new("test-txn".to_string(),config);letmutparams=HashMap::new();params.insert("id".to_string(),serde_json::Value::Number(1.into()));letresult=transaction.execute_query("SELECT * FROM users WHERE id = $1".to_string(),params).await;assert!(result.is_ok());letrollback_result=transaction.rollback().await;assert!(rollback_result.is_ok());}#[tokio::test]asyncfntest_transaction_manager(){letmutmanager=TransactionManager::new();letconfig=TransactionConfig::default();lettxn_id=manager.start_transaction(config);lettransaction=manager.get_transaction(&txn_id);assert!(transaction.is_some());letcommit_result=manager.commit_transaction(&txn_id).await;assert!(commit_result.is_ok());}}
// rust/03-query-optimization.rs/*Query optimization patterns and best practices*/usestd::collections::HashMap;useserde::{Deserialize,Serialize};usestd::time::Duration;/// Query execution plan.#[derive(Debug, Clone, Serialize, Deserialize)]pubstructQueryPlan{pubquery_id:String,pubestimated_cost:f64,pubestimated_rows:u64,pubexecution_time:Duration,puboperations:Vec<QueryOperation>,}#[derive(Debug, Clone, Serialize, Deserialize)]pubstructQueryOperation{puboperation_type:String,pubtable_name:String,pubindex_used:Option<String>,pubcost:f64,pubrows:u64,}/// Query optimizer.pubstructQueryOptimizer{statistics:HashMap<String,TableStatistics>,indexes:HashMap<String,Vec<IndexInfo>>,}#[derive(Debug, Clone, Serialize, Deserialize)]pubstructTableStatistics{pubtable_name:String,pubrow_count:u64,pubavg_row_size:u64,publast_updated:std::time::SystemTime,}#[derive(Debug, Clone, Serialize, Deserialize)]pubstructIndexInfo{pubindex_name:String,pubcolumn_name:String,pubcardinality:u64,pubis_unique:bool,pubis_primary:bool,}implQueryOptimizer{pubfnnew()->Self{Self{statistics:HashMap::new(),indexes:HashMap::new(),}}/// Analyze a query and return an optimized plan.pubasyncfnoptimize_query(&self,query:&str)->Result<QueryPlan,String>{letquery_id=format!("query-{}",uuid::Uuid::new_v4());// Parse the queryletparsed_query=self.parse_query(query)?;// Generate execution planletplan=self.generate_execution_plan(&parsed_query).await?;Ok(QueryPlan{query_id,estimated_cost:plan.estimated_cost,estimated_rows:plan.estimated_rows,execution_time:plan.execution_time,operations:plan.operations,})}/// Parse a SQL query.fnparse_query(&self,query:&str)->Result<ParsedQuery,String>{// In a real implementation, you would use a SQL parser// For this example, we'll create a simple parserletquery_lower=query.to_lowercase();ifquery_lower.starts_with("select"){Ok(ParsedQuery{query_type:QueryType::Select,tables:self.extract_tables(query),columns:self.extract_columns(query),conditions:self.extract_conditions(query),joins:self.extract_joins(query),order_by:self.extract_order_by(query),limit:self.extract_limit(query),})}else{Err("Unsupported query type".to_string())}}/// Extract table names from query.fnextract_tables(&self,query:&str)->Vec<String>{// Simple table extraction - in a real implementation,// you would use a proper SQL parserletmuttables=Vec::new();letquery_lower=query.to_lowercase();ifquery_lower.contains("from"){letfrom_part=query_lower.split("from").nth(1).unwrap_or("");ifletSome(table)=from_part.split_whitespace().next(){tables.push(table.to_string());}}tables}/// Extract column names from query.fnextract_columns(&self,query:&str)->Vec<String>{// Simple column extractionletmutcolumns=Vec::new();letquery_lower=query.to_lowercase();ifquery_lower.starts_with("select"){letselect_part=query_lower.split("from").next().unwrap_or("");ifselect_part.contains("*"){columns.push("*".to_string());}else{// Extract individual columnsletcolumns_part=select_part.replace("select","").trim().to_string();forcolumnincolumns_part.split(","){columns.push(column.trim().to_string());}}}columns}/// Extract WHERE conditions from query.fnextract_conditions(&self,query:&str)->Vec<String>{// Simple condition extractionletmutconditions=Vec::new();letquery_lower=query.to_lowercase();ifquery_lower.contains("where"){letwhere_part=query_lower.split("where").nth(1).unwrap_or("");ifletSome(condition)=where_part.split("order").next(){conditions.push(condition.trim().to_string());}}conditions}/// Extract JOIN clauses from query.fnextract_joins(&self,query:&str)->Vec<String>{// Simple join extractionletmutjoins=Vec::new();letquery_lower=query.to_lowercase();ifquery_lower.contains("join"){letjoin_parts:Vec<&str>=query_lower.split("join").collect();forpartinjoin_parts.iter().skip(1){ifletSome(join)=part.split_whitespace().next(){joins.push(join.to_string());}}}joins}/// Extract ORDER BY clause from query.fnextract_order_by(&self,query:&str)->Vec<String>{// Simple ORDER BY extractionletmutorder_by=Vec::new();letquery_lower=query.to_lowercase();ifquery_lower.contains("order by"){letorder_part=query_lower.split("order by").nth(1).unwrap_or("");ifletSome(column)=order_part.split_whitespace().next(){order_by.push(column.to_string());}}order_by}/// Extract LIMIT clause from query.fnextract_limit(&self,query:&str)->Option<u64>{// Simple LIMIT extractionletquery_lower=query.to_lowercase();ifquery_lower.contains("limit"){letlimit_part=query_lower.split("limit").nth(1).unwrap_or("");ifletSome(limit_str)=limit_part.split_whitespace().next(){returnlimit_str.parse().ok();}}None}/// Generate execution plan for a parsed query.asyncfngenerate_execution_plan(&self,query:&ParsedQuery)->Result<QueryPlan,String>{letmutoperations=Vec::new();letmuttotal_cost=0.0;letmuttotal_rows=0;// Generate operations for each tablefortablein&query.tables{letstats=self.statistics.get(table).cloned().unwrap_or_else(||{TableStatistics{table_name:table.clone(),row_count:1000,avg_row_size:100,last_updated:std::time::SystemTime::now(),}});letoperation=QueryOperation{operation_type:"Seq Scan".to_string(),table_name:table.clone(),index_used:None,cost:stats.row_countasf64*0.01,rows:stats.row_count,};operations.push(operation);total_cost+=stats.row_countasf64*0.01;total_rows+=stats.row_count;}// Apply filtersif!query.conditions.is_empty(){letfilter_operation=QueryOperation{operation_type:"Filter".to_string(),table_name:"".to_string(),index_used:None,cost:total_rowsasf64*0.1,rows:total_rows/10,};operations.push(filter_operation);total_cost+=total_rowsasf64*0.1;total_rows/=10;}// Apply sorting if neededif!query.order_by.is_empty(){letsort_operation=QueryOperation{operation_type:"Sort".to_string(),table_name:"".to_string(),index_used:None,cost:total_rowsasf64*0.2,rows:total_rows,};operations.push(sort_operation);total_cost+=total_rowsasf64*0.2;}Ok(QueryPlan{query_id:"".to_string(),estimated_cost:total_cost,estimated_rows:total_rows,execution_time:Duration::from_millis((total_cost*10.0)asu64),operations,})}/// Add table statistics.pubfnadd_table_statistics(&mutself,stats:TableStatistics){self.statistics.insert(stats.table_name.clone(),stats);}/// Add index information.pubfnadd_index_info(&mutself,table_name:String,index_info:IndexInfo){self.indexes.entry(table_name).or_insert_with(Vec::new).push(index_info);}}#[derive(Debug, Clone)]pubstructParsedQuery{pubquery_type:QueryType,pubtables:Vec<String>,pubcolumns:Vec<String>,pubconditions:Vec<String>,pubjoins:Vec<String>,puborder_by:Vec<String>,publimit:Option<u64>,}#[derive(Debug, Clone)]pubenumQueryType{Select,Insert,Update,Delete,}#[cfg(test)]modtests{usesuper::*;#[tokio::test]asyncfntest_query_optimizer(){letmutoptimizer=QueryOptimizer::new();letstats=TableStatistics{table_name:"users".to_string(),row_count:1000,avg_row_size:100,last_updated:std::time::SystemTime::now(),};optimizer.add_table_statistics(stats);letquery="SELECT * FROM users WHERE id = 1";letplan=optimizer.optimize_query(query).await.unwrap();assert!(plan.estimated_cost>0.0);assert!(plan.estimated_rows>0);}#[test]fntest_query_parsing(){letoptimizer=QueryOptimizer::new();letquery="SELECT id, name FROM users WHERE age > 18 ORDER BY name LIMIT 10";letparsed=optimizer.parse_query(query).unwrap();assert_eq!(parsed.tables,vec!["users"]);assert_eq!(parsed.columns,vec!["id","name"]);assert!(!parsed.conditions.is_empty());assert!(!parsed.order_by.is_empty());assert_eq!(parsed.limit,Some(10));}}