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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
#[macro_export]
#[doc(hidden)]
macro_rules! __diesel_column {
    ($($table:ident)::*, $column_name:ident -> ($($Type:tt)*), $($doc:expr),*) => {
        $(
            #[doc=$doc]
        )*
        #[allow(non_camel_case_types, dead_code)]
        #[derive(Debug, Clone, Copy)]
        pub struct $column_name;

        impl $crate::expression::Expression for $column_name {
            type SqlType = $($Type)*;
        }

        impl<DB> $crate::query_builder::QueryFragment<DB> for $column_name where
            DB: $crate::backend::Backend,
            <$($table)::* as QuerySource>::FromClause: QueryFragment<DB>,
        {
            fn walk_ast(&self, mut out: $crate::query_builder::AstPass<DB>) -> $crate::result::QueryResult<()> {
                $($table)::*.from_clause().walk_ast(out.reborrow())?;
                out.push_sql(".");
                out.push_identifier(stringify!($column_name))
            }
        }

        impl_query_id!($column_name);

        impl SelectableExpression<$($table)::*> for $column_name {
        }

        impl<QS> AppearsOnTable<QS> for $column_name where
            QS: AppearsInFromClause<$($table)::*, Count=Once>,
        {
        }

        impl<Left, Right> SelectableExpression<
            Join<Left, Right, LeftOuter>,
        > for $column_name where
            $column_name: AppearsOnTable<Join<Left, Right, LeftOuter>>,
            Left: AppearsInFromClause<$($table)::*, Count=Once>,
            Right: AppearsInFromClause<$($table)::*, Count=Never>,
        {
        }

        impl<Left, Right> SelectableExpression<
            Join<Left, Right, Inner>,
        > for $column_name where
            $column_name: AppearsOnTable<Join<Left, Right, Inner>>,
            Join<Left, Right, Inner>: AppearsInFromClause<$($table)::*, Count=Once>,
        {
        }

        // FIXME: Remove this when overlapping marker traits are stable
        impl<Join, On> SelectableExpression<JoinOn<Join, On>> for $column_name where
            $column_name: SelectableExpression<Join> + AppearsOnTable<JoinOn<Join, On>>,
        {
        }

        // FIXME: Remove this when overlapping marker traits are stable
        impl<From> SelectableExpression<SelectStatement<From>> for $column_name where
            $column_name: SelectableExpression<From> + AppearsOnTable<SelectStatement<From>>,
        {
        }

        impl $crate::expression::NonAggregate for $column_name {}

        impl $crate::query_source::Column for $column_name {
            type Table = $($table)::*;

            fn name() -> &'static str {
                stringify!($column_name)
            }
        }

        impl<T> $crate::EqAll<T> for $column_name where
            T: $crate::expression::AsExpression<$($Type)*>,
            $crate::expression::helper_types::Eq<$column_name, T>: $crate::Expression<SqlType=$crate::types::Bool>,
        {
            type Output = $crate::expression::helper_types::Eq<Self, T>;

            fn eq_all(self, rhs: T) -> Self::Output {
                $crate::expression::operators::Eq::new(self, rhs.as_expression())
            }
        }

        __diesel_generate_ops_impls_if_numeric!($column_name, $($Type)*);
    }
}

