scooby 0.5.0

An SQL query builder with a pleasant fluent API closely imitating actual SQL
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
mod on_conflict;
mod values;

use std::fmt::{self, Display, Formatter};

use crate::postgres::general::{Column, Expression, OutputExpression, TableName, WithClause};
use crate::tools::{joined, IntoIteratorOfSameType, IntoNonZeroArray};

pub use on_conflict::{OnConflictClause, OnConflictClauseBuilder};
pub use values::{DefaultValues, Values, WithColumns, WithoutColumns};

/// Start building a new `INSERT INTO` statement with the given table name.
///
/// Returns a [`BareInsertInto`] structure which requires that you specify
/// what type of a `VALUES` clause you wish to have:
///
/// 1. For `DEFAULT VALUES`, call [`default_values`][BareInsertInto::default_values]
/// 2. For `VALUES (...)` with unspecified columns, call [`values`][BareInsertInto::values]
/// 3. For `(...) VALUES (...)`, call [`columns`][BareInsertInto::columns]
///
/// First two options will give you an [`InsertInto`] structure directly
///
/// Option 3 will expect you to specify at least one set of values through [`values`][InsertIntoColumnsBuilder::values] method
///
/// Call `to_string` on the final `InsertInto` structure to finalize and get an SQL string.
///
/// # Supported clauses
///
/// | Clause        | Method                                   |
/// |---------------|------------------------------------------|
/// | `VALUES`      | [`values`][InsertInto::values]           |
/// | `ON CONFLICT` | [`on_conflict`][InsertInto::on_conflict] |
/// | `RETURNING`   | [`returning`][InsertInto::returning]     |
///
/// # Specifying a `WITH` clause
///
/// To create an `INSERT INTO` statement with a `WITH` clause, start with [`with`][crate::postgres::with] instead of this function.
///
/// # Examples
///
/// ```
/// use scooby::postgres::insert_into;
///
/// let sql = insert_into("Dummy").default_values().to_string();
///
/// assert_eq!(sql, "INSERT INTO Dummy DEFAULT VALUES")
/// ```
///
/// ```
/// use scooby::postgres::{insert_into, Parameters};
///
/// let mut params = Parameters::new();
///
/// let sql = insert_into("Rectangle")
///     .columns(("width", "height"))
///     .values([params.next_array()])
///     .returning("id")
///     .to_string();
///
/// assert_eq!(sql, "INSERT INTO Rectangle (width, height) VALUES ($1, $2) RETURNING id");
/// ```
pub fn insert_into(table_name: impl Into<TableName>) -> BareInsertInto {
    BareInsertInto {
        table_name: table_name.into(),
        with: None,
    }
}

pub(crate) fn insert_into_with(table_name: TableName, with: WithClause) -> BareInsertInto {
    BareInsertInto {
        table_name,
        with: Some(with),
    }
}

/// Bare `INSERT INTO` statement without a valid `VALUES` clause specified
///
/// You will want to make use of three methods to convert this into a usable statement:
///
/// - [`default_values`][BareInsertInto::default_values] to add a `DEFAULT VALUES` clause
/// - [`values`][BareInsertInto::values] to add `VALUES (...)` clause with unspecified columns
/// - [`columns`][BareInsertInto::columns] to start building a `(...) VALUES (...)` clause with specific columns
#[must_use = "Making a bare INSERT INTO statement is pointless"]
#[derive(Debug)]
pub struct BareInsertInto {
    table_name: TableName,
    with: Option<WithClause>,
}

impl BareInsertInto {
    /// Add a `DEFAULT VALUES` clause to this statement
    ///
    /// ```
    /// use scooby::postgres::insert_into;
    ///
    /// let sql = insert_into("Dummy").default_values().to_string();
    ///
    /// assert_eq!(sql, "INSERT INTO Dummy DEFAULT VALUES");
    /// ```
    pub fn default_values(self) -> InsertInto<DefaultValues> {
        InsertInto::new(self.table_name, DefaultValues, self.with)
    }

