mik-sql 0.1.2

SQL query builder with Mongo-style filters - sql_read!, sql_create!, sql_update!, sql_delete!
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
//! Core types for the SQL query builder.

use crate::validate::assert_valid_sql_identifier;

/// SQL comparison operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Operator {
    /// Equal: `=`
    Eq,
    /// Not equal: `!=`
    Ne,
    /// Greater than: `>`
    Gt,
    /// Greater than or equal: `>=`
    Gte,
    /// Less than: `<`
    Lt,
    /// Less than or equal: `<=`
    Lte,
    /// In array: `IN` or `= ANY`
    In,
    /// Not in array: `NOT IN` or `!= ALL`
    NotIn,
    /// Regex match: `~` (Postgres) or `LIKE` (`SQLite`)
    Regex,
    /// Pattern match: `LIKE`
    Like,
    /// Case-insensitive pattern match: `ILIKE` (Postgres) or `LIKE` (`SQLite`)
    ILike,
    /// String starts with: `LIKE $1 || '%'`
    StartsWith,
    /// String ends with: `LIKE '%' || $1`
    EndsWith,
    /// String contains: `LIKE '%' || $1 || '%'`
    Contains,
    /// Between two values: `BETWEEN $1 AND $2`
    Between,
}

/// Logical operators for compound filters.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum LogicalOp {
    /// All conditions must match: `AND`
    And,
    /// At least one condition must match: `OR`
    Or,
    /// Negate the condition: `NOT`
    Not,
}

/// A filter expression that can be simple or compound.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum FilterExpr {
    /// A simple field comparison.
    Simple(Filter),
    /// A compound filter with logical operator.
    Compound(CompoundFilter),
}

/// A compound filter combining multiple expressions with a logical operator.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct CompoundFilter {
    /// The logical operator (AND, OR, NOT) to combine filters.
    pub op: LogicalOp,
    /// The filter expressions to combine.
    pub filters: Vec<FilterExpr>,
}

impl CompoundFilter {
    /// Create an AND compound filter.
    #[must_use]
    pub const fn and(filters: Vec<FilterExpr>) -> Self {
        Self {
            op: LogicalOp::And,
            filters,
        }
    }

    /// Create an OR compound filter.
    #[must_use]
    pub const fn or(filters: Vec<FilterExpr>) -> Self {
        Self {
            op: LogicalOp::Or,
            filters,
        }
    }

    /// Create a NOT compound filter (wraps a single filter).
    #[must_use]
    pub fn not(filter: FilterExpr) -> Self {
        Self {
            op: LogicalOp::Not,
            filters: vec![filter],
        }
    }
}

impl FilterExpr {
    /// Collect all simple filters from this expression into a vector.
    ///
    /// This flattens compound filters, extracting all individual `Filter` items.
    /// Used by the `merge:` option in `sql_read!` to iterate over user filters.
    #[must_use]
    pub fn collect_filters(&self) -> Vec<Filter> {
        let mut result = Vec::new();
        self.collect_filters_into(&mut result);
        result
    }

    fn collect_filters_into(&self, result: &mut Vec<Filter>) {
        match self {
            Self::Simple(f) => result.push(f.clone()),
            Self::Compound(c) => {
                for expr in &c.filters {
                    expr.collect_filters_into(result);
                }
            },
        }
    }

    /// Returns an iterator over all simple filters in this expression.
    ///
    /// This flattens compound filters, yielding all individual `Filter` items.
    #[must_use]
    pub fn iter(&self) -> FilterExprIter {
        self.into_iter()
    }
}

/// Iterator over filters in a `FilterExpr`.
#[derive(Debug)]
pub struct FilterExprIter {
    filters: std::vec::IntoIter<Filter>,
}

impl Iterator for FilterExprIter {
    type Item = Filter;

    fn next(&mut self) -> Option<Self::Item> {
        self.filters.next()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.filters.size_hint()
    }
}

impl IntoIterator for &FilterExpr {
    type Item = Filter;
    type IntoIter = FilterExprIter;

    fn into_iter(self) -> Self::IntoIter {
        FilterExprIter {
            filters: self.collect_filters().into_iter(),
        }
    }
}

/// Aggregation functions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AggregateFunc {
    /// Count rows: `COUNT(*)`
    Count,
    /// Count distinct values: `COUNT(DISTINCT field)`
    CountDistinct,
    /// Sum values: `SUM(field)`
    Sum,
    /// Average value: `AVG(field)`
    Avg,
    /// Minimum value: `MIN(field)`
    Min,
    /// Maximum value: `MAX(field)`
    Max,
}

