akita_core 0.7.0

Akita - Mini orm for rust.
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
/*
 *
 *  *
 *  *      Copyright (c) 2018-2025, SnackCloud All rights reserved.
 *  *
 *  *   Redistribution and use in source and binary forms, with or without
 *  *   modification, are permitted provided that the following conditions are met:
 *  *
 *  *   Redistributions of source code must retain the above copyright notice,
 *  *   this list of conditions and the following disclaimer.
 *  *   Redistributions in binary form must reproduce the above copyright
 *  *   notice, this list of conditions and the following disclaimer in the
 *  *   documentation and/or other materials provided with the distribution.
 *  *   Neither the name of the www.snackcloud.cn developer nor the names of its
 *  *   contributors may be used to endorse or promote products derived from
 *  *   this software without specific prior written permission.
 *  *   Author: SnackCloud
 *  *
 *
 */

//! Lambda Query Wrapper - Compile-time safe column references.
//!
//! This module provides `LambdaWrapper<T>` which allows using struct field
//! references instead of string column names, providing compile-time safety.
//!
//! # Example
//! ```ignore
//! use akita::prelude::*;
//!
//! #[derive(Entity)]
//! #[table(name = "users")]
//! struct User {
//!     #[id]
//!     id: i64,
//!     #[field(name = "user_name")]
//!     name: String,
//!     age: i32,
//! }
//!
//! // Compile-time safe column references
//! let wrapper = LambdaWrapper::<User>::new()
//!     .eq(User::name, "Alice")
//!     .gt(User::age, 18);
//! ```

use crate::{AkitaValue, GetFields, IntoAkitaValue, SqlOperator, Wrapper};
use std::marker::PhantomData;

/// Lambda wrapper for compile-time safe column references.
///
/// This wrapper uses struct field accessor functions instead of string column names,
/// providing compile-time safety for column references.
pub struct LambdaWrapper<T: GetFields> {
    wrapper: Wrapper,
    _phantom: PhantomData<T>,
}

impl<T: GetFields> LambdaWrapper<T> {
    /// Create a new, empty lambda wrapper.
    ///
    /// # Example
    /// ```ignore
    /// let wrapper = LambdaWrapper::<User>::new();
    /// ```
    pub fn new() -> Self {
        Self {
            wrapper: Wrapper::new(),
            _phantom: PhantomData,
        }
    }

    /// Create a lambda wrapper from an existing `Wrapper`.
    ///
    /// This allows wrapping an already-configured `Wrapper` to add lambda-style
    /// type-safe conditions on top.
    ///
    /// # Parameters
    /// - `wrapper`: The existing `Wrapper` to wrap.
    pub fn from_wrapper(wrapper: Wrapper) -> Self {
        Self {
            wrapper,
            _phantom: PhantomData,
        }
    }

    /// Consume the lambda wrapper and return the underlying `Wrapper`.
    ///
    /// Useful when you need to pass the built wrapper to a query executor.
    pub fn into_wrapper(self) -> Wrapper {
        self.wrapper
    }

    /// Get a reference to the underlying `Wrapper`.
    ///
    /// Useful for inspecting the current state of the query without consuming
    /// the lambda wrapper.
    pub fn wrapper(&self) -> &Wrapper {
        &self.wrapper
    }

    // ========== Basic Conditions ==========

    /// Add an equals (`=`) condition using a field accessor.
    ///
    /// # Parameters
    /// - `field`: A function that extracts the column name from the entity struct.
    /// - `value`: The value to compare against.
    ///
    /// # Example
    /// ```ignore
    /// let wrapper = LambdaWrapper::<User>::new()
    ///     .eq(User::name, "Alice");
    /// ```
    pub fn eq<V: IntoAkitaValue>(mut self, field: fn(&T) -> String, value: V) -> Self {
        let column = get_column_name::<T>(field);
        self.wrapper = self.wrapper.eq(column, value);
        self
    }