    /// Add a `VALUES (...)` clause with unspecified columns to this statement
    ///
    /// ```
    /// use scooby::postgres::insert_into;
    ///
    /// let sql = insert_into("Dummy").values([("$1", "$2"), ("$3", "$4")]).to_string();
    ///
    /// assert_eq!(sql, "INSERT INTO Dummy VALUES ($1, $2), ($3, $4)");
    /// ```
    pub fn values<T: IntoNonZeroArray<Expression, N>, const N: usize>(
        self,
        values: impl IntoIterator<Item = T>,
    ) -> InsertInto<WithoutColumns<N>> {
        let values = values
            .into_iter()
            .map(IntoNonZeroArray::into_non_zero_array)
            .collect();

        InsertInto::new(self.table_name, WithoutColumns::new(values), self.with)
    }

    /// Begin building a `(...) VALUES (...)` clause for this statement.
    ///
    /// Expects a non-zero list of columns: an array, a tuple, or a single value.
    ///
    /// Returns an [`InsertIntoColumnsBuilder`] structure which requires you to specify at least one set of values.
    ///
    /// ```
    /// use scooby::postgres::insert_into;
    ///
    /// let sql = insert_into("Dummy")
    ///     .columns(("col1", "col2"))
    ///     .values([("$1", "$2"), ("$3", "$4")])
    ///     .to_string();
    ///
    /// assert_eq!(sql, "INSERT INTO Dummy (col1, col2) VALUES ($1, $2), ($3, $4)");
    pub fn columns<const N: usize>(
        self,
        columns: impl IntoNonZeroArray<Column, N>,
    ) -> InsertIntoColumnsBuilder<N> {
        InsertIntoColumnsBuilder {
            table_name: self.table_name,
            with: self.with,
            columns: columns.into_non_zero_array(),
        }
    }
}

/// Intermediate structure to ensure one cannot build an `INSERT INTO` statement with columns, but without values
///
/// Use the only provided [`values`][InsertIntoColumnsBuilder::values] method to add at least one set of values.
#[must_use = "Making a bare INSERT INTO statement with columns is pointless"]
#[derive(Debug)]
pub struct InsertIntoColumnsBuilder<const N: usize> {
    table_name: TableName,
    with: Option<WithClause>,
    columns: [Column; N],
}

impl<const N: usize> InsertIntoColumnsBuilder<N> {
    /// Add first one or more sets of values.
    ///
    /// Further values and additional clauses may be added by calling appropriate methods
    /// on the returned [`InsertInto`] structure.
    ///
    /// ```
    /// use scooby::postgres::insert_into;
    ///
    /// let sql = insert_into("Dummy")
    ///     .columns(("col1", "col2"))
    ///     .values([("$1", "$2"), ("$3", "$4")])
    ///     .to_string();
    ///
    /// assert_eq!(sql, "INSERT INTO Dummy (col1, col2) VALUES ($1, $2), ($3, $4)");
    pub fn values<T: IntoNonZeroArray<Expression, N>>(
        self,
        values: impl IntoIterator<Item = T>,
    ) -> InsertInto<WithColumns<N>> {
        let values = values
            .into_iter()
            .map(IntoNonZeroArray::into_non_zero_array)
            .collect();

        InsertInto::new(
            self.table_name,
            WithColumns::new(self.columns, values),
            self.with,
        )
    }
}

/// `INSERT INTO` statement with a `VALUES` clause, and possibly additional clauses.
///
/// Finalize and turn into `String` by calling `to_string`.
///
/// See [`insert_into`] docs for more details and examples.
#[must_use = "Making an INSERT INTO statement without using it is pointless"]
#[derive(Debug, Clone)]
pub struct InsertInto<V: Values> {
    table_name: TableName,
    with: Option<WithClause>,
    values: V,
    returning: Vec<OutputExpression>,
    on_conflict: Option<OnConflictClause>,
}

