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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
mod distinct;
mod from_item;
mod join;
mod limit;
mod offset;
mod order_by;

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

use crate::postgres::general::{Condition, Expression, WithClause};
use crate::tools::{joined, IntoIteratorOfSameType};

pub use distinct::Distinct;
pub use from_item::FromItem;
pub use join::Joinable;
pub use limit::Limit;
pub use offset::Offset;
pub use order_by::{OrderBy, Orderable};

/// Create a new `SELECT` statement with given expressions.
///
/// Returns a [`Select`] structure that allows adding additional clauses. Call `to_string` to finalize and get SQL.
///
/// # Supported clauses
///
/// | Clause        | Method                               |
/// |---------------|--------------------------------------|
/// | `ALL`         | [`from`][Select::from]               |
/// | `DISTINCT`    | [`distinct`][Select::distinct]       |
/// | `DISTINCT ON` | [`distinct_on`][Select::distinct_on] |
/// | `FROM`        | [`from`][Select::from]               |
/// | `WHERE`       | [`where_`][Select::where_]           |
/// | `GROUP BY`    | [`group_by`][Select::group_by]       |
/// | `HAVING`      | [`having`][Select::having]           |
/// | `ORDER BY`    | [`order_by`][Select::order_by]       |
/// | `LIMIT`       | [`limit`][Select::limit]             |
/// | `OFFSET`      | [`offset`][Select::offset]           |
///
/// # Specifying a `WITH` clause
///
/// To create a `SELECT` statement with a `WITH` clause, start with [`with`][crate::postgres::with] instead of this function.
///
/// # Useful traits to import
///
/// - [`Orderable`][crate::postgres::Orderable] to easily stick `DESC`/`ASC`/etc. on strings
/// - [`Joinable`][crate::postgres::Joinable] to easily create joins from string table names
/// - [`Aliasable`][crate::postgres::Aliasable] to easily make `x AS y` aliases for columns and such
///
/// # Examples
///
/// ```
/// use scooby::postgres::select;
///
/// let sql = select("1 + 1").to_string();
///
/// assert_eq!(sql, "SELECT 1 + 1")
/// ```
///
/// ```
/// use scooby::postgres::{select, Joinable, Orderable, Aliasable};
///
/// let sql = select(("country.name".as_("name"), "COUNT(*)".as_("count")))
///     .from(
///         "Country"
///             .as_("country")
///             .inner_join("City".as_("city"))
///             .on("city.country_id = country.id"),
///     )
///     .where_("city.population > 1000000")
///     .group_by("country.name")
///     .order_by("count".desc())
///     .limit(10)
///     .to_string();
///
/// assert_eq!(sql, "SELECT country.name AS name, COUNT(*) AS count FROM Country AS country INNER JOIN City AS city ON city.country_id = country.id WHERE city.population > 1000000 GROUP BY country.name ORDER BY count DESC LIMIT 10");
/// ```
pub fn select(expressions: impl IntoIteratorOfSameType<Expression>) -> Select {
    Select {
        expressions: expressions.into_some_iter().collect(),
        ..Default::default()
    }
}

pub(crate) fn select_with(expressions: Vec<Expression>, with_clause: WithClause) -> Select {
    Select {
        expressions,
        with: Some(with_clause),
        ..Default::default()
    }
}

/// An alternative way to create `SELECT` statements, starting from the `FROM` clause for convenience.
///
/// Returns a [`FromSelectBuilder`] structure, which expects you to specify expressions for the actual `SELECT` clause
/// by calling its `select` method
///
/// # Examples
///
/// ```
/// use scooby::postgres::from;
///
/// let sql = from("Points").select(("x", "y")).where_("x > 1").to_string();
///
/// assert_eq!(sql, "SELECT x, y FROM Points WHERE x > 1");
/// ```
pub fn from(from: impl IntoIteratorOfSameType<FromItem>) -> FromSelectBuilder {
    FromSelectBuilder {
        from: from.into_some_iter().collect(),
    }
}

