prax-query 0.9.1

Type-safe query builder for the Prax ORM
Documentation
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
//! Typed arena allocation for query builder chains.
//!
//! This module provides arena-based allocation for efficient query construction
//! with minimal heap allocations.
//!
//! # Benefits
//!
//! - **Batch deallocation**: All allocations freed at once when scope ends
//! - **Cache-friendly**: Contiguous memory allocation
//! - **Fast allocation**: O(1) bump pointer allocation
//! - **No fragmentation**: No individual deallocation overhead
//!
//! # Example
//!
//! ```rust
//! use prax_query::mem_optimize::arena::QueryArena;
//!
//! let arena = QueryArena::new();
//!
//! // Build query within arena scope
//! let sql = arena.scope(|scope| {
//!     let filter = scope.eq("status", "active");
//!     let filter = scope.and(vec![
//!         filter,
//!         scope.gt("age", 18),
//!     ]);
//!     scope.build_select("users", filter)
//! });
//!
//! // Arena memory freed, but sql String is owned
//! ```

use bumpalo::Bump;
use std::cell::Cell;
use std::fmt::Write;

use super::interning::InternedStr;

// ============================================================================
// Query Arena
// ============================================================================

/// Arena allocator for query building.
///
/// Provides fast allocation with batch deallocation when the scope ends.
pub struct QueryArena {
    bump: Bump,
    stats: Cell<ArenaStats>,
}

impl QueryArena {
    /// Create a new query arena with default capacity.
    pub fn new() -> Self {
        Self {
            bump: Bump::new(),
            stats: Cell::new(ArenaStats::default()),
        }
    }

    /// Create an arena with specified initial capacity.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            bump: Bump::with_capacity(capacity),
            stats: Cell::new(ArenaStats::default()),
        }
    }

    /// Execute a closure with an arena scope.
    ///
    /// The scope provides allocation methods. All allocations are valid
    /// within the closure and freed when it returns.
    pub fn scope<F, R>(&self, f: F) -> R
    where
        F: FnOnce(&ArenaScope<'_>) -> R,
    {
        let scope = ArenaScope::new(&self.bump, &self.stats);
        f(&scope)
    }

    /// Reset the arena for reuse.
    ///
    /// This is O(1) - just resets the bump pointer.
    pub fn reset(&mut self) {
        self.bump.reset();
        self.stats.set(ArenaStats::default());
    }

    /// Get the number of bytes currently allocated.
    pub fn allocated_bytes(&self) -> usize {
        self.bump.allocated_bytes()
    }

    /// Get arena statistics.
    pub fn stats(&self) -> ArenaStats {
        self.stats.get()
    }
}

impl Default for QueryArena {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Arena Scope
// ============================================================================

/// A scope for allocating within an arena.
///
/// All allocations made through this scope are freed when the scope ends.
pub struct ArenaScope<'a> {
    bump: &'a Bump,
    stats: &'a Cell<ArenaStats>,
}

impl<'a> ArenaScope<'a> {
    fn new(bump: &'a Bump, stats: &'a Cell<ArenaStats>) -> Self {
        Self { bump, stats }
    }

    fn record_alloc(&self, bytes: usize) {
        let mut s = self.stats.get();
        s.allocations += 1;
        s.total_bytes += bytes;
        self.stats.set(s);
    }