/// Specifies that a table exists, and what columns it has. This will create a
/// new public module, with the same name, as the name of the table. In this
/// module, you'll find a unit struct named `table`, and a unit struct with the
/// names of each of the columns. In the definition, you can also specify an
/// additional set of columns which exist, but should not be selected by default
/// (for example, for things like full text search)
///
/// By default this allows a maximum of 16 columns per table, in order to reduce
/// compilation time. You can increase this limit to 26 by enabling the
/// `large-tables` feature, or up to 52 by enabling the `huge-tables` feature.
/// Enabling `huge-tables` will *substantially* increase compile times.
///
/// Example usage
/// -------------
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// table! {
///     users {
///         id -> Integer,
///         name -> VarChar,
///         favorite_color -> Nullable<VarChar>,
///     }
/// }
/// # fn main() {}
/// ```
///
/// You may also specify a primary key if it's called something other than `id`.
/// Tables with no primary key, or composite primary containing more than 3
/// columns are not supported.
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// table! {
///     users (non_standard_primary_key) {
///         non_standard_primary_key -> Integer,
///         name -> VarChar,
///         favorite_color -> Nullable<VarChar>,
///     }
/// }
/// # fn main() {}
/// ```
///
/// For tables with composite primary keys, list all of the columns in the
/// primary key.
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// table! {
///     followings (user_id, post_id) {
///         user_id -> Integer,
///         post_id -> Integer,
///         favorited -> Bool,
///     }
/// }
/// # fn main() {
/// #     use diesel::prelude::*;
/// #     use self::followings::dsl::*;
/// #     // Poor man's assert_eq! -- since this is type level this would fail
/// #     // to compile if the wrong primary key were generated
/// #     let (user_id {}, post_id {}) = followings.primary_key();
/// # }
/// ```
///
/// If you are using types that aren't from Diesel's core types, you can specify
/// which types to import. Note that the path given has to be an absolute path
/// relative to the crate root. You cannot use `self` or `super`.
///
/// ```
/// #[macro_use] extern crate diesel;
/// # /*
/// extern crate diesel_full_text_search;
/// # */
/// # mod diesel_full_text_search {
/// #     pub struct TsVector;
/// # }
///
/// table! {
///     use diesel::types::*;
///     use diesel_full_text_search::*;
///
///     posts {
///         id -> Integer,
///         title -> Text,
///         keywords -> TsVector,
///     }
/// }
/// # fn main() {}
/// ```
///
///
/// If you want to add documentation to the generated code you can use the
/// following syntax:
///
/// ```
/// #[macro_use] extern crate diesel;
///
/// table! {
///
///     /// The table containing all blog posts
///     posts {
///         /// The post's unique id
///         id -> Integer,
///         /// The post's title
///         title -> Text,
///     }
/// }
/// # fn main() {}
/// ```
///
/// This module will also contain several helper types:
///
/// dsl
/// ---
///
/// This simply re-exports the table, renamed to the same name as the module,
/// and each of the columns. This is useful to glob import when you're dealing
/// primarily with one table, to allow writing `users.filter(name.eq("Sean"))`
/// instead of `users::table.filter(users::name.eq("Sean"))`.
///
/// `all_columns`
/// -----------
///
/// A constant will be assigned called `all_columns`. This is what will be
/// selected if you don't otherwise specify a select clause. It's type will be
/// `table::AllColumns`. You can also get this value from the
/// `Table::all_columns` function.
///
/// star
/// ----
///
/// This will be the qualified "star" expression for this table (e.g.
/// `users.*`). Internally, we read columns by index, not by name, so this
/// column is not safe to read data out of, and it has had it's SQL type set to
/// `()` to prevent accidentally using it as such. It is sometimes useful for
/// count statements however. It can also be accessed through the `Table.star()`
/// method.
///
/// `SqlType`
/// -------
///
/// A type alias called `SqlType` will be created. It will be the SQL type of
/// `all_columns`. The SQL type is needed for things like [returning boxed
/// queries][boxed_queries].
///
/// [boxed_queries]: prelude/trait.BoxedDsl.html#example-1
///
/// `BoxedQuery`
/// ----------
///
/// ```ignore
/// pub type BoxedQuery<'a, DB, ST = SqlType> = BoxedSelectStatement<'a, ST, table, DB>;
/// ```
#[macro_export]
macro_rules! table {
    // Put imports into the import field
    (
        @parse
        import = [$(use $($import:tt)::+;)*];
        table_doc = [];
        use $($new_import:tt)::+; $($rest:tt)+
    ) => {
        table! {
            @parse
            import = [$(use $($import)::+;)* use $($new_import)::+;];
            table_doc = [];
            $($rest)+
        }
    };

    // Put doc annotation into the doc field
    (
        @parse
        import = [$(use $($import:tt)::+;)*];
        table_doc = [$($doc:expr,)*];
        #[doc=$new_doc:expr] $($rest:tt)+
    ) => {
        table! {
            @parse
            import = [$(use $($import)::+;)*];
            table_doc = [$($doc,)*$new_doc,];
            $($rest)+
        }
    };

    // We are finished parsing the import list and the table documentation
    // Now we forward the remaining tokens to parse the body of the table
    // definition
    (
        @parse
        import = [$(use $($import:tt)::+;)+];
        table_doc = [$($doc:expr,)*];
        $($rest:tt)+
    ) => {
        table! {
            @parse_body
            import = [$(use $($import)::+;)*];
            table_doc = [$($doc,)*];
            $($rest)+
        }
    };

    // We are finished parsing the import list and the table documentation
    // Because the import list is empty we add a default import (diesel::types::*)
    // After that we forward the remaining tokens to parse the body of the table
    // definition
    (
        @parse
        import = [];
        table_doc = [$($doc:expr,)*];
        $($rest:tt)+
    ) => {
        table! {
            @parse_body
            import = [use $crate::types::*;];
            table_doc = [$($doc,)*];
            $($rest)+
        }
    };

    // Add the primary key if it's not present
    (
        @parse_body
        import = [$(use $($import:tt)::+;)+];
        table_doc = [$($doc:expr,)*];
        $($table_name:ident).+ {$($body:tt)*}
    ) => {
        table! {
            @parse_body
            import = [$(use $($import)::+;)+];
            table_doc = [$($doc,)*];
            $($table_name).+ (id) {$($body)*}
        }
    };

    // Add the schema name if it's not present
    (
        @parse_body
        import = [$(use $($import:tt)::+;)+];
        table_doc = [$($doc:expr,)*];
        $name:ident $(($($pk:ident),+))* {$($body:tt)*}
    ) => {
        table! {
            @parse_body
            import = [$(use $($import)::+;)+];
            table_doc = [$($doc,)*];
            public . $name $(($($pk),+))* {$($body)*}
        }
    };
    // Terminal with single-column pk
    (
        @parse_body
        import = [$(use $($import:tt)::+;)+];
        table_doc = [$($doc:expr,)*];
        $schema_name:ident . $name:ident ($pk:ident) $body:tt
    ) => {
        table_body! {
            $schema_name . $name ($pk) $body
            import = [$(use $($import)::+;)+];
            table_doc = [$($doc)*];
        }
    };

    // Terminal with composite pk (add a trailing comma)
    (
        @parse_body
        import = [$(use $($import:tt)::+;)+];
        table_doc = [$($doc:expr,)*];
        $schema_name:ident . $name:ident ($pk:ident, $($composite_pk:ident),+) $body:tt
    ) => {
        table_body! {
            $schema_name . $name ($pk, $($composite_pk,)+) $body
            import = [$(use $($import)::+;)+];
            table_doc = [$($doc)*];
        }
    };

    // Terminal with invalid syntax
    // This is needed to prevent unbounded recursion on for example
    // table! {
    //     something strange
    // }
    (
        @parse_body
        import = [$(use $($import:tt)::+;)*];
        table_doc = [$($doc:expr,)*];
        $($rest:tt)*
    ) => {
        // Remove this workaround as soon as rust issue 40872 is implemented
        // https://github.com/rust-lang/rust/issues/40872
        const ERROR: i32 = env!("invalid table! syntax");
    };

    // Put a parse annotation and empty fields for imports and documentation on top
    // This is the entry point for parsing the table dsl
    ($($rest:tt)+) => {
        table! {
            @parse
            import = [];
            table_doc = [];
            $($rest)+
        }
    }
}