/// `SELECT` statement, possibly with additional clauses.
///
/// Finalize and turn into `String` by calling `to_string`.
///
/// See [`select`] docs for more details and examples.
#[must_use = "Making a SELECT statement without using it is pointless"]
#[derive(Default, Debug, Clone)]
pub struct Select {
    with: Option<WithClause>,
    expressions: Vec<Expression>,
    from: Vec<FromItem>,
    where_: Vec<Condition>,
    group_by: Vec<Expression>,
    having: Vec<Condition>,
    order_by: Vec<OrderBy>,
    limit: Option<Limit>,
    offset: Option<Offset>,
    distinct: Option<Distinct>,
}

impl Select {
    /// Add more expressions to be selected
    ///
    /// ```
    /// use scooby::postgres::select;
    ///
    /// let sql = select(("id", "name"))
    ///     .from("Person")
    ///     .and_select("age")
    ///     .and_select(("occupation_id", "city_id"))
    ///     .to_string();
    ///
    /// assert_eq!(sql, "SELECT id, name, age, occupation_id, city_id FROM Person");
    /// ```
    pub fn and_select(mut self, expressions: impl IntoIteratorOfSameType<Expression>) -> Self {
        self.expressions.extend(expressions.into_some_iter());
        self
    }

    /// Explicitly specify `SELECT ALL`, i.e. non-distinct query
    ///
    /// ```
    /// use scooby::postgres::select;
    /// let sql = select("*").all().from("City").to_string();
    /// assert_eq!(sql, "SELECT ALL * FROM City");
    /// ```
    pub fn all(mut self) -> Self {
        self.distinct = Some(Distinct::All);
        self
    }

    /// Set a simple `DISTINCT` clause
    ///
    /// ```
    /// use scooby::postgres::select;
    /// let sql = select("*").distinct().from("City").to_string();
    /// assert_eq!(sql, "SELECT DISTINCT * FROM City");
    /// ```
    pub fn distinct(mut self) -> Self {
        self.distinct = Some(Distinct::Distinct);
        self
    }

    /// Set a `DISTINCT ON (...)` clause
    ///
    /// ```
    /// use scooby::postgres::select;
    /// let sql = select("*").distinct_on("id").from("City").to_string();
    /// assert_eq!(sql, "SELECT DISTINCT ON (id) * FROM City");
    /// ```
    pub fn distinct_on(mut self, expressions: impl IntoIteratorOfSameType<Expression>) -> Self {
        self.distinct = Some(Distinct::DistinctOn(expressions.into_some_iter().collect()));
        self
    }

    /// Set or add more items in a `FROM` clause
    ///
    /// Import [`Joinable`][crate::postgres::Joinable] for convenient joins.
    ///
    /// You can pass subselects as well, so long as you make sure they're aliased.
    ///
    /// ```
    /// use scooby::postgres::select;
    /// let sql = select("*").from("City").from(("Other", "Third")).to_string();
    /// assert_eq!(sql, "SELECT * FROM City, Other, Third");
    /// ```
    ///
    /// ```
    /// use scooby::postgres::{select, Joinable};
    ///
    /// let sql = select("col1")
    ///     .from(
    ///         "Person p"
    ///             .inner_join("City c")
    ///             .on("c.id = p.city_id")
    ///             .left_join("Belonging b")
    ///             .on("p.id = b.person_id"),
    ///     )
    ///     .to_string();
    ///
    /// assert_eq!(sql, "SELECT col1 FROM Person p INNER JOIN City c ON c.id = p.city_id LEFT JOIN Belonging b ON p.id = b.person_id");
    /// ```
    ///
    /// ```
    /// use scooby::postgres::{select, Aliasable};
    ///
    /// let sql = select("*")
    ///     .from(select("id").from("City").as_("x"))
    ///     .to_string();
    ///
    /// assert_eq!(sql, "SELECT * FROM (SELECT id FROM City) AS x");
    /// ```
    pub fn from(mut self, from: impl IntoIteratorOfSameType<FromItem>) -> Self {
        self.from.extend(from.into_some_iter());
        self
    }

