1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! Performance optimized query building
//!
//! This module implements optimized versions of query building operations
//! to reduce allocations and improve performance for hot paths.
use super::builder::QueryBuilder;
use once_cell::sync::Lazy;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
/// Cache for common SQL patterns to reduce string allocations
#[allow(dead_code)]
static QUERY_TEMPLATE_CACHE: Lazy<RwLock<HashMap<String, String>>> =
Lazy::new(|| RwLock::new(HashMap::new()));
/// Cache for parameter placeholders to avoid repeated generation
static PLACEHOLDER_CACHE: Lazy<RwLock<HashMap<usize, String>>> =
Lazy::new(|| RwLock::new(HashMap::new()));
/// Performance-optimized SQL generation with caching
impl<M> QueryBuilder<M> {
/// Generate parameter placeholders with caching for better performance
pub fn generate_placeholders_cached(count: usize) -> String {
// Check cache first
if let Ok(cache) = PLACEHOLDER_CACHE.read() {
if let Some(cached) = cache.get(&count) {
return cached.clone();
}
}
// Generate placeholders
let placeholders = (1..=count)
.map(|i| format!("${}", i))
.collect::<Vec<_>>()
.join(", ");
// Cache for future use
if let Ok(mut cache) = PLACEHOLDER_CACHE.write() {
cache.insert(count, placeholders.clone());
}
placeholders
}
/// Generate sequential parameter placeholders starting from a specific index
/// Used for proper parameter ordering in complex queries
pub fn generate_sequential_placeholders(start_index: usize, count: usize) -> String {
if count == 0 {
return String::new();
}
let placeholders = (start_index..start_index + count)
.map(|i| format!("${}", i))
.collect::<Vec<_>>()
.join(", ");
placeholders
}
/// Optimized SQL generation with pre-allocated capacity
pub fn to_sql_optimized(&self) -> String {
// Pre-calculate approximate SQL length to reduce allocations
let estimated_length = self.estimate_sql_length();
let mut sql = String::with_capacity(estimated_length);
match self.query_type {
super::types::QueryType::Select => {
self.build_select_sql_optimized(&mut sql);
}
_ => {
// Fallback to regular implementation for non-SELECT queries
return self.to_sql();
}
}
sql
}
/// Estimate SQL length to pre-allocate string capacity
fn estimate_sql_length(&self) -> usize {
let mut length = 100; // Base SQL overhead
// Estimate SELECT clause length
for field in &self.select_fields {
length += field.len() + 2; // field + ", "
}
// Estimate FROM clause length
for table in &self.from_tables {
length += table.len() + 10; // " FROM " + table
}
// Estimate WHERE clause length
for condition in &self.where_conditions {
length += condition.column.len() + 20; // column + operator + placeholder
}
// Estimate JOIN clause length
for join in &self.joins {
length += join.table.len() + 30; // JOIN type + table + ON condition
}
length
}
/// Build SELECT SQL with optimized string operations and correct parameter indexing
fn build_select_sql_optimized(&self, sql: &mut String) {
let mut param_counter = 1usize;
// SELECT clause
if self.distinct {
sql.push_str("SELECT DISTINCT ");
} else {
sql.push_str("SELECT ");
}
// Fields
if self.select_fields.is_empty() {
sql.push('*');
} else {
for (i, field) in self.select_fields.iter().enumerate() {
if i > 0 {
sql.push_str(", ");
}
sql.push_str(field);
}
}
// FROM clause
if !self.from_tables.is_empty() {
sql.push_str(" FROM ");
for (i, table) in self.from_tables.iter().enumerate() {
if i > 0 {
sql.push_str(", ");
}
sql.push_str(table);
}
}
// JOINs
for join in &self.joins {
sql.push(' ');
match join.join_type {
super::types::JoinType::Inner => sql.push_str("INNER JOIN"),
super::types::JoinType::Left => sql.push_str("LEFT JOIN"),
super::types::JoinType::Right => sql.push_str("RIGHT JOIN"),
super::types::JoinType::Full => sql.push_str("FULL JOIN"),
}
sql.push(' ');
sql.push_str(&join.table);
sql.push_str(" ON ");
// Handle on_conditions
for (i, (left_col, right_col)) in join.on_conditions.iter().enumerate() {
if i > 0 {
sql.push_str(" AND ");
}
sql.push_str(left_col);
sql.push_str(" = ");
sql.push_str(right_col);
}
}
// WHERE clause
if !self.where_conditions.is_empty() {
sql.push_str(" WHERE ");
for (i, condition) in self.where_conditions.iter().enumerate() {
if i > 0 {
sql.push_str(" AND ");
}
// Handle special cases
if condition.column == "RAW" {
if let Some(ref value) = condition.value {
if let serde_json::Value::String(raw_sql) = value {
sql.push_str(raw_sql);
}
}
} else if condition.column == "EXISTS" || condition.column == "NOT EXISTS" {
sql.push_str(&condition.column);
sql.push(' ');
if let Some(ref value) = condition.value {
if let serde_json::Value::String(subquery) = value {
sql.push_str(subquery);
}
}
} else {
// Regular conditions
sql.push_str(&condition.column);
match condition.operator {
super::types::QueryOperator::Equal => sql.push_str(" = "),
super::types::QueryOperator::NotEqual => sql.push_str(" != "),
super::types::QueryOperator::GreaterThan => sql.push_str(" > "),
super::types::QueryOperator::LessThan => sql.push_str(" < "),
super::types::QueryOperator::GreaterThanOrEqual => sql.push_str(" >= "),
super::types::QueryOperator::LessThanOrEqual => sql.push_str(" <= "),
super::types::QueryOperator::Like => sql.push_str(" LIKE "),
super::types::QueryOperator::NotLike => sql.push_str(" NOT LIKE "),
super::types::QueryOperator::In => {
sql.push_str(" IN (");
let placeholder_count = condition.values.len();
if placeholder_count > 0 {
let placeholders = Self::generate_sequential_placeholders(
param_counter,
placeholder_count,
);
sql.push_str(&placeholders);
param_counter += placeholder_count;
}
sql.push(')');
continue; // Skip the normal parameter handling
}
super::types::QueryOperator::NotIn => {
sql.push_str(" NOT IN (");
let placeholder_count = condition.values.len();
if placeholder_count > 0 {
let placeholders = Self::generate_sequential_placeholders(
param_counter,
placeholder_count,
);
sql.push_str(&placeholders);
param_counter += placeholder_count;
}
sql.push(')');
continue; // Skip the normal parameter handling
}
super::types::QueryOperator::IsNull => {
sql.push_str(" IS NULL");
continue;
}
super::types::QueryOperator::IsNotNull => {
sql.push_str(" IS NOT NULL");
continue;
}
super::types::QueryOperator::Between => {
sql.push_str(&format!(
" BETWEEN ${} AND ${}",
param_counter,
param_counter + 1
));
param_counter += 2;
continue;
}
super::types::QueryOperator::Raw => {
// For raw SQL expressions, just add the value directly
if let Some(ref value) = condition.value {
if let serde_json::Value::String(raw_expr) = value {
sql.push(' ');
sql.push_str(raw_expr);
}
}
continue;
}
}
// Add parameter placeholder for regular operators
sql.push_str(&format!("${}", param_counter));
param_counter += 1;
}
}
}
// GROUP BY
if !self.group_by.is_empty() {
sql.push_str(" GROUP BY ");
for (i, column) in self.group_by.iter().enumerate() {
if i > 0 {
sql.push_str(", ");
}
sql.push_str(column);
}
}
// HAVING
if !self.having_conditions.is_empty() {
sql.push_str(" HAVING ");
for (i, condition) in self.having_conditions.iter().enumerate() {
if i > 0 {
sql.push_str(" AND ");
}
sql.push_str(&condition.column);
// Handle HAVING operators with proper parameter indexing
match condition.operator {
super::types::QueryOperator::Equal => sql.push_str(" = "),
super::types::QueryOperator::GreaterThan => sql.push_str(" > "),
super::types::QueryOperator::LessThan => sql.push_str(" < "),
_ => sql.push_str(" = "), // Default to equals
}
sql.push_str(&format!("${}", param_counter));
param_counter += 1;
}
}
// ORDER BY
if !self.order_by.is_empty() {
sql.push_str(" ORDER BY ");
for (i, (column, direction)) in self.order_by.iter().enumerate() {
if i > 0 {
sql.push_str(", ");
}
sql.push_str(column);
match direction {
super::types::OrderDirection::Asc => sql.push_str(" ASC"),
super::types::OrderDirection::Desc => sql.push_str(" DESC"),
}
}
}
// LIMIT
if let Some(limit) = self.limit_count {
sql.push_str(" LIMIT ");
sql.push_str(&limit.to_string());
}
// OFFSET
if let Some(offset) = self.offset_value {
sql.push_str(" OFFSET ");
sql.push_str(&offset.to_string());
}
}
}
/// Query builder pool for reusing query builder instances to reduce allocations
pub struct QueryBuilderPool {
pool: Arc<RwLock<Vec<QueryBuilder<()>>>>,
max_size: usize,
}
impl QueryBuilderPool {
pub fn new(max_size: usize) -> Self {
Self {
pool: Arc::new(RwLock::new(Vec::with_capacity(max_size))),
max_size,
}
}
/// Get a query builder from the pool or create a new one
pub fn acquire(&self) -> QueryBuilder<()> {
if let Ok(mut pool) = self.pool.write() {
if let Some(mut builder) = pool.pop() {
// Reset the builder to default state
builder.reset();
return builder;
}
}
// Create new builder if pool is empty
QueryBuilder::new()
}
/// Return a query builder to the pool
pub fn release(&self, builder: QueryBuilder<()>) {
if let Ok(mut pool) = self.pool.write() {
if pool.len() < self.max_size {
pool.push(builder);
}
// If pool is full, just drop the builder
}
}
}
impl<M> QueryBuilder<M> {
/// Reset query builder to default state for reuse
pub fn reset(&mut self) {
self.query_type = super::types::QueryType::Select;
self.select_fields.clear();
self.from_tables.clear();
self.insert_table = None;
self.update_table = None;
self.delete_table = None;
self.set_clauses.clear();
self.where_conditions.clear();
self.joins.clear();
self.order_by.clear();
self.group_by.clear();
self.having_conditions.clear();
self.limit_count = None;
self.offset_value = None;
self.distinct = false;
}
}
/// Global query builder pool instance
static GLOBAL_QUERY_POOL: Lazy<QueryBuilderPool> = Lazy::new(|| {
QueryBuilderPool::new(100) // Pool of up to 100 query builders
});
/// Get a query builder from the global pool
pub fn acquire_query_builder() -> QueryBuilder<()> {
GLOBAL_QUERY_POOL.acquire()
}
/// Return a query builder to the global pool
pub fn release_query_builder(builder: QueryBuilder<()>) {
GLOBAL_QUERY_POOL.release(builder);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_placeholder_caching() {
let placeholders1 = QueryBuilder::<()>::generate_placeholders_cached(3);
let placeholders2 = QueryBuilder::<()>::generate_placeholders_cached(3);
assert_eq!(placeholders1, "$1, $2, $3");
assert_eq!(placeholders1, placeholders2);
}
#[test]
fn test_query_builder_pool() {
let pool = QueryBuilderPool::new(2);
let builder1 = pool.acquire();
let builder2 = pool.acquire();
pool.release(builder1);
pool.release(builder2);
let builder3 = pool.acquire(); // Should reuse from pool
assert!(!builder3.from_tables.is_empty() || builder3.from_tables.is_empty());
// Basic check
}
#[test]
fn test_optimized_sql_generation() {
let query: QueryBuilder<()> = QueryBuilder::new()
.from("users")
.select("id, name, email")
.where_eq("active", "true");
let sql = query.to_sql_optimized();
assert!(sql.contains("SELECT"));
assert!(sql.contains("FROM users"));
assert!(sql.contains("WHERE"));
}
}