#[macro_export]
#[doc(hidden)]
macro_rules! table_body {
    // Parse the documentation of a table column and store it in current_column_doc
    // Forward the remaining table body to further instances of this macro
    (
        schema_name = $schema_name:ident,
        table_name = $name:ident,
        primary_key_ty = $primary_key_ty:ty,
        primary_key_expr = $primary_key_expr:expr,
        columns = [$($column_name:ident -> $Type:tt; doc = [$($doc:expr)*],)*],
        imports = ($($($import:tt)::+),+),
        table_doc = [$($table_doc:expr)*],
        current_column_doc = [$($column_doc:expr)*],
        #[doc=$new_doc:expr]
        $($body:tt)*
    ) => {
        table_body! {
            schema_name = $schema_name,
            table_name = $name,
            primary_key_ty = $primary_key_ty,
            primary_key_expr = $primary_key_expr,
            columns = [$($column_name -> $Type; doc = [$($doc)*],)*],
            imports = ($($($import)::+),+),
            table_doc = [$($table_doc)*],
            current_column_doc = [$($column_doc)*$new_doc],
            $($body)*
        }
    };

    // Parse a table column definition
    // Forward any remaining table column to further instances
    // of this macro
    //
    // This case will attempt to keep the type destructured so we can match
    // on it to determine if the column is numeric, later. The next branch
    // will catch any types which don't match this structure
    (
        schema_name = $schema_name:ident,
        table_name = $name:ident,
        primary_key_ty = $primary_key_ty:ty,
        primary_key_expr = $primary_key_expr:expr,
        columns = [$($column_name:ident -> $Type:tt; doc = [$($doc:expr)*],)*],
        imports = ($($($import:tt)::+),+),
        table_doc = [$($table_doc:expr)*],
        current_column_doc = [$($column_doc:expr)*],
        $new_column_name:ident -> $($ty_path:tt)::* $(<$($ty_params:tt)::*>)*,
        $($body:tt)*
    ) => {
        table_body! {
            schema_name = $schema_name,
            table_name = $name,
            primary_key_ty = $primary_key_ty,
            primary_key_expr = $primary_key_expr,
            columns = [$($column_name -> $Type; doc = [$($doc)*],)*
                       $new_column_name -> ($($ty_path)::*$(<$($ty_params)::*>)*); doc = [$($column_doc)*],],
            imports = ($($($import)::+),+),
            table_doc = [$($table_doc)*],
            current_column_doc = [],
            $($body)*
        }
    };

    // Parse a table column definition with a complex type
    //
    // This is identical to the previous branch, but we are capturing the whole
    // thing as a `ty` token.
    (
        schema_name = $schema_name:ident,
        table_name = $name:ident,
        primary_key_ty = $primary_key_ty:ty,
        primary_key_expr = $primary_key_expr:expr,
        columns = [$($column_name:ident -> $Type:tt; doc = [$($doc:expr)*],)*],
        imports = ($($($import:tt)::+),+),
        table_doc = [$($table_doc:expr)*],
        current_column_doc = [$($column_doc:expr)*],
        $new_column_name:ident -> $new_column_ty:ty,
        $($body:tt)*
    ) => {
        table_body! {
            schema_name = $schema_name,
            table_name = $name,
            primary_key_ty = $primary_key_ty,
            primary_key_expr = $primary_key_expr,
            columns = [$($column_name -> $Type; doc = [$($doc)*],)*
                       $new_column_name -> ($new_column_ty); doc = [$($column_doc)*],],
            imports = ($($($import)::+),+),
            table_doc = [$($table_doc)*],
            current_column_doc = [],
            $($body)*
        }
    };

    // Parse the table name  and the primary keys
    // Forward the table body to further parsing layers that parses
    // the column definitions
    (
        $schema_name:ident . $name:ident ($pk:ident) {
            $($body:tt)+
        }
        import = [$(use $($import:tt)::+;)+];
        table_doc = [$($table_doc:expr)*];
    ) => {
        table_body! {
            schema_name = $schema_name,
            table_name = $name,
            primary_key_ty = columns::$pk,
            primary_key_expr = columns::$pk,
            columns = [],
            imports = ($($($import)::+),+),
            table_doc = [$($table_doc)*],
            current_column_doc = [],
            $($body)+
        }
    };

    (
        $schema_name:ident . $name:ident ($($pk:ident,)+) {
            $($body:tt)+
        }
        import = [$(use $($import:tt)::+;)+];
        table_doc = [$($table_doc:expr)*];
    ) => {
        table_body! {
            schema_name = $schema_name,
            table_name = $name,
            primary_key_ty = ($(columns::$pk,)+),
            primary_key_expr = ($(columns::$pk,)+),
            columns = [],
            imports = ($($($import)::+),+),
            table_doc = [$($table_doc)*],
            current_column_doc = [],
            $($body)+
        }
    };

    // Finish parsing the table dsl. Now expand the parsed informations into
    // the corresponding rust code
    (
        schema_name = $schema_name:ident,
        table_name = $table_name:ident,
        primary_key_ty = $primary_key_ty:ty,
        primary_key_expr = $primary_key_expr:expr,
        columns = [$($column_name:ident -> ($($column_ty:tt)*); doc = [$($doc:expr)*] ,)+],
        imports = ($($($import:tt)::+),+),
        table_doc = [$($table_doc:expr)*],
        current_column_doc = [],
    ) => {
        $(
            #[doc=$table_doc]
        )*
        pub mod $table_name {
            #![allow(dead_code)]
            use $crate::{
                QuerySource,
                Table,
                JoinTo,
            };
            use $crate::associations::HasTable;
            use $crate::query_builder::*;
            use $crate::query_builder::nodes::Identifier;
            use $crate::query_source::{AppearsInFromClause, Once, Never};
            use $crate::query_source::joins::PleaseGenerateInverseJoinImpls;
            $(use $($import)::+;)+
            pub use self::columns::*;

            /// Re-exports all of the columns of this table, as well as the
            /// table struct renamed to the module name. This is meant to be
            /// glob imported for functions which only deal with one table.
            pub mod dsl {
                pub use super::columns::{$($column_name),+};
                pub use super::table as $table_name;
            }

            #[allow(non_upper_case_globals, dead_code)]
            /// A tuple of all of the columns on this table
            pub const all_columns: ($($column_name,)+) = ($($column_name,)+);

            #[allow(non_camel_case_types)]
            #[derive(Debug, Clone, Copy)]
            /// The actual table struct
            ///
            /// This is the type which provides the base methods of the query
            /// builder, such as `.select` and `.filter`.
            pub struct table;

            impl table {
                #[allow(dead_code)]
                /// Represents `table_name.*`, which is sometimes necessary
                /// for efficient count queries. It cannot be used in place of
                /// `all_columns`
                pub fn star(&self) -> star {
                    star
                }
            }

            /// The SQL type of all of the columns on this table
            pub type SqlType = ($($($column_ty)*,)+);

            /// Helper type for reperesenting a boxed query from this table
            pub type BoxedQuery<'a, DB, ST = SqlType> = BoxedSelectStatement<'a, ST, table, DB>;

            __diesel_table_query_source_impl!(table, $schema_name, $table_name);

            impl AsQuery for table {
                type SqlType = SqlType;
                type Query = SelectStatement<Self>;

                fn as_query(self) -> Self::Query {
                    SelectStatement::simple(self)
                }
            }

            impl Table for table {
                type PrimaryKey = $primary_key_ty;
                type AllColumns = ($($column_name,)+);

                fn primary_key(&self) -> Self::PrimaryKey {
                    $primary_key_expr
                }

                fn all_columns() -> Self::AllColumns {
                    ($($column_name,)+)
                }
            }

            impl HasTable for table {
                type Table = Self;

                fn table() -> Self::Table {
                    table
                }
            }

            impl IntoUpdateTarget for table {
                type WhereClause = <<Self as AsQuery>::Query as IntoUpdateTarget>::WhereClause;

                fn into_update_target(self) -> UpdateTarget<Self::Table, Self::WhereClause> {
                    self.as_query().into_update_target()
                }
            }

            impl AppearsInFromClause<table> for table {
                type Count = Once;
            }

            impl<T> AppearsInFromClause<T> for table where
                T: Table + JoinTo<table>,
            {
                type Count = Never;
            }

            impl<T> JoinTo<T> for table where
                T: JoinTo<table> + JoinTo<PleaseGenerateInverseJoinImpls<table>>,
            {
                type FromClause = T;
                type OnClause = <T as JoinTo<table>>::OnClause;

                fn join_target(rhs: T) -> (Self::FromClause, Self::OnClause) {
                    let (_, on_clause) = T::join_target(table);
                    (rhs, on_clause)
                }
            }

            impl_query_id!(table);

            /// Contains all of the columns of this table
            pub mod columns {
                use super::table;
                use $crate::{Expression, SelectableExpression, AppearsOnTable, QuerySource};
                use $crate::backend::Backend;
                use $crate::query_builder::{QueryFragment, AstPass, SelectStatement};
                use $crate::query_source::joins::{Join, JoinOn, Inner, LeftOuter};
                use $crate::query_source::{AppearsInFromClause, Once, Never};
                use $crate::result::QueryResult;
                $(use $($import)::+;)+

                #[allow(non_camel_case_types, dead_code)]
                #[derive(Debug, Clone, Copy)]
                /// Represents `table_name.*`, which is sometimes needed for
                /// efficient count queries. It cannot be used in place of
                /// `all_columns`, and has a `SqlType` of `()` to prevent it
                /// being used that way
                pub struct star;

                impl Expression for star {
                    type SqlType = ();
                }

                impl<DB: Backend> QueryFragment<DB> for star where
                    <table as QuerySource>::FromClause: QueryFragment<DB>,
                {
                    fn walk_ast(&self, mut out: AstPass<DB>) -> QueryResult<()> {
                        table.from_clause().walk_ast(out.reborrow())?;
                        out.push_sql(".*");
                        Ok(())
                    }
                }

                impl SelectableExpression<table> for star {
                }

                impl AppearsOnTable<table> for star {
                }

                $(__diesel_column!(table, $column_name -> ($($column_ty)*), $($doc),*);)+
            }
        }
    }
}