    /// Allocate a string in the arena.
    #[inline]
    pub fn alloc_str(&self, s: &str) -> &'a str {
        self.record_alloc(s.len());
        self.bump.alloc_str(s)
    }

    /// Allocate a slice in the arena.
    #[inline]
    pub fn alloc_slice<T: Copy>(&self, slice: &[T]) -> &'a [T] {
        self.record_alloc(std::mem::size_of_val(slice));
        self.bump.alloc_slice_copy(slice)
    }

    /// Allocate a slice from an iterator.
    #[inline]
    pub fn alloc_slice_iter<T, I>(&self, iter: I) -> &'a [T]
    where
        I: IntoIterator<Item = T>,
        I::IntoIter: ExactSizeIterator,
    {
        let iter = iter.into_iter();
        self.record_alloc(iter.len() * std::mem::size_of::<T>());
        self.bump.alloc_slice_fill_iter(iter)
    }

    /// Allocate a single value in the arena.
    #[inline]
    pub fn alloc<T>(&self, value: T) -> &'a T {
        self.record_alloc(std::mem::size_of::<T>());
        self.bump.alloc(value)
    }

    /// Allocate a mutable value in the arena.
    #[inline]
    pub fn alloc_mut<T>(&self, value: T) -> &'a mut T {
        self.record_alloc(std::mem::size_of::<T>());
        self.bump.alloc(value)
    }

    // ========================================================================
    // Filter Construction
    // ========================================================================

    /// Create an equality filter.
    #[inline]
    pub fn eq<V: Into<ScopedValue<'a>>>(&self, field: &str, value: V) -> ScopedFilter<'a> {
        ScopedFilter::Equals(self.alloc_str(field), value.into())
    }

    /// Create a not-equals filter.
    #[inline]
    pub fn ne<V: Into<ScopedValue<'a>>>(&self, field: &str, value: V) -> ScopedFilter<'a> {
        ScopedFilter::NotEquals(self.alloc_str(field), value.into())
    }

    /// Create a less-than filter.
    #[inline]
    pub fn lt<V: Into<ScopedValue<'a>>>(&self, field: &str, value: V) -> ScopedFilter<'a> {
        ScopedFilter::Lt(self.alloc_str(field), value.into())
    }

    /// Create a less-than-or-equal filter.
    #[inline]
    pub fn lte<V: Into<ScopedValue<'a>>>(&self, field: &str, value: V) -> ScopedFilter<'a> {
        ScopedFilter::Lte(self.alloc_str(field), value.into())
    }

    /// Create a greater-than filter.
    #[inline]
    pub fn gt<V: Into<ScopedValue<'a>>>(&self, field: &str, value: V) -> ScopedFilter<'a> {
        ScopedFilter::Gt(self.alloc_str(field), value.into())
    }

    /// Create a greater-than-or-equal filter.
    #[inline]
    pub fn gte<V: Into<ScopedValue<'a>>>(&self, field: &str, value: V) -> ScopedFilter<'a> {
        ScopedFilter::Gte(self.alloc_str(field), value.into())
    }

    /// Create an IN filter.
    #[inline]
    pub fn is_in(&self, field: &str, values: Vec<ScopedValue<'a>>) -> ScopedFilter<'a> {
        ScopedFilter::In(self.alloc_str(field), self.alloc_slice_iter(values))
    }

    /// Create a NOT IN filter.
    #[inline]
    pub fn not_in(&self, field: &str, values: Vec<ScopedValue<'a>>) -> ScopedFilter<'a> {
        ScopedFilter::NotIn(self.alloc_str(field), self.alloc_slice_iter(values))
    }

    /// Create a CONTAINS filter.
    #[inline]
    pub fn contains<V: Into<ScopedValue<'a>>>(&self, field: &str, value: V) -> ScopedFilter<'a> {
        ScopedFilter::Contains(self.alloc_str(field), value.into())
    }

    /// Create a STARTS WITH filter.
    #[inline]
    pub fn starts_with<V: Into<ScopedValue<'a>>>(&self, field: &str, value: V) -> ScopedFilter<'a> {
        ScopedFilter::StartsWith(self.alloc_str(field), value.into())
    }

    /// Create an ENDS WITH filter.
    #[inline]
    pub fn ends_with<V: Into<ScopedValue<'a>>>(&self, field: &str, value: V) -> ScopedFilter<'a> {
        ScopedFilter::EndsWith(self.alloc_str(field), value.into())
    }

    /// Create an IS NULL filter.
    #[inline]
    pub fn is_null(&self, field: &str) -> ScopedFilter<'a> {
        ScopedFilter::IsNull(self.alloc_str(field))
    }

    /// Create an IS NOT NULL filter.
    #[inline]
    pub fn is_not_null(&self, field: &str) -> ScopedFilter<'a> {
        ScopedFilter::IsNotNull(self.alloc_str(field))
    }

    /// Combine filters with AND.
    #[inline]
    pub fn and(&self, filters: Vec<ScopedFilter<'a>>) -> ScopedFilter<'a> {
        // Filter out None filters
        let filters: Vec<_> = filters
            .into_iter()
            .filter(|f| !matches!(f, ScopedFilter::None))
            .collect();

        match filters.len() {
            0 => ScopedFilter::None,
            1 => filters.into_iter().next().unwrap(),
            _ => ScopedFilter::And(self.alloc_slice_iter(filters)),
        }
    }

    /// Combine filters with OR.
    #[inline]
    pub fn or(&self, filters: Vec<ScopedFilter<'a>>) -> ScopedFilter<'a> {
        let filters: Vec<_> = filters
            .into_iter()
            .filter(|f| !matches!(f, ScopedFilter::None))
            .collect();

        match filters.len() {
            0 => ScopedFilter::None,
            1 => filters.into_iter().next().unwrap(),
            _ => ScopedFilter::Or(self.alloc_slice_iter(filters)),
        }
    }

    /// Negate a filter.
    #[inline]
    pub fn not(&self, filter: ScopedFilter<'a>) -> ScopedFilter<'a> {
        if matches!(filter, ScopedFilter::None) {
            return ScopedFilter::None;
        }
        ScopedFilter::Not(self.alloc(filter))
    }

    // ========================================================================
    // Query Building
    // ========================================================================

    /// Build a SELECT query string.
    pub fn build_select(&self, table: &str, filter: ScopedFilter<'a>) -> String {
        let mut sql = String::with_capacity(128);
        sql.push_str("SELECT * FROM ");
        sql.push_str(table);

        if !matches!(filter, ScopedFilter::None) {
            sql.push_str(" WHERE ");
            filter.write_sql(&mut sql, &mut 1);
        }

        sql
    }

    /// Build a SELECT query with specific columns.
    pub fn build_select_columns(
        &self,
        table: &str,
        columns: &[&str],
        filter: ScopedFilter<'a>,
    ) -> String {
        let mut sql = String::with_capacity(128);
        sql.push_str("SELECT ");

        for (i, col) in columns.iter().enumerate() {
            if i > 0 {
                sql.push_str(", ");
            }
            sql.push_str(col);
        }

        sql.push_str(" FROM ");
        sql.push_str(table);

        if !matches!(filter, ScopedFilter::None) {
            sql.push_str(" WHERE ");
            filter.write_sql(&mut sql, &mut 1);
        }

        sql
    }

    /// Build a complete query with all parts.
    pub fn build_query(&self, query: &ScopedQuery<'a>) -> String {
        let mut sql = String::with_capacity(256);

        // SELECT
        sql.push_str("SELECT ");
        if query.columns.is_empty() {
            sql.push('*');
        } else {
            for (i, col) in query.columns.iter().enumerate() {
                if i > 0 {
                    sql.push_str(", ");
                }
                sql.push_str(col);
            }
        }

        // FROM
        sql.push_str(" FROM ");
        sql.push_str(query.table);

        // WHERE
        if !matches!(query.filter, ScopedFilter::None) {
            sql.push_str(" WHERE ");
            query.filter.write_sql(&mut sql, &mut 1);
        }

        // ORDER BY
        if !query.order_by.is_empty() {
            sql.push_str(" ORDER BY ");
            for (i, (col, dir)) in query.order_by.iter().enumerate() {
                if i > 0 {
                    sql.push_str(", ");
                }
                sql.push_str(col);
                sql.push(' ');
                sql.push_str(dir);
            }
        }

        // LIMIT
        if let Some(limit) = query.limit {
            write!(sql, " LIMIT {}", limit).unwrap();
        }

        // OFFSET
        if let Some(offset) = query.offset {
            write!(sql, " OFFSET {}", offset).unwrap();
        }

        sql
    }

    /// Create a new query builder.
    pub fn query(&self, table: &str) -> ScopedQuery<'a> {
        ScopedQuery {
            table: self.alloc_str(table),
            columns: &[],
            filter: ScopedFilter::None,
            order_by: &[],
            limit: None,
            offset: None,
        }
    }
}

// ============================================================================
// Scoped Filter
// ============================================================================

/// A filter allocated within an arena scope.
#[derive(Debug, Clone)]
pub enum ScopedFilter<'a> {
    /// No filter.
    None,
    /// Equality.
    Equals(&'a str, ScopedValue<'a>),
    /// Not equals.
    NotEquals(&'a str, ScopedValue<'a>),
    /// Less than.
    Lt(&'a str, ScopedValue<'a>),
    /// Less than or equal.
    Lte(&'a str, ScopedValue<'a>),
    /// Greater than.
    Gt(&'a str, ScopedValue<'a>),
    /// Greater than or equal.
    Gte(&'a str, ScopedValue<'a>),
    /// In list.
    In(&'a str, &'a [ScopedValue<'a>]),
    /// Not in list.
    NotIn(&'a str, &'a [ScopedValue<'a>]),
    /// Contains.
    Contains(&'a str, ScopedValue<'a>),
    /// Starts with.
    StartsWith(&'a str, ScopedValue<'a>),
    /// Ends with.
    EndsWith(&'a str, ScopedValue<'a>),
    /// Is null.
    IsNull(&'a str),
    /// Is not null.
    IsNotNull(&'a str),
    /// And.
    And(&'a [ScopedFilter<'a>]),
    /// Or.
    Or(&'a [ScopedFilter<'a>]),
    /// Not.
    Not(&'a ScopedFilter<'a>),
}

impl<'a> ScopedFilter<'a> {
    /// Write SQL to a string buffer.
    pub fn write_sql(&self, buf: &mut String, param_idx: &mut usize) {
        match self {
            ScopedFilter::None => {}
            ScopedFilter::Equals(field, _) => {
                write!(buf, "{} = ${}", field, param_idx).unwrap();
                *param_idx += 1;
            }
            ScopedFilter::NotEquals(field, _) => {
                write!(buf, "{} != ${}", field, param_idx).unwrap();
                *param_idx += 1;
            }
            ScopedFilter::Lt(field, _) => {
                write!(buf, "{} < ${}", field, param_idx).unwrap();
                *param_idx += 1;
            }
            ScopedFilter::Lte(field, _) => {
                write!(buf, "{} <= ${}", field, param_idx).unwrap();
                *param_idx += 1;
            }
            ScopedFilter::Gt(field, _) => {
                write!(buf, "{} > ${}", field, param_idx).unwrap();
                *param_idx += 1;
            }
            ScopedFilter::Gte(field, _) => {
                write!(buf, "{} >= ${}", field, param_idx).unwrap();
                *param_idx += 1;
            }
            ScopedFilter::In(field, values) => {
                write!(buf, "{} IN (", field).unwrap();
                for (i, _) in values.iter().enumerate() {
                    if i > 0 {
                        buf.push_str(", ");
                    }
                    write!(buf, "${}", param_idx).unwrap();
                    *param_idx += 1;
                }
                buf.push(')');
            }
            ScopedFilter::NotIn(field, values) => {
                write!(buf, "{} NOT IN (", field).unwrap();
                for (i, _) in values.iter().enumerate() {
                    if i > 0 {
                        buf.push_str(", ");
                    }
                    write!(buf, "${}", param_idx).unwrap();
                    *param_idx += 1;
                }
                buf.push(')');
            }
            ScopedFilter::Contains(field, _) => {
                write!(buf, "{} LIKE ${}", field, param_idx).unwrap();
                *param_idx += 1;
            }
            ScopedFilter::StartsWith(field, _) => {
                write!(buf, "{} LIKE ${}", field, param_idx).unwrap();
                *param_idx += 1;
            }
            ScopedFilter::EndsWith(field, _) => {
                write!(buf, "{} LIKE ${}", field, param_idx).unwrap();
                *param_idx += 1;
            }
            ScopedFilter::IsNull(field) => {
                write!(buf, "{} IS NULL", field).unwrap();
            }
            ScopedFilter::IsNotNull(field) => {
                write!(buf, "{} IS NOT NULL", field).unwrap();
            }
            ScopedFilter::And(filters) => {
                buf.push('(');
                for (i, filter) in filters.iter().enumerate() {
                    if i > 0 {
                        buf.push_str(" AND ");
                    }
                    filter.write_sql(buf, param_idx);
                }
                buf.push(')');
            }
            ScopedFilter::Or(filters) => {
                buf.push('(');
                for (i, filter) in filters.iter().enumerate() {
                    if i > 0 {
                        buf.push_str(" OR ");
                    }
                    filter.write_sql(buf, param_idx);
                }
                buf.push(')');
            }
            ScopedFilter::Not(filter) => {
                buf.push_str("NOT (");
                filter.write_sql(buf, param_idx);
                buf.push(')');
            }
        }
    }
}

// ============================================================================
// Scoped Value
// ============================================================================

/// A value allocated within an arena scope.
#[derive(Debug, Clone)]
pub enum ScopedValue<'a> {
    /// Null.
    Null,
    /// Boolean.
    Bool(bool),
    /// Integer.
    Int(i64),
    /// Float.
    Float(f64),
    /// String (borrowed from arena).
    String(&'a str),
    /// Interned string (shared reference).
    Interned(InternedStr),
}

impl<'a> From<bool> for ScopedValue<'a> {
    fn from(v: bool) -> Self {
        ScopedValue::Bool(v)
    }
}

impl<'a> From<i32> for ScopedValue<'a> {
    fn from(v: i32) -> Self {
        ScopedValue::Int(v as i64)
    }
}

impl<'a> From<i64> for ScopedValue<'a> {
    fn from(v: i64) -> Self {
        ScopedValue::Int(v)
    }
}

impl<'a> From<f64> for ScopedValue<'a> {
    fn from(v: f64) -> Self {
        ScopedValue::Float(v)
    }
}

impl<'a> From<&'a str> for ScopedValue<'a> {
    fn from(v: &'a str) -> Self {
        ScopedValue::String(v)
    }
}

impl<'a> From<InternedStr> for ScopedValue<'a> {
    fn from(v: InternedStr) -> Self {
        ScopedValue::Interned(v)
    }
}

// ============================================================================
// Scoped Query
// ============================================================================

/// A query being built within an arena scope.
#[derive(Debug, Clone)]
pub struct ScopedQuery<'a> {
    /// Table name.
    pub table: &'a str,
    /// Columns to select.
    pub columns: &'a [&'a str],
    /// Filter.
    pub filter: ScopedFilter<'a>,
    /// Order by clauses.
    pub order_by: &'a [(&'a str, &'a str)],
    /// Limit.
    pub limit: Option<usize>,
    /// Offset.
    pub offset: Option<usize>,
}

impl<'a> ScopedQuery<'a> {
    /// Set columns to select.
    pub fn select(mut self, columns: &'a [&'a str]) -> Self {
        self.columns = columns;
        self
    }

    /// Set filter.
    pub fn filter(mut self, filter: ScopedFilter<'a>) -> Self {
        self.filter = filter;
        self
    }

    /// Set order by.
    pub fn order_by(mut self, order_by: &'a [(&'a str, &'a str)]) -> Self {
        self.order_by = order_by;
        self
    }

    /// Set limit.
    pub fn limit(mut self, limit: usize) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Set offset.
    pub fn offset(mut self, offset: usize) -> Self {
        self.offset = Some(offset);
        self
    }
}