impl<V: Values> InsertInto<V> {
    fn new(table_name: TableName, values: V, with: Option<WithClause>) -> InsertInto<V> {
        InsertInto {
            table_name,
            with,
            values,
            on_conflict: None,
            returning: Vec::new(),
        }
    }

    /// Add one or more `RETURNING` expressions.
    ///
    /// ```
    /// use scooby::postgres::insert_into;
    ///
    /// let sql = insert_into("Dummy")
    ///     .default_values()
    ///     .returning("id")
    ///     .returning(("width", "height"))
    ///     .to_string();
    ///
    /// assert_eq!(sql, "INSERT INTO Dummy DEFAULT VALUES RETURNING id, width, height");
    /// ```
    pub fn returning(mut self, expressions: impl IntoIteratorOfSameType<OutputExpression>) -> Self {
        self.returning.extend(expressions.into_some_iter());
        self
    }

    /// Add an `ON CONFLICT` clause to this statement.
    ///
    /// Returns a [`OnConflictClauseBuilder`] structure which requires you to specify
    /// an action to do when a conflict happens using follow up methods.
    ///
    /// ```
    /// use scooby::postgres::insert_into;
    ///
    /// let sql = insert_into("Dummy")
    ///     .values(["a"])
    ///     .on_conflict()
    ///     .do_nothing()
    ///     .to_string();
    ///
    /// assert_eq!(sql, "INSERT INTO Dummy VALUES (a) ON CONFLICT DO NOTHING");
    /// ```
    pub fn on_conflict(self) -> OnConflictClauseBuilder<V> {
        OnConflictClauseBuilder::new(self)
    }
}

impl<const N: usize> InsertInto<WithColumns<N>> {
    /// Add one or more sets of values.
    ///
    /// ```
    /// use scooby::postgres::insert_into;
    ///
    /// let sql = insert_into("Dummy")
    ///     .columns(("col1", "col2"))
    ///     .values([("$1", "$2")])
    ///     .values([("$3", "$4"), ("$5", "$6")])
    ///     .to_string();
    ///
    /// assert_eq!(sql, "INSERT INTO Dummy (col1, col2) VALUES ($1, $2), ($3, $4), ($5, $6)");
    pub fn values<T: IntoNonZeroArray<Expression, N>>(
        mut self,
        new_values: impl IntoIterator<Item = T>,
    ) -> Self {
        self.values.add(new_values);
        self
    }
}

impl<const N: usize> InsertInto<WithoutColumns<N>> {
    /// Add one or more sets of values.
    ///
    /// ```
    /// use scooby::postgres::insert_into;
    ///
    /// let sql = insert_into("Dummy")
    ///     .values([("$1", "$2")])
    ///     .values([("$3", "$4"), ("$5", "$6")])
    ///     .to_string();
    ///
    /// assert_eq!(sql, "INSERT INTO Dummy VALUES ($1, $2), ($3, $4), ($5, $6)");
    pub fn values<T: IntoNonZeroArray<Expression, N>>(
        mut self,
        new_values: impl IntoIterator<Item = T>,
    ) -> Self {
        self.values.add(new_values);
        self
    }
}

