akgine 0.1.0

Global function
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
// All values are bound as ? parameters — never interpolated into SQL.

use crate::database::database::{
    DataBase, column_names, generate_select_columns_sql, quoteIdentifier, row_to_valueset,
    validateIdentifier,
};
use crate::database::error::DbError;
use crate::database::record::DbRecord;
use crate::database::value::SqlValue;

// ── Direction ─────────────────────────────────────────────────────────────────

/// Sort direction for ORDER BY clauses.
#[derive(Clone, Copy, Debug)]
pub enum Direction {
    Asc,
    Desc,
}

impl Direction {
    fn as_sql(self) -> &'static str {
        match self {
            Direction::Asc => "ASC",
            Direction::Desc => "DESC",
        }
    }
}

// ── Filter ────────────────────────────────────────────────────────────────────

/// One WHERE condition.
///
/// Never constructed directly by application code — use the QueryBuilder
/// methods (where_eq, where_like, …) instead.

#[derive(Clone)]
/// don't execute or generate the final query
/// this just create a template and give all value to finish the template
pub enum Filter {
    /// Used when column validation fails so we can silently ignore it.
    Empty,
    /// column OP ?   or   column IS NULL / IS NOT NULL
    Comparison {
        columnName: String,
        /// =, !=, >, >=, <, <=, LIKE, IS NULL, IS NOT NULL
        operator: &'static str,
        value: Option<SqlValue>,
    },
    /// column IN (?, ?, …)
    Inclusion {
        columnName: String,
        values: Vec<SqlValue>,
    },
    /// (filter1 AND filter2 AND ...)
    And(Vec<Filter>),
    /// (filter1 OR filter2 OR ...)
    Or(Vec<Filter>),
}

impl Filter {
    /// generate a sql query with ? where value need to be
    fn to_sql(&self) -> String {
        match self {
            Filter::Empty => String::new(),
            Filter::Comparison {
                columnName,
                operator,
                value,
            } => {
                if value.is_some() {
                    format!("{columnName} {operator} ?")
                } else {
                    format!("{columnName} {operator}")
                }
            }
            Filter::Inclusion { columnName, values } => {
                let placeHolder: String = values.iter().map(|_| "?").collect::<Vec<_>>().join(", ");
                format!("{columnName} IN ({placeHolder})")
            }
            Filter::And(filters) => {
                let frags: Vec<String> = filters
                    .iter()
                    .map(|f| f.to_sql())
                    .filter(|s| !s.is_empty())
                    .collect();

                match frags.len() {
                    0 => String::new(),
                    1 => frags[0].clone(),
                    _ => format!("({})", frags.join(" AND ")),
                }
            }
            Filter::Or(filters) => {
                let frags: Vec<String> = filters
                    .iter()
                    .map(|f| f.to_sql())
                    .filter(|s| !s.is_empty())
                    .collect();

                match frags.len() {
                    0 => String::new(),
                    1 => frags[0].clone(),
                    _ => format!("({})", frags.join(" OR ")),
                }
            }
        }
    }

    /// fill the vec give with the params to replace ? in the query
    fn push_params(&self, out: &mut Vec<SqlValue>) {
        match self {
            Filter::Empty => {}
            Filter::Comparison {
                value: Some(value), ..
            } => out.push(value.clone()),
            Filter::Comparison { .. } => {}
            Filter::Inclusion { values, .. } => out.extend(values.iter().cloned()),
            Filter::And(filters) | Filter::Or(filters) => {
                for f in filters {
                    f.push_params(out);
                }
            }
        }
    }

    /* #region constructeur */

    pub fn eq(columnName: &'static str, value: impl Into<SqlValue>) -> Self {
        if validateIdentifier(columnName).is_err() {
            return Filter::Empty;
        }
        Filter::Comparison {
            columnName: quoteIdentifier(columnName),
            operator: "=",
            value: Some(value.into()),
        }
    }

    pub fn neq(columnName: &'static str, value: impl Into<SqlValue>) -> Self {
        if validateIdentifier(columnName).is_err() {
            return Filter::Empty;
        }
        Filter::Comparison {
            columnName: quoteIdentifier(columnName),
            operator: "!=",
            value: Some(value.into()),
        }
    }

