prax-query 0.9.3

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
//! Static filter construction for zero-allocation filters.
//!
//! This module provides zero-cost filter construction through:
//! - Static field name constants
//! - Type-level filter builders
//! - Compile-time filter macros
//!
//! # Performance
//!
//! Static filters avoid heap allocations entirely:
//! - Field names are `&'static str` (no `Cow` overhead)
//! - Values are constructed inline
//! - Common patterns are pre-computed
//!
//! # Examples
//!
//! ```rust
//! use prax_query::static_filter::{StaticFilter, eq, gt, and2};
//! use prax_query::static_filter::fields;
//!
//! // Zero-allocation filter construction
//! let filter = eq(fields::ID, 42);
//! let filter = gt(fields::AGE, 18);
//!
//! // Combine two filters (optimized path)
//! let filter = and2(
//!     eq(fields::ACTIVE, true),
//!     gt(fields::SCORE, 100),
//! );
//! ```

use crate::filter::{Filter, FilterValue, ValueList};
use std::borrow::Cow;

/// A static filter with compile-time known field name.
///
/// This is a zero-cost abstraction over `Filter` that avoids
/// the `Cow<'static, str>` overhead for field names.
#[derive(Debug, Clone, PartialEq)]
pub struct StaticFilter {
    inner: Filter,
}

impl StaticFilter {
    /// Create a new static filter.
    #[inline]
    pub const fn new(inner: Filter) -> Self {
        Self { inner }
    }

    /// Convert to the underlying Filter.
    #[inline]
    pub fn into_filter(self) -> Filter {
        self.inner
    }

    /// Get a reference to the underlying Filter.
    #[inline]
    pub fn as_filter(&self) -> &Filter {
        &self.inner
    }
}

impl From<StaticFilter> for Filter {
    #[inline]
    fn from(f: StaticFilter) -> Self {
        f.inner
    }
}

/// Common field name constants for zero-allocation filters.
///
/// These are pre-defined `&'static str` values for common database columns.
/// Using these avoids the overhead of `Cow::Borrowed` construction.
pub mod fields {
    /// Primary key field.
    pub const ID: &str = "id";
    /// UUID field.
    pub const UUID: &str = "uuid";
    /// Name field.
    pub const NAME: &str = "name";
    /// Email field.
    pub const EMAIL: &str = "email";
    /// Username field.
    pub const USERNAME: &str = "username";
    /// Password hash field.
    pub const PASSWORD: &str = "password";
    /// Title field.
    pub const TITLE: &str = "title";
    /// Description field.
    pub const DESCRIPTION: &str = "description";
    /// Content field.
    pub const CONTENT: &str = "content";
    /// Body field.
    pub const BODY: &str = "body";
    /// Status field.
    pub const STATUS: &str = "status";
    /// Type field.
    pub const TYPE: &str = "type";
    /// Role field.
    pub const ROLE: &str = "role";
    /// Active flag field.
    pub const ACTIVE: &str = "active";
    /// Enabled flag field.
    pub const ENABLED: &str = "enabled";
    /// Deleted flag field.
    pub const DELETED: &str = "deleted";
    /// Verified flag field.
    pub const VERIFIED: &str = "verified";
    /// Published flag field.
    pub const PUBLISHED: &str = "published";
    /// Count field.
    pub const COUNT: &str = "count";
    /// Score field.
    pub const SCORE: &str = "score";
    /// Priority field.
    pub const PRIORITY: &str = "priority";
    /// Order/sort order field.
    pub const ORDER: &str = "order";
    /// Position field.
    pub const POSITION: &str = "position";
    /// Age field.
    pub const AGE: &str = "age";
    /// Amount field.
    pub const AMOUNT: &str = "amount";
    /// Price field.
    pub const PRICE: &str = "price";
    /// Quantity field.
    pub const QUANTITY: &str = "quantity";
    /// Foreign key: user_id.
    pub const USER_ID: &str = "user_id";
    /// Foreign key: post_id.
    pub const POST_ID: &str = "post_id";
    /// Foreign key: comment_id.
    pub const COMMENT_ID: &str = "comment_id";
    /// Foreign key: category_id.
    pub const CATEGORY_ID: &str = "category_id";
    /// Foreign key: parent_id.
    pub const PARENT_ID: &str = "parent_id";
    /// Foreign key: author_id.
    pub const AUTHOR_ID: &str = "author_id";
    /// Foreign key: owner_id.
    pub const OWNER_ID: &str = "owner_id";
    /// Timestamp: created_at.
    pub const CREATED_AT: &str = "created_at";
    /// Timestamp: updated_at.
    pub const UPDATED_AT: &str = "updated_at";
    /// Timestamp: deleted_at.
    pub const DELETED_AT: &str = "deleted_at";
    /// Timestamp: published_at.
    pub const PUBLISHED_AT: &str = "published_at";
    /// Timestamp: expires_at.
    pub const EXPIRES_AT: &str = "expires_at";
    /// Timestamp: starts_at.
    pub const STARTS_AT: &str = "starts_at";
    /// Timestamp: ends_at.
    pub const ENDS_AT: &str = "ends_at";
    /// Timestamp: last_login_at.
    pub const LAST_LOGIN_AT: &str = "last_login_at";
    /// Timestamp: verified_at.
    pub const VERIFIED_AT: &str = "verified_at";
    /// Slug field.
    pub const SLUG: &str = "slug";
    /// URL field.
    pub const URL: &str = "url";
    /// Path field.
    pub const PATH: &str = "path";
    /// Key field.
    pub const KEY: &str = "key";
    /// Value field.
    pub const VALUE: &str = "value";
    /// Token field.
    pub const TOKEN: &str = "token";
    /// Code field.
    pub const CODE: &str = "code";
    /// Version field.
    pub const VERSION: &str = "version";
}

