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
//! This module contains the logic for building queries,
//! as well as struct for representing columns.

mod delete;
mod select;
mod table;
mod update;

pub use table::{Column, TypedColumn};

use std::{
    marker::PhantomData,
    ops::{BitAnd, BitOr, Not}, future::{IntoFuture, Future}, pin::Pin,
};

use async_trait::async_trait;
use tokio_postgres::{types::ToSql, Row};

use crate::_get_client;

pub use delete::Delete;
pub use select::Select;
pub use update::{NoneSet, SomeSet, Update};

/// A trait implemented by everything that goes inside a query.
pub trait PushChunk<'a> {
    /// Pushes the containing string and the params to the provided buffer.
    fn push_to_buffer<T>(&mut self, buffer: &mut Query<'a, T>);
}

/// Trait used to mark exectuable queries. It is used
/// to make use of generics for executing them.
#[async_trait]
pub trait Executable {
    /// What output should this query result in?
    type Output;

    /// The actual function for executing a query.
    async fn exec(self) -> Result<Self::Output, crate::Error>;
}

/// A struct for storing a complete query along with
/// parameters and output type.
///
/// Depending on the output type, [`Executable`] is implemented differently
/// to allow for easy parsing.
pub struct Query<'a, T = Vec<Row>>(pub String, Vec<&'a (dyn ToSql + Sync)>, PhantomData<T>);

/// A trait implemented by query builders
pub trait ToQuery<'a, T>: PushChunk<'a> {
    /// A default implementation for building a query which can then be executed.
    fn to_query(&mut self) -> Query<'a, T> {
        // Create a new query object.
        let mut query = Query::default();

        // Push the query statement and parameters.
        self.push_to_buffer(&mut query);

        // Replace question mark placeholders with the postgres ones
        query.0 = replace_question_marks(query.0);

        // Return the exectuable query.
        query
    }
}

/// A basic chunk of SQL and it's params.
///
/// This is bundes the params with the relevant part of the statement
/// and thus makes ordering them much easier.
pub struct SqlChunk<'a>(pub String, pub Vec<&'a (dyn ToSql + Sync)>);

/// A generic implementation of `IntoFuture` for all viable query builders
/// ensures that each can be built _and_ executed simply
/// by calling `.await`.

/// Push multiple `PushChunk` objects to a buffer with a separator
/// between each of them.
///
/// Like `Vec::join()`.
fn push_all_with_sep<'a, T, U: PushChunk<'a>>(
    vec: &mut Vec<U>,
    buffer: &mut Query<'a, T>,
    sep: &str,
) {
    if vec.is_empty() {
        return;
    }

    for i in vec {
        i.push_to_buffer(buffer);
        buffer.0.push_str(sep);
    }

    // Remove the last `sep` as it's not
    // in between elements.
    buffer.0.truncate(buffer.0.len() - sep.len());
}