// ============================================================================
// Statistics
// ============================================================================

/// Statistics for arena usage.
#[derive(Debug, Clone, Copy, Default)]
pub struct ArenaStats {
    /// Number of allocations.
    pub allocations: usize,
    /// Total bytes allocated.
    pub total_bytes: usize,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_arena_basic_filter() {
        let arena = QueryArena::new();

        let sql = arena.scope(|scope| scope.build_select("users", scope.eq("id", 42)));

        assert!(sql.contains("SELECT * FROM users"));
        assert!(sql.contains("WHERE"));
        assert!(sql.contains("id = $1"));
    }

    #[test]
    fn test_arena_complex_filter() {
        let arena = QueryArena::new();

        let sql = arena.scope(|scope| {
            let filter = scope.and(vec![
                scope.eq("active", true),
                scope.or(vec![scope.gt("age", 18), scope.is_not_null("verified_at")]),
            ]);
            scope.build_select("users", filter)
        });

        assert!(sql.contains("AND"));
        assert!(sql.contains("OR"));
    }

    #[test]
    fn test_arena_reset() {
        let mut arena = QueryArena::with_capacity(1024);

        // Use arena
        let _ = arena.scope(|scope| scope.build_select("users", scope.eq("id", 1)));
        let bytes1 = arena.allocated_bytes();

        // Reset
        arena.reset();

        // Use again
        let _ = arena.scope(|scope| scope.build_select("posts", scope.eq("id", 2)));
        let bytes2 = arena.allocated_bytes();

        // Should be similar (reusing memory)
        assert!(bytes2 <= bytes1 * 2);
    }

    #[test]
    fn test_arena_query_builder() {
        let arena = QueryArena::new();

        let sql = arena.scope(|scope| {
            let query = scope
                .query("users")
                .filter(scope.eq("active", true))
                .limit(10)
                .offset(20);
            scope.build_query(&query)
        });

        assert!(sql.contains("SELECT * FROM users"));
        assert!(sql.contains("LIMIT 10"));
        assert!(sql.contains("OFFSET 20"));
    }

    #[test]
    fn test_arena_in_filter() {
        let arena = QueryArena::new();

        let sql = arena.scope(|scope| {
            let filter = scope.is_in(
                "status",
                vec!["pending".into(), "processing".into(), "completed".into()],
            );
            scope.build_select("orders", filter)
        });

        assert!(sql.contains("IN"));
        assert!(sql.contains("$1"));
        assert!(sql.contains("$2"));
        assert!(sql.contains("$3"));
    }

    #[test]
    fn test_arena_stats() {
        let arena = QueryArena::new();

        arena.scope(|scope| {
            let _ = scope.alloc_str("test string");
            let _ = scope.alloc_str("another string");
        });

        let stats = arena.stats();
        assert_eq!(stats.allocations, 2);
    }
}