#[macro_export]
#[doc(hidden)]
macro_rules! __diesel_table_query_source_impl {
    ($table_struct:ident, public, $table_name:ident) => {
        impl QuerySource for $table_struct {
            type FromClause = Identifier<'static>;
            type DefaultSelection = <Self as Table>::AllColumns;

            fn from_clause(&self) -> Self::FromClause {
                Identifier(stringify!($table_name))
            }

            fn default_selection(&self) -> Self::DefaultSelection {
                Self::all_columns()
            }
        }
    };

    ($table_struct:ident, $schema_name:ident, $table_name:ident) => {
        impl QuerySource for $table_struct {
            type FromClause = $crate::query_builder::nodes::
                InfixNode<'static, Identifier<'static>, Identifier<'static>>;
            type DefaultSelection = <Self as Table>::AllColumns;

            fn from_clause(&self) -> Self::FromClause {
                $crate::query_builder::nodes::InfixNode::new(
                    Identifier(stringify!($schema_name)),
                    Identifier(stringify!($table_name)),
                    ".",
                )
            }

            fn default_selection(&self) -> Self::DefaultSelection {
                Self::all_columns()
            }
        }
    };
}

/// Allow two tables to be referenced in a join query.
///
/// # Example
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// # use diesel::prelude::*;
/// mod schema {
///    table! {
///         users(id) {
///             id -> Integer,
///         }
///     }
///     table! {
///         posts(id) {
///             id -> Integer,
///             user_id -> Integer,
///         }
///     }
///
/// }
///
/// joinable!(schema::posts -> schema::users(user_id));
///
/// # fn main() {
/// use schema::*;
///
/// // Without the joinable! call, this wouldn't compile
/// let query = users::table.inner_join(posts::table);
/// # }
/// ```
#[macro_export]
macro_rules! joinable {
    ($($child:ident)::* -> $($parent:ident)::* ($source:ident)) => {
        joinable_inner!($($child)::* ::table => $($parent)::* ::table : ($($child)::* ::$source = $($parent)::* ::table));
        joinable_inner!($($parent)::* ::table => $($child)::* ::table : ($($child)::* ::$source = $($parent)::* ::table));
    }
}