    /// Add one or more `WHERE` conditions, `AND`'ed together with themselves and existing conditions.
    ///
    /// ```
    /// use scooby::postgres::select;
    ///
    /// let sql = select("col1")
    ///     .from("Dummy")
    ///     .where_(("x > 1", "y > 1"))
    ///     .where_("z > 1")
    ///     .to_string();
    ///
    /// assert_eq!(sql, "SELECT col1 FROM Dummy WHERE x > 1 AND y > 1 AND z > 1");
    /// ```
    pub fn where_(mut self, conditions: impl IntoIteratorOfSameType<Condition>) -> Self {
        self.where_.extend(conditions.into_some_iter());
        self
    }

    /// Add one or more expressions in a `GROUP BY` clause
    ///
    /// ```
    /// use scooby::postgres::select;
    ///
    /// let sql = select(("country_id", "COUNT(*)"))
    ///     .from("City")
    ///     .group_by("country_id")
    ///     .to_string();
    ///
    /// assert_eq!(sql, "SELECT country_id, COUNT(*) FROM City GROUP BY country_id");
    /// ```
    pub fn group_by(mut self, groupings: impl IntoIteratorOfSameType<Expression>) -> Self {
        self.group_by.extend(groupings.into_some_iter());
        self
    }

    /// Add one or more expressions in a `HAVING` clause
    ///
    /// ```
    /// use scooby::postgres::select;
    ///
    /// let sql = select(("country_id", "COUNT(*)"))
    ///     .from("City")
    ///     .group_by("country_id")
    ///     .having("COUNT(*) > 10000")
    ///     .to_string();
    ///
    /// assert_eq!(sql, "SELECT country_id, COUNT(*) FROM City GROUP BY country_id HAVING COUNT(*) > 10000");
    /// ```
    pub fn having(mut self, conditions: impl IntoIteratorOfSameType<Condition>) -> Self {
        self.having.extend(conditions.into_some_iter());
        self
    }

    /// Set or add more sort expressions in an `ORDER BY` clause.
    ///
    /// Import [`Orderable`][crate::postgres::Orderable] for convenient order specifications.
    ///
    /// ```
    /// use scooby::postgres::select;
    /// let sql = select("*").from("City").order_by("id").to_string();
    /// assert_eq!(sql, "SELECT * FROM City ORDER BY id");
    /// ```
    ///
    /// ```
    /// use scooby::postgres::{select, Orderable};
    ///
    /// let sql = select("*")
    ///     .from("City")
    ///     .order_by(("last_modified".desc(), "id".desc()))
    ///     .to_string();
    ///
    /// assert_eq!(sql, "SELECT * FROM City ORDER BY last_modified DESC, id DESC");
    /// ```
    pub fn order_by(mut self, order_bys: impl IntoIteratorOfSameType<OrderBy>) -> Self {
        self.order_by.extend(order_bys.into_some_iter());
        self
    }

    /// Set a `LIMIT` clause
    ///
    /// ```
    /// use scooby::postgres::select;
    /// let sql = select("*").from("City").limit(10).to_string();
    /// assert_eq!(sql, "SELECT * FROM City LIMIT 10");
    /// ```
    pub fn limit(mut self, limit: impl Into<Limit>) -> Self {
        self.limit = Some(limit.into());
        self
    }

    /// Set an `OFFSET` clause
    ///
    /// ```
    /// use scooby::postgres::select;
    /// let sql = select("*").from("City").offset(10).to_string();
    /// assert_eq!(sql, "SELECT * FROM City OFFSET 10");
    /// ```
    pub fn offset(mut self, offset: impl Into<Offset>) -> Self {
        self.offset = Some(offset.into());
        self
    }
}

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

        write!(f, "SELECT")?;

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

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

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

        if !self.where_.is_empty() {
            write!(f, " WHERE {}", joined(&self.where_, " AND "))?;
        }

        if !self.group_by.is_empty() {
            write!(f, " GROUP BY {}", joined(&self.group_by, ", "))?;
        }

        if !self.having.is_empty() {
            write!(f, " HAVING {}", joined(&self.having, " AND "))?;
        }

        if !self.order_by.is_empty() {
            write!(f, " ORDER BY {}", joined(&self.order_by, ", "))?;
        }

        if let Some(ref limit) = self.limit {
            write!(f, " LIMIT {}", limit)?;
        }

        if let Some(ref offset) = self.offset {
            write!(f, " OFFSET {}", offset)?;
        }

        Ok(())
    }
}