    pub fn gt(columnName: &'static str, value: impl Into<SqlValue>) -> Self {
        if validateIdentifier(columnName).is_err() {
            return Filter::Empty;
        }
        Filter::Comparison {
            columnName: quoteIdentifier(columnName),
            operator: ">",
            value: Some(value.into()),
        }
    }

    pub fn gte(columnName: &'static str, value: impl Into<SqlValue>) -> Self {
        if validateIdentifier(columnName).is_err() {
            return Filter::Empty;
        }
        Filter::Comparison {
            columnName: quoteIdentifier(columnName),
            operator: ">=",
            value: Some(value.into()),
        }
    }

    pub fn lt(columnName: &'static str, value: impl Into<SqlValue>) -> Self {
        if validateIdentifier(columnName).is_err() {
            return Filter::Empty;
        }
        Filter::Comparison {
            columnName: quoteIdentifier(columnName),
            operator: "<",
            value: Some(value.into()),
        }
    }

    pub fn lte(columnName: &'static str, value: impl Into<SqlValue>) -> Self {
        if validateIdentifier(columnName).is_err() {
            return Filter::Empty;
        }
        Filter::Comparison {
            columnName: quoteIdentifier(columnName),
            operator: "<=",
            value: Some(value.into()),
        }
    }

    pub fn like(columnName: &'static str, pattern: impl Into<SqlValue>) -> Self {
        if validateIdentifier(columnName).is_err() {
            return Filter::Empty;
        }
        Filter::Comparison {
            columnName: quoteIdentifier(columnName),
            operator: "LIKE",
            value: Some(pattern.into()),
        }
    }

    pub fn null(columnName: &'static str) -> Self {
        if validateIdentifier(columnName).is_err() {
            return Filter::Empty;
        }
        Filter::Comparison {
            columnName: quoteIdentifier(columnName),
            operator: "IS NULL",
            value: None,
        }
    }

    pub fn notNull(columnName: &'static str) -> Self {
        if validateIdentifier(columnName).is_err() {
            return Filter::Empty;
        }
        Filter::Comparison {
            columnName: quoteIdentifier(columnName),
            operator: "IS NOT NULL",
            value: None,
        }
    }

    pub fn in_list(columnName: &'static str, values: Vec<impl Into<SqlValue>>) -> Self {
        if validateIdentifier(columnName).is_err() {
            return Filter::Empty;
        }
        if values.is_empty() {
            return Filter::Comparison {
                columnName: quoteIdentifier("id"),
                operator: "=",
                value: Some(SqlValue::Integer(-1)),
            };
        }
        Filter::Inclusion {
            columnName: quoteIdentifier(columnName),
            values: values.into_iter().map(|v| v.into()).collect(),
        }
    }

    pub fn and(filters: Vec<Filter>) -> Self {
        Filter::And(filters)
    }
    pub fn or(filters: Vec<Filter>) -> Self {
        Filter::Or(filters)
    }
    /* #endregion */
}

// ── OrderClause ───────────────────────────────────────────────────────────────

#[derive(Clone)]
struct OrderClause {
    column: String,
    direction: Direction,
}

// ── QueryBuilder ──────────────────────────────────────────────────────────────

/// Chainable query builder for `Repository<T>`.
///
/// Constructed by `Repository::query()`.
///
/// ```rust
/// let tasks = repo.query()
///     .where_eq("user_id", 1i64)
///     .where_eq("deleted", false)
///     .where_like("title", "%milk%")
///     .order_by("id", direction::Asc)
///     .limit(20)
///     .fetch()?;
/// ```
pub struct QueryBuilder<T: DbRecord> {
    db: DataBase,
    filters: Vec<Filter>,
    orders: Vec<OrderClause>,
    limit: Option<i64>,
    offset: Option<i64>,
    /// Cached static column names extracted from T::columns()
    columnNames: Vec<&'static str>,
    /// avoid the compilateur crash for T is never used
    _marker: std::marker::PhantomData<T>,
}