#[macro_export]
#[doc(hidden)]
macro_rules! joinable_inner {
    ($left_table:path => $right_table:path : ($foreign_key:path = $parent_table:path)) => {
        joinable_inner!(
            left_table_ty = $left_table,
            right_table_ty = $right_table,
            right_table_expr = $right_table,
            foreign_key = $foreign_key,
            primary_key_ty = <$parent_table as $crate::query_source::Table>::PrimaryKey,
            primary_key_expr = $parent_table.primary_key(),
        );
    };

    (
        left_table_ty = $left_table_ty:ty,
        right_table_ty = $right_table_ty:ty,
        right_table_expr = $right_table_expr:expr,
        foreign_key = $foreign_key:path,
        primary_key_ty = $primary_key_ty:ty,
        primary_key_expr = $primary_key_expr:expr,
    ) => {
        impl $crate::JoinTo<$right_table_ty> for $left_table_ty {
            type FromClause = $right_table_ty;
            type OnClause = $crate::expression::helper_types::Eq<
                $crate::expression::nullable::Nullable<$foreign_key>,
                $crate::expression::nullable::Nullable<$primary_key_ty>,
            >;

            fn join_target(rhs: $right_table_ty) -> (Self::FromClause, Self::OnClause) {
                use $crate::{ExpressionMethods, NullableExpressionMethods};

                (rhs, $foreign_key.nullable().eq($primary_key_expr.nullable()))
            }
        }
    }
}