/// Intermediate structure to build a `SELECT` statement starting from a `FROM` clause
///
/// Use the only provided [`select`][FromSelectBuilder::select] method to add a `SELECT` clause
#[must_use = "Making a FromSelectBuilder struct without using it is pointless"]
#[derive(Debug)]
pub struct FromSelectBuilder {
    from: Vec<FromItem>,
}

impl FromSelectBuilder {
    /// Specify expressions to be selected, turning this into a [`Select`] structure.
    ///
    /// ```
    /// use scooby::postgres::from;
    ///
    /// let sql = from("Points").select(("x", "y")).to_string();
    ///
    /// assert_eq!(sql, "SELECT x, y FROM Points");
    /// ```
    pub fn select(self, expressions: impl IntoIteratorOfSameType<Expression>) -> Select {
        Select {
            expressions: expressions.into_some_iter().collect(),
            from: self.from,
            ..Default::default()
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::postgres::tools::tests::assert_correct_postgresql;
    use crate::postgres::{from, select, with, Aliasable, Joinable, Orderable};

    #[test]
    fn bare() {
        let sql = select(()).to_string();
        assert_correct_postgresql(&sql, "SELECT");
    }

    #[test]
    fn without_from() {
        let sql = select("1 + 1").to_string();
        assert_correct_postgresql(&sql, "SELECT 1 + 1");
    }

    #[test]
    fn all() {
        let sql = select("*").all().from("City").to_string();
        assert_correct_postgresql(&sql, "SELECT ALL * FROM City");
    }

    #[test]
    fn distinct() {
        let sql = select("*").distinct().from("City").to_string();
        assert_correct_postgresql(&sql, "SELECT DISTINCT * FROM City");
    }

    #[test]
    fn tuple_of_columns() {
        let sql = select(("id", "name")).from("Person").to_string();
        assert_correct_postgresql(&sql, "SELECT id, name FROM Person")
    }

    #[test]
    fn slice_of_columns() {
        let sql = select(&["id", "name"]).from("Person").to_string();
        assert_correct_postgresql(&sql, "SELECT id, name FROM Person")
    }

    #[test]
    fn array_of_columns() {
        let sql = select(["id", "name"]).from("Person").to_string();
        assert_correct_postgresql(&sql, "SELECT id, name FROM Person")
    }

    #[test]
    fn no_columns() {
        let sql = select(()).from("Person").to_string();
        assert_correct_postgresql(&sql, "SELECT FROM Person");
    }

    #[test]
    fn and_select() {
        let sql = select(("id", "name"))
            .from("Person")
            .and_select("age")
            .and_select(("occupation_id", "city_id"))
            .to_string();

        assert_correct_postgresql(
            &sql,
            "SELECT id, name, age, occupation_id, city_id FROM Person",
        )
    }

    #[test]
    fn from_single_table() {
        let sql = select("name").from("Person").to_string();
        assert_correct_postgresql(&sql, "SELECT name FROM Person");
    }

    #[test]
    fn from_twice() {
        let sql = select("*").from("OneTable").from("OtherTable").to_string();
        assert_correct_postgresql(&sql, "SELECT * FROM OneTable, OtherTable");
    }

    #[test]
    fn from_alias() {
        let sql = select("*").from("Person".as_("p")).to_string();
        assert_correct_postgresql(&sql, "SELECT * FROM Person AS p");
    }

    #[test]
    fn from_tuple_of_tables() {
        let sql = select(&["p.name", "c.name", "d.name"])
            .from(("Person p", "City c", "District d"))
            .to_string();

        assert_correct_postgresql(
            &sql,
            "SELECT p.name, c.name, d.name FROM Person p, City c, District d",
        );
    }

    #[test]
    fn from_join() {
        let sql = select("col1")
            .from("Person p".join("City c").on("c.id = p.city_id"))
            .to_string();

        assert_correct_postgresql(
            &sql,
            "SELECT col1 FROM Person p JOIN City c ON c.id = p.city_id",
        );
    }

    #[test]
    fn from_join_with_alias() {
        let sql = select("*")
            .from(
                "Person"
                    .as_("p")
                    .join("City".as_("c"))
                    .on("c.id = p.city_id"),
            )
            .to_string();

        assert_correct_postgresql(
            &sql,
            "SELECT * FROM Person AS p JOIN City AS c ON c.id = p.city_id",
        );
    }

    #[test]
    fn from_multiple_joins() {
        let sql = select("col1")
            .from(
                "Person p"
                    .inner_join("City c")
                    .on("c.id = p.city_id")
                    .left_join("Belonging b")
                    .on("p.id = b.person_id"),
            )
            .to_string();

        assert_correct_postgresql(&sql, "SELECT col1 FROM Person p INNER JOIN City c ON c.id = p.city_id LEFT JOIN Belonging b ON p.id = b.person_id");
    }

    #[test]
    fn cross_join() {
        let sql = select("*").from("One".cross_join("Two")).to_string();

        assert_correct_postgresql(&sql, "SELECT * FROM One CROSS JOIN Two");
    }

    #[test]
    fn cross_join_chain() {
        let sql = select("*")
            .from("One".cross_join("Two").cross_join("Three"))
            .to_string();

        assert_correct_postgresql(&sql, "SELECT * FROM One CROSS JOIN Two CROSS JOIN Three");
    }

    #[test]
    fn nested_join_madness() {
        let sql = select("*")
            .from(
                "t1".left_join("t2".cross_join("t3").cross_join("t4"))
                    .on("(t2.a = t1.a AND t3.b = t1.b AND t4.c = t1.c)"),
            )
            .to_string();

        assert_correct_postgresql(&sql, "SELECT * FROM t1 LEFT JOIN (t2 CROSS JOIN t3 CROSS JOIN t4) ON (t2.a = t1.a AND t3.b = t1.b AND t4.c = t1.c)");
    }

    #[test]
    fn from_heterogeneous_tables() {
        let sql = select("*")
            .from((
                "Person p".inner_join("City c").on("c.id = p.city_id"),
                "OtherTable o",
            ))
            .to_string();

        assert_correct_postgresql(
            &sql,
            "SELECT * FROM Person p INNER JOIN City c ON c.id = p.city_id, OtherTable o",
        )
    }

    #[test]
    fn from_subselect() {
        let sql = select("*")
            .from(select("id").from("City").as_("x"))
            .to_string();

        assert_correct_postgresql(&sql, "SELECT * FROM (SELECT id FROM City) AS x");
    }

    #[test]
    fn from_subselect_with_alias() {
        let subselect = select(("id", "planet_id")).from("City");
        let sql = select("*")
            .from(
                subselect
                    .as_("c")
                    .inner_join("Planet".as_("p"))
                    .on("c.planet_id = p.id"),
            )
            .to_string();

        assert_correct_postgresql(&sql, "SELECT * FROM (SELECT id, planet_id FROM City) AS c INNER JOIN Planet AS p ON c.planet_id = p.id");
    }

    #[test]
    fn group_by() {
        let sql = select(("country_id", "COUNT(*)"))
            .from("City")
            .group_by("country_id")
            .to_string();

        assert_correct_postgresql(
            &sql,
            "SELECT country_id, COUNT(*) FROM City GROUP BY country_id",
        );
    }

    #[test]
    fn order_by() {
        let sql = select("*").from("City").order_by("id").to_string();
        assert_correct_postgresql(&sql, "SELECT * FROM City ORDER BY id");
    }

    #[test]
    fn order_by_two() {
        let sql = select("*")
            .from("City")
            .order_by(("country_id", "id"))
            .to_string();

        assert_correct_postgresql(&sql, "SELECT * FROM City ORDER BY country_id, id");
    }

    #[test]
    fn order_by_desc() {
        let sql = select("*").from("City").order_by("id".desc()).to_string();
        assert_correct_postgresql(&sql, "SELECT * FROM City ORDER BY id DESC");
    }

    #[test]
    fn limit() {
        let sql = select("whatever").from("SomeTable").limit(5).to_string();
        assert_correct_postgresql(&sql, "SELECT whatever FROM SomeTable LIMIT 5");
    }

    #[test]
    fn offset() {
        let sql = select("whatever").from("SomeTable").offset(5).to_string();
        assert_correct_postgresql(&sql, "SELECT whatever FROM SomeTable OFFSET 5");
    }

    #[test]
    fn limit_with_offset() {
        let sql = select("whatever")
            .from("SomeTable")
            .limit(10)
            .offset(5)
            .to_string();

        assert_correct_postgresql(&sql, "SELECT whatever FROM SomeTable LIMIT 10 OFFSET 5");
    }

    #[test]
    fn with_select() {
        let sql = with("thing")
            .as_(select("1 + 1"))
            .select("x")
            .from("thing")
            .to_string();

        assert_correct_postgresql(&sql, "WITH thing AS (SELECT 1 + 1) SELECT x FROM thing");
    }

    #[test]
    fn with_two_selects() {
        let sql = with("one")
            .as_(select("1 + 1"))
            .and_with("two")
            .as_(select("2 + 2"))
            .select(("one.x", "two.x"))
            .from(("one", "two"))
            .to_string();

        assert_correct_postgresql(
            &sql,
            "WITH one AS (SELECT 1 + 1), two AS (SELECT 2 + 2) SELECT one.x, two.x FROM one, two",
        );
    }

    #[test]
    fn complex_cte_example() {
        let sql = with("regional_sales")
            .as_(
                select(("region", "SUM(amount)".as_("total_sales")))
                    .from("orders")
                    .group_by("region"),
            )
            .and_with("top_regions")
            .as_(select("region").from("regional_sales").where_(format!(
                "total_sales > ({})",
                select("SUM(total_sales)/10").from("regional_sales")
            )))
            .select((
                "region",
                "product",
                "SUM(quantity)".as_("product_units"),
                "SUM(amount)".as_("product_sales"),
            ))
            .from("orders")
            .where_(format!(
                "region IN ({})",
                select("region").from("top_regions")
            ))
            .group_by(("region", "product"))
            .to_string();

        assert_correct_postgresql(&sql, "WITH regional_sales AS (SELECT region, SUM(amount) AS total_sales FROM orders GROUP BY region), top_regions AS (SELECT region FROM regional_sales WHERE total_sales > (SELECT SUM(total_sales)/10 FROM regional_sales)) SELECT region, product, SUM(quantity) AS product_units, SUM(amount) AS product_sales FROM orders WHERE region IN (SELECT region FROM top_regions) GROUP BY region, product");
    }

    #[test]
    fn complex_query_example() {
        let sql = select(("country.name".as_("name"), "COUNT(*)".as_("count")))
            .from(
                "Country"
                    .as_("country")
                    .inner_join("City".as_("city"))
                    .on("city.country_id = country.id"),
            )
            .where_("city.population > 1000000")
            .group_by("country.name")
            .order_by("count".desc())
            .limit(10)
            .to_string();

        assert_correct_postgresql(&sql, "SELECT country.name AS name, COUNT(*) AS count FROM Country AS country INNER JOIN City AS city ON city.country_id = country.id WHERE city.population > 1000000 GROUP BY country.name ORDER BY count DESC LIMIT 10");
    }

    #[test]
    fn starting_with_from() {
        let sql = from("Points").select(("x", "y")).to_string();

        assert_correct_postgresql(&sql, "SELECT x, y FROM Points");
    }

    #[test]
    fn limit_with_parameter() {
        let sql = select("1 + 1").limit("$1").to_string();

        assert_correct_postgresql(&sql, "SELECT 1 + 1 LIMIT $1");
    }

    #[test]
    fn offset_with_parameters() {
        let sql = select("1 + 1").offset("$1").to_string();

        assert_correct_postgresql(&sql, "SELECT 1 + 1 OFFSET $1");
    }
}