/// An enum representing the `WHERE` clause of a query.
pub enum Where<'a> {
    /// A number of conditions joined by `AND`.
    And(Vec<Where<'a>>),
    /// A number of conditions joined by `OR`.
    Or(Vec<Where<'a>>),
    /// A negated condition.
    Not(Box<Where<'a>>),
    /// A raw condition.
    Raw(SqlChunk<'a>),
    /// An empty `WHERE` clause.
    Empty,
}

/// Replace all `?` placeholders with the Postgres variant
/// `$1`, `$2`, etc.
fn replace_question_marks(stmt: String) -> String {
    // Since we change '?' to e.g. '$1' we need to
    // reserve some more space to avoid reallocating.
    const RESERVED: usize = 9;
    let mut buf = String::with_capacity(stmt.len() + RESERVED);

    // Tracking variables
    let mut counter = 1;
    let mut last_index = 0;

    // Looping through all '?' in the string
    for (i, _) in stmt.match_indices('?') {
        // Push everything until the '?'
        buf.push_str(&stmt[last_index..i]);

        // Push '$' including the number
        buf.push('$');
        buf.push_str(&counter.to_string());

        // Update variables
        counter += 1;
        last_index = i + 1;
    }

    // Push the tail
    buf.push_str(&stmt[last_index..]);

    buf
}

impl<'a, T> Default for Query<'a, T> {
    fn default() -> Self {
        Self("".into(), vec![], PhantomData::<T>)
    }
}

impl<'a, T> Query<'a, T> {
    /// Create a new query by passing a raw statement as well as parameters.
    pub fn new(stmt: String, params: Vec<&'a (dyn ToSql + Sync)> ) -> Query<'a, T> {
        Query(replace_question_marks(stmt), params, PhantomData::<T>)
    }
}

impl<'a> PushChunk<'a> for SqlChunk<'a> {
    fn push_to_buffer<T>(&mut self, buffer: &mut Query<'a, T>) {
        buffer.0.push_str(&self.0);
        buffer.1.append(&mut self.1);
    }
}

#[async_trait]
impl<'a, T> Executable for Query<'a, Vec<T>>
where
    T: TryFrom<Row, Error = crate::Error> + Send,
{
    type Output = Vec<T>;

    async fn exec(self) -> Result<Self::Output, crate::Error> {
        let client = _get_client()?;
        let rows = client.query(&self.0, &self.1).await?;

        rows.into_iter().map(|i| T::try_from(i)).collect()
    }
}

#[async_trait]
impl<'a, T> Executable for Query<'a, Option<T>>
where
    T: TryFrom<Row, Error = crate::Error> + Send,
{
    type Output = Option<T>;

    async fn exec(self) -> Result<Self::Output, crate::Error> {
        let client = _get_client()?;
        let rows = client.query(&self.0, &self.1).await?;

        rows.into_iter()
            .map(|i: Row| T::try_from(i))
            .next()
            .transpose()
    }
}

#[async_trait]
impl<'a> Executable for Query<'a, u64> {
    type Output = u64;

    async fn exec(self) -> Result<Self::Output, crate::Error> {
        let client = _get_client()?;

        Ok(client.execute(&self.0, &self.1).await?)
    }
}

/// Implement IntoFuture for Query so that any executable Query
/// may be executed by calling `.await`.
impl<'a, T: 'a> IntoFuture for Query<'a, T>
where
    Query<'a, T>: Executable<Output = T>
{
    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + 'a>>;
    type Output = Result<T, crate::Error>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(
            async move {
                self.exec().await
            }
        )
    }
}

impl<'a> Where<'a> {
    /// Create a new WHERE expression with parameters.
    pub(crate) fn new(expr: String, params: Vec<&'a (dyn ToSql + Sync)>) -> Where<'a> {
        Self::Raw(SqlChunk(expr, params))
    }

    /// Check whether the WHERE clause is empty.
    pub(crate) fn is_empty(&self) -> bool {
        use Where::*;

        match self {
            Empty => true,
            And(vec) => vec.iter().all(|i| i.is_empty()),
            Or(vec) => vec.iter().all(|i| i.is_empty()),
            Not(inner) => inner.is_empty(),
            Raw(chunk) => chunk.0.is_empty(),
        }
    }

    /// Combine two conditions using AND.
    ///
    /// You can also use the `&` operator.
    pub fn and(self, other: Where<'a>) -> Where<'a> {
        self.bitand(other)
    }

    /// Combine two conditions using OR.
    ///
    /// You can also use the `|` operator.
    ///
    /// # Example
    /// ```ignore
    /// Where::new("id = ?", vec![&7])
    ///     .or(Where::new("name = ?", vec![&"John"]))
    /// ```
    pub fn or(self, other: Where<'a>) -> Where<'a> {
        self.bitor(other)
    }
}

impl<'a> Default for Where<'a> {
    fn default() -> Self {
        Where::new("".into(), vec![])
    }
}

impl<'a> BitAnd for Where<'a> {
    type Output = Where<'a>;

    fn bitand(mut self, mut other: Self) -> Self::Output {
        use Where::*;

        if let Empty = self {
            return other;
        }

        if let Empty = other {
            return self;
        }

        // If self is already an AND variant,
        // simply add other to the vec.
        // This prevents unnecessary nesting.
        if let And(ref mut vec) = self {
            // If other is also AND append the whole vec.
            if let And(ref mut other_vec) = other {
                vec.append(other_vec);
            } else {
                vec.push(other);
            }
            return self;
        }

        if let And(ref mut vec) = other {
            vec.push(self);
            return other;
        }

        And(vec![self, other])
    }
}

impl<'a> BitOr for Where<'a> {
    type Output = Where<'a>;

    fn bitor(mut self, mut other: Self) -> Self::Output {
        use Where::*;

        if let Empty = self {
            return other;
        }
        if let Empty = other {
            return self;
        }

        // If self is already an OR variant,
        // simply add other to the vec.
        // This prevents unnecessary nesting.
        if let Or(ref mut vec) = self {
            // If other is also OR append the whole vec.
            if let And(ref mut other_vec) = other {
                vec.append(other_vec);
            } else {
                vec.push(other);
            }
            return self;
        }

        if let Or(ref mut vec) = other {
            vec.push(self);
            return other;
        }

        Or(vec![self, other])
    }
}

impl<'a> Not for Where<'a> {
    type Output = Where<'a>;

    fn not(self) -> Self::Output {
        use Where::*;

        if let Not(inner) = self {
            return *inner;
        }

        Not(Box::new(self))
    }
}

impl<'a> PushChunk<'a> for Where<'a> {
    fn push_to_buffer<T>(&mut self, buffer: &mut Query<'a, T>) {
        use Where::*;

        if self.is_empty() {
            return;
        }

        match self {
            Raw(chunk) => {
                chunk.push_to_buffer(buffer);
            }
            Not(inner) => {
                buffer.0.push_str("NOT (");
                inner.push_to_buffer(buffer);
                buffer.0.push(')');
            }
            And(vec) => {
                buffer.0.push('(');
                push_all_with_sep(vec, buffer, ") AND (");
                buffer.0.push(')');
            }
            Or(vec) => {
                buffer.0.push('(');
                push_all_with_sep(vec, buffer, ") OR (");
                buffer.0.push(')');
            }
            Empty => (),
        }
    }
}