/// Allow two tables which are otherwise unrelated to be used together in a
/// multi-table join. This macro only needs to be invoked when the two tables
/// don't have an association between them (e.g. parent to grandchild)
///
/// # Example
///
/// ```ignore
/// // This would be required to do `users.inner_join(posts.inner_join(comments))`
/// // if there were an association between users and posts, and an association
/// // between posts and comments, but no association between users and comments
/// enable_multi_table_joins!(users, comments);
/// ```
#[macro_export]
macro_rules! enable_multi_table_joins {
    ($left_mod:ident, $right_mod:ident) => {
        impl $crate::query_source::AppearsInFromClause<$left_mod::table>
            for $right_mod::table
        {
            type Count = $crate::query_source::Never;
        }

        impl $crate::query_source::AppearsInFromClause<$right_mod::table>
            for $left_mod::table
        {
            type Count = $crate::query_source::Never;
        }
    }
}

/// Takes a query `QueryFragment` expression as an argument and returns a string
/// of SQL with placeholders for the dynamic values.
///
/// # Example
///
/// ### Returning SQL from a count statment:
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// # table! {
/// #     users {
/// #         id -> Timestamp,
/// #         n -> Integer,
/// #     }
/// # }
/// # // example requires setup for users table
/// # use self::users::dsl::*;
/// # use diesel::*;
/// #
/// # fn main() {
/// let sql = debug_sql!(users.count());
/// assert_eq!(sql, "SELECT COUNT(*) FROM `users`");
/// # }
/// ```
#[macro_export]
macro_rules! debug_sql {
    ($query:expr) => {{
        use $crate::query_builder::{QueryFragment, QueryBuilder};
        use $crate::query_builder::debug::DebugQueryBuilder;
        let mut query_builder = DebugQueryBuilder::new();
        QueryFragment::<$crate::backend::Debug>::to_sql(&$query, &mut query_builder).unwrap();
        query_builder.finish()
    }};
}

