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
/// Convert given set of tuples into `Values`.
///
/// ```rust
/// # use quaint::{col, values, ast::*, visitor::{Visitor, Sqlite}};
/// # fn main() -> Result<(), quaint::error::Error> {
///
/// let condition = Row::from((col!("id"), col!("name")))
///     .in_selection(values!((1, "Musti"), (2, "Naukio")));
///
/// let query = Select::from_table("cats").so_that(condition);
/// let (sql, _) = Sqlite::build(query)?;
///
/// assert_eq!(
///     "SELECT `cats`.* FROM `cats` WHERE (`id`,`name`) IN (VALUES (?,?),(?,?))",
///     sql
/// );
/// # Ok(())
/// # }
/// ```
#[macro_export]
macro_rules! values {
    ($($x:expr),*) => (
        Values::from(std::iter::empty() $(.chain(std::iter::once(Row::from($x))))*)
    );
}

/// Marks a given string or a tuple as a column. Useful when using a column in
/// calculations, e.g.
///
/// ``` rust
/// # use quaint::{col, val, ast::*, visitor::{Visitor, Sqlite}};
/// # fn main() -> Result<(), quaint::error::Error> {
/// let join = "dogs".on(("dogs", "slave_id").equals(Column::from(("cats", "master_id"))));
///
/// let query = Select::from_table("cats")
///     .value(Table::from("cats").asterisk())
///     .value(col!("dogs", "age") - val!(4))
///     .inner_join(join);
///
/// let (sql, params) = Sqlite::build(query)?;
///
/// assert_eq!(
///     "SELECT `cats`.*, (`dogs`.`age` - ?) FROM `cats` INNER JOIN `dogs` ON `dogs`.`slave_id` = `cats`.`master_id`",
///     sql
/// );
/// # Ok(())
/// # }
/// ```
#[macro_export]
macro_rules! col {
    ($e1:expr) => {
        Expression::from(Column::from($e1))
    };

    ($e1:expr, $e2:expr) => {
        Expression::from(Column::from(($e1, $e2)))
    };
}

/// Marks a given string as a value. Useful when using a value in calculations,
/// e.g.
///
/// ``` rust
/// # use quaint::{col, val, ast::*, visitor::{Visitor, Sqlite}};
/// # fn main() -> Result<(), quaint::error::Error> {
/// let join = "dogs".on(("dogs", "slave_id").equals(Column::from(("cats", "master_id"))));
///
/// let query = Select::from_table("cats")
///     .value(Table::from("cats").asterisk())
///     .value(col!("dogs", "age") - val!(4))
///     .inner_join(join);
///
/// let (sql, params) = Sqlite::build(query)?;
///
/// assert_eq!(
///     "SELECT `cats`.*, (`dogs`.`age` - ?) FROM `cats` INNER JOIN `dogs` ON `dogs`.`slave_id` = `cats`.`master_id`",
///     sql
/// );
/// # Ok(())
/// # }
/// ```
#[macro_export]
macro_rules! val {
    ($val:expr) => {
        Expression::from($val)
    };
}

macro_rules! value {
    ($target:ident: $kind:ty,$paramkind:ident,$that:expr) => {
        impl<'a> From<$kind> for crate::ast::ValueType<'a> {
            fn from(that: $kind) -> Self {
                let $target = that;
                crate::ast::ValueType::$paramkind(Some($that))
            }
        }

        impl<'a> From<Option<$kind>> for crate::ast::ValueType<'a> {
            fn from(that: Option<$kind>) -> Self {
                match that {
                    Some(val) => crate::ast::ValueType::from(val),
                    None => crate::ast::ValueType::$paramkind(None),
                }
            }
        }

        impl<'a> From<$kind> for crate::ast::Value<'a> {
            fn from(that: $kind) -> Self {
                crate::ast::Value::from(crate::ast::ValueType::from(that))
            }
        }

        impl<'a> From<Option<$kind>> for crate::ast::Value<'a> {
            fn from(that: Option<$kind>) -> Self {
                crate::ast::Value::from(crate::ast::ValueType::from(that))
            }
        }
    };
}

macro_rules! aliasable {
    ($($kind:ty),*) => (
        $(
            impl<'a> Aliasable<'a> for $kind {
                type Target = Table<'a>;

                fn alias<T>(self, alias: T) -> Self::Target
                where
                    T: Into<Cow<'a, str>>,
                {
                    let table: Table = self.into();
                    table.alias(alias)
                }
            }
        )*
    );
}

macro_rules! function {
    ($($kind:ident),*) => (
        $(
            impl<'a> From<$kind<'a>> for Function<'a> {
                fn from(f: $kind<'a>) -> Self {
                    Function {
                        typ_: FunctionType::$kind(f),
                        alias: None,
                    }
                }
            }

            impl<'a> From<$kind<'a>> for Expression<'a> {
                fn from(f: $kind<'a>) -> Self {
                    Function::from(f).into()
                }
            }
        )*
    );
}

macro_rules! expression {
    ($kind:ident,$paramkind:ident) => {
        impl<'a> From<$kind<'a>> for Expression<'a> {
            fn from(that: $kind<'a>) -> Self {
                Expression {
                    kind: ExpressionKind::$paramkind(that),
                    alias: None,
                }
            }
        }
    };
}

/// A test-generator to test types in the defined database.
#[cfg(test)]
macro_rules! test_type {
    ($name:ident($db:ident, $sql_type:literal, $(($input:expr, $output:expr)),+ $(,)?)) => {
        paste::item! {
            #[test]
            fn [< test_type_ $name >] () -> crate::Result<()> {
                use crate::ast::*;
                use crate::connector::Queryable;
                use crate::tests::test_api::TestApi;
                use tokio::runtime::Builder;

                let rt = Builder::new_multi_thread().enable_all().build().unwrap();

                rt.block_on(async {
                    let mut setup = [< $db _test_api >]().await?;
                    let table = setup.create_type_table($sql_type).await?;

                    $(
                        let input = $input;
                        let output = $output;

                        let insert = Insert::single_into(&table).value("value", input);
                        setup.conn().insert(insert.into()).await?;

                        let select = Select::from_table(&table).column("value").order_by("id".descend());
                        let res = setup.conn().select(select).await?.into_single()?;

                        assert_eq!(Some(&output), res.at(0));
                    )+

                    Result::<(), crate::error::Error>::Ok(())
                }).unwrap();

                Ok(())
            }
        }
    };

    ($name:ident($db:ident, $sql_type:literal, $($value:expr),+ $(,)?)) => {
        paste::item! {
            #[test]
            fn [< test_type_ $name >] () -> crate::Result<()> {
                use crate::ast::*;
                use crate::connector::Queryable;
                use crate::tests::test_api::TestApi;
                use tokio::runtime::Builder;

                let rt = Builder::new_multi_thread().enable_all().build().unwrap();

                rt.block_on(async {
                    let mut setup = [< $db _test_api >]().await?;
                    let table = setup.create_type_table($sql_type).await?;

                    $(
                        let value = $value;
                        let insert = Insert::single_into(&table).value("value", value.clone());
                        setup.conn().insert(insert.into()).await?;

                        let select = Select::from_table(&table).column("value").order_by("id".descend());
                        let res = setup.conn().select(select).await?.into_single()?;

                        assert_eq!(Some(&value), res.at(0));
                    )+

                    Result::<(), crate::error::Error>::Ok(())
                }).unwrap();

                Ok(())
            }
        }
    };
}