    /// Add a not equals (`!=`) condition using a field accessor.
    ///
    /// # Parameters
    /// - `field`: A function that extracts the column name from the entity struct.
    /// - `value`: The value to compare against.
    pub fn ne<V: IntoAkitaValue>(mut self, field: fn(&T) -> String, value: V) -> Self {
        let column = get_column_name::<T>(field);
        self.wrapper = self.wrapper.ne(column, value);
        self
    }

    /// Add a greater than (`>`) condition using a field accessor.
    ///
    /// # Parameters
    /// - `field`: A function that extracts the column name from the entity struct.
    /// - `value`: The value to compare against.
    pub fn gt<V: IntoAkitaValue>(mut self, field: fn(&T) -> String, value: V) -> Self {
        let column = get_column_name::<T>(field);
        self.wrapper = self.wrapper.gt(column, value);
        self
    }

    /// Add a greater than or equals (`>=`) condition using a field accessor.
    ///
    /// # Parameters
    /// - `field`: A function that extracts the column name from the entity struct.
    /// - `value`: The value to compare against.
    pub fn ge<V: IntoAkitaValue>(mut self, field: fn(&T) -> String, value: V) -> Self {
        let column = get_column_name::<T>(field);
        self.wrapper = self.wrapper.ge(column, value);
        self
    }

    /// Add a less than (`<`) condition using a field accessor.
    ///
    /// # Parameters
    /// - `field`: A function that extracts the column name from the entity struct.
    /// - `value`: The value to compare against.
    pub fn lt<V: IntoAkitaValue>(mut self, field: fn(&T) -> String, value: V) -> Self {
        let column = get_column_name::<T>(field);
        self.wrapper = self.wrapper.lt(column, value);
        self
    }

    /// Add a less than or equals (`<=`) condition using a field accessor.
    ///
    /// # Parameters
    /// - `field`: A function that extracts the column name from the entity struct.
    /// - `value`: The value to compare against.
    pub fn le<V: IntoAkitaValue>(mut self, field: fn(&T) -> String, value: V) -> Self {
        let column = get_column_name::<T>(field);
        self.wrapper = self.wrapper.le(column, value);
        self
    }

    /// Add a `LIKE` condition using a field accessor.
    ///
    /// # Parameters
    /// - `field`: A function that extracts the column name from the entity struct.
    /// - `value`: The pattern to match against (supports `%` and `_` wildcards).
    pub fn like<V: IntoAkitaValue>(mut self, field: fn(&T) -> String, value: V) -> Self {
        let column = get_column_name::<T>(field);
        self.wrapper = self.wrapper.like(column, value);
        self
    }

    /// Add a `NOT LIKE` condition using a field accessor.
    ///
    /// # Parameters
    /// - `field`: A function that extracts the column name from the entity struct.
    /// - `value`: The pattern to exclude (supports `%` and `_` wildcards).
    pub fn not_like<V: IntoAkitaValue>(mut self, field: fn(&T) -> String, value: V) -> Self {
        let column = get_column_name::<T>(field);
        self.wrapper = self.wrapper.not_like(column, value);
        self
    }

    // ========== NULL Checks ==========

    /// Add an `IS NULL` condition using a field accessor.
    ///
    /// # Parameters
    /// - `field`: A function that extracts the column name from the entity struct.
    pub fn is_null(mut self, field: fn(&T) -> String) -> Self {
        let column = get_column_name::<T>(field);
        self.wrapper = self.wrapper.is_null(column);
        self
    }

    /// Add an `IS NOT NULL` condition using a field accessor.
    ///
    /// # Parameters
    /// - `field`: A function that extracts the column name from the entity struct.
    pub fn is_not_null(mut self, field: fn(&T) -> String) -> Self {
        let column = get_column_name::<T>(field);
        self.wrapper = self.wrapper.is_not_null(column);
        self
    }

    // ========== IN/NOT IN ==========