// ============================================================================
// Zero-allocation filter constructors
// ============================================================================

/// Create an equality filter with static field name.
///
/// This is the fastest way to create an equality filter - no heap allocation
/// if the value is a primitive type.
///
/// # Example
///
/// ```rust
/// use prax_query::static_filter::{eq, fields};
///
/// let filter = eq(fields::ID, 42);
/// let filter = eq(fields::ACTIVE, true);
/// let filter = eq(fields::NAME, "Alice");
/// ```
#[inline]
pub fn eq(field: &'static str, value: impl Into<FilterValue>) -> Filter {
    Filter::Equals(Cow::Borrowed(field), value.into())
}

/// Create a not-equals filter with static field name.
#[inline]
pub fn ne(field: &'static str, value: impl Into<FilterValue>) -> Filter {
    Filter::NotEquals(Cow::Borrowed(field), value.into())
}

/// Create a less-than filter with static field name.
#[inline]
pub fn lt(field: &'static str, value: impl Into<FilterValue>) -> Filter {
    Filter::Lt(Cow::Borrowed(field), value.into())
}

/// Create a less-than-or-equal filter with static field name.
#[inline]
pub fn lte(field: &'static str, value: impl Into<FilterValue>) -> Filter {
    Filter::Lte(Cow::Borrowed(field), value.into())
}

/// Create a greater-than filter with static field name.
#[inline]
pub fn gt(field: &'static str, value: impl Into<FilterValue>) -> Filter {
    Filter::Gt(Cow::Borrowed(field), value.into())
}

/// Create a greater-than-or-equal filter with static field name.
#[inline]
pub fn gte(field: &'static str, value: impl Into<FilterValue>) -> Filter {
    Filter::Gte(Cow::Borrowed(field), value.into())
}

/// Create an IS NULL filter with static field name.
#[inline]
pub const fn is_null(field: &'static str) -> Filter {
    Filter::IsNull(Cow::Borrowed(field))
}

/// Create an IS NOT NULL filter with static field name.
#[inline]
pub const fn is_not_null(field: &'static str) -> Filter {
    Filter::IsNotNull(Cow::Borrowed(field))
}

/// Create a LIKE %value% filter with static field name.
#[inline]
pub fn contains(field: &'static str, value: impl Into<FilterValue>) -> Filter {
    Filter::Contains(Cow::Borrowed(field), value.into())
}

/// Create a LIKE value% filter with static field name.
#[inline]
pub fn starts_with(field: &'static str, value: impl Into<FilterValue>) -> Filter {
    Filter::StartsWith(Cow::Borrowed(field), value.into())
}

/// Create a LIKE %value filter with static field name.
#[inline]
pub fn ends_with(field: &'static str, value: impl Into<FilterValue>) -> Filter {
    Filter::EndsWith(Cow::Borrowed(field), value.into())
}

/// Create an IN filter with static field name.
#[inline]
pub fn in_list(field: &'static str, values: impl Into<ValueList>) -> Filter {
    Filter::In(Cow::Borrowed(field), values.into())
}

/// Create a NOT IN filter with static field name.
#[inline]
pub fn not_in_list(field: &'static str, values: impl Into<ValueList>) -> Filter {
    Filter::NotIn(Cow::Borrowed(field), values.into())
}

// ============================================================================
// Optimized combinators for small filter counts
// ============================================================================

/// Combine exactly 2 filters with AND (optimized, avoids vec allocation overhead).
#[inline]
pub fn and2(a: Filter, b: Filter) -> Filter {
    Filter::And(Box::new([a, b]))
}

/// Combine exactly 3 filters with AND.
#[inline]
pub fn and3(a: Filter, b: Filter, c: Filter) -> Filter {
    Filter::And(Box::new([a, b, c]))
}

/// Combine exactly 4 filters with AND.
#[inline]
pub fn and4(a: Filter, b: Filter, c: Filter, d: Filter) -> Filter {
    Filter::And(Box::new([a, b, c, d]))
}

/// Combine exactly 5 filters with AND.
#[inline]
pub fn and5(a: Filter, b: Filter, c: Filter, d: Filter, e: Filter) -> Filter {
    Filter::And(Box::new([a, b, c, d, e]))
}

/// Combine exactly 2 filters with OR (optimized, avoids vec allocation overhead).
#[inline]
pub fn or2(a: Filter, b: Filter) -> Filter {
    Filter::Or(Box::new([a, b]))
}

