vantage-sql 0.6.20

Vantage extension for SQL databases (Postgres, MySQL, SQLite)
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
//! Backend-specific condition wrappers and operation traits.
//!
//! **Conditions:** Each wrapper (e.g., `SqliteCondition`) is a newtype around
//! `Expression<BackendType>`. It accepts `Expression<F>` for any `F: Into<BackendType>`,
//! plus common types (`Identifier`, `Fx`) via `From`.
//!
//! **Operations:** Each backend gets a vendor-specific operation trait (e.g.
//! `SqliteOperation<T>`) that produces the backend's condition type directly.
//! These are blanket-implemented for all `Expressive<T>` where `T: Into<AnyType>`,
//! and the condition type implements `Expressive<AnyType>` to enable chaining:
//!
//! ```ignore
//! use vantage_sql::sqlite::operation::SqliteOperation;
//! let price = Column::<i64>::new("price");
//! price.gt(10).eq(false)  // => SqliteCondition wrapping (price > 10) = 0
//! ```

use vantage_expressions::traits::expressive::ExpressiveEnum;
use vantage_expressions::{Expression, Expressive};

use crate::primitives::fx::Fx;
use crate::primitives::identifier::Identifier;

macro_rules! define_sql_condition {
    ($name:ident, $any_type:ty) => {
        /// Condition wrapper that preserves type inference for `with_condition()`.
        #[derive(Debug, Clone)]
        pub struct $name(pub Expression<$any_type>);

        impl $name {
            pub fn into_expr(self) -> Expression<$any_type> {
                self.0
            }

            /// Create from a typed expression by mapping scalars via `Into<BackendType>`.
            ///
            /// Used by the generic `From<Expression<F>>` impl.
            pub fn from_typed<F>(expr: Expression<F>) -> Self
            where
                F: Into<$any_type> + Send + Clone + 'static,
            {
                use vantage_expressions::ExpressionMap;
                Self(expr.map())
            }
        }

        // From Expression<F> where F: Into<BackendType> — accepts both
        // Expression<BackendType> (identity) and typed Expression<i64> etc.
        impl<F> From<Expression<F>> for $name
        where
            F: Into<$any_type> + Send + Clone + 'static,
        {
            fn from(expr: Expression<F>) -> Self {
                Self::from_typed(expr)
            }
        }

        // From Identifier
        impl From<Identifier> for $name {
            fn from(id: Identifier) -> Self {
                use vantage_expressions::Expressive;
                Self(id.expr())
            }
        }

        // Into Expression<BackendType> — unwrap the newtype
        impl From<$name> for Expression<$any_type> {
            fn from(cond: $name) -> Self {
                cond.0
            }
        }

        // From Fx<BackendType>
        impl From<Fx<$any_type>> for $name {
            fn from(fx: Fx<$any_type>) -> Self {
                Self(fx.into())
            }
        }
    };
}

#[cfg(feature = "sqlite")]
define_sql_condition!(SqliteCondition, crate::sqlite::types::AnySqliteType);

#[cfg(feature = "postgres")]
define_sql_condition!(PostgresCondition, crate::postgres::types::AnyPostgresType);

#[cfg(feature = "mysql")]
define_sql_condition!(MysqlCondition, crate::mysql::types::AnyMysqlType);

// MySQL-specific: FulltextMatch
#[cfg(feature = "mysql")]
impl From<crate::mysql::statements::primitives::FulltextMatch> for MysqlCondition {
    fn from(fm: crate::mysql::statements::primitives::FulltextMatch) -> Self {
        Self(fm.into())
    }
}

// ── Backend-typed identifier wrapper ────────────────────────────────

/// Defines a backend-specific identifier wrapper that only implements
/// `Expressive<$any_type>`, avoiding ambiguity when multiple backend
/// features are enabled.
///
/// Usage: `define_typed_ident!(PgIdent, pg_ident, AnyPostgresType, PostgresCondition);`
#[macro_export]
macro_rules! define_typed_ident {
    ($struct_name:ident, $fn_name:ident, $any_type:ty, $condition:ty) => {
        #[derive(Debug, Clone)]
        pub struct $struct_name($crate::primitives::identifier::Identifier);

        impl $struct_name {
            pub fn new(name: impl Into<String>) -> Self {
                Self($crate::primitives::identifier::ident(name))
            }

            pub fn dot_of(mut self, prefix: impl Into<String>) -> Self {
                self.0 = self.0.dot_of(prefix);
                self
            }

            pub fn with_alias(mut self, alias: impl Into<String>) -> Self {
                self.0 = self.0.with_alias(alias);
                self
            }

            pub fn name(&self) -> String {
                self.0.name()
            }

            pub fn alias(&self) -> Option<&str> {
                self.0.alias()
            }
        }

        impl $crate::vantage_expressions::Expressive<$any_type> for $struct_name {
            fn expr(&self) -> $crate::vantage_expressions::Expression<$any_type> {
                $crate::vantage_expressions::Expressive::<$any_type>::expr(&self.0)
            }
        }

        impl From<$struct_name> for $crate::vantage_expressions::Expression<$any_type> {
            fn from(id: $struct_name) -> Self {
                $crate::vantage_expressions::Expressive::<$any_type>::expr(&id.0)
            }
        }

        impl From<$struct_name> for $condition {
            fn from(id: $struct_name) -> Self {
                Self::from_typed($crate::vantage_expressions::Expressive::<$any_type>::expr(
                    &id.0,
                ))
            }
        }

        /// Shorthand constructor.
        pub fn $fn_name(name: impl Into<String>) -> $struct_name {
            $struct_name::new(name)
        }
    };
}