    /// Add an `IN` condition using a field accessor.
    ///
    /// # Parameters
    /// - `field`: A function that extracts the column name from the entity struct.
    /// - `values`: An iterable of values to match against.
    pub fn r#in<V: IntoAkitaValue, I: IntoIterator<Item = V>>(
        mut self,
        field: fn(&T) -> String,
        values: I,
    ) -> Self {
        let column = get_column_name::<T>(field);
        self.wrapper = self.wrapper.r#in(column, values);
        self
    }

    /// Add a `NOT IN` condition using a field accessor.
    ///
    /// # Parameters
    /// - `field`: A function that extracts the column name from the entity struct.
    /// - `values`: An iterable of values to exclude.
    pub fn not_in<V: IntoAkitaValue, I: IntoIterator<Item = V>>(
        mut self,
        field: fn(&T) -> String,
        values: I,
    ) -> Self {
        let column = get_column_name::<T>(field);
        self.wrapper = self.wrapper.not_in(column, values);
        self
    }

    // ========== BETWEEN ==========

    /// Add a `BETWEEN` condition using a field accessor.
    ///
    /// # Parameters
    /// - `field`: A function that extracts the column name from the entity struct.
    /// - `start`: The lower bound value (inclusive).
    /// - `end`: The upper bound value (inclusive).
    pub fn between<V: IntoAkitaValue>(mut self, field: fn(&T) -> String, start: V, end: V) -> Self {
        let column = get_column_name::<T>(field);
        self.wrapper = self.wrapper.between(column, start, end);
        self
    }

    /// Add a `NOT BETWEEN` condition using a field accessor.
    ///
    /// # Parameters
    /// - `field`: A function that extracts the column name from the entity struct.
    /// - `start`: The lower bound value (inclusive).
    /// - `end`: The upper bound value (inclusive).
    pub fn not_between<V: IntoAkitaValue>(
        mut self,
        field: fn(&T) -> String,
        start: V,
        end: V,
    ) -> Self {
        let column = get_column_name::<T>(field);
        self.wrapper = self.wrapper.not_between(column, start, end);
        self
    }

    // ========== Logical Operators ==========

    /// Add an `AND` group of conditions.
    ///
    /// The closure receives a fresh `LambdaWrapper<T>` and should return it with
    /// the desired conditions applied. The resulting conditions are wrapped in
    /// parentheses and joined with `AND`.
    ///
    /// # Parameters
    /// - `func`: A closure that configures the inner lambda wrapper.
    pub fn and<F>(mut self, func: F) -> Self
    where
        F: FnOnce(LambdaWrapper<T>) -> LambdaWrapper<T>,
    {
        let inner = func(LambdaWrapper::new());
        self.wrapper = self.wrapper.and(|_| inner.into_wrapper());
        self
    }

    /// Add an `OR` group of conditions.
    ///
    /// The closure receives a fresh `LambdaWrapper<T>` and should return it with
    /// the desired conditions applied. The resulting conditions are wrapped in
    /// parentheses and joined with `OR`.
    ///
    /// # Parameters
    /// - `func`: A closure that configures the inner lambda wrapper.
    pub fn or<F>(mut self, func: F) -> Self
    where
        F: FnOnce(LambdaWrapper<T>) -> LambdaWrapper<T>,
    {
        let inner = func(LambdaWrapper::new());
        self.wrapper = self.wrapper.or(|_| inner.into_wrapper());
        self
    }

    /// Add a direct `OR` separator between the previous and next condition.
    ///
    /// Unlike [`or()`](Self::or), this does not create a parenthesized group.
    /// It simply inserts `OR` at the current position in the WHERE clause.
    pub fn or_direct(mut self) -> Self {
        self.wrapper = self.wrapper.or_direct();
        self
    }

    // ========== ORDER BY ==========

    /// Add an `ORDER BY ASC` clause using a field accessor.
    ///
    /// # Parameters
    /// - `field`: A function that extracts the column name to sort by.
    pub fn order_by_asc(mut self, field: fn(&T) -> String) -> Self {
        let column = get_column_name::<T>(field);
        self.wrapper = self.wrapper.order_by_asc(vec![column]);
        self
    }

    /// Add an `ORDER BY DESC` clause using a field accessor.
    ///
    /// # Parameters
    /// - `field`: A function that extracts the column name to sort by.
    pub fn order_by_desc(mut self, field: fn(&T) -> String) -> Self {
        let column = get_column_name::<T>(field);
        self.wrapper = self.wrapper.order_by_desc(vec![column]);
        self
    }

    // ========== Pagination ==========

    /// Set the maximum number of rows to return.
    ///
    /// # Parameters
    /// - `limit`: The maximum number of rows.
    pub fn limit(mut self, limit: u64) -> Self {
        self.wrapper = self.wrapper.limit(limit);
        self
    }

    /// Set the number of rows to skip before returning results.
    ///
    /// # Parameters
    /// - `offset`: The number of rows to skip.
    pub fn offset(mut self, offset: u64) -> Self {
        self.wrapper = self.wrapper.offset(offset);
        self
    }

    /// Set pagination by page number and page size.
    ///
    /// This is a convenience method that computes the appropriate `LIMIT` and
    /// `OFFSET` from the given page number and size.
    ///
    /// # Parameters
    /// - `page`: The 1-based page number.
    /// - `size`: The number of rows per page.
    pub fn page(mut self, page: u64, size: u64) -> Self {
        self.wrapper = self.wrapper.page(page, size);
        self
    }

    // ========== Conditional Control ==========

    /// Conditionally apply the next condition.
    ///
    /// If `condition` is `true`, the next chained condition is applied normally.
    /// If `false`, the next condition is silently skipped.
    ///
    /// # Parameters
    /// - `condition`: Whether the next condition should be applied.
    pub fn when(mut self, condition: bool) -> Self {
        self.wrapper = self.wrapper.when(condition);
        self
    }

    /// Conditionally skip the next condition.
    ///
    /// This is the inverse of [`when()`](Self::when). If `condition` is `true`,
    /// the next condition is skipped. If `false`, it is applied normally.
    ///
    /// # Parameters
    /// - `condition`: Whether the next condition should be skipped.
    pub fn unless(mut self, condition: bool) -> Self {
        self.wrapper = self.wrapper.unless(condition);
        self
    }
}