/// Combine exactly 3 filters with OR.
#[inline]
pub fn or3(a: Filter, b: Filter, c: Filter) -> Filter {
    Filter::Or(Box::new([a, b, c]))
}

/// Combine exactly 4 filters with OR.
#[inline]
pub fn or4(a: Filter, b: Filter, c: Filter, d: Filter) -> Filter {
    Filter::Or(Box::new([a, b, c, d]))
}

/// Combine exactly 5 filters with OR.
#[inline]
pub fn or5(a: Filter, b: Filter, c: Filter, d: Filter, e: Filter) -> Filter {
    Filter::Or(Box::new([a, b, c, d, e]))
}

/// Negate a filter.
#[inline]
pub fn not(filter: Filter) -> Filter {
    Filter::Not(Box::new(filter))
}

// ============================================================================
// Compact filter value types
// ============================================================================

/// A compact filter value optimized for common cases.
///
/// Uses a tagged union representation to minimize size:
/// - Discriminant is inline with data
/// - Small strings can be stored inline (future optimization)
#[derive(Debug, Clone, PartialEq)]
#[repr(u8)]
pub enum CompactValue {
    /// Null value.
    Null = 0,
    /// Boolean true.
    True = 1,
    /// Boolean false.
    False = 2,
    /// Small integer (-128 to 127).
    SmallInt(i8) = 3,
    /// Full integer.
    Int(i64) = 4,
    /// Float value.
    Float(f64) = 5,
    /// String value.
    String(String) = 6,
}

impl CompactValue {
    /// Convert to a FilterValue.
    #[inline]
    pub fn into_filter_value(self) -> FilterValue {
        match self {
            Self::Null => FilterValue::Null,
            Self::True => FilterValue::Bool(true),
            Self::False => FilterValue::Bool(false),
            Self::SmallInt(v) => FilterValue::Int(v as i64),
            Self::Int(v) => FilterValue::Int(v),
            Self::Float(v) => FilterValue::Float(v),
            Self::String(v) => FilterValue::String(v),
        }
    }
}

impl From<bool> for CompactValue {
    #[inline]
    fn from(v: bool) -> Self {
        if v { Self::True } else { Self::False }
    }
}

impl From<i32> for CompactValue {
    #[inline]
    fn from(v: i32) -> Self {
        if (-128..=127).contains(&v) {
            Self::SmallInt(v as i8)
        } else {
            Self::Int(v as i64)
        }
    }
}

impl From<i64> for CompactValue {
    #[inline]
    fn from(v: i64) -> Self {
        if (-128..=127).contains(&v) {
            Self::SmallInt(v as i8)
        } else {
            Self::Int(v)
        }
    }
}

impl From<f64> for CompactValue {
    #[inline]
    fn from(v: f64) -> Self {
        Self::Float(v)
    }
}

impl From<String> for CompactValue {
    #[inline]
    fn from(v: String) -> Self {
        Self::String(v)
    }
}

impl From<&str> for CompactValue {
    #[inline]
    fn from(v: &str) -> Self {
        Self::String(v.to_string())
    }
}

impl From<CompactValue> for FilterValue {
    #[inline]
    fn from(v: CompactValue) -> Self {
        v.into_filter_value()
    }
}

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

    #[test]
    fn test_eq_filter() {
        let filter = eq(fields::ID, 42);
        assert!(matches!(filter, Filter::Equals(_, FilterValue::Int(42))));
    }

    #[test]
    fn test_gt_filter() {
        let filter = gt(fields::AGE, 18);
        assert!(matches!(filter, Filter::Gt(_, FilterValue::Int(18))));
    }

    #[test]
    fn test_is_null_filter() {
        let filter = is_null(fields::DELETED_AT);
        assert!(matches!(filter, Filter::IsNull(_)));
    }

    #[test]
    fn test_and2_filter() {
        let filter = and2(eq(fields::ACTIVE, true), gt(fields::SCORE, 100));
        assert!(matches!(filter, Filter::And(_)));
    }

    #[test]
    fn test_or2_filter() {
        let filter = or2(eq(fields::STATUS, "active"), eq(fields::STATUS, "pending"));
        assert!(matches!(filter, Filter::Or(_)));
    }

    #[test]
    fn test_compact_value_bool() {
        let v: CompactValue = true.into();
        assert!(matches!(v, CompactValue::True));
        assert_eq!(v.into_filter_value(), FilterValue::Bool(true));
    }

    #[test]
    fn test_compact_value_small_int() {
        let v: CompactValue = 42i32.into();
        assert!(matches!(v, CompactValue::SmallInt(42)));
    }

    #[test]
    fn test_compact_value_large_int() {
        let v: CompactValue = 1000i32.into();
        assert!(matches!(v, CompactValue::Int(1000)));
    }

    #[test]
    fn test_field_constants() {
        assert_eq!(fields::ID, "id");
        assert_eq!(fields::EMAIL, "email");
        assert_eq!(fields::CREATED_AT, "created_at");
    }
}