// ── Vendor-specific operation traits ─────────────────────────────────

#[macro_export]
macro_rules! define_sql_operation {
    ($trait_name:ident, $condition:ident, $any_type:ty) => {
        /// Vendor-specific operations producing the backend's condition type.
        ///
        /// Blanket-implemented for all `Expressive<T>` where `T: Into<AnyType>`.
        /// The condition type itself implements `Expressive<AnyType>`, enabling
        /// cross-type chaining like `price.gt(10).eq(false)`.
        pub trait $trait_name<T>: $crate::vantage_expressions::Expressive<T>
        where
            T: Into<$any_type> + Send + Clone + 'static,
        {
            /// `(self OR other)` — joins two conditions into a
            /// `ConditionGroup`.
            ///
            /// Use this method to write alternatives. Do not write
            /// `"a OR b"` as text. The group writes its own brackets,
            /// and it keeps its meaning next to the other conditions.
            /// Text has no brackets, and `AND` binds more tightly than
            /// `OR`. Thus `role = 'admin' AND a OR b` means
            /// `(role = 'admin' AND a) OR b`.
            ///
            /// A chain stays flat: `a.or_(b).or_(c)` gives
            /// `(a OR b OR c)`.
            fn or_(
                &self,
                other: impl $crate::vantage_expressions::Expressive<T>,
            ) -> $crate::primitives::ConditionGroup<T>
            where
                Self: Sized,
            {
                $crate::primitives::or_(self.expr(), other.expr())
            }

            /// `(self AND other)` — joins two conditions into a
            /// `ConditionGroup`.
            ///
            /// A table joins its conditions with `AND` already. Use this
            /// method when you must make a group inside an `or_`.
            fn and_(
                &self,
                other: impl $crate::vantage_expressions::Expressive<T>,
            ) -> $crate::primitives::ConditionGroup<T>
            where
                Self: Sized,
            {
                $crate::primitives::and_(self.expr(), other.expr())
            }

            /// `field = value`
            fn eq(&self, value: impl $crate::vantage_expressions::Expressive<T>) -> $condition
            where
                Self: Sized,
            {
                $crate::condition::build_sql_binary::<T, $any_type, $condition>(
                    self, value, "{} = {}",
                )
            }

            /// `field != value`
            fn ne(&self, value: impl $crate::vantage_expressions::Expressive<T>) -> $condition
            where
                Self: Sized,
            {
                $crate::condition::build_sql_binary::<T, $any_type, $condition>(
                    self, value, "{} != {}",
                )
            }

            /// `field > value`
            fn gt(&self, value: impl $crate::vantage_expressions::Expressive<T>) -> $condition
            where
                Self: Sized,
            {
                $crate::condition::build_sql_binary::<T, $any_type, $condition>(
                    self, value, "{} > {}",
                )
            }

            /// `field >= value`
            fn gte(&self, value: impl $crate::vantage_expressions::Expressive<T>) -> $condition
            where
                Self: Sized,
            {
                $crate::condition::build_sql_binary::<T, $any_type, $condition>(
                    self, value, "{} >= {}",
                )
            }

            /// `field < value`
            fn lt(&self, value: impl $crate::vantage_expressions::Expressive<T>) -> $condition
            where
                Self: Sized,
            {
                $crate::condition::build_sql_binary::<T, $any_type, $condition>(
                    self, value, "{} < {}",
                )
            }

            /// `field <= value`
            fn lte(&self, value: impl $crate::vantage_expressions::Expressive<T>) -> $condition
            where
                Self: Sized,
            {
                $crate::condition::build_sql_binary::<T, $any_type, $condition>(
                    self, value, "{} <= {}",
                )
            }

            /// `field IN (values_expression)`
            fn in_(&self, values: impl $crate::vantage_expressions::Expressive<T>) -> $condition
            where
                Self: Sized,
            {
                $crate::condition::build_sql_binary::<T, $any_type, $condition>(
                    self,
                    values,
                    "{} IN ({})",
                )
            }

            /// `field IN (a, b, c)` from a slice of scalar values
            fn in_list<V: Into<T> + Clone>(&self, values: &[V]) -> $condition
            where
                Self: Sized,
                T: Clone,
            {
                use $crate::vantage_expressions::Expression;
                use $crate::vantage_expressions::traits::expressive::ExpressiveEnum;
                let params: Vec<Expression<T>> = values
                    .iter()
                    .map(|v| Expression::new("{}", vec![ExpressiveEnum::Scalar(v.clone().into())]))
                    .collect();
                let expr: Expression<T> = Expression::new(
                    "{} IN ({})",
                    vec![
                        ExpressiveEnum::Nested(self.expr()),
                        ExpressiveEnum::Nested(Expression::from_vec(params, ", ")),
                    ],
                );
                $condition::from_typed(expr)
            }

            /// `field NOT IN (values_expression)`
            fn not_in(&self, values: impl $crate::vantage_expressions::Expressive<T>) -> $condition
            where
                Self: Sized,
            {
                $crate::condition::build_sql_binary::<T, $any_type, $condition>(
                    self,
                    values,
                    "{} NOT IN ({})",
                )
            }

            /// `field NOT IN (a, b, c)` from a slice of scalar values
            fn not_in_list<V: Into<T> + Clone>(&self, values: &[V]) -> $condition
            where
                Self: Sized,
                T: Clone,
            {
                use $crate::vantage_expressions::Expression;
                use $crate::vantage_expressions::traits::expressive::ExpressiveEnum;
                let params: Vec<Expression<T>> = values
                    .iter()
                    .map(|v| Expression::new("{}", vec![ExpressiveEnum::Scalar(v.clone().into())]))
                    .collect();
                let expr: Expression<T> = Expression::new(
                    "{} NOT IN ({})",
                    vec![
                        ExpressiveEnum::Nested(self.expr()),
                        ExpressiveEnum::Nested(Expression::from_vec(params, ", ")),
                    ],
                );
                $condition::from_typed(expr)
            }

            /// `CAST(expr AS type_name)`
            fn cast(&self, type_name: &str) -> $condition
            where
                Self: Sized,
            {
                use $crate::vantage_expressions::Expression;
                use $crate::vantage_expressions::traits::expressive::ExpressiveEnum;
                let expr: Expression<T> = Expression::new(
                    format!("CAST({{}} AS {type_name})"),
                    vec![ExpressiveEnum::Nested(self.expr())],
                );
                $condition::from_typed(expr)
            }

            /// `field IS NULL`
            fn is_null(&self) -> $condition
            where
                Self: Sized,
            {
                use $crate::vantage_expressions::Expression;
                use $crate::vantage_expressions::traits::expressive::ExpressiveEnum;
                let expr: Expression<T> =
                    Expression::new("{} IS NULL", vec![ExpressiveEnum::Nested(self.expr())]);
                $condition::from_typed(expr)
            }

            /// `field IS NOT NULL`
            fn is_not_null(&self) -> $condition
            where
                Self: Sized,
            {
                use $crate::vantage_expressions::Expression;
                use $crate::vantage_expressions::traits::expressive::ExpressiveEnum;
                let expr: Expression<T> =
                    Expression::new("{} IS NOT NULL", vec![ExpressiveEnum::Nested(self.expr())]);
                $condition::from_typed(expr)
            }
        }

        /// Blanket: any `Expressive<T>` where `T: Into<AnyType>` gets the
        /// operation trait for free.
        impl<T, S> $trait_name<T> for S
        where
            S: $crate::vantage_expressions::Expressive<T>,
            T: Into<$any_type> + Send + Clone + 'static,
        {
        }

        /// Condition chaining: the condition type wraps `Expression<AnyType>`,
        /// so implementing `Expressive<AnyType>` gives it the operation trait
        /// via the blanket above.
        impl $crate::vantage_expressions::Expressive<$any_type> for $condition {
            fn expr(&self) -> $crate::vantage_expressions::Expression<$any_type> {
                self.0.clone()
            }
        }
    };
}

/// Helper for `define_sql_operation!`: build a binary expression, map to
/// the backend's condition type. Public so the macro can call it from
/// any module.
pub fn build_sql_binary<T, AnyType, Cond>(
    lhs: &(impl Expressive<T> + ?Sized),
    rhs: impl Expressive<T>,
    template: &str,
) -> Cond
where
    T: Into<AnyType> + Send + Clone + 'static,
    Cond: From<Expression<T>>,
{
    let expr: Expression<T> = Expression::new(
        template,
        vec![
            ExpressiveEnum::Nested(lhs.expr()),
            ExpressiveEnum::Nested(rhs.expr()),
        ],
    );
    Cond::from(expr)
}