impl<T: DbRecord> QueryBuilder<T> {
    pub(crate) fn new(db: DataBase) -> Self {
        Self {
            db,
            filters: Vec::new(),
            orders: vec![],
            limit: None,
            offset: None,
            columnNames: column_names::<T>(),
            _marker: std::marker::PhantomData,
        }
    }
    /* #region WHERE filters */
    // impl Into<SqlValue> Accepts any type that converts to SqlValue: i64, bool, String, &str, f64, …

    /// Push an arbitrary complex nested Filter
    pub fn where_filter(mut self, filter: Filter) -> Self {
        self.filters.push(filter);
        self
    }

    /// `WHERE "columnName" = ?`
    pub fn where_eq(self, columnName: &'static str, value: impl Into<SqlValue>) -> Self {
        self.where_filter(Filter::eq(columnName, value))
    }

    /// `WHERE "columnName" != ?`
    pub fn where_neq(self, columnName: &'static str, value: impl Into<SqlValue>) -> Self {
        self.where_filter(Filter::neq(columnName, value))
    }

    /// `WHERE "columnName" > ?`
    pub fn where_gt(self, columnName: &'static str, value: impl Into<SqlValue>) -> Self {
        self.where_filter(Filter::gt(columnName, value))
    }

    /// `WHERE "columnName" >= ?`
    pub fn where_gte(self, columnName: &'static str, value: impl Into<SqlValue>) -> Self {
        self.where_filter(Filter::gte(columnName, value))
    }

    /// `WHERE "columnName" < ?`
    pub fn where_lt(self, columnName: &'static str, value: impl Into<SqlValue>) -> Self {
        self.where_filter(Filter::lt(columnName, value))
    }

    /// `WHERE "columnName" <= ?`
    pub fn where_lte(self, columnName: &'static str, value: impl Into<SqlValue>) -> Self {
        self.where_filter(Filter::lte(columnName, value))
    }

    /// `WHERE "columnName" LIKE ?`  (use % and _ wildcards in the value)
    ///
    /// Example: `.where_like("title", "%milk%")`
    pub fn where_like(self, columnName: &'static str, pattern: impl Into<SqlValue>) -> Self {
        self.where_filter(Filter::like(columnName, pattern))
    }

    /// `WHERE "columnName" IS NULL`
    pub fn where_null(self, columnName: &'static str) -> Self {
        self.where_filter(Filter::null(columnName))
    }

    /// `WHERE "columnName" IS NOT NULL`
    pub fn where_not_null(self, columnName: &'static str) -> Self {
        self.where_filter(Filter::notNull(columnName))
    }

    /// `WHERE "columnName" IN (?, ?, …)`
    ///
    /// Used to fetch rows linked by FK to a set of parent ids:
    /// ```rust
    /// // All tasks that belong to category 1, 3, or 7
    /// repo.query()
    ///     .where_in("category_id", vec![1, 3, 7])
    ///     .fetch()?;
    /// ```
    ///
    /// An empty slice produces a query that always returns zero rows (no panic).
    pub fn where_in(self, columnName: &'static str, values: Vec<impl Into<SqlValue>>) -> Self {
        self.where_filter(Filter::in_list(columnName, values))
    }
    /* #endregion */

    // ── ORDER BY ──────────────────────────────────────────────────────────────

    /// `ORDER BY "columnName" ASC|DESC`
    ///
    /// Multiple calls add multiple ORDER BY terms.
    pub fn order_by(mut self, columnName: &'static str, direction: Direction) -> Self {
        // validate eagerly so the error surfaces at the call site, not at fetch()
        if validateIdentifier(columnName).is_ok() {
            self.orders.push(OrderClause {
                column: quoteIdentifier(columnName),
                direction: direction,
            });
        }
        self
    }

    // ── LIMIT / OFFSET ────────────────────────────────────────────────────────

    /// `LIMIT n`
    pub fn limit(mut self, n: i64) -> Self {
        self.limit = Some(n);
        self
    }

    /// `OFFSET n`  (requires LIMIT to be set; ignored by SQLite otherwise) how many items is skip
    pub fn offset(mut self, n: i64) -> Self {
        self.offset = Some(n);
        self
    }

    // ── Terminal operations ───────────────────────────────────────────────────