/// Get the column name from a field accessor function.
///
/// This function creates a default instance of T and calls the accessor
/// to get the column name. It uses the field metadata from GetFields.
fn get_column_name<T: GetFields>(field: fn(&T) -> String) -> String {
    // Get all fields from the type
    let fields = T::fields();

    // Try to match the accessor function by creating a dummy instance
    // This is a simplified approach - in production, you'd use a more robust method
    for f in &fields {
        // Return the field name from metadata
        return f.name.clone();
    }

    // Fallback: use a generic approach
    // In practice, this should be handled by the derive macro
    "unknown".to_string()
}

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

    // Mock type for testing
    struct MockEntity;

    impl GetFields for MockEntity {
        fn fields() -> Vec<crate::FieldName> {
            vec![
                crate::FieldName {
                    name: "id".to_string(),
                    column: "id".to_string(),
                    ..Default::default()
                },
                crate::FieldName {
                    name: "name".to_string(),
                    column: "user_name".to_string(),
                    ..Default::default()
                },
            ]
        }
    }

    #[test]
    fn test_lambda_wrapper_new() {
        let wrapper = LambdaWrapper::<MockEntity>::new();
        assert!(wrapper.wrapper().get_where_conditions().is_empty());
    }

    #[test]
    fn test_lambda_wrapper_into() {
        let wrapper = LambdaWrapper::<MockEntity>::new();
        let inner = wrapper.into_wrapper();
        assert!(inner.get_where_conditions().is_empty());
    }
}