impl<V: Values> Display for InsertInto<V> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        if let Some(with_clause) = &self.with {
            write!(f, "{} ", with_clause)?;
        }

        write!(f, "INSERT INTO {} {}", self.table_name, self.values)?;

        if !self.returning.is_empty() {
            write!(f, " RETURNING {}", joined(&self.returning, ", "))?;
        }

        if let Some(on_conflict_clause) = &self.on_conflict {
            write!(f, " {}", on_conflict_clause)?;
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use crate::postgres::tools::tests::assert_correct_postgresql;
    use crate::postgres::{insert_into, select, with, Parameters};

    #[test]
    fn default_values() {
        let sql = insert_into("Dummy").default_values().to_string();
        assert_correct_postgresql(&sql, "INSERT INTO Dummy DEFAULT VALUES");
    }

    #[test]
    fn no_columns() {
        let sql = insert_into("Dummy").values(["a"]).to_string();
        assert_correct_postgresql(&sql, "INSERT INTO Dummy VALUES (a)");
    }

    #[test]
    fn no_columns_multiple_values() {
        let sql = insert_into("Dummy")
            .values([("a", "b"), ("c", "d")])
            .values([("e", "f")])
            .to_string();

        assert_correct_postgresql(&sql, "INSERT INTO Dummy VALUES (a, b), (c, d), (e, f)");
    }

    // FIXME: This currently compiles and panics at runtime, but ideally should not even compile
    #[test]
    #[should_panic]
    fn zero_length_columns() {
        let values: [[String; 0]; 1] = [[]];
        let sql = insert_into("Dummy").columns([]).values(values).to_string();

        assert_correct_postgresql(&sql, "INSERT INTO Dummy () VALUES ");
    }

    #[test]
    fn single_column() {
        let sql = insert_into("Dummy")
            .columns("col1")
            .values(["a"])
            .to_string();

        assert_correct_postgresql(&sql, "INSERT INTO Dummy (col1) VALUES (a)");
    }

    #[test]
    fn multiple_columns() {
        let sql = insert_into("Dummy")
            .columns(("col1", "col2"))
            .values([("a", "b")])
            .to_string();

        assert_correct_postgresql(&sql, "INSERT INTO Dummy (col1, col2) VALUES (a, b)");
    }

    #[test]
    fn many_values() {
        let sql = insert_into("Dummy")
            .columns(("col1", "col2"))
            .values([("a", "b"), ("c", "d")])
            .values([("e", "f")])
            .to_string();

        assert_correct_postgresql(
            &sql,
            "INSERT INTO Dummy (col1, col2) VALUES (a, b), (c, d), (e, f)",
        );
    }

    #[test]
    fn returning() {
        let sql = insert_into("Dummy")
            .columns("col1")
            .values(["a"])
            .returning("id")
            .to_string();

        assert_correct_postgresql(&sql, "INSERT INTO Dummy (col1) VALUES (a) RETURNING id");
    }

    #[test]
    fn returning_two() {
        let sql = insert_into("Dummy")
            .columns("col1")
            .values(["a"])
            .returning(("id", "place"))
            .to_string();

        assert_correct_postgresql(
            &sql,
            "INSERT INTO Dummy (col1) VALUES (a) RETURNING id, place",
        );
    }

    #[test]
    fn cte() {
        let sql = with("thing")
            .as_(select("1 + 1"))
            .insert_into("Dummy")
            .values(["a"])
            .to_string();

        assert_correct_postgresql(
            &sql,
            "WITH thing AS (SELECT 1 + 1) INSERT INTO Dummy VALUES (a)",
        );
    }

    #[test]
    fn array_params_with_columns() {
        let mut params = Parameters::new();

        let sql = insert_into("Dummy")
            .columns(("col1", "col2"))
            .values([params.next_array()])
            .to_string();

        assert_correct_postgresql(&sql, "INSERT INTO Dummy (col1, col2) VALUES ($1, $2)");
    }

    #[test]
    fn array_params_without_columns() {
        let mut params = Parameters::new();

        let sql = insert_into("Dummy")
            .values([params.next_array::<2>()])
            .to_string();

        assert_correct_postgresql(&sql, "INSERT INTO Dummy VALUES ($1, $2)");
    }

    #[test]
    fn on_conflict_do_nothing() {
        let sql = insert_into("Dummy")
            .values(["a"])
            .on_conflict()
            .do_nothing()
            .to_string();

        assert_correct_postgresql(&sql, "INSERT INTO Dummy VALUES (a) ON CONFLICT DO NOTHING");
    }

    #[test]
    fn on_conflict_do_update_set() {
        let sql = insert_into("Dummy")
            .values(["a"])
            .on_conflict()
            .do_update_set([("col", "1")])
            .to_string();

        assert_correct_postgresql(
            &sql,
            "INSERT INTO Dummy VALUES (a) ON CONFLICT DO UPDATE SET col = 1",
        );
    }
}