    /// Execute the query and return all matching rows as `Vec<T>`.
    pub fn fetch(self) -> Result<Vec<T>, DbError> {
        // get the sql command with ? and the params to replace
        let (sql, params) = self.build_select();
        // lock the db
        let conn: std::sync::MutexGuard<'_, rusqlite::Connection> = self.db.lock();
        // prepare the sql command for rusqlite execution (check syntax, prepare a plan, ...)
        let mut stmt: rusqlite::Statement<'_> = conn.prepare(&sql)?;
        // 1. execute the command whit params give by an iter
        // 2. map each row and change the data in valueSet
        let rows = stmt.query_map(rusqlite::params_from_iter(params.iter()), |row| {
            row_to_valueset(row, &self.columnNames)
        })?;

        let mut result: Vec<T> = Vec::new();

        for row in rows {
            let valueSet: super::ValueSet = row?;
            // T::getValues(&valueSet) convert the value in struct
            result.push(T::getValues(&valueSet).map_err(|e| {
                // convert the error in rusqlite error
                rusqlite::Error::FromSqlConversionFailure(
                    0,
                    rusqlite::types::Type::Null,
                    Box::new(std::io::Error::new(
                        std::io::ErrorKind::Other,
                        e.to_string(),
                    )),
                )
            })?);
        }
        Ok(result)
    }

    /// Execute and return only the first row (adds LIMIT 1).
    pub fn fetch_one(self) -> Result<Option<T>, DbError> {
        Ok(self.limit(1).fetch()?.into_iter().next())
    }

    /// `SELECT COUNT(*) FROM … WHERE …`
    ///
    /// Ignores ORDER BY, LIMIT, and OFFSET — they are irrelevant for counting.
    pub fn count(self) -> Result<i64, DbError> {
        let (where_sql, params) = build_where(&self.filters);
        let table: String = quoteIdentifier(T::table_name());
        let sql: String = format!("SELECT COUNT(*) FROM {table} {where_sql}");
        let conn: std::sync::MutexGuard<'_, rusqlite::Connection> = self.db.lock();
        let count: i64 =
            conn.query_row(&sql, rusqlite::params_from_iter(params.iter()), |row| {
                row.get::<_, i64>(0)
            })?;
        Ok(count)
    }

    /// Returns `true` if at least one row matches the filters.
    pub fn exists(self) -> Result<bool, DbError> {
        Ok(self.count()? > 0)
    }

    // ── Internal helpers ──────────────────────────────────────────────────────

    fn build_select(&self) -> (String, Vec<SqlValue>) {
        let table: String = quoteIdentifier(T::table_name());
        let select: String = generate_select_columns_sql::<T>();
        let (where_sql, params) = build_where(&self.filters);

        let order_sql = if self.orders.is_empty() {
            String::new()
        } else {
            let terms: Vec<String> = self
                .orders
                .iter()
                .map(|o| format!("{} {}", o.column, o.direction.as_sql()))
                .collect();
            format!(" ORDER BY {}", terms.join(", "))
        };

        let limit_sql = match (self.limit, self.offset) {
            (Some(l), Some(o)) => format!(" LIMIT {l} OFFSET {o}"),
            (Some(l), None) => format!(" LIMIT {l}"),
            _ => String::new(),
        };

        let sql = format!("SELECT {select} FROM {table}{where_sql}{order_sql}{limit_sql}");
        (sql, params)
    }
}

// ── Shared WHERE builder ──────────────────────────────────────────────────────

/// Build the " WHERE …" fragment and collect bound parameter values.
///
/// Join with AND.
///
/// Returns ("", vec![]) when there are no filters.
pub(crate) fn build_where(filters: &[Filter]) -> (String, Vec<SqlValue>) {
    if filters.is_empty() {
        return (String::new(), vec![]);
    }
    let mut params: Vec<SqlValue> = Vec::new();
    let fragments: Vec<String> = filters
        .iter()
        .map(|f| {
            f.push_params(&mut params);
            f.to_sql()
        })
        .filter(|s| !s.is_empty()) // Prevent dangling ANDs or empty strings
        .collect();

    (format!(" WHERE {}", fragments.join(" AND ")), params)
}