/// An aggregation expression.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Aggregate {
    /// The aggregation function to apply.
    pub func: AggregateFunc,
    /// Field to aggregate, None for COUNT(*).
    pub field: Option<String>,
    /// Optional alias for the result.
    pub alias: Option<String>,
}

impl Aggregate {
    /// Create a COUNT(*) aggregation.
    #[must_use]
    pub fn count() -> Self {
        Self {
            func: AggregateFunc::Count,
            field: None,
            alias: Some("count".to_string()),
        }
    }

    /// Create a COUNT(field) aggregation.
    ///
    /// # Panics
    ///
    /// Panics if the field name is not a valid SQL identifier.
    pub fn count_field(field: impl Into<String>) -> Self {
        let field = field.into();
        assert_valid_sql_identifier(&field, "aggregate field");
        Self {
            func: AggregateFunc::Count,
            field: Some(field),
            alias: None,
        }
    }

    /// Create a COUNT(DISTINCT field) aggregation.
    ///
    /// # Panics
    ///
    /// Panics if the field name is not a valid SQL identifier.
    pub fn count_distinct(field: impl Into<String>) -> Self {
        let field = field.into();
        assert_valid_sql_identifier(&field, "aggregate field");
        Self {
            func: AggregateFunc::CountDistinct,
            field: Some(field),
            alias: None,
        }
    }

    /// Create a SUM(field) aggregation.
    ///
    /// # Panics
    ///
    /// Panics if the field name is not a valid SQL identifier.
    pub fn sum(field: impl Into<String>) -> Self {
        let field = field.into();
        assert_valid_sql_identifier(&field, "aggregate field");
        Self {
            func: AggregateFunc::Sum,
            field: Some(field),
            alias: None,
        }
    }

    /// Create an AVG(field) aggregation.
    ///
    /// # Panics
    ///
    /// Panics if the field name is not a valid SQL identifier.
    pub fn avg(field: impl Into<String>) -> Self {
        let field = field.into();
        assert_valid_sql_identifier(&field, "aggregate field");
        Self {
            func: AggregateFunc::Avg,
            field: Some(field),
            alias: None,
        }
    }

    /// Create a MIN(field) aggregation.
    ///
    /// # Panics
    ///
    /// Panics if the field name is not a valid SQL identifier.
    pub fn min(field: impl Into<String>) -> Self {
        let field = field.into();
        assert_valid_sql_identifier(&field, "aggregate field");
        Self {
            func: AggregateFunc::Min,
            field: Some(field),
            alias: None,
        }
    }

    /// Create a MAX(field) aggregation.
    ///
    /// # Panics
    ///
    /// Panics if the field name is not a valid SQL identifier.
    pub fn max(field: impl Into<String>) -> Self {
        let field = field.into();
        assert_valid_sql_identifier(&field, "aggregate field");
        Self {
            func: AggregateFunc::Max,
            field: Some(field),
            alias: None,
        }
    }

    /// Set an alias for the aggregation result.
    ///
    /// # Panics
    ///
    /// Panics if the alias is not a valid SQL identifier.
    pub fn as_alias(mut self, alias: impl Into<String>) -> Self {
        let alias = alias.into();
        assert_valid_sql_identifier(&alias, "aggregate alias");
        self.alias = Some(alias);
        self
    }

    /// Generate SQL for this aggregation.
    #[must_use]
    pub fn to_sql(&self) -> String {
        let expr = match (&self.func, &self.field) {
            (AggregateFunc::Count, None) => "COUNT(*)".to_string(),
            (AggregateFunc::Count, Some(f)) => format!("COUNT({f})"),
            (AggregateFunc::CountDistinct, Some(f)) => format!("COUNT(DISTINCT {f})"),
            (AggregateFunc::Sum, Some(f)) => format!("SUM({f})"),
            (AggregateFunc::Avg, Some(f)) => format!("AVG({f})"),
            (AggregateFunc::Min, Some(f)) => format!("MIN({f})"),
            (AggregateFunc::Max, Some(f)) => format!("MAX({f})"),
            _ => "COUNT(*)".to_string(),
        };

        match &self.alias {
            Some(a) => format!("{expr} AS {a}"),
            None => expr,
        }
    }
}

/// SQL parameter values.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Value {
    /// SQL NULL value.
    Null,
    /// Boolean value (true/false).
    Bool(bool),
    /// 64-bit signed integer.
    Int(i64),
    /// 64-bit floating point number.
    Float(f64),
    /// UTF-8 string value.
    String(String),
    /// Array of values (for IN, BETWEEN operators).
    Array(Vec<Self>),
}