/// Takes takes a query `QueryFragment` expression as an argument and prints out
/// the SQL with placeholders for the dynamic values.
///
/// # Example
///
/// ### Printing SQL from a count statment:
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// # table! {
/// #     users {
/// #         id -> Timestamp,
/// #         n -> Integer,
/// #     }
/// # }
/// # // example requires setup for users table
/// # use self::users::dsl::*;
/// # use diesel::*;
/// #
/// # fn main() {
/// print_sql!(users.count());
/// # }
/// ```
#[macro_export]
macro_rules! print_sql {
    ($query:expr) => {
        println!("{}", &debug_sql!($query));
    };
}

// The order of these modules is important (at least for those which have tests).
// Utililty macros which don't call any others need to come first.
#[macro_use] mod internal;
#[macro_use] mod parse;
#[macro_use] mod query_id;
#[macro_use] mod static_cond;
#[macro_use] mod macros_from_codegen;
#[macro_use] mod ops;

#[macro_use] mod as_changeset;
#[macro_use] mod associations;
#[macro_use] mod identifiable;
#[macro_use] mod insertable;

#[cfg(test)]
mod tests {
    use prelude::*;

    table! {
        foo.bars {
            id -> Integer,
            baz -> Text,
        }
    }

    mod my_types {
        pub struct MyCustomType;
    }

    table! {
        use types::*;
        use macros::tests::my_types::*;

        table_with_custom_types {
            id -> Integer,
            my_type -> MyCustomType,
        }
    }

    table! {
        use types::*;
        use macros::tests::my_types::*;

        /// Table documentation
        ///
        /// some in detail documentation
        table_with_custom_type_and_id (a) {
            /// Column documentation
            ///
            /// some more details
            a -> Integer,
            my_type -> MyCustomType,
        }
    }

    #[test]
    fn table_with_custom_schema() {
        let expected_sql = "SELECT `foo`.`bars`.`baz` FROM `foo`.`bars`";
        assert_eq!(expected_sql, debug_sql!(bars::table.select(bars::baz)));
    }

    table! {
        use types;
        use types::*;

        table_with_arbitrarily_complex_types {
            id -> types::Integer,
            qualified_nullable -> types::Nullable<types::Integer>,
            deeply_nested_type -> Option<Nullable<Integer>>,
            // This actually should work, but there appears to be a rustc bug
            // on the `AsExpression` bound for `EqAll` when the ty param is a projection
            // projected_type -> <Nullable<Integer> as types::IntoNullable>::Nullable,
            random_tuple -> (Integer, Integer),
        }
    }
}