/// Sort direction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SortDir {
    /// Ascending order (smallest to largest, A to Z).
    Asc,
    /// Descending order (largest to smallest, Z to A).
    Desc,
}

/// Sort field with direction.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SortField {
    /// The column name to sort by.
    pub field: String,
    /// The sort direction (ascending or descending).
    pub dir: SortDir,
}

impl SortField {
    /// Create a new sort field.
    pub fn new(field: impl Into<String>, dir: SortDir) -> Self {
        Self {
            field: field.into(),
            dir,
        }
    }

    /// Parse a sort string like "name,-created_at" into sort fields.
    ///
    /// Fields prefixed with `-` are sorted descending.
    /// Validates against allowed fields list.
    ///
    /// # Security Note
    ///
    /// If `allowed` is empty, ALL fields are allowed. For user input, always
    /// provide an explicit whitelist to prevent sorting by sensitive columns.
    pub fn parse_sort_string(sort: &str, allowed: &[&str]) -> Result<Vec<Self>, String> {
        let mut result = Vec::new();

        for part in sort.split(',') {
            let part = part.trim();
            if part.is_empty() {
                continue;
            }

            let (field, dir) = part
                .strip_prefix('-')
                .map_or((part, SortDir::Asc), |stripped| (stripped, SortDir::Desc));

            // Validate against whitelist (empty = allow all, consistent with FilterValidator)
            if !allowed.is_empty() && !allowed.contains(&field) {
                return Err(format!(
                    "Sort field '{field}' not allowed. Allowed: {allowed:?}"
                ));
            }

            result.push(Self::new(field, dir));
        }

        Ok(result)
    }
}

/// Filter condition.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Filter {
    /// The column name to filter on.
    pub field: String,
    /// The comparison operator to use.
    pub op: Operator,
    /// The value to compare against.
    pub value: Value,
}

impl Filter {
    /// Create a new filter condition.
    #[must_use]
    pub fn new(field: impl Into<String>, op: Operator, value: Value) -> Self {
        Self {
            field: field.into(),
            op,
            value,
        }
    }
}

/// Query result with SQL string and parameters.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
#[must_use = "QueryResult must be used to execute the query"]
pub struct QueryResult {
    /// The generated SQL query string.
    pub sql: String,
    /// The parameter values to bind to the query.
    pub params: Vec<Value>,
}

impl QueryResult {
    /// Create a new query result.
    #[must_use]
    pub fn new(sql: impl Into<String>, params: Vec<Value>) -> Self {
        Self {
            sql: sql.into(),
            params,
        }
    }
}

/// A computed field expression with alias.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ComputedField {
    /// The alias for the computed field.
    pub alias: String,
    /// The SQL expression (e.g., "`first_name` || ' ' || `last_name`").
    pub expression: String,
}

impl ComputedField {
    /// Create a new computed field.
    pub fn new(alias: impl Into<String>, expression: impl Into<String>) -> Self {
        Self {
            alias: alias.into(),
            expression: expression.into(),
        }
    }

    /// Generate the SQL for this computed field.
    #[must_use]
    pub fn to_sql(&self) -> String {
        format!("({}) AS {}", self.expression, self.alias)
    }
}

/// Cursor pagination direction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum CursorDirection {
    /// Paginate forward (after the cursor).
    After,
    /// Paginate backward (before the cursor).
    Before,
}

/// Helper function to create a simple filter expression.
///
/// # Panics
///
/// Panics if the field name is not a valid SQL identifier.
pub fn simple(field: impl Into<String>, op: Operator, value: Value) -> FilterExpr {
    let field = field.into();
    assert_valid_sql_identifier(&field, "filter field");
    FilterExpr::Simple(Filter { field, op, value })
}

/// Helper function to create an AND compound filter.
#[must_use]
pub const fn and(filters: Vec<FilterExpr>) -> FilterExpr {
    FilterExpr::Compound(CompoundFilter::and(filters))
}

/// Helper function to create an OR compound filter.
#[must_use]
pub const fn or(filters: Vec<FilterExpr>) -> FilterExpr {
    FilterExpr::Compound(CompoundFilter::or(filters))
}

/// Helper function to create a NOT filter.
#[must_use]
pub fn not(filter: FilterExpr) -> FilterExpr {
    FilterExpr::Compound(CompoundFilter::not(filter))
}