diesel_derives/
lib.rs

1// Clippy lints
2#![allow(
3    clippy::needless_doctest_main,
4    clippy::needless_pass_by_value,
5    clippy::map_unwrap_or
6)]
7#![warn(
8    clippy::mut_mut,
9    clippy::non_ascii_literal,
10    clippy::similar_names,
11    clippy::unicode_not_nfc,
12    clippy::if_not_else,
13    clippy::items_after_statements,
14    clippy::used_underscore_binding,
15    missing_copy_implementations
16)]
17#![cfg_attr(feature = "nightly", feature(proc_macro_diagnostic))]
18
19extern crate diesel_table_macro_syntax;
20extern crate proc_macro;
21extern crate proc_macro2;
22extern crate quote;
23extern crate syn;
24
25use proc_macro::TokenStream;
26use sql_function::ExternSqlBlock;
27use syn::parse_quote;
28
29mod allow_tables_to_appear_in_same_query;
30mod attrs;
31mod deprecated;
32mod field;
33mod model;
34mod parsers;
35mod util;
36
37mod as_changeset;
38mod as_expression;
39mod associations;
40mod diesel_for_each_tuple;
41mod diesel_numeric_ops;
42mod diesel_public_if;
43mod from_sql_row;
44mod has_query;
45mod identifiable;
46mod insertable;
47mod multiconnection;
48mod query_id;
49mod queryable;
50mod queryable_by_name;
51mod selectable;
52mod sql_function;
53mod sql_type;
54mod table;
55#[cfg(test)]
56mod tests;
57mod valid_grouping;
58
59/// Implements `AsChangeset`
60///
61/// To implement `AsChangeset` this derive needs to know the corresponding table
62/// type. By default, it uses the `snake_case` type name with an added `s` from
63/// the current scope.
64/// It is possible to change this default by using `#[diesel(table_name = something)]`.
65///
66/// If a field name of your struct differs
67/// from the name of the corresponding column, you can annotate the field with
68/// `#[diesel(column_name = some_column_name)]`.
69///
70/// Your struct can also contain fields which implement `AsChangeset`. This is
71/// useful when you want to have one field map to more than one column (for
72/// example, an enum that maps to a label and a value column). Add
73/// `#[diesel(embed)]` to any such fields.
74///
75/// To provide custom serialization behavior for a field, you can use
76/// `#[diesel(serialize_as = SomeType)]`. If this attribute is present, Diesel
77/// will call `.into` on the corresponding field and serialize the instance of `SomeType`,
78/// rather than the actual field on your struct. This can be used to add custom behavior for a
79/// single field, or use types that are otherwise unsupported by Diesel.
80/// Normally, Diesel produces two implementations of the `AsChangeset` trait for your
81/// struct using this derive: one for an owned version and one for a borrowed version.
82/// Using `#[diesel(serialize_as)]` implies a conversion using `.into` which consumes the underlying value.
83/// Hence, once you use `#[diesel(serialize_as)]`, Diesel can no longer insert borrowed
84/// versions of your struct.
85///
86/// By default, any `Option` fields on the struct are skipped if their value is
87/// `None`. If you would like to assign `NULL` to the field instead, you can
88/// annotate your struct with `#[diesel(treat_none_as_null = true)]`.
89///
90/// # Attributes
91///
92/// ## Optional container attributes
93///
94/// * `#[diesel(treat_none_as_null = true)]`, specifies that
95///   the derive should treat `None` values as `NULL`. By default
96///   `Option::<T>::None` is just skipped. To insert a `NULL` using default
97///   behavior use `Option::<Option<T>>::Some(None)`
98/// * `#[diesel(table_name = path::to::table)]`, specifies a path to the table for which the
99///   current type is a changeset. The path is relative to the current module.
100///   If this attribute is not used, the type name converted to
101///   `snake_case` with an added `s` is used as table name.
102/// * `#[diesel(primary_key(id1, id2))]` to specify the struct field that
103///   that corresponds to the primary key. If not used, `id` will be
104///   assumed as primary key field
105///
106/// ## Optional field attributes
107///
108/// * `#[diesel(column_name = some_column_name)]`, overrides the column name
109///   of the current field to `some_column_name`. By default, the field
110///   name is used as column name.
111/// * `#[diesel(embed)]`, specifies that the current field maps not only
112///   to a single database field, but is a struct that implements `AsChangeset`.
113/// * `#[diesel(serialize_as = SomeType)]`, instead of serializing the actual
114///   field type, Diesel will convert the field into `SomeType` using `.into` and
115///   serialize that instead. By default, this derive will serialize directly using
116///   the actual field type.
117/// * `#[diesel(treat_none_as_null = true/false)]`, overrides the container-level
118///   `treat_none_as_null` attribute for the current field.
119/// * `#[diesel(skip_update)]`, skips updating this field. Useful for working with
120///   generated columns.
121#[cfg_attr(diesel_docsrs, doc = "\n# Expanded Code\n\n<details>\n<summary> Expanded Code </summary>\n\n\n### Without attributes\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(AsChangeset)]\nstruct User {\n    id: i32,\n    name: String,\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n    use diesel;\n    impl diesel::query_builder::AsChangeset for User {\n        type Target = users::table;\n        type Changeset = <(\n            diesel::dsl::Eq<users::r#name, String>,\n        ) as diesel::query_builder::AsChangeset>::Changeset;\n        fn as_changeset(\n            self,\n        ) -> <Self as diesel::query_builder::AsChangeset>::Changeset {\n            diesel::query_builder::AsChangeset::as_changeset((\n                diesel::ExpressionMethods::eq(users::r#name, self.name),\n            ))\n        }\n    }\n    impl<\'update> diesel::query_builder::AsChangeset for &\'update User {\n        type Target = users::table;\n        type Changeset = <(\n            diesel::dsl::Eq<users::r#name, &\'update String>,\n        ) as diesel::query_builder::AsChangeset>::Changeset;\n        fn as_changeset(\n            self,\n        ) -> <Self as diesel::query_builder::AsChangeset>::Changeset {\n            diesel::query_builder::AsChangeset::as_changeset((\n                diesel::ExpressionMethods::eq(users::r#name, &self.name),\n            ))\n        }\n    }\n};\n```\n\n\n### With `#[diesel(treat_none_as_null = true)]`\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(AsChangeset)]\n#[diesel(treat_none_as_null = true)]\nstruct User {\n    id: i32,\n    name: Option<String>,\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n    use diesel;\n    impl diesel::query_builder::AsChangeset for User {\n        type Target = users::table;\n        type Changeset = <(\n            diesel::dsl::Eq<users::r#name, Option<String>>,\n        ) as diesel::query_builder::AsChangeset>::Changeset;\n        fn as_changeset(\n            self,\n        ) -> <Self as diesel::query_builder::AsChangeset>::Changeset {\n            diesel::query_builder::AsChangeset::as_changeset((\n                diesel::ExpressionMethods::eq(users::r#name, self.name),\n            ))\n        }\n    }\n    impl<\'update> diesel::query_builder::AsChangeset for &\'update User {\n        type Target = users::table;\n        type Changeset = <(\n            diesel::dsl::Eq<users::r#name, &\'update Option<String>>,\n        ) as diesel::query_builder::AsChangeset>::Changeset;\n        fn as_changeset(\n            self,\n        ) -> <Self as diesel::query_builder::AsChangeset>::Changeset {\n            diesel::query_builder::AsChangeset::as_changeset((\n                diesel::ExpressionMethods::eq(users::r#name, &self.name),\n            ))\n        }\n    }\n};\n```\n\n\n### With `#[diesel(primary_key(id, short_code))]`\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(AsChangeset)]\n#[diesel(primary_key(id, short_code))]\nstruct User {\n    id: i32,\n    short_code: String,\n    name: String,\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n    use diesel;\n    impl diesel::query_builder::AsChangeset for User {\n        type Target = users::table;\n        type Changeset = <(\n            diesel::dsl::Eq<users::r#name, String>,\n        ) as diesel::query_builder::AsChangeset>::Changeset;\n        fn as_changeset(\n            self,\n        ) -> <Self as diesel::query_builder::AsChangeset>::Changeset {\n            diesel::query_builder::AsChangeset::as_changeset((\n                diesel::ExpressionMethods::eq(users::r#name, self.name),\n            ))\n        }\n    }\n    impl<\'update> diesel::query_builder::AsChangeset for &\'update User {\n        type Target = users::table;\n        type Changeset = <(\n            diesel::dsl::Eq<users::r#name, &\'update String>,\n        ) as diesel::query_builder::AsChangeset>::Changeset;\n        fn as_changeset(\n            self,\n        ) -> <Self as diesel::query_builder::AsChangeset>::Changeset {\n            diesel::query_builder::AsChangeset::as_changeset((\n                diesel::ExpressionMethods::eq(users::r#name, &self.name),\n            ))\n        }\n    }\n};\n```\n\n\n### With `#[diesel(table_name = crate::schema::users)]`\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(AsChangeset)]\n#[diesel(table_name = crate::schema::admin_users)]\nstruct User {\n    id: i32,\n    name: String,\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n    use diesel;\n    impl diesel::query_builder::AsChangeset for User {\n        type Target = crate::schema::admin_users::table;\n        type Changeset = <(\n            diesel::dsl::Eq<crate::schema::admin_users::r#name, String>,\n        ) as diesel::query_builder::AsChangeset>::Changeset;\n        fn as_changeset(\n            self,\n        ) -> <Self as diesel::query_builder::AsChangeset>::Changeset {\n            diesel::query_builder::AsChangeset::as_changeset((\n                diesel::ExpressionMethods::eq(\n                    crate::schema::admin_users::r#name,\n                    self.name,\n                ),\n            ))\n        }\n    }\n    impl<\'update> diesel::query_builder::AsChangeset for &\'update User {\n        type Target = crate::schema::admin_users::table;\n        type Changeset = <(\n            diesel::dsl::Eq<crate::schema::admin_users::r#name, &\'update String>,\n        ) as diesel::query_builder::AsChangeset>::Changeset;\n        fn as_changeset(\n            self,\n        ) -> <Self as diesel::query_builder::AsChangeset>::Changeset {\n            diesel::query_builder::AsChangeset::as_changeset((\n                diesel::ExpressionMethods::eq(\n                    crate::schema::admin_users::r#name,\n                    &self.name,\n                ),\n            ))\n        }\n    }\n};\n```\n\n\n### With `#[serialize_as = String]`\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(AsChangeset)]\nstruct User {\n    id: i32,\n    name: String,\n    #[diesel(serialize_as = String)]\n    age: i32,\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n    use diesel;\n    impl diesel::query_builder::AsChangeset for User {\n        type Target = users::table;\n        type Changeset = <(\n            diesel::dsl::Eq<users::r#name, String>,\n            diesel::dsl::Eq<users::r#age, String>,\n        ) as diesel::query_builder::AsChangeset>::Changeset;\n        fn as_changeset(\n            self,\n        ) -> <Self as diesel::query_builder::AsChangeset>::Changeset {\n            diesel::query_builder::AsChangeset::as_changeset((\n                diesel::ExpressionMethods::eq(users::r#name, self.name),\n                users::r#age.eq(::std::convert::Into::<String>::into(self.age)),\n            ))\n        }\n    }\n};\n```\n\n\n### With `#[diesel(embed)]`\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(AsChangeset)]\nstruct User {\n    id: i32,\n    name: String,\n    #[diesel(embed)]\n    post: Post,\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n    use diesel;\n    impl diesel::query_builder::AsChangeset for User {\n        type Target = users::table;\n        type Changeset = <(\n            diesel::dsl::Eq<users::r#name, String>,\n            Post,\n        ) as diesel::query_builder::AsChangeset>::Changeset;\n        fn as_changeset(\n            self,\n        ) -> <Self as diesel::query_builder::AsChangeset>::Changeset {\n            diesel::query_builder::AsChangeset::as_changeset((\n                diesel::ExpressionMethods::eq(users::r#name, self.name),\n                self.post,\n            ))\n        }\n    }\n    impl<\'update> diesel::query_builder::AsChangeset for &\'update User {\n        type Target = users::table;\n        type Changeset = <(\n            diesel::dsl::Eq<users::r#name, &\'update String>,\n            &\'update Post,\n        ) as diesel::query_builder::AsChangeset>::Changeset;\n        fn as_changeset(\n            self,\n        ) -> <Self as diesel::query_builder::AsChangeset>::Changeset {\n            diesel::query_builder::AsChangeset::as_changeset((\n                diesel::ExpressionMethods::eq(users::r#name, &self.name),\n                &self.post,\n            ))\n        }\n    }\n};\n```\n\n\n### With `#[diesel(column_name = username)]`\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(AsChangeset)]\nstruct User {\n    id: i32,\n    #[diesel(column_name = username)]\n    name: String,\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n    use diesel;\n    impl diesel::query_builder::AsChangeset for User {\n        type Target = users::table;\n        type Changeset = <(\n            diesel::dsl::Eq<users::r#username, String>,\n        ) as diesel::query_builder::AsChangeset>::Changeset;\n        fn as_changeset(\n            self,\n        ) -> <Self as diesel::query_builder::AsChangeset>::Changeset {\n            diesel::query_builder::AsChangeset::as_changeset((\n                diesel::ExpressionMethods::eq(users::r#username, self.name),\n            ))\n        }\n    }\n    impl<\'update> diesel::query_builder::AsChangeset for &\'update User {\n        type Target = users::table;\n        type Changeset = <(\n            diesel::dsl::Eq<users::r#username, &\'update String>,\n        ) as diesel::query_builder::AsChangeset>::Changeset;\n        fn as_changeset(\n            self,\n        ) -> <Self as diesel::query_builder::AsChangeset>::Changeset {\n            diesel::query_builder::AsChangeset::as_changeset((\n                diesel::ExpressionMethods::eq(users::r#username, &self.name),\n            ))\n        }\n    }\n};\n```\n\n\n### With `#[diesel(treat_none_as_null = true)]`\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(AsChangeset)]\nstruct User {\n    id: i32,\n    #[diesel(treat_none_as_null = true)]\n    name: Option<String>,\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n    use diesel;\n    impl diesel::query_builder::AsChangeset for User {\n        type Target = users::table;\n        type Changeset = <(\n            diesel::dsl::Eq<users::r#name, Option<String>>,\n        ) as diesel::query_builder::AsChangeset>::Changeset;\n        fn as_changeset(\n            self,\n        ) -> <Self as diesel::query_builder::AsChangeset>::Changeset {\n            diesel::query_builder::AsChangeset::as_changeset((\n                diesel::ExpressionMethods::eq(users::r#name, self.name),\n            ))\n        }\n    }\n    impl<\'update> diesel::query_builder::AsChangeset for &\'update User {\n        type Target = users::table;\n        type Changeset = <(\n            diesel::dsl::Eq<users::r#name, &\'update Option<String>>,\n        ) as diesel::query_builder::AsChangeset>::Changeset;\n        fn as_changeset(\n            self,\n        ) -> <Self as diesel::query_builder::AsChangeset>::Changeset {\n            diesel::query_builder::AsChangeset::as_changeset((\n                diesel::ExpressionMethods::eq(users::r#name, &self.name),\n            ))\n        }\n    }\n};\n```\n\n\n### With `#[diesel(skip_update)]`\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(AsChangeset)]\nstruct User {\n    id: i32,\n    #[diesel(skip_update)]\n    name: String,\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n    use diesel;\n    impl diesel::query_builder::AsChangeset for User {\n        type Target = users::table;\n        type Changeset = <() as diesel::query_builder::AsChangeset>::Changeset;\n        fn as_changeset(\n            self,\n        ) -> <Self as diesel::query_builder::AsChangeset>::Changeset {\n            diesel::query_builder::AsChangeset::as_changeset(())\n        }\n    }\n    impl<\'update> diesel::query_builder::AsChangeset for &\'update User {\n        type Target = users::table;\n        type Changeset = <() as diesel::query_builder::AsChangeset>::Changeset;\n        fn as_changeset(\n            self,\n        ) -> <Self as diesel::query_builder::AsChangeset>::Changeset {\n            diesel::query_builder::AsChangeset::as_changeset(())\n        }\n    }\n};\n```\n\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/as_changeset.md")))]
122#[cfg_attr(
123    all(not(feature = "without-deprecated"), feature = "with-deprecated"),
124    proc_macro_derive(
125        AsChangeset,
126        attributes(diesel, table_name, column_name, primary_key, changeset_options)
127    )
128)]
129#[cfg_attr(
130    any(feature = "without-deprecated", not(feature = "with-deprecated")),
131    proc_macro_derive(AsChangeset, attributes(diesel))
132)]
133pub fn derive_as_changeset(input: TokenStream) -> TokenStream {
134    derive_as_changeset_inner(input.into()).into()
135}
136
137fn derive_as_changeset_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
138    syn::parse2(input)
139        .and_then(as_changeset::derive)
140        .unwrap_or_else(syn::Error::into_compile_error)
141}
142
143/// Implements all required variants of `AsExpression`
144///
145/// This derive will generate the following impls:
146///
147/// - `impl AsExpression<SqlType> for YourType`
148/// - `impl AsExpression<Nullable<SqlType>> for YourType`
149/// - `impl AsExpression<SqlType> for &'a YourType`
150/// - `impl AsExpression<Nullable<SqlType>> for &'a YourType`
151/// - `impl AsExpression<SqlType> for &'a &'b YourType`
152/// - `impl AsExpression<Nullable<SqlType>> for &'a &'b YourType`
153///
154/// If your type is unsized,
155/// you can specify this by adding the annotation `#[diesel(not_sized)]`
156/// as attribute on the type. This will skip the impls for non-reference types.
157///
158/// Using this derive requires implementing the `ToSql` trait for your type.
159///
160/// # Attributes:
161///
162/// ## Required container attributes
163///
164/// * `#[diesel(sql_type = SqlType)]`, to specify the sql type of the
165///   generated implementations. If the attribute exists multiple times
166///   impls for each sql type is generated.
167///
168/// ## Optional container attributes
169///
170/// * `#[diesel(not_sized)]`, to skip generating impls that require
171///   that the type is `Sized`
172///
173#[cfg_attr(diesel_docsrs, doc = "\n# Expanded Code\n\n<details>\n<summary> Expanded Code </summary>\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(AsExpression)]\n#[diesel(sql_type = diesel::sql_type::Integer)]\nenum Foo {\n    Bar,\n    Baz,\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n    use diesel;\n    impl<\'__expr> diesel::expression::AsExpression<diesel::sql_type::Integer>\n    for &\'__expr Foo {\n        type Expression = diesel::internal::derives::as_expression::Bound<\n            diesel::sql_type::Integer,\n            Self,\n        >;\n        fn as_expression(\n            self,\n        ) -> <Self as diesel::expression::AsExpression<\n            diesel::sql_type::Integer,\n        >>::Expression {\n            diesel::internal::derives::as_expression::Bound::new(self)\n        }\n    }\n    impl<\n        \'__expr,\n    > diesel::expression::AsExpression<\n        diesel::sql_types::Nullable<diesel::sql_type::Integer>,\n    > for &\'__expr Foo {\n        type Expression = diesel::internal::derives::as_expression::Bound<\n            diesel::sql_types::Nullable<diesel::sql_type::Integer>,\n            Self,\n        >;\n        fn as_expression(\n            self,\n        ) -> <Self as diesel::expression::AsExpression<\n            diesel::sql_types::Nullable<diesel::sql_type::Integer>,\n        >>::Expression {\n            diesel::internal::derives::as_expression::Bound::new(self)\n        }\n    }\n    impl<\'__expr, \'__expr2> diesel::expression::AsExpression<diesel::sql_type::Integer>\n    for &\'__expr2 &\'__expr Foo {\n        type Expression = diesel::internal::derives::as_expression::Bound<\n            diesel::sql_type::Integer,\n            Self,\n        >;\n        fn as_expression(\n            self,\n        ) -> <Self as diesel::expression::AsExpression<\n            diesel::sql_type::Integer,\n        >>::Expression {\n            diesel::internal::derives::as_expression::Bound::new(self)\n        }\n    }\n    impl<\n        \'__expr,\n        \'__expr2,\n    > diesel::expression::AsExpression<\n        diesel::sql_types::Nullable<diesel::sql_type::Integer>,\n    > for &\'__expr2 &\'__expr Foo {\n        type Expression = diesel::internal::derives::as_expression::Bound<\n            diesel::sql_types::Nullable<diesel::sql_type::Integer>,\n            Self,\n        >;\n        fn as_expression(\n            self,\n        ) -> <Self as diesel::expression::AsExpression<\n            diesel::sql_types::Nullable<diesel::sql_type::Integer>,\n        >>::Expression {\n            diesel::internal::derives::as_expression::Bound::new(self)\n        }\n    }\n    impl<\n        __DB,\n    > diesel::serialize::ToSql<\n        diesel::sql_types::Nullable<diesel::sql_type::Integer>,\n        __DB,\n    > for Foo\n    where\n        __DB: diesel::backend::Backend,\n        Self: diesel::serialize::ToSql<diesel::sql_type::Integer, __DB>,\n    {\n        fn to_sql<\'__b>(\n            &\'__b self,\n            out: &mut diesel::serialize::Output<\'__b, \'_, __DB>,\n        ) -> diesel::serialize::Result {\n            diesel::serialize::ToSql::<\n                diesel::sql_type::Integer,\n                __DB,\n            >::to_sql(self, out)\n        }\n    }\n    impl diesel::expression::AsExpression<diesel::sql_type::Integer> for Foo {\n        type Expression = diesel::internal::derives::as_expression::Bound<\n            diesel::sql_type::Integer,\n            Self,\n        >;\n        fn as_expression(\n            self,\n        ) -> <Self as diesel::expression::AsExpression<\n            diesel::sql_type::Integer,\n        >>::Expression {\n            diesel::internal::derives::as_expression::Bound::new(self)\n        }\n    }\n    impl diesel::expression::AsExpression<\n        diesel::sql_types::Nullable<diesel::sql_type::Integer>,\n    > for Foo {\n        type Expression = diesel::internal::derives::as_expression::Bound<\n            diesel::sql_types::Nullable<diesel::sql_type::Integer>,\n            Self,\n        >;\n        fn as_expression(\n            self,\n        ) -> <Self as diesel::expression::AsExpression<\n            diesel::sql_types::Nullable<diesel::sql_type::Integer>,\n        >>::Expression {\n            diesel::internal::derives::as_expression::Bound::new(self)\n        }\n    }\n};\n```\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/as_expression.md")))]
174#[cfg_attr(
175    all(not(feature = "without-deprecated"), feature = "with-deprecated"),
176    proc_macro_derive(AsExpression, attributes(diesel, sql_type))
177)]
178#[cfg_attr(
179    any(feature = "without-deprecated", not(feature = "with-deprecated")),
180    proc_macro_derive(AsExpression, attributes(diesel))
181)]
182pub fn derive_as_expression(input: TokenStream) -> TokenStream {
183    derive_as_expression_inner(input.into()).into()
184}
185
186fn derive_as_expression_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
187    syn::parse2(input)
188        .and_then(as_expression::derive)
189        .unwrap_or_else(syn::Error::into_compile_error)
190}
191
192/// Implement required traits for the associations API
193///
194/// This derive implements support for Diesel's associations api. Check the
195/// module level documentation of the `diesel::associations` module for details.
196///
197/// This derive generates the following impls:
198/// * `impl BelongsTo<Parent> for YourType`
199/// * `impl BelongsTo<&'a Parent> for YourType`
200///
201/// # Attributes
202///
203/// # Required container attributes
204///
205/// * `#[diesel(belongs_to(User))]`, to specify a child-to-parent relationship
206///   between the current type and the specified parent type (`User`).
207///   If this attribute is given multiple times, multiple relationships
208///   are generated. `#[diesel(belongs_to(User, foreign_key = mykey))]` variant
209///   allows us to specify the name of the foreign key. If the foreign key
210///   is not specified explicitly, the remote lower case type name with
211///   appended `_id` is used as a foreign key name. (`user_id` in this example
212///   case)
213///
214/// # Optional container attributes
215///
216/// * `#[diesel(table_name = path::to::table)]` specifies a path to the table this
217///   type belongs to. The path is relative to the current module.
218///   If this attribute is not used, the type name converted to
219///   `snake_case` with an added `s` is used as table name.
220///
221/// # Optional field attributes
222///
223/// * `#[diesel(column_name = some_column_name)]`, overrides the column the current
224///   field maps to `some_column_name`. By default, the field name is used
225///   as a column name.
226///
227#[cfg_attr(diesel_docsrs, doc = "\n# Expanded Code\n\n<details>\n<summary> Expanded Code </summary>\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(Associations)]\n#[diesel(belongs_to(User))]\nstruct Post {\n    id: i32,\n    title: String,\n    user_id: i32,\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n    use diesel;\n    impl<__FK> diesel::associations::BelongsTo<User> for Post\n    where\n        __FK: std::hash::Hash + std::cmp::Eq,\n        for<\'__a> &\'__a i32: std::convert::Into<::std::option::Option<&\'__a __FK>>,\n        for<\'__a> &\'__a User: diesel::associations::Identifiable<Id = &\'__a __FK>,\n    {\n        type ForeignKey = __FK;\n        type ForeignKeyColumn = posts::user_id;\n        fn foreign_key(&self) -> std::option::Option<&Self::ForeignKey> {\n            std::convert::Into::into(&self.user_id)\n        }\n        fn foreign_key_column() -> Self::ForeignKeyColumn {\n            posts::user_id\n        }\n    }\n    impl<__FK> diesel::associations::BelongsTo<&\'_ User> for Post\n    where\n        __FK: std::hash::Hash + std::cmp::Eq,\n        for<\'__a> &\'__a i32: std::convert::Into<::std::option::Option<&\'__a __FK>>,\n        for<\'__a> &\'__a User: diesel::associations::Identifiable<Id = &\'__a __FK>,\n    {\n        type ForeignKey = __FK;\n        type ForeignKeyColumn = posts::user_id;\n        fn foreign_key(&self) -> std::option::Option<&Self::ForeignKey> {\n            std::convert::Into::into(&self.user_id)\n        }\n        fn foreign_key_column() -> Self::ForeignKeyColumn {\n            posts::user_id\n        }\n    }\n};\n```\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/associations.md")))]
228#[cfg_attr(
229    all(not(feature = "without-deprecated"), feature = "with-deprecated"),
230    proc_macro_derive(Associations, attributes(diesel, belongs_to, column_name, table_name))
231)]
232#[cfg_attr(
233    any(feature = "without-deprecated", not(feature = "with-deprecated")),
234    proc_macro_derive(Associations, attributes(diesel, belongs_to, column_name, table_name))
235)]
236pub fn derive_associations(input: TokenStream) -> TokenStream {
237    derive_associations_inner(input.into()).into()
238}
239
240fn derive_associations_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
241    syn::parse2(input)
242        .and_then(associations::derive)
243        .unwrap_or_else(syn::Error::into_compile_error)
244}
245
246/// Implement numeric operators for the current query node
247#[proc_macro_derive(DieselNumericOps)]
248pub fn derive_diesel_numeric_ops(input: TokenStream) -> TokenStream {
249    derive_diesel_numeric_ops_inner(input.into()).into()
250}
251
252fn derive_diesel_numeric_ops_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
253    syn::parse2(input)
254        .map(diesel_numeric_ops::derive)
255        .unwrap_or_else(syn::Error::into_compile_error)
256}
257
258/// Implements `Queryable` for types that correspond to a single SQL type. The type must implement `FromSql`.
259///
260/// This derive is mostly useful to implement support deserializing
261/// into rust types not supported by Diesel itself.
262///
263/// There are no options or special considerations needed for this derive.
264///
265#[cfg_attr(diesel_docsrs, doc = "\n# Expanded Code\n\n<details>\n<summary> Expanded Code </summary>\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(FromSqlRow)]\nenum Foo {\n    Bar,\n    Baz,\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n    use diesel;\n    impl<__DB, __ST> diesel::deserialize::Queryable<__ST, __DB> for Foo\n    where\n        __DB: diesel::backend::Backend,\n        __ST: diesel::sql_types::SingleValue,\n        Self: diesel::deserialize::FromSql<__ST, __DB>,\n    {\n        type Row = Self;\n        fn build(row: Self) -> diesel::deserialize::Result<Self> {\n            diesel::deserialize::Result::Ok(row)\n        }\n    }\n};\n```\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/from_sql_row.md")))]
266#[proc_macro_derive(FromSqlRow, attributes(diesel))]
267pub fn derive_from_sql_row(input: TokenStream) -> TokenStream {
268    derive_from_sql_row_inner(input.into()).into()
269}
270
271fn derive_from_sql_row_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
272    syn::parse2(input)
273        .and_then(from_sql_row::derive)
274        .unwrap_or_else(syn::Error::into_compile_error)
275}
276
277/// Implements `Identifiable` for references of the current type
278///
279/// By default, the primary key field is assumed to be a single field called `id`.
280/// If it isn't, you can put `#[diesel(primary_key(your_id))]` on your struct.
281/// If you have a composite primary key, the syntax is `#[diesel(primary_key(id1, id2))]`.
282///
283/// By default, `#[derive(Identifiable)]` will assume that your table is
284/// in scope and its name is the plural form of your struct name.
285/// Diesel uses basic pluralization rules.
286/// It only adds an `s` to the end, and converts `CamelCase` to `snake_case`.
287/// If your table name doesn't follow this convention or is not in scope,
288/// you can specify a path to the table with `#[diesel(table_name = path::to::table)]`.
289/// Our rules for inferring table names are considered public API.
290/// It will never change without a major version bump.
291///
292/// This derive generates the following impls:
293/// * `impl Identifiable for &'a YourType`
294/// * `impl Identifiable for &'_ &'a YourType`
295///
296/// # Attributes
297///
298/// ## Optional container attributes
299///
300/// * `#[diesel(table_name = path::to::table)]` specifies a path to the table this
301///   type belongs to. The path is relative to the current module.
302///   If this attribute is not used, the type name converted to
303///   `snake_case` with an added `s` is used as table name
304/// * `#[diesel(primary_key(id1, id2))]` to specify the struct field that
305///   that corresponds to the primary key. If not used, `id` will be
306///   assumed as primary key field
307///
308/// # Optional field attributes
309///
310/// * `#[diesel(column_name = some_column_name)]`, overrides the column the current
311///   field maps to `some_column_name`. By default, the field name is used
312///   as a column name.
313///
314#[cfg_attr(diesel_docsrs, doc = "\n# Expanded Code\n\n<details>\n<summary> Expanded Code </summary>\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(Identifiable)]\nstruct User {\n    id: i32,\n    name: String,\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n    use diesel;\n    impl diesel::associations::HasTable for User {\n        type Table = users::table;\n        fn table() -> <Self as diesel::associations::HasTable>::Table {\n            users::table\n        }\n    }\n    impl<\'ident> diesel::associations::Identifiable for &\'ident User {\n        type Id = (&\'ident i32);\n        fn id(self) -> <Self as diesel::associations::Identifiable>::Id {\n            (&self.id)\n        }\n    }\n    impl<\'ident> diesel::associations::Identifiable for &\'_ &\'ident User {\n        type Id = (&\'ident i32);\n        fn id(self) -> <Self as diesel::associations::Identifiable>::Id {\n            (&self.id)\n        }\n    }\n};\n```\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/identifiable.md")))]
315#[cfg_attr(
316    all(not(feature = "without-deprecated"), feature = "with-deprecated"),
317    proc_macro_derive(Identifiable, attributes(diesel, table_name, column_name, primary_key))
318)]
319#[cfg_attr(
320    any(feature = "without-deprecated", not(feature = "with-deprecated")),
321    proc_macro_derive(Identifiable, attributes(diesel))
322)]
323pub fn derive_identifiable(input: TokenStream) -> TokenStream {
324    derive_identifiable_inner(input.into()).into()
325}
326
327fn derive_identifiable_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
328    syn::parse2(input)
329        .and_then(identifiable::derive)
330        .unwrap_or_else(syn::Error::into_compile_error)
331}
332
333/// Implements `Insertable`
334///
335/// To implement `Insertable` this derive needs to know the corresponding table
336/// type. By default, it uses the `snake_case` type name with an added `s`
337/// from the current scope.
338/// It is possible to change this default by using `#[diesel(table_name = something)]`.
339/// If `table_name` attribute is given multiple times, impls for each table are generated.
340///
341/// If a field name of your
342/// struct differs from the name of the corresponding column,
343/// you can annotate the field with `#[diesel(column_name = some_column_name)]`.
344///
345/// Your struct can also contain fields which implement `Insertable`. This is
346/// useful when you want to have one field map to more than one column (for
347/// example, an enum that maps to a label and a value column). Add
348/// `#[diesel(embed)]` to any such fields.
349///
350/// To provide custom serialization behavior for a field, you can use
351/// `#[diesel(serialize_as = SomeType)]`. If this attribute is present, Diesel
352/// will call `.into` on the corresponding field and serialize the instance of `SomeType`,
353/// rather than the actual field on your struct. This can be used to add custom behavior for a
354/// single field, or use types that are otherwise unsupported by Diesel.
355/// Using `#[diesel(serialize_as)]` is **incompatible** with `#[diesel(embed)]`.
356/// Normally, Diesel produces two implementations of the `Insertable` trait for your
357/// struct using this derive: one for an owned version and one for a borrowed version.
358/// Using `#[diesel(serialize_as)]` implies a conversion using `.into` which consumes the underlying value.
359/// Hence, once you use `#[diesel(serialize_as)]`, Diesel can no longer insert borrowed
360/// versions of your struct.
361///
362/// # Attributes
363///
364/// ## Optional container attributes
365///
366/// * `#[diesel(table_name = path::to::table)]`, specifies a path to the table this type
367///   is insertable into. The path is relative to the current module.
368///   If this attribute is not used, the type name converted to
369///   `snake_case` with an added `s` is used as table name
370/// * `#[diesel(treat_none_as_default_value = false)]`, specifies that `None` values
371///   should be converted to `NULL` values on the SQL side instead of being treated as `DEFAULT`
372///   value primitive. *Note*: This option may control if your query is stored in the
373///   prepared statement cache or not*
374///
375/// ## Optional field attributes
376///
377/// * `#[diesel(column_name = some_column_name)]`, overrides the column the current
378///   field maps to `some_column_name`. By default, the field name is used
379///   as column name
380/// * `#[diesel(embed)]`, specifies that the current field maps not only
381///   to a single database field, but is a struct that implements `Insertable`
382/// * `#[diesel(serialize_as = SomeType)]`, instead of serializing the actual
383///   field type, Diesel will convert the field into `SomeType` using `.into` and
384///   serialize that instead. By default, this derive will serialize directly using
385///   the actual field type.
386/// * `#[diesel(treat_none_as_default_value = true/false)]`, overrides the container-level
387///   `treat_none_as_default_value` attribute for the current field.
388/// * `#[diesel(skip_insertion)]`, skips insertion of this field. Useful for working with
389///   generated columns.
390///
391/// # Examples
392///
393/// If we want to customize the serialization during insert, we can use `#[diesel(serialize_as)]`.
394///
395/// ```rust
396/// # extern crate diesel;
397/// # extern crate dotenvy;
398/// # include!("../../diesel/src/doctest_setup.rs");
399/// # use diesel::{prelude::*, serialize::{ToSql, Output, self}, deserialize::{FromSqlRow}, expression::AsExpression, sql_types, backend::Backend};
400/// # use schema::users;
401/// # use std::io::Write;
402/// #
403/// #[derive(Debug, FromSqlRow, AsExpression)]
404/// #[diesel(sql_type = sql_types::Text)]
405/// struct UppercaseString(pub String);
406///
407/// impl Into<UppercaseString> for String {
408///     fn into(self) -> UppercaseString {
409///         UppercaseString(self.to_uppercase())
410///     }
411/// }
412///
413/// impl<DB> ToSql<sql_types::Text, DB> for UppercaseString
414///     where
415///         DB: Backend,
416///         String: ToSql<sql_types::Text, DB>,
417/// {
418///     fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> serialize::Result {
419///         self.0.to_sql(out)
420///     }
421/// }
422///
423/// #[derive(Insertable, PartialEq, Debug)]
424/// #[diesel(table_name = users)]
425/// struct InsertableUser {
426///     id: i32,
427///     #[diesel(serialize_as = UppercaseString)]
428///     name: String,
429/// }
430///
431/// # fn main() {
432/// #     run_test();
433/// # }
434/// #
435/// # fn run_test() -> QueryResult<()> {
436/// #     use schema::users::dsl::*;
437/// #     let connection = &mut connection_no_data();
438/// #     diesel::sql_query("CREATE TEMPORARY TABLE users (id INTEGER PRIMARY KEY, name VARCHAR(255) NOT NULL)")
439/// #         .execute(connection)
440/// #         .unwrap();
441/// let user = InsertableUser {
442///     id: 1,
443///     name: "thomas".to_string(),
444/// };
445///
446/// diesel::insert_into(users)
447///     .values(user)
448///     .execute(connection)
449///     .unwrap();
450///
451/// assert_eq!(
452///     Ok("THOMAS".to_string()),
453///     users.select(name).first(connection)
454/// );
455/// # Ok(())
456/// # }
457/// ```
458///
459#[cfg_attr(diesel_docsrs, doc = "\n# Expanded Code\n\n<details>\n<summary> Expanded Code </summary>\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(Insertable)]\nstruct User {\n    id: i32,\n    name: String,\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n    use diesel;\n    impl diesel::insertable::Insertable<users::table> for User\n    where\n        i32: diesel::expression::AsExpression<\n            <users::r#id as diesel::Expression>::SqlType,\n        >,\n        String: diesel::expression::AsExpression<\n            <users::r#name as diesel::Expression>::SqlType,\n        >,\n    {\n        type Values = <(\n            std::option::Option<diesel::dsl::Eq<users::r#id, i32>>,\n            std::option::Option<diesel::dsl::Eq<users::r#name, String>>,\n        ) as diesel::insertable::Insertable<users::table>>::Values;\n        fn values(\n            self,\n        ) -> <(\n            std::option::Option<diesel::dsl::Eq<users::r#id, i32>>,\n            std::option::Option<diesel::dsl::Eq<users::r#name, String>>,\n        ) as diesel::insertable::Insertable<users::table>>::Values {\n            diesel::insertable::Insertable::<\n                users::table,\n            >::values((\n                std::option::Option::Some(\n                    diesel::ExpressionMethods::eq(users::r#id, self.id),\n                ),\n                std::option::Option::Some(\n                    diesel::ExpressionMethods::eq(users::r#name, self.name),\n                ),\n            ))\n        }\n    }\n    impl<\'insert> diesel::insertable::Insertable<users::table> for &\'insert User\n    where\n        &\'insert i32: diesel::expression::AsExpression<\n            <users::r#id as diesel::Expression>::SqlType,\n        >,\n        &\'insert String: diesel::expression::AsExpression<\n            <users::r#name as diesel::Expression>::SqlType,\n        >,\n    {\n        type Values = <(\n            std::option::Option<diesel::dsl::Eq<users::r#id, &\'insert i32>>,\n            std::option::Option<diesel::dsl::Eq<users::r#name, &\'insert String>>,\n        ) as diesel::insertable::Insertable<users::table>>::Values;\n        fn values(\n            self,\n        ) -> <(\n            std::option::Option<diesel::dsl::Eq<users::r#id, &\'insert i32>>,\n            std::option::Option<diesel::dsl::Eq<users::r#name, &\'insert String>>,\n        ) as diesel::insertable::Insertable<users::table>>::Values {\n            diesel::insertable::Insertable::<\n                users::table,\n            >::values((\n                std::option::Option::Some(\n                    diesel::ExpressionMethods::eq(users::r#id, &self.id),\n                ),\n                std::option::Option::Some(\n                    diesel::ExpressionMethods::eq(users::r#name, &self.name),\n                ),\n            ))\n        }\n    }\n    impl diesel::internal::derives::insertable::UndecoratedInsertRecord<users::table>\n    for User {}\n};\n```\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/insertable.md")))]
460#[cfg_attr(
461    all(not(feature = "without-deprecated"), feature = "with-deprecated"),
462    proc_macro_derive(Insertable, attributes(diesel, table_name, column_name))
463)]
464#[cfg_attr(
465    any(feature = "without-deprecated", not(feature = "with-deprecated")),
466    proc_macro_derive(Insertable, attributes(diesel))
467)]
468pub fn derive_insertable(input: TokenStream) -> TokenStream {
469    derive_insertable_inner(input.into()).into()
470}
471
472fn derive_insertable_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
473    syn::parse2(input)
474        .and_then(insertable::derive)
475        .unwrap_or_else(syn::Error::into_compile_error)
476}
477
478/// Implements `QueryId`
479///
480/// For example, given this struct:
481///
482/// ```rust
483/// # extern crate diesel;
484/// #[derive(diesel::query_builder::QueryId)]
485/// pub struct And<Left, Right> {
486///     left: Left,
487///     right: Right,
488/// }
489/// ```
490///
491/// the following implementation will be generated
492///
493/// ```rust
494/// # extern crate diesel;
495/// # struct And<Left, Right>(Left, Right);
496/// # use diesel::query_builder::QueryId;
497/// impl<Left, Right> QueryId for And<Left, Right>
498/// where
499///     Left: QueryId,
500///     Right: QueryId,
501/// {
502///     type QueryId = And<Left::QueryId, Right::QueryId>;
503///
504///     const HAS_STATIC_QUERY_ID: bool = Left::HAS_STATIC_QUERY_ID && Right::HAS_STATIC_QUERY_ID;
505/// }
506/// ```
507///
508/// If the SQL generated by a struct is not uniquely identifiable by its type,
509/// meaning that `HAS_STATIC_QUERY_ID` should always be false,
510/// you shouldn't derive this trait.
511/// In that case, you should implement it manually instead.
512///
513#[cfg_attr(diesel_docsrs, doc = "\n# Expanded Code\n\n<details>\n<summary> Expanded Code </summary>\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(QueryId)]\nstruct Query;\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n    use diesel;\n    #[allow(non_camel_case_types)]\n    impl diesel::query_builder::QueryId for Query {\n        type QueryId = Query;\n        const HAS_STATIC_QUERY_ID: bool = true;\n        const IS_WINDOW_FUNCTION: bool = false;\n    }\n};\n```\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/query_id.md")))]
514#[proc_macro_derive(QueryId, attributes(diesel))]
515pub fn derive_query_id(input: TokenStream) -> TokenStream {
516    derive_query_id_inner(input.into()).into()
517}
518
519fn derive_query_id_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
520    syn::parse2(input)
521        .map(query_id::derive)
522        .unwrap_or_else(syn::Error::into_compile_error)
523}
524
525/// Implements `Queryable` to load the result of statically typed queries
526///
527/// This trait can only be derived for structs, not enums.
528///
529/// **Note**: When this trait is derived, it will assume that __all fields on
530/// your struct__ matches __all fields in the query__, including the order and
531/// count. This means that field order is significant if you're using
532/// `#[derive(Queryable)]`. __Field name has no effect__. If you see errors while
533/// loading data into a struct that derives `Queryable`: Consider using
534/// [`#[derive(Selectable)]`] + `#[diesel(check_for_backend(YourBackendType))]`
535/// to check for mismatching fields at compile-time.
536///
537/// To provide custom deserialization behavior for a field, you can use
538/// `#[diesel(deserialize_as = SomeType)]`. If this attribute is present, Diesel
539/// will deserialize the corresponding field into `SomeType`, rather than the
540/// actual field type on your struct and then call
541/// [`.try_into`](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into)
542/// to convert it to the actual field type. This can be used to add custom behavior for a
543/// single field, or use types that are otherwise unsupported by Diesel.
544/// (Note: all types that have `Into<T>` automatically implement `TryInto<T>`,
545/// for cases where your conversion is not fallible.)
546///
547/// # Attributes
548///
549/// ## Optional field attributes
550///
551/// * `#[diesel(deserialize_as = Type)]`, instead of deserializing directly
552///   into the field type, the implementation will deserialize into `Type`.
553///   Then `Type` is converted via
554///   `.try_into()` call into the field type. By default, this derive will deserialize directly into the field type
555///   The `try_into()` method can be provided by:
556///   + Implementing any of the [`TryInto`]/[`TryFrom`]/[`Into`]/[`From`] traits
557///   + Using an method on the type directly (Useful if it's not possible to implement the traits mentioned above
558///     due to the orphan rule)
559///
560/// [`TryInto`]: https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html
561/// [`TryFrom`]: https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html
562/// [`Into`]: https://doc.rust-lang.org/stable/std/convert/trait.Into.html
563/// [`From`]: https://doc.rust-lang.org/stable/std/convert/trait.From.html
564///
565/// # Examples
566///
567/// If we just want to map a query to our struct, we can use `derive`.
568///
569/// ```rust
570/// # extern crate diesel;
571/// # extern crate dotenvy;
572/// # include!("../../diesel/src/doctest_setup.rs");
573/// #
574/// #[derive(Queryable, PartialEq, Debug)]
575/// struct User {
576///     id: i32,
577///     name: String,
578/// }
579///
580/// # fn main() {
581/// #     run_test();
582/// # }
583/// #
584/// # fn run_test() -> QueryResult<()> {
585/// #     use schema::users::dsl::*;
586/// #     let connection = &mut establish_connection();
587/// let first_user = users.first(connection)?;
588/// let expected = User {
589///     id: 1,
590///     name: "Sean".into(),
591/// };
592/// assert_eq!(expected, first_user);
593/// #     Ok(())
594/// # }
595/// ```
596///
597/// If we want to do additional work during deserialization, we can use
598/// `deserialize_as` to use a different implementation.
599///
600/// ```rust
601/// # extern crate diesel;
602/// # extern crate dotenvy;
603/// # include!("../../diesel/src/doctest_setup.rs");
604/// #
605/// # use schema::users;
606/// # use diesel::backend::{self, Backend};
607/// # use diesel::deserialize::{self, Queryable, FromSql};
608/// # use diesel::sql_types::Text;
609/// #
610/// struct LowercaseString(String);
611///
612/// impl Into<String> for LowercaseString {
613///     fn into(self) -> String {
614///         self.0
615///     }
616/// }
617///
618/// impl<DB> Queryable<Text, DB> for LowercaseString
619/// where
620///     DB: Backend,
621///     String: FromSql<Text, DB>,
622/// {
623///     type Row = String;
624///
625///     fn build(s: String) -> deserialize::Result<Self> {
626///         Ok(LowercaseString(s.to_lowercase()))
627///     }
628/// }
629///
630/// #[derive(Queryable, PartialEq, Debug)]
631/// struct User {
632///     id: i32,
633///     #[diesel(deserialize_as = LowercaseString)]
634///     name: String,
635/// }
636///
637/// # fn main() {
638/// #     run_test();
639/// # }
640/// #
641/// # fn run_test() -> QueryResult<()> {
642/// #     use schema::users::dsl::*;
643/// #     let connection = &mut establish_connection();
644/// let first_user = users.first(connection)?;
645/// let expected = User {
646///     id: 1,
647///     name: "sean".into(),
648/// };
649/// assert_eq!(expected, first_user);
650/// #     Ok(())
651/// # }
652/// ```
653///
654/// Alternatively, we can implement the trait for our struct manually.
655///
656/// ```rust
657/// # extern crate diesel;
658/// # extern crate dotenvy;
659/// # include!("../../diesel/src/doctest_setup.rs");
660/// #
661/// use diesel::deserialize::{self, FromSqlRow, Queryable};
662/// use diesel::row::Row;
663/// use schema::users;
664///
665/// # /*
666/// type DB = diesel::sqlite::Sqlite;
667/// # */
668/// #[derive(PartialEq, Debug)]
669/// struct User {
670///     id: i32,
671///     name: String,
672/// }
673///
674/// impl Queryable<users::SqlType, DB> for User
675/// where
676///     (i32, String): FromSqlRow<users::SqlType, DB>,
677/// {
678///     type Row = (i32, String);
679///
680///     fn build((id, name): Self::Row) -> deserialize::Result<Self> {
681///         Ok(User {
682///             id,
683///             name: name.to_lowercase(),
684///         })
685///     }
686/// }
687///
688/// # fn main() {
689/// #     run_test();
690/// # }
691/// #
692/// # fn run_test() -> QueryResult<()> {
693/// #     use schema::users::dsl::*;
694/// #     let connection = &mut establish_connection();
695/// let first_user = users.first(connection)?;
696/// let expected = User {
697///     id: 1,
698///     name: "sean".into(),
699/// };
700/// assert_eq!(expected, first_user);
701/// #     Ok(())
702/// # }
703/// ```
704///
705#[cfg_attr(diesel_docsrs, doc = "\n# Expanded Code\n\n<details>\n<summary> Expanded Code </summary>\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(Queryable)]\nstruct User {\n    id: i32,\n    name: String,\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n    use diesel;\n    use diesel::row::{Row as _, Field as _};\n    impl<\n        __DB: diesel::backend::Backend,\n        __ST0,\n        __ST1,\n    > diesel::deserialize::Queryable<(__ST0, __ST1), __DB> for User\n    where\n        (i32, String): diesel::deserialize::FromStaticSqlRow<(__ST0, __ST1), __DB>,\n    {\n        type Row = (i32, String);\n        fn build(row: (i32, String)) -> diesel::deserialize::Result<Self> {\n            use std::convert::TryInto;\n            diesel::deserialize::Result::Ok(Self {\n                id: row.0.try_into()?,\n                name: row.1.try_into()?,\n            })\n        }\n    }\n};\n```\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/queryable.md")))]
706#[cfg_attr(
707    all(not(feature = "without-deprecated"), feature = "with-deprecated"),
708    proc_macro_derive(Queryable, attributes(diesel, column_name))
709)]
710#[cfg_attr(
711    any(feature = "without-deprecated", not(feature = "with-deprecated")),
712    proc_macro_derive(Queryable, attributes(diesel))
713)]
714pub fn derive_queryable(input: TokenStream) -> TokenStream {
715    derive_queryable_inner(input.into()).into()
716}
717
718fn derive_queryable_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
719    syn::parse2(input)
720        .and_then(queryable::derive)
721        .unwrap_or_else(syn::Error::into_compile_error)
722}
723
724/// Implements `QueryableByName` for untyped sql queries, such as that one generated
725/// by `sql_query`
726///
727/// To derive this trait, Diesel needs to know the SQL type of each field.
728/// It can get the data from the corresponding table type.
729/// It uses the `snake_case` type name with an added `s`.
730/// It is possible to change this default by using `#[diesel(table_name = something)]`.
731/// If you define use the table type, the SQL type will be
732/// `diesel::dsl::SqlTypeOf<table_name::column_name>`. In cases which there are no table type,
733/// you can do the same by annotating each field with `#[diesel(sql_type = SomeType)]`.
734///
735/// If the name of a field on your struct is different from the column in your
736/// `table!` declaration, or if you're deriving this trait on a tuple struct,
737/// you can annotate the field with `#[diesel(column_name = some_column)]`. For tuple
738/// structs, all fields must have this annotation.
739///
740/// If a field is another struct which implements `QueryableByName`,
741/// instead of a column, you can annotate that with `#[diesel(embed)]`.
742/// Then all fields contained by that inner struct are loaded into the embedded struct.
743///
744/// To provide custom deserialization behavior for a field, you can use
745/// `#[diesel(deserialize_as = SomeType)]`. If this attribute is present, Diesel
746/// will deserialize the corresponding field into `SomeType`, rather than the
747/// actual field type on your struct and then call `.into` to convert it to the
748/// actual field type. This can be used to add custom behavior for a
749/// single field, or use types that are otherwise unsupported by Diesel.
750///
751/// # Attributes
752///
753/// ## Optional container attributes
754///
755/// * `#[diesel(table_name = path::to::table)]`, to specify that this type contains
756///   columns for the specified table. The path is relative to the current module.
757///   If no field attributes are specified the derive will use the sql type of
758///   the corresponding column.
759/// * `#[diesel(check_for_backend(diesel::pg::Pg, diesel::mysql::Mysql))]`, instructs
760///   the derive to generate additional code to identify potential type mismatches.
761///   It accepts a list of backend types to check the types against. Using this option
762///   will result in much better error messages in cases where some types in your `QueryableByName`
763///   struct don't match. You need to specify the concrete database backend
764///   this specific struct is indented to be used with, as otherwise rustc can't correctly
765///   identify the required deserialization implementation.
766///
767/// ## Optional field attributes
768///
769/// * `#[diesel(column_name = some_column)]`, overrides the column name for
770///   a given field. If not set, the name of the field is used as a column
771///   name. This attribute is required on tuple structs, if
772///   `#[diesel(table_name = some_table)]` is used, otherwise it's optional.
773/// * `#[diesel(sql_type = SomeType)]`, assumes `SomeType` as sql type of the
774///   corresponding field. These attributes have precedence over all other
775///   variants to specify the sql type.
776/// * `#[diesel(deserialize_as = Type)]`, instead of deserializing directly
777///   into the field type, the implementation will deserialize into `Type`.
778///   Then `Type` is converted via `.into()` into the field type. By default,
779///   this derive will deserialize directly into the field type
780/// * `#[diesel(embed)]`, specifies that the current field maps not only
781///   a single database column, but it is a type that implements
782///   `QueryableByName` on its own
783///
784/// # Examples
785///
786/// If we just want to map a query to our struct, we can use `derive`.
787///
788/// ```rust
789/// # extern crate diesel;
790/// # extern crate dotenvy;
791/// # include!("../../diesel/src/doctest_setup.rs");
792/// # use schema::users;
793/// # use diesel::sql_query;
794/// #
795/// #[derive(QueryableByName, PartialEq, Debug)]
796/// struct User {
797///     id: i32,
798///     name: String,
799/// }
800///
801/// # fn main() {
802/// #     run_test();
803/// # }
804/// #
805/// # fn run_test() -> QueryResult<()> {
806/// #     let connection = &mut establish_connection();
807/// let first_user = sql_query("SELECT * FROM users ORDER BY id LIMIT 1").get_result(connection)?;
808/// let expected = User {
809///     id: 1,
810///     name: "Sean".into(),
811/// };
812/// assert_eq!(expected, first_user);
813/// #     Ok(())
814/// # }
815/// ```
816///
817/// If we want to do additional work during deserialization, we can use
818/// `deserialize_as` to use a different implementation.
819///
820/// ```rust
821/// # extern crate diesel;
822/// # extern crate dotenvy;
823/// # include!("../../diesel/src/doctest_setup.rs");
824/// # use diesel::sql_query;
825/// # use schema::users;
826/// # use diesel::backend::{self, Backend};
827/// # use diesel::deserialize::{self, FromSql};
828/// #
829/// struct LowercaseString(String);
830///
831/// impl Into<String> for LowercaseString {
832///     fn into(self) -> String {
833///         self.0
834///     }
835/// }
836///
837/// impl<DB, ST> FromSql<ST, DB> for LowercaseString
838/// where
839///     DB: Backend,
840///     String: FromSql<ST, DB>,
841/// {
842///     fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
843///         String::from_sql(bytes).map(|s| LowercaseString(s.to_lowercase()))
844///     }
845/// }
846///
847/// #[derive(QueryableByName, PartialEq, Debug)]
848/// struct User {
849///     id: i32,
850///     #[diesel(deserialize_as = LowercaseString)]
851///     name: String,
852/// }
853///
854/// # fn main() {
855/// #     run_test();
856/// # }
857/// #
858/// # fn run_test() -> QueryResult<()> {
859/// #     let connection = &mut establish_connection();
860/// let first_user = sql_query("SELECT * FROM users ORDER BY id LIMIT 1").get_result(connection)?;
861/// let expected = User {
862///     id: 1,
863///     name: "sean".into(),
864/// };
865/// assert_eq!(expected, first_user);
866/// #     Ok(())
867/// # }
868/// ```
869///
870/// The custom derive generates impls similar to the following one
871///
872/// ```rust
873/// # extern crate diesel;
874/// # extern crate dotenvy;
875/// # include!("../../diesel/src/doctest_setup.rs");
876/// # use schema::users;
877/// # use diesel::sql_query;
878/// # use diesel::deserialize::{self, QueryableByName, FromSql};
879/// # use diesel::row::NamedRow;
880/// # use diesel::backend::Backend;
881/// #
882/// #[derive(PartialEq, Debug)]
883/// struct User {
884///     id: i32,
885///     name: String,
886/// }
887///
888/// impl<DB> QueryableByName<DB> for User
889/// where
890///     DB: Backend,
891///     i32: FromSql<diesel::dsl::SqlTypeOf<users::id>, DB>,
892///     String: FromSql<diesel::dsl::SqlTypeOf<users::name>, DB>,
893/// {
894///     fn build<'a>(row: &impl NamedRow<'a, DB>) -> deserialize::Result<Self> {
895///         let id = NamedRow::get::<diesel::dsl::SqlTypeOf<users::id>, _>(row, "id")?;
896///         let name = NamedRow::get::<diesel::dsl::SqlTypeOf<users::name>, _>(row, "name")?;
897///
898///         Ok(Self { id, name })
899///     }
900/// }
901///
902/// # fn main() {
903/// #     run_test();
904/// # }
905/// #
906/// # fn run_test() -> QueryResult<()> {
907/// #     let connection = &mut establish_connection();
908/// let first_user = sql_query("SELECT * FROM users ORDER BY id LIMIT 1").get_result(connection)?;
909/// let expected = User {
910///     id: 1,
911///     name: "Sean".into(),
912/// };
913/// assert_eq!(expected, first_user);
914/// #     Ok(())
915/// # }
916/// ```
917///
918#[cfg_attr(diesel_docsrs, doc = "\n# Expanded Code\n\n<details>\n<summary> Expanded Code </summary>\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(QueryableByName)]\nstruct User {\n    id: i32,\n    name: String,\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n    use diesel;\n    impl<__DB: diesel::backend::Backend> diesel::deserialize::QueryableByName<__DB>\n    for User\n    where\n        i32: diesel::deserialize::FromSql<diesel::dsl::SqlTypeOf<users::r#id>, __DB>,\n        String: diesel::deserialize::FromSql<\n            diesel::dsl::SqlTypeOf<users::r#name>,\n            __DB,\n        >,\n    {\n        fn build<\'__a>(\n            row: &impl diesel::row::NamedRow<\'__a, __DB>,\n        ) -> diesel::deserialize::Result<Self> {\n            let mut id = {\n                let field = diesel::row::NamedRow::get::<\n                    diesel::dsl::SqlTypeOf<users::r#id>,\n                    i32,\n                >(row, \"id\")?;\n                <i32 as std::convert::Into<i32>>::into(field)\n            };\n            let mut name = {\n                let field = diesel::row::NamedRow::get::<\n                    diesel::dsl::SqlTypeOf<users::r#name>,\n                    String,\n                >(row, \"name\")?;\n                <String as std::convert::Into<String>>::into(field)\n            };\n            diesel::deserialize::Result::Ok(Self { id: id, name: name })\n        }\n    }\n};\n```\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/queryable_by_name.md")))]
919#[cfg_attr(
920    all(not(feature = "without-deprecated"), feature = "with-deprecated"),
921    proc_macro_derive(QueryableByName, attributes(diesel, table_name, column_name, sql_type))
922)]
923#[cfg_attr(
924    any(feature = "without-deprecated", not(feature = "with-deprecated")),
925    proc_macro_derive(QueryableByName, attributes(diesel))
926)]
927pub fn derive_queryable_by_name(input: TokenStream) -> TokenStream {
928    derive_queryable_by_name_inner(input.into()).into()
929}
930
931fn derive_queryable_by_name_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
932    syn::parse2(input)
933        .and_then(queryable_by_name::derive)
934        .unwrap_or_else(syn::Error::into_compile_error)
935}
936
937/// Implements `Selectable`
938///
939/// To implement `Selectable` this derive needs to know the corresponding table
940/// type. By default, it uses the `snake_case` type name with an added `s`.
941/// It is possible to change this default by using `#[diesel(table_name = something)]`.
942///
943/// If the name of a field on your struct is different from the column in your
944/// `table!` declaration, or if you're deriving this trait on a tuple struct,
945/// you can annotate the field with `#[diesel(column_name = some_column)]`. For tuple
946/// structs, all fields must have this annotation.
947///
948/// If a field is another struct which implements `Selectable`,
949/// instead of a column, you can annotate that with `#[diesel(embed)]`.
950/// Then all fields contained by that inner struct are selected as separate tuple.
951/// Fields from an inner struct can come from a different table, as long as the
952/// select clause is valid in the current query.
953///
954/// The derive enables using the `SelectableHelper::as_select` method to construct
955/// select clauses, in order to use LoadDsl, you might also check the
956/// `Queryable` trait and derive.
957///
958/// # Attributes
959///
960/// ## Type attributes
961///
962/// * `#[diesel(table_name = path::to::table)]`, specifies a path to the table for which the
963///   current type is selectable. The path is relative to the current module.
964///   If this attribute is not used, the type name converted to
965///   `snake_case` with an added `s` is used as table name.
966///
967/// ## Optional Type attributes
968///
969/// * `#[diesel(check_for_backend(diesel::pg::Pg, diesel::mysql::Mysql))]`, instructs
970///   the derive to generate additional code to identify potential type mismatches.
971///   It accepts a list of backend types to check the types against. Using this option
972///   will result in much better error messages in cases where some types in your `Queryable`
973///   struct don't match. You need to specify the concrete database backend
974///   this specific struct is indented to be used with, as otherwise rustc can't correctly
975///   identify the required deserialization implementation.
976///
977/// ## Field attributes
978///
979/// * `#[diesel(column_name = some_column)]`, overrides the column name for
980///   a given field. If not set, the name of the field is used as column
981///   name.
982/// * `#[diesel(embed)]`, specifies that the current field maps not only
983///   a single database column, but is a type that implements
984///   `Selectable` on its own
985/// * `#[diesel(select_expression = some_custom_select_expression)]`, overrides
986///   the entire select expression for the given field. It may be used to select with
987///   custom tuples, or specify `select_expression = my_table::some_field.is_not_null()`,
988///   or separate tables...
989///   It may be used in conjunction with `select_expression_type` (described below)
990/// * `#[diesel(select_expression_type = the_custom_select_expression_type]`, should be used
991///   in conjunction with `select_expression` (described above) if the type is too complex
992///   for diesel to infer it automatically. This will be required if select_expression is a custom
993///   function call that doesn't have the corresponding associated type defined at the same path.
994///   Example use (this would actually be inferred):
995///   `#[diesel(select_expression_type = dsl::IsNotNull<my_table::some_field>)]`
996///
997#[cfg_attr(diesel_docsrs, doc = "\n# Expanded Code\n\n<details>\n<summary> Expanded Code </summary>\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(Selectable)]\nstruct User {\n    id: i32,\n    name: String,\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n    use diesel;\n    use diesel::expression::Selectable;\n    impl<__DB: diesel::backend::Backend> Selectable<__DB> for User {\n        type SelectExpression = (users::r#id, users::r#name);\n        fn construct_selection() -> Self::SelectExpression {\n            (users::r#id, users::r#name)\n        }\n    }\n};\n```\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/selectable.md")))]
998#[proc_macro_derive(Selectable, attributes(diesel))]
999pub fn derive_selectable(input: TokenStream) -> TokenStream {
1000    derive_selectable_inner(input.into()).into()
1001}
1002
1003fn derive_selectable_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
1004    syn::parse2(input)
1005        .and_then(|i| selectable::derive(i, None))
1006        .unwrap_or_else(syn::Error::into_compile_error)
1007}
1008
1009/// Implement necessary traits for adding a new sql type
1010///
1011/// This trait implements all necessary traits to define a
1012/// new sql type. This is useful for adding support for unsupported
1013/// or custom types on the sql side. The sql type will be usable for
1014/// all backends you specified via the attributes listed below.
1015///
1016/// This derive will implement `NotNull`, `HasSqlType` and `SingleValue`.
1017/// When using this derive macro,
1018/// you need to specify how the type is represented on various backends.
1019/// You don't need to specify every backend,
1020/// only the ones supported by your type.
1021///
1022/// For PostgreSQL, add `#[diesel(postgres_type(name = "pg_type_name", schema = "pg_schema_name"))]`
1023/// or `#[diesel(postgres_type(oid = "some_oid", array_oid = "some_oid"))]` for
1024/// builtin types.
1025/// For MySQL, specify which variant of `MysqlType` should be used
1026/// by adding `#[diesel(mysql_type(name = "Variant"))]`.
1027/// For SQLite, specify which variant of `SqliteType` should be used
1028/// by adding `#[diesel(sqlite_type(name = "Variant"))]`.
1029///
1030/// # Attributes
1031///
1032/// ## Type attributes
1033///
1034/// * `#[diesel(postgres_type(name = "TypeName", schema = "public"))]` specifies support for
1035///   a postgresql type with the name `TypeName` in the schema `public`. Prefer this variant
1036///   for types with no stable OID (== everything but the builtin types). It is possible to leaf
1037///   of the `schema` part. In that case, Diesel defaults to the default postgres search path.
1038/// * `#[diesel(postgres_type(oid = 42, array_oid = 142))]`, specifies support for a
1039///   postgresql type with the given `oid` and `array_oid`. This variant
1040///   should only be used with types that have a stable OID.
1041/// * `#[diesel(sqlite_type(name = "TypeName"))]`, specifies support for a sqlite type
1042///   with the given name. `TypeName` needs to be one of the possible values
1043///   in `SqliteType`
1044/// * `#[diesel(mysql_type(name = "TypeName"))]`, specifies support for a mysql type
1045///   with the given name. `TypeName` needs to be one of the possible values
1046///   in `MysqlType`
1047///
1048#[cfg_attr(diesel_docsrs, doc = "\n# Expanded Code\n\n<details>\n<summary> Expanded Code </summary>\n\n\n### SQLite\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(SqlType)]\n#[diesel(sqlite_type(name = \"Integer\"))]\nstruct Integer;\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n    use diesel;\n    impl diesel::sql_types::SqlType for Integer {\n        type IsNull = diesel::sql_types::is_nullable::NotNull;\n        const IS_ARRAY: bool = false;\n    }\n    impl diesel::sql_types::SingleValue for Integer {}\n    impl diesel::sql_types::HasSqlType<Integer> for diesel::sqlite::Sqlite {\n        fn metadata(_: &mut ()) -> diesel::sqlite::SqliteType {\n            diesel::sqlite::SqliteType::Integer\n        }\n    }\n};\n```\n\n\n### PostgreSQL\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(SqlType)]\n#[diesel(postgres_type(oid = 42, array_oid = 142))]\nstruct Integer;\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n    use diesel;\n    impl diesel::sql_types::SqlType for Integer {\n        type IsNull = diesel::sql_types::is_nullable::NotNull;\n        const IS_ARRAY: bool = false;\n    }\n    impl diesel::sql_types::SingleValue for Integer {}\n    use diesel::pg::{PgMetadataLookup, PgTypeMetadata};\n    impl diesel::sql_types::HasSqlType<Integer> for diesel::pg::Pg {\n        fn metadata(_: &mut Self::MetadataLookup) -> PgTypeMetadata {\n            PgTypeMetadata::new(42, 142)\n        }\n    }\n};\n```\n\n\n### MySQL\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(SqlType)]\n#[diesel(mysql_type(name = \"Long\"))]\nstruct Integer;\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n    use diesel;\n    impl diesel::sql_types::SqlType for Integer {\n        type IsNull = diesel::sql_types::is_nullable::NotNull;\n        const IS_ARRAY: bool = false;\n    }\n    impl diesel::sql_types::SingleValue for Integer {}\n    impl diesel::sql_types::HasSqlType<Integer> for diesel::mysql::Mysql {\n        fn metadata(_: &mut ()) -> diesel::mysql::MysqlType {\n            diesel::mysql::MysqlType::Long\n        }\n    }\n};\n```\n\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/sql_type.md")))]
1049#[cfg_attr(
1050    all(not(feature = "without-deprecated"), feature = "with-deprecated"),
1051    proc_macro_derive(SqlType, attributes(diesel, postgres, sqlite_type, mysql_type))
1052)]
1053#[cfg_attr(
1054    any(feature = "without-deprecated", not(feature = "with-deprecated")),
1055    proc_macro_derive(SqlType, attributes(diesel))
1056)]
1057pub fn derive_sql_type(input: TokenStream) -> TokenStream {
1058    derive_sql_type_inner(input.into()).into()
1059}
1060
1061fn derive_sql_type_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
1062    syn::parse2(input)
1063        .and_then(sql_type::derive)
1064        .unwrap_or_else(syn::Error::into_compile_error)
1065}
1066
1067/// Implements `ValidGrouping`
1068///
1069/// This trait can be automatically derived for structs with no type parameters
1070/// which are never aggregate, as well as for structs which are `NonAggregate`
1071/// when all type parameters are `NonAggregate`. For example:
1072///
1073/// ```ignore
1074/// #[derive(ValidGrouping)]
1075/// struct LiteralOne;
1076///
1077/// #[derive(ValidGrouping)]
1078/// struct Plus<Lhs, Rhs>(Lhs, Rhs);
1079///
1080/// // The following impl will be generated:
1081///
1082/// impl<GroupByClause> ValidGrouping<GroupByClause> for LiteralOne {
1083///     type IsAggregate = is_aggregate::Never;
1084/// }
1085///
1086/// impl<Lhs, Rhs, GroupByClause> ValidGrouping<GroupByClause> for Plus<Lhs, Rhs>
1087/// where
1088///     Lhs: ValidGrouping<GroupByClause>,
1089///     Rhs: ValidGrouping<GroupByClause>,
1090///     Lhs::IsAggregate: MixedAggregates<Rhs::IsAggregate>,
1091/// {
1092///     type IsAggregate = <Lhs::IsAggregate as MixedAggregates<Rhs::IsAggregate>>::Output;
1093/// }
1094/// ```
1095///
1096/// For types which are always considered aggregate (such as an aggregate
1097/// function), annotate your struct with `#[diesel(aggregate)]` to set `IsAggregate`
1098/// explicitly to `is_aggregate::Yes`.
1099///
1100/// # Attributes
1101///
1102/// ## Optional container attributes
1103///
1104/// * `#[diesel(aggregate)]` for cases where the type represents an aggregating
1105///   SQL expression
1106///
1107#[cfg_attr(diesel_docsrs, doc = "\n# Expanded Code\n\n<details>\n<summary> Expanded Code </summary>\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(ValidGrouping)]\nstruct Query;\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n    use diesel;\n    impl<__GroupByClause> diesel::expression::ValidGrouping<__GroupByClause> for Query {\n        type IsAggregate = diesel::expression::is_aggregate::Never;\n    }\n};\n```\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/valid_grouping.md")))]
1108#[proc_macro_derive(ValidGrouping, attributes(diesel))]
1109pub fn derive_valid_grouping(input: TokenStream) -> TokenStream {
1110    derive_valid_grouping_inner(input.into()).into()
1111}
1112
1113fn derive_valid_grouping_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
1114    syn::parse2(input)
1115        .and_then(valid_grouping::derive)
1116        .unwrap_or_else(syn::Error::into_compile_error)
1117}
1118
1119/// Declare a sql function for use in your code.
1120///
1121/// Diesel only provides support for a very small number of SQL functions.
1122/// This macro enables you to add additional functions from the SQL standard,
1123/// as well as any custom functions your application might have.
1124///
1125/// This is a legacy variant of the [`#[declare_sql_function]`] attribute macro, which
1126/// should be preferred instead. It will generate the same code as the attribute macro
1127/// and also it will accept the same syntax as the other macro.
1128///
1129/// The syntax for this macro is very similar to that of a normal Rust function,
1130/// except the argument and return types will be the SQL types being used.
1131/// Typically, these types will come from [`diesel::sql_types`](../diesel/sql_types/index.html)
1132///
1133/// This macro will generate two items. A function with the name that you've
1134/// given, and a module with a helper type representing the return type of your
1135/// function. For example, this invocation:
1136///
1137/// ```ignore
1138/// define_sql_function!(fn lower(x: Text) -> Text);
1139/// ```
1140///
1141/// will generate this code:
1142///
1143/// ```ignore
1144/// pub fn lower<X>(x: X) -> lower<X> {
1145///     ...
1146/// }
1147///
1148/// pub type lower<X> = ...;
1149/// ```
1150///
1151/// Most attributes given to this macro will be put on the generated function
1152/// (including doc comments).
1153///
1154/// # Adding Doc Comments
1155///
1156/// ```no_run
1157/// # extern crate diesel;
1158/// # use diesel::*;
1159/// #
1160/// # table! { crates { id -> Integer, name -> VarChar, } }
1161/// #
1162/// use diesel::sql_types::Text;
1163///
1164/// define_sql_function! {
1165///     /// Represents the `canon_crate_name` SQL function, created in
1166///     /// migration ....
1167///     fn canon_crate_name(a: Text) -> Text;
1168/// }
1169///
1170/// # fn main() {
1171/// # use self::crates::dsl::*;
1172/// let target_name = "diesel";
1173/// crates.filter(canon_crate_name(name).eq(canon_crate_name(target_name)));
1174/// // This will generate the following SQL
1175/// // SELECT * FROM crates WHERE canon_crate_name(crates.name) = canon_crate_name($1)
1176/// # }
1177/// ```
1178///
1179/// # Special Attributes
1180///
1181/// There are a handful of special attributes that Diesel will recognize. They
1182/// are:
1183///
1184/// - `#[aggregate]`
1185///   - Indicates that this is an aggregate function, and that `NonAggregate`
1186///     shouldn't be implemented.
1187/// - `#[sql_name = "name"]`
1188///   - The SQL to be generated is different from the Rust name of the function.
1189///     This can be used to represent functions which can take many argument
1190///     types, or to capitalize function names.
1191///
1192#[cfg_attr(diesel_docsrs, doc = "\n# Expanded Code\n\n<details>\n<summary> Expanded Code </summary>\n\n\n\n#### Input\n\n```rust,ignore\ndefine_sql_function! {\n    fn lower(input : Text) -> Text;\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\n#[allow(non_camel_case_types)]\npub fn lower<input>(input: input) -> lower<input>\nwhere\n    input: diesel::expression::AsExpression<Text>,\n{\n    lower_utils::lower {\n        input: input.as_expression(),\n    }\n}\n#[allow(non_camel_case_types, non_snake_case)]\n///The return type of [`lower()`](fn@lower)\npub type lower<input> = lower_utils::lower<\n    <input as diesel::expression::AsExpression<Text>>::Expression,\n>;\n#[doc(hidden)]\n#[allow(non_camel_case_types, non_snake_case, unused_imports)]\npub(crate) mod lower_utils {\n    use diesel::{self, QueryResult};\n    use diesel::expression::{\n        AsExpression, Expression, SelectableExpression, AppearsOnTable, ValidGrouping,\n    };\n    use diesel::query_builder::{QueryFragment, AstPass};\n    use diesel::sql_types::*;\n    use diesel::internal::sql_functions::*;\n    use super::*;\n    #[derive(Debug, Clone, Copy, diesel::query_builder::QueryId)]\n    #[derive(diesel::sql_types::DieselNumericOps)]\n    pub struct lower<input> {\n        pub(super) input: input,\n    }\n    ///The return type of [`lower()`](fn@lower)\n    pub type HelperType<input> = lower<<input as AsExpression<Text>>::Expression>;\n    impl<input> Expression for lower<input>\n    where\n        (input): Expression,\n    {\n        type SqlType = Text;\n    }\n    impl<input, __DieselInternal> SelectableExpression<__DieselInternal> for lower<input>\n    where\n        input: SelectableExpression<__DieselInternal>,\n        Self: AppearsOnTable<__DieselInternal>,\n    {}\n    impl<input, __DieselInternal> AppearsOnTable<__DieselInternal> for lower<input>\n    where\n        input: AppearsOnTable<__DieselInternal>,\n        Self: Expression,\n    {}\n    impl<input, __DieselInternal> FunctionFragment<__DieselInternal> for lower<input>\n    where\n        __DieselInternal: diesel::backend::Backend,\n        input: QueryFragment<__DieselInternal>,\n    {\n        const FUNCTION_NAME: &\'static str = \"lower\";\n        #[allow(unused_assignments)]\n        fn walk_arguments<\'__b>(\n            &\'__b self,\n            mut out: AstPass<\'_, \'__b, __DieselInternal>,\n        ) -> QueryResult<()> {\n            let mut needs_comma = false;\n            if !self.input.is_noop(out.backend())? {\n                if needs_comma {\n                    out.push_sql(\", \");\n                }\n                self.input.walk_ast(out.reborrow())?;\n                needs_comma = true;\n            }\n            Ok(())\n        }\n    }\n    impl<input, __DieselInternal> QueryFragment<__DieselInternal> for lower<input>\n    where\n        __DieselInternal: diesel::backend::Backend,\n        input: QueryFragment<__DieselInternal>,\n    {\n        fn walk_ast<\'__b>(\n            &\'__b self,\n            mut out: AstPass<\'_, \'__b, __DieselInternal>,\n        ) -> QueryResult<()> {\n            out.push_sql(<Self as FunctionFragment<__DieselInternal>>::FUNCTION_NAME);\n            out.push_sql(\"(\");\n            self.walk_arguments(out.reborrow())?;\n            out.push_sql(\")\");\n            Ok(())\n        }\n    }\n    #[derive(ValidGrouping)]\n    pub struct __Derived<input>(input);\n    impl<input, __DieselInternal> ValidGrouping<__DieselInternal> for lower<input>\n    where\n        __Derived<input>: ValidGrouping<__DieselInternal>,\n    {\n        type IsAggregate = <__Derived<\n            input,\n        > as ValidGrouping<__DieselInternal>>::IsAggregate;\n    }\n    use diesel::sqlite::{Sqlite, SqliteConnection};\n    use diesel::serialize::ToSql;\n    use diesel::deserialize::{FromSqlRow, StaticallySizedRow};\n    #[allow(dead_code)]\n    /// Registers an implementation for this function on the given connection\n    ///\n    /// This function must be called for every `SqliteConnection` before\n    /// this SQL function can be used on SQLite. The implementation must be\n    /// deterministic (returns the same result given the same arguments). If\n    /// the function is nondeterministic, call\n    /// `register_nondeterministic_impl` instead.\n    pub fn register_impl<F, Ret, input>(\n        conn: &mut SqliteConnection,\n        f: F,\n    ) -> QueryResult<()>\n    where\n        F: Fn(input) -> Ret + std::panic::UnwindSafe + Send + \'static,\n        (input,): FromSqlRow<(Text,), Sqlite> + StaticallySizedRow<(Text,), Sqlite>,\n        Ret: ToSql<Text, Sqlite>,\n    {\n        conn.register_sql_function::<\n                (Text,),\n                Text,\n                _,\n                _,\n                _,\n            >(\"lower\", true, move |(input,)| f(input))\n    }\n    #[allow(dead_code)]\n    /// Registers an implementation for this function on the given connection\n    ///\n    /// This function must be called for every `SqliteConnection` before\n    /// this SQL function can be used on SQLite.\n    /// `register_nondeterministic_impl` should only be used if your\n    /// function can return different results with the same arguments (e.g.\n    /// `random`). If your function is deterministic, you should call\n    /// `register_impl` instead.\n    pub fn register_nondeterministic_impl<F, Ret, input>(\n        conn: &mut SqliteConnection,\n        mut f: F,\n    ) -> QueryResult<()>\n    where\n        F: FnMut(input) -> Ret + std::panic::UnwindSafe + Send + \'static,\n        (input,): FromSqlRow<(Text,), Sqlite> + StaticallySizedRow<(Text,), Sqlite>,\n        Ret: ToSql<Text, Sqlite>,\n    {\n        conn.register_sql_function::<\n                (Text,),\n                Text,\n                _,\n                _,\n                _,\n            >(\"lower\", false, move |(input,)| f(input))\n    }\n}\n```\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/define_sql_function.md")))]
1193#[proc_macro]
1194pub fn define_sql_function(input: TokenStream) -> TokenStream {
1195    define_sql_function_inner(input.into()).into()
1196}
1197
1198fn define_sql_function_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
1199    syn::parse2(input)
1200        .map(|input| sql_function::expand(<[_]>::into_vec(::alloc::boxed::box_new([input]))vec![input], false, false))
1201        .unwrap_or_else(syn::Error::into_compile_error)
1202}
1203
1204/// A legacy version of [`define_sql_function!`].
1205///
1206/// The difference is that it makes the helper type available in a module named the exact same as
1207/// the function:
1208///
1209/// ```ignore
1210/// sql_function!(fn lower(x: Text) -> Text);
1211/// ```
1212///
1213/// will generate this code:
1214///
1215/// ```ignore
1216/// pub fn lower<X>(x: X) -> lower::HelperType<X> {
1217///     ...
1218/// }
1219///
1220/// pub(crate) mod lower {
1221///     pub type HelperType<X> = ...;
1222/// }
1223/// ```
1224///
1225/// This turned out to be an issue for the support of the `auto_type` feature, which is why
1226/// [`define_sql_function!`] was introduced (and why this is deprecated).
1227///
1228/// SQL functions declared with this version of the macro will not be usable with `#[auto_type]`
1229/// or `Selectable` `select_expression` type inference.
1230#[deprecated(since = "2.2.0", note = "Use [`define_sql_function`] instead")]
1231#[proc_macro]
1232#[cfg(all(feature = "with-deprecated", not(feature = "without-deprecated")))]
1233pub fn sql_function_proc(input: TokenStream) -> TokenStream {
1234    sql_function_proc_inner(input.into()).into()
1235}
1236
1237#[cfg(all(feature = "with-deprecated", not(feature = "without-deprecated")))]
1238fn sql_function_proc_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
1239    syn::parse2(input)
1240        .map(|i| sql_function::expand(<[_]>::into_vec(::alloc::boxed::box_new([i]))vec![i], true, false))
1241        .unwrap_or_else(syn::Error::into_compile_error)
1242}
1243
1244/// This is an internal diesel macro that
1245/// helps to implement all traits for tuples of
1246/// various sizes
1247#[doc(hidden)]
1248#[proc_macro]
1249pub fn __diesel_for_each_tuple(input: TokenStream) -> TokenStream {
1250    __diesel_for_each_tuple_inner(input.into()).into()
1251}
1252
1253fn __diesel_for_each_tuple_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
1254    syn::parse2(input)
1255        .map(diesel_for_each_tuple::expand)
1256        .unwrap_or_else(syn::Error::into_compile_error)
1257}
1258
1259/// This is an internal diesel macro that
1260/// helps to restrict the visibility of an item based
1261/// on a feature flag
1262#[doc(hidden)]
1263#[proc_macro_attribute]
1264pub fn __diesel_public_if(attrs: TokenStream, input: TokenStream) -> TokenStream {
1265    __diesel_public_if_inner(attrs.into(), input.into()).into()
1266}
1267
1268fn __diesel_public_if_inner(
1269    attrs: proc_macro2::TokenStream,
1270    input: proc_macro2::TokenStream,
1271) -> proc_macro2::TokenStream {
1272    syn::parse2(input)
1273        .and_then(|input| syn::parse2(attrs).map(|a| (a, input)))
1274        .map(|(a, i)| diesel_public_if::expand(a, i))
1275        .unwrap_or_else(syn::Error::into_compile_error)
1276}
1277
1278/// Specifies that a table exists, and what columns it has. This will create a
1279/// new public module, with the same name, as the name of the table. In this
1280/// module, you will find a unit struct named `table`, and a unit struct with the
1281/// name of each column.
1282///
1283/// By default, this allows a maximum of 32 columns per table.
1284/// You can increase this limit to 64 by enabling the `64-column-tables` feature.
1285/// You can increase it to 128 by enabling the `128-column-tables` feature.
1286/// You can decrease it to 16 columns,
1287/// which improves compilation time,
1288/// by disabling the default features of Diesel.
1289/// Note that enabling 64 column tables or larger will substantially increase
1290/// the compile time of Diesel.
1291///
1292/// Example usage
1293/// -------------
1294///
1295/// ```rust
1296/// # extern crate diesel;
1297///
1298/// diesel::table! {
1299///     users {
1300///         id -> Integer,
1301///         name -> VarChar,
1302///         favorite_color -> Nullable<VarChar>,
1303///     }
1304/// }
1305/// ```
1306///
1307/// You may also specify a primary key if it is called something other than `id`.
1308/// Tables with no primary key aren't supported.
1309///
1310/// ```rust
1311/// # extern crate diesel;
1312///
1313/// diesel::table! {
1314///     users (non_standard_primary_key) {
1315///         non_standard_primary_key -> Integer,
1316///         name -> VarChar,
1317///         favorite_color -> Nullable<VarChar>,
1318///     }
1319/// }
1320/// ```
1321///
1322/// For tables with composite primary keys, list all the columns in the primary key.
1323///
1324/// ```rust
1325/// # extern crate diesel;
1326///
1327/// diesel::table! {
1328///     followings (user_id, post_id) {
1329///         user_id -> Integer,
1330///         post_id -> Integer,
1331///         favorited -> Bool,
1332///     }
1333/// }
1334/// # fn main() {
1335/// #     use diesel::prelude::Table;
1336/// #     use self::followings::dsl::*;
1337/// #     // Poor man's assert_eq! -- since this is type level this would fail
1338/// #     // to compile if the wrong primary key were generated
1339/// #     let (user_id {}, post_id {}) = followings.primary_key();
1340/// # }
1341/// ```
1342///
1343/// If you are using types that aren't from Diesel's core types, you can specify
1344/// which types to import.
1345///
1346/// ```
1347/// # extern crate diesel;
1348/// # mod diesel_full_text_search {
1349/// #     #[derive(diesel::sql_types::SqlType)]
1350/// #     pub struct TsVector;
1351/// # }
1352///
1353/// diesel::table! {
1354///     use diesel::sql_types::*;
1355/// #    use crate::diesel_full_text_search::*;
1356/// # /*
1357///     use diesel_full_text_search::*;
1358/// # */
1359///
1360///     posts {
1361///         id -> Integer,
1362///         title -> Text,
1363///         keywords -> TsVector,
1364///     }
1365/// }
1366/// # fn main() {}
1367/// ```
1368///
1369/// If you want to add documentation to the generated code, you can use the
1370/// following syntax:
1371///
1372/// ```
1373/// # extern crate diesel;
1374///
1375/// diesel::table! {
1376///     /// The table containing all blog posts
1377///     posts {
1378///         /// The post's unique id
1379///         id -> Integer,
1380///         /// The post's title
1381///         title -> Text,
1382///     }
1383/// }
1384/// ```
1385///
1386/// If you have a column with the same name as a Rust reserved keyword, you can use
1387/// the `sql_name` attribute like this:
1388///
1389/// ```
1390/// # extern crate diesel;
1391///
1392/// diesel::table! {
1393///     posts {
1394///         id -> Integer,
1395///         /// This column is named `mytype` but references the table `type` column.
1396///         #[sql_name = "type"]
1397///         mytype -> Text,
1398///     }
1399/// }
1400/// ```
1401///
1402/// This module will also contain several helper types:
1403///
1404/// dsl
1405/// ---
1406///
1407/// This simply re-exports the table, renamed to the same name as the module,
1408/// and each of the columns. This is useful to glob import when you're dealing
1409/// primarily with one table, to allow writing `users.filter(name.eq("Sean"))`
1410/// instead of `users::table.filter(users::name.eq("Sean"))`.
1411///
1412/// `all_columns`
1413/// -----------
1414///
1415/// A constant will be assigned called `all_columns`. This is what will be
1416/// selected if you don't otherwise specify a select clause. It's type will be
1417/// `table::AllColumns`. You can also get this value from the
1418/// `Table::all_columns` function.
1419///
1420/// star
1421/// ----
1422///
1423/// This will be the qualified "star" expression for this table (e.g.
1424/// `users.*`). Internally, we read columns by index, not by name, so this
1425/// column is not safe to read data out of, and it has had its SQL type set to
1426/// `()` to prevent accidentally using it as such. It is sometimes useful for
1427/// counting statements, however. It can also be accessed through the `Table.star()`
1428/// method.
1429///
1430/// `SqlType`
1431/// -------
1432///
1433/// A type alias called `SqlType` will be created. It will be the SQL type of
1434/// `all_columns`. The SQL type is needed for things like returning boxed
1435/// queries.
1436///
1437/// `BoxedQuery`
1438/// ----------
1439///
1440/// ```ignore
1441/// pub type BoxedQuery<'a, DB, ST = SqlType> = BoxedSelectStatement<'a, ST, table, DB>;
1442/// ```
1443///
1444#[cfg_attr(diesel_docsrs, doc = "\n# Expanded Code\n\n<details>\n<summary> Expanded Code </summary>\n\n\n\n#### Input\n\n```rust,ignore\ntable! {\n    users { id -> Integer, name -> Text, }\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\n#[allow(unused_imports, dead_code, unreachable_pub, unused_qualifications)]\npub mod users {\n    use ::diesel;\n    pub use self::columns::*;\n    use diesel::sql_types::*;\n    #[doc = concat!(\n        \"Re-exports all of the columns of this \", \"table\", \", as well as the\"\n    )]\n    #[doc = concat!(\"table\", \" struct renamed to the module name. This is meant to be\")]\n    #[doc = concat!(\n        \"glob imported for functions which only deal with one \", \"table\", \".\"\n    )]\n    pub mod dsl {\n        pub use super::columns::id;\n        pub use super::columns::name;\n        pub use super::table as users;\n    }\n    #[allow(non_upper_case_globals, dead_code)]\n    #[doc = concat!(\"A tuple of all of the columns on this\", \"table\")]\n    pub const all_columns: (id, name) = (id, name);\n    #[allow(non_camel_case_types)]\n    #[derive(\n        Debug,\n        Clone,\n        Copy,\n        diesel::query_builder::QueryId,\n        Default,\n        PartialEq,\n        Eq,\n        PartialOrd,\n        Ord,\n        Hash\n    )]\n    #[doc = concat!(\"The actual \", \"table\", \" struct\")]\n    ///\n    /// This is the type which provides the base methods of the query\n    /// builder, such as `.select` and `.filter`.\n    pub struct table;\n    impl table {\n        #[allow(dead_code)]\n        #[doc = concat!(\n            \"Represents `\", \"table\", \"_name.*`, which is sometimes necessary\"\n        )]\n        /// for efficient count queries. It cannot be used in place of\n        /// `all_columns`\n        pub fn star(&self) -> star {\n            star\n        }\n    }\n    #[doc = concat!(\"The SQL type of all of the columns on this \", \"table\")]\n    pub type SqlType = (Integer, Text);\n    #[doc = concat!(\"Helper type for representing a boxed query from this \", \"table\")]\n    pub type BoxedQuery<\'a, DB, ST = SqlType> = diesel::internal::table_macro::BoxedSelectStatement<\n        \'a,\n        ST,\n        diesel::internal::table_macro::FromClause<table>,\n        DB,\n    >;\n    impl diesel::QuerySource for table {\n        type FromClause = diesel::internal::table_macro::StaticQueryFragmentInstance<\n            table,\n        >;\n        type DefaultSelection = <Self as diesel::query_source::QueryRelation>::AllColumns;\n        fn from_clause(&self) -> Self::FromClause {\n            diesel::internal::table_macro::StaticQueryFragmentInstance::new()\n        }\n        fn default_selection(&self) -> Self::DefaultSelection {\n            <Self as diesel::query_source::QueryRelation>::all_columns()\n        }\n    }\n    impl diesel::internal::table_macro::PlainQuerySource for table {}\n    impl<DB> diesel::query_builder::QueryFragment<DB> for table\n    where\n        DB: diesel::backend::Backend,\n        <Self as diesel::internal::table_macro::StaticQueryFragment>::Component: diesel::query_builder::QueryFragment<\n            DB,\n        >,\n    {\n        fn walk_ast<\'b>(\n            &\'b self,\n            __diesel_internal_pass: diesel::query_builder::AstPass<\'_, \'b, DB>,\n        ) -> diesel::result::QueryResult<()> {\n            <Self as diesel::internal::table_macro::StaticQueryFragment>::STATIC_COMPONENT\n                .walk_ast(__diesel_internal_pass)\n        }\n    }\n    impl diesel::internal::table_macro::StaticQueryFragment for table {\n        type Component = diesel::internal::table_macro::Identifier<\'static>;\n        const STATIC_COMPONENT: &\'static Self::Component = &diesel::internal::table_macro::Identifier(\n            \"users\",\n        );\n    }\n    impl diesel::query_builder::AsQuery for table {\n        type SqlType = SqlType;\n        type Query = diesel::internal::table_macro::SelectStatement<\n            diesel::internal::table_macro::FromClause<Self>,\n        >;\n        fn as_query(self) -> Self::Query {\n            diesel::internal::table_macro::SelectStatement::simple(self)\n        }\n    }\n    impl diesel::Table for table {\n        type PrimaryKey = id;\n        type AllColumns = (id, name);\n        fn primary_key(&self) -> Self::PrimaryKey {\n            id\n        }\n        fn all_columns() -> Self::AllColumns {\n            (id, name)\n        }\n    }\n    impl diesel::associations::HasTable for table {\n        type Table = Self;\n        fn table() -> Self::Table {\n            table\n        }\n    }\n    impl diesel::query_builder::IntoUpdateTarget for table {\n        type WhereClause = <<Self as diesel::query_builder::AsQuery>::Query as diesel::query_builder::IntoUpdateTarget>::WhereClause;\n        fn into_update_target(\n            self,\n        ) -> diesel::query_builder::UpdateTarget<Self::Table, Self::WhereClause> {\n            use diesel::query_builder::AsQuery;\n            let q: diesel::internal::table_macro::SelectStatement<\n                diesel::internal::table_macro::FromClause<table>,\n            > = self.as_query();\n            q.into_update_target()\n        }\n    }\n    impl<T> diesel::insertable::Insertable<T> for table\n    where\n        <table as diesel::query_builder::AsQuery>::Query: diesel::insertable::Insertable<\n            T,\n        >,\n    {\n        type Values = <<table as diesel::query_builder::AsQuery>::Query as diesel::insertable::Insertable<\n            T,\n        >>::Values;\n        fn values(self) -> Self::Values {\n            use diesel::query_builder::AsQuery;\n            self.as_query().values()\n        }\n    }\n    impl<\'a, T> diesel::insertable::Insertable<T> for &\'a table\n    where\n        table: diesel::insertable::Insertable<T>,\n    {\n        type Values = <table as diesel::insertable::Insertable<T>>::Values;\n        fn values(self) -> Self::Values {\n            (*self).values()\n        }\n    }\n    impl diesel::query_source::AppearsInFromClause<Self> for table {\n        type Count = diesel::query_source::Once;\n    }\n    impl<S> diesel::internal::table_macro::AliasAppearsInFromClause<S, Self> for table\n    where\n        S: diesel::query_source::AliasSource<Target = Self>,\n    {\n        type Count = diesel::query_source::Never;\n    }\n    impl<\n        S1,\n        S2,\n    > diesel::internal::table_macro::AliasAliasAppearsInFromClause<Self, S2, S1>\n    for table\n    where\n        S1: diesel::query_source::AliasSource<Target = Self>,\n        S2: diesel::query_source::AliasSource<Target = Self>,\n        S1: diesel::internal::table_macro::AliasAliasAppearsInFromClauseSameTable<\n            S2,\n            Self,\n        >,\n    {\n        type Count = <S1 as diesel::internal::table_macro::AliasAliasAppearsInFromClauseSameTable<\n            S2,\n            Self,\n        >>::Count;\n    }\n    impl<S> diesel::query_source::AppearsInFromClause<diesel::query_source::Alias<S>>\n    for table\n    where\n        S: diesel::query_source::AliasSource,\n    {\n        type Count = diesel::query_source::Never;\n    }\n    impl<\n        S,\n        C,\n    > diesel::internal::table_macro::FieldAliasMapperAssociatedTypesDisjointnessTrick<\n        Self,\n        S,\n        C,\n    > for table\n    where\n        S: diesel::query_source::AliasSource<Target = Self> + ::std::clone::Clone,\n        C: diesel::query_source::QueryRelationField<QueryRelation = Self>,\n    {\n        type Out = diesel::query_source::AliasedField<S, C>;\n        fn map(\n            __diesel_internal_column: C,\n            __diesel_internal_alias: &diesel::query_source::Alias<S>,\n        ) -> Self::Out {\n            __diesel_internal_alias.field(__diesel_internal_column)\n        }\n    }\n    impl diesel::query_source::AppearsInFromClause<table>\n    for diesel::internal::table_macro::NoFromClause {\n        type Count = diesel::query_source::Never;\n    }\n    impl<\n        Left,\n        Right,\n        Kind,\n    > diesel::JoinTo<diesel::internal::table_macro::Join<Left, Right, Kind>> for table\n    where\n        diesel::internal::table_macro::Join<Left, Right, Kind>: diesel::JoinTo<Self>,\n        Left: diesel::query_source::QuerySource,\n        Right: diesel::query_source::QuerySource,\n    {\n        type FromClause = diesel::internal::table_macro::Join<Left, Right, Kind>;\n        type OnClause = <diesel::internal::table_macro::Join<\n            Left,\n            Right,\n            Kind,\n        > as diesel::JoinTo<Self>>::OnClause;\n        fn join_target(\n            __diesel_internal_rhs: diesel::internal::table_macro::Join<Left, Right, Kind>,\n        ) -> (Self::FromClause, Self::OnClause) {\n            let (_, __diesel_internal_on_clause) = diesel::internal::table_macro::Join::join_target(\n                Self,\n            );\n            (__diesel_internal_rhs, __diesel_internal_on_clause)\n        }\n    }\n    impl<Join, On> diesel::JoinTo<diesel::internal::table_macro::JoinOn<Join, On>>\n    for table\n    where\n        diesel::internal::table_macro::JoinOn<Join, On>: diesel::JoinTo<Self>,\n    {\n        type FromClause = diesel::internal::table_macro::JoinOn<Join, On>;\n        type OnClause = <diesel::internal::table_macro::JoinOn<\n            Join,\n            On,\n        > as diesel::JoinTo<Self>>::OnClause;\n        fn join_target(\n            __diesel_internal_rhs: diesel::internal::table_macro::JoinOn<Join, On>,\n        ) -> (Self::FromClause, Self::OnClause) {\n            let (_, __diesel_internal_on_clause) = diesel::internal::table_macro::JoinOn::join_target(\n                Self,\n            );\n            (__diesel_internal_rhs, __diesel_internal_on_clause)\n        }\n    }\n    impl<\n        F,\n        S,\n        D,\n        W,\n        O,\n        L,\n        Of,\n        G,\n    > diesel::JoinTo<\n        diesel::internal::table_macro::SelectStatement<\n            diesel::internal::table_macro::FromClause<F>,\n            S,\n            D,\n            W,\n            O,\n            L,\n            Of,\n            G,\n        >,\n    > for table\n    where\n        diesel::internal::table_macro::SelectStatement<\n            diesel::internal::table_macro::FromClause<F>,\n            S,\n            D,\n            W,\n            O,\n            L,\n            Of,\n            G,\n        >: diesel::JoinTo<Self>,\n        F: diesel::query_source::QuerySource,\n    {\n        type FromClause = diesel::internal::table_macro::SelectStatement<\n            diesel::internal::table_macro::FromClause<F>,\n            S,\n            D,\n            W,\n            O,\n            L,\n            Of,\n            G,\n        >;\n        type OnClause = <diesel::internal::table_macro::SelectStatement<\n            diesel::internal::table_macro::FromClause<F>,\n            S,\n            D,\n            W,\n            O,\n            L,\n            Of,\n            G,\n        > as diesel::JoinTo<Self>>::OnClause;\n        fn join_target(\n            __diesel_internal_rhs: diesel::internal::table_macro::SelectStatement<\n                diesel::internal::table_macro::FromClause<F>,\n                S,\n                D,\n                W,\n                O,\n                L,\n                Of,\n                G,\n            >,\n        ) -> (Self::FromClause, Self::OnClause) {\n            let (_, __diesel_internal_on_clause) = diesel::internal::table_macro::SelectStatement::join_target(\n                Self,\n            );\n            (__diesel_internal_rhs, __diesel_internal_on_clause)\n        }\n    }\n    impl<\n        \'a,\n        QS,\n        ST,\n        DB,\n    > diesel::JoinTo<\n        diesel::internal::table_macro::BoxedSelectStatement<\n            \'a,\n            diesel::internal::table_macro::FromClause<QS>,\n            ST,\n            DB,\n        >,\n    > for table\n    where\n        diesel::internal::table_macro::BoxedSelectStatement<\n            \'a,\n            diesel::internal::table_macro::FromClause<QS>,\n            ST,\n            DB,\n        >: diesel::JoinTo<Self>,\n        QS: diesel::query_source::QuerySource,\n    {\n        type FromClause = diesel::internal::table_macro::BoxedSelectStatement<\n            \'a,\n            diesel::internal::table_macro::FromClause<QS>,\n            ST,\n            DB,\n        >;\n        type OnClause = <diesel::internal::table_macro::BoxedSelectStatement<\n            \'a,\n            diesel::internal::table_macro::FromClause<QS>,\n            ST,\n            DB,\n        > as diesel::JoinTo<Self>>::OnClause;\n        fn join_target(\n            __diesel_internal_rhs: diesel::internal::table_macro::BoxedSelectStatement<\n                \'a,\n                diesel::internal::table_macro::FromClause<QS>,\n                ST,\n                DB,\n            >,\n        ) -> (Self::FromClause, Self::OnClause) {\n            let (_, __diesel_internal_on_clause) = diesel::internal::table_macro::BoxedSelectStatement::join_target(\n                Self,\n            );\n            (__diesel_internal_rhs, __diesel_internal_on_clause)\n        }\n    }\n    impl<S> diesel::JoinTo<diesel::query_source::Alias<S>> for table\n    where\n        diesel::query_source::Alias<S>: diesel::JoinTo<Self>,\n    {\n        type FromClause = diesel::query_source::Alias<S>;\n        type OnClause = <diesel::query_source::Alias<\n            S,\n        > as diesel::JoinTo<Self>>::OnClause;\n        fn join_target(\n            __diesel_internal_rhs: diesel::query_source::Alias<S>,\n        ) -> (Self::FromClause, Self::OnClause) {\n            let (_, __diesel_internal_on_clause) = diesel::query_source::Alias::<\n                S,\n            >::join_target(Self);\n            (__diesel_internal_rhs, __diesel_internal_on_clause)\n        }\n    }\n    #[doc = concat!(\"Contains all of the columns of this \", \"table\")]\n    pub mod columns {\n        use ::diesel;\n        use super::table;\n        use diesel::sql_types::*;\n        #[allow(non_camel_case_types, dead_code)]\n        #[derive(\n            Debug,\n            Clone,\n            Copy,\n            diesel::query_builder::QueryId,\n            PartialEq,\n            Eq,\n            PartialOrd,\n            Ord,\n            Hash\n        )]\n        #[doc = concat!(\n            \"Represents `\", \"table\", \"_name.*`, which is sometimes needed for\"\n        )]\n        /// efficient count queries. It cannot be used in place of\n        /// `all_columns`, and has a `SqlType` of `()` to prevent it\n        /// being used that way\n        pub struct star;\n        impl<__GB> diesel::expression::ValidGrouping<__GB> for star\n        where\n            (id, name): diesel::expression::ValidGrouping<__GB>,\n        {\n            type IsAggregate = <(\n                id,\n                name,\n            ) as diesel::expression::ValidGrouping<__GB>>::IsAggregate;\n        }\n        impl diesel::Expression for star {\n            type SqlType = diesel::expression::expression_types::NotSelectable;\n        }\n        impl<DB: diesel::backend::Backend> diesel::query_builder::QueryFragment<DB>\n        for star\n        where\n            <table as diesel::QuerySource>::FromClause: diesel::query_builder::QueryFragment<\n                DB,\n            >,\n        {\n            #[allow(non_snake_case)]\n            fn walk_ast<\'b>(\n                &\'b self,\n                mut __diesel_internal_out: diesel::query_builder::AstPass<\'_, \'b, DB>,\n            ) -> diesel::result::QueryResult<()> {\n                use diesel::QuerySource;\n                if !__diesel_internal_out.should_skip_from() {\n                    const FROM_CLAUSE: diesel::internal::table_macro::StaticQueryFragmentInstance<\n                        table,\n                    > = diesel::internal::table_macro::StaticQueryFragmentInstance::new();\n                    FROM_CLAUSE.walk_ast(__diesel_internal_out.reborrow())?;\n                    __diesel_internal_out.push_sql(\".\");\n                }\n                __diesel_internal_out.push_sql(\"*\");\n                Ok(())\n            }\n        }\n        impl diesel::SelectableExpression<table> for star {}\n        impl diesel::AppearsOnTable<table> for star {}\n        #[allow(non_camel_case_types, dead_code)]\n        #[derive(\n            Debug,\n            Clone,\n            Copy,\n            diesel::query_builder::QueryId,\n            Default,\n            PartialEq,\n            Eq,\n            PartialOrd,\n            Ord,\n            Hash\n        )]\n        pub struct id;\n        impl diesel::expression::Expression for id {\n            type SqlType = Integer;\n        }\n        impl<DB> diesel::query_builder::QueryFragment<DB> for id\n        where\n            DB: diesel::backend::Backend,\n            diesel::internal::table_macro::StaticQueryFragmentInstance<\n                table,\n            >: diesel::query_builder::QueryFragment<DB>,\n        {\n            #[allow(non_snake_case)]\n            fn walk_ast<\'b>(\n                &\'b self,\n                mut __diesel_internal_out: diesel::query_builder::AstPass<\'_, \'b, DB>,\n            ) -> diesel::result::QueryResult<()> {\n                if !__diesel_internal_out.should_skip_from() {\n                    const FROM_CLAUSE: diesel::internal::table_macro::StaticQueryFragmentInstance<\n                        table,\n                    > = diesel::internal::table_macro::StaticQueryFragmentInstance::new();\n                    FROM_CLAUSE.walk_ast(__diesel_internal_out.reborrow())?;\n                    __diesel_internal_out.push_sql(\".\");\n                }\n                __diesel_internal_out.push_identifier(\"id\")\n            }\n        }\n        impl diesel::SelectableExpression<super::table> for id {}\n        impl<QS> diesel::AppearsOnTable<QS> for id\n        where\n            QS: diesel::query_source::AppearsInFromClause<\n                super::table,\n                Count = diesel::query_source::Once,\n            >,\n        {}\n        impl<\n            Left,\n            Right,\n        > diesel::SelectableExpression<\n            diesel::internal::table_macro::Join<\n                Left,\n                Right,\n                diesel::internal::table_macro::LeftOuter,\n            >,\n        > for id\n        where\n            id: diesel::AppearsOnTable<\n                diesel::internal::table_macro::Join<\n                    Left,\n                    Right,\n                    diesel::internal::table_macro::LeftOuter,\n                >,\n            >,\n            Self: diesel::SelectableExpression<Left>,\n            Right: diesel::query_source::AppearsInFromClause<\n                    super::table,\n                    Count = diesel::query_source::Never,\n                > + diesel::query_source::QuerySource,\n            Left: diesel::query_source::QuerySource,\n        {}\n        impl<\n            Left,\n            Right,\n        > diesel::SelectableExpression<\n            diesel::internal::table_macro::Join<\n                Left,\n                Right,\n                diesel::internal::table_macro::Inner,\n            >,\n        > for id\n        where\n            id: diesel::AppearsOnTable<\n                diesel::internal::table_macro::Join<\n                    Left,\n                    Right,\n                    diesel::internal::table_macro::Inner,\n                >,\n            >,\n            Left: diesel::query_source::AppearsInFromClause<super::table>\n                + diesel::query_source::QuerySource,\n            Right: diesel::query_source::AppearsInFromClause<super::table>\n                + diesel::query_source::QuerySource,\n            (\n                Left::Count,\n                Right::Count,\n            ): diesel::internal::table_macro::Pick<Left, Right>,\n            Self: diesel::SelectableExpression<\n                <(\n                    Left::Count,\n                    Right::Count,\n                ) as diesel::internal::table_macro::Pick<Left, Right>>::Selection,\n            >,\n        {}\n        impl<\n            Join,\n            On,\n        > diesel::SelectableExpression<diesel::internal::table_macro::JoinOn<Join, On>>\n        for id\n        where\n            id: diesel::SelectableExpression<Join>\n                + diesel::AppearsOnTable<\n                    diesel::internal::table_macro::JoinOn<Join, On>,\n                >,\n        {}\n        impl<\n            From,\n        > diesel::SelectableExpression<\n            diesel::internal::table_macro::SelectStatement<\n                diesel::internal::table_macro::FromClause<From>,\n            >,\n        > for id\n        where\n            From: diesel::query_source::QuerySource,\n            id: diesel::SelectableExpression<From>\n                + diesel::AppearsOnTable<\n                    diesel::internal::table_macro::SelectStatement<\n                        diesel::internal::table_macro::FromClause<From>,\n                    >,\n                >,\n        {}\n        impl<__GB> diesel::expression::ValidGrouping<__GB> for id\n        where\n            __GB: diesel::expression::IsContainedInGroupBy<\n                id,\n                Output = diesel::expression::is_contained_in_group_by::Yes,\n            >,\n        {\n            type IsAggregate = diesel::expression::is_aggregate::Yes;\n        }\n        impl diesel::expression::ValidGrouping<()> for id {\n            type IsAggregate = diesel::expression::is_aggregate::No;\n        }\n        impl diesel::expression::IsContainedInGroupBy<id> for id {\n            type Output = diesel::expression::is_contained_in_group_by::Yes;\n        }\n        impl<T> diesel::EqAll<T> for id\n        where\n            T: diesel::expression::AsExpression<Integer>,\n            diesel::dsl::Eq<\n                id,\n                T::Expression,\n            >: diesel::Expression<SqlType = diesel::sql_types::Bool>,\n        {\n            type Output = diesel::dsl::Eq<Self, T::Expression>;\n            fn eq_all(self, __diesel_internal_rhs: T) -> Self::Output {\n                use diesel::expression_methods::ExpressionMethods;\n                self.eq(__diesel_internal_rhs)\n            }\n        }\n        impl<Rhs> ::std::ops::Add<Rhs> for id\n        where\n            Rhs: diesel::expression::AsExpression<\n                <<id as diesel::Expression>::SqlType as diesel::sql_types::ops::Add>::Rhs,\n            >,\n        {\n            type Output = diesel::internal::table_macro::ops::Add<Self, Rhs::Expression>;\n            fn add(self, __diesel_internal_rhs: Rhs) -> Self::Output {\n                diesel::internal::table_macro::ops::Add::new(\n                    self,\n                    __diesel_internal_rhs.as_expression(),\n                )\n            }\n        }\n        impl<Rhs> ::std::ops::Sub<Rhs> for id\n        where\n            Rhs: diesel::expression::AsExpression<\n                <<id as diesel::Expression>::SqlType as diesel::sql_types::ops::Sub>::Rhs,\n            >,\n        {\n            type Output = diesel::internal::table_macro::ops::Sub<Self, Rhs::Expression>;\n            fn sub(self, __diesel_internal_rhs: Rhs) -> Self::Output {\n                diesel::internal::table_macro::ops::Sub::new(\n                    self,\n                    __diesel_internal_rhs.as_expression(),\n                )\n            }\n        }\n        impl<Rhs> ::std::ops::Div<Rhs> for id\n        where\n            Rhs: diesel::expression::AsExpression<\n                <<id as diesel::Expression>::SqlType as diesel::sql_types::ops::Div>::Rhs,\n            >,\n        {\n            type Output = diesel::internal::table_macro::ops::Div<Self, Rhs::Expression>;\n            fn div(self, __diesel_internal_rhs: Rhs) -> Self::Output {\n                diesel::internal::table_macro::ops::Div::new(\n                    self,\n                    __diesel_internal_rhs.as_expression(),\n                )\n            }\n        }\n        impl<Rhs> ::std::ops::Mul<Rhs> for id\n        where\n            Rhs: diesel::expression::AsExpression<\n                <<id as diesel::Expression>::SqlType as diesel::sql_types::ops::Mul>::Rhs,\n            >,\n        {\n            type Output = diesel::internal::table_macro::ops::Mul<Self, Rhs::Expression>;\n            fn mul(self, __diesel_internal_rhs: Rhs) -> Self::Output {\n                diesel::internal::table_macro::ops::Mul::new(\n                    self,\n                    __diesel_internal_rhs.as_expression(),\n                )\n            }\n        }\n        impl diesel::query_source::Column for id {\n            type Table = super::table;\n            const NAME: &\'static str = \"id\";\n        }\n        #[allow(non_camel_case_types, dead_code)]\n        #[derive(\n            Debug,\n            Clone,\n            Copy,\n            diesel::query_builder::QueryId,\n            Default,\n            PartialEq,\n            Eq,\n            PartialOrd,\n            Ord,\n            Hash\n        )]\n        pub struct name;\n        impl diesel::expression::Expression for name {\n            type SqlType = Text;\n        }\n        impl<DB> diesel::query_builder::QueryFragment<DB> for name\n        where\n            DB: diesel::backend::Backend,\n            diesel::internal::table_macro::StaticQueryFragmentInstance<\n                table,\n            >: diesel::query_builder::QueryFragment<DB>,\n        {\n            #[allow(non_snake_case)]\n            fn walk_ast<\'b>(\n                &\'b self,\n                mut __diesel_internal_out: diesel::query_builder::AstPass<\'_, \'b, DB>,\n            ) -> diesel::result::QueryResult<()> {\n                if !__diesel_internal_out.should_skip_from() {\n                    const FROM_CLAUSE: diesel::internal::table_macro::StaticQueryFragmentInstance<\n                        table,\n                    > = diesel::internal::table_macro::StaticQueryFragmentInstance::new();\n                    FROM_CLAUSE.walk_ast(__diesel_internal_out.reborrow())?;\n                    __diesel_internal_out.push_sql(\".\");\n                }\n                __diesel_internal_out.push_identifier(\"name\")\n            }\n        }\n        impl diesel::SelectableExpression<super::table> for name {}\n        impl<QS> diesel::AppearsOnTable<QS> for name\n        where\n            QS: diesel::query_source::AppearsInFromClause<\n                super::table,\n                Count = diesel::query_source::Once,\n            >,\n        {}\n        impl<\n            Left,\n            Right,\n        > diesel::SelectableExpression<\n            diesel::internal::table_macro::Join<\n                Left,\n                Right,\n                diesel::internal::table_macro::LeftOuter,\n            >,\n        > for name\n        where\n            name: diesel::AppearsOnTable<\n                diesel::internal::table_macro::Join<\n                    Left,\n                    Right,\n                    diesel::internal::table_macro::LeftOuter,\n                >,\n            >,\n            Self: diesel::SelectableExpression<Left>,\n            Right: diesel::query_source::AppearsInFromClause<\n                    super::table,\n                    Count = diesel::query_source::Never,\n                > + diesel::query_source::QuerySource,\n            Left: diesel::query_source::QuerySource,\n        {}\n        impl<\n            Left,\n            Right,\n        > diesel::SelectableExpression<\n            diesel::internal::table_macro::Join<\n                Left,\n                Right,\n                diesel::internal::table_macro::Inner,\n            >,\n        > for name\n        where\n            name: diesel::AppearsOnTable<\n                diesel::internal::table_macro::Join<\n                    Left,\n                    Right,\n                    diesel::internal::table_macro::Inner,\n                >,\n            >,\n            Left: diesel::query_source::AppearsInFromClause<super::table>\n                + diesel::query_source::QuerySource,\n            Right: diesel::query_source::AppearsInFromClause<super::table>\n                + diesel::query_source::QuerySource,\n            (\n                Left::Count,\n                Right::Count,\n            ): diesel::internal::table_macro::Pick<Left, Right>,\n            Self: diesel::SelectableExpression<\n                <(\n                    Left::Count,\n                    Right::Count,\n                ) as diesel::internal::table_macro::Pick<Left, Right>>::Selection,\n            >,\n        {}\n        impl<\n            Join,\n            On,\n        > diesel::SelectableExpression<diesel::internal::table_macro::JoinOn<Join, On>>\n        for name\n        where\n            name: diesel::SelectableExpression<Join>\n                + diesel::AppearsOnTable<\n                    diesel::internal::table_macro::JoinOn<Join, On>,\n                >,\n        {}\n        impl<\n            From,\n        > diesel::SelectableExpression<\n            diesel::internal::table_macro::SelectStatement<\n                diesel::internal::table_macro::FromClause<From>,\n            >,\n        > for name\n        where\n            From: diesel::query_source::QuerySource,\n            name: diesel::SelectableExpression<From>\n                + diesel::AppearsOnTable<\n                    diesel::internal::table_macro::SelectStatement<\n                        diesel::internal::table_macro::FromClause<From>,\n                    >,\n                >,\n        {}\n        impl<__GB> diesel::expression::ValidGrouping<__GB> for name\n        where\n            __GB: diesel::expression::IsContainedInGroupBy<\n                name,\n                Output = diesel::expression::is_contained_in_group_by::Yes,\n            >,\n        {\n            type IsAggregate = diesel::expression::is_aggregate::Yes;\n        }\n        impl diesel::expression::ValidGrouping<()> for name {\n            type IsAggregate = diesel::expression::is_aggregate::No;\n        }\n        impl diesel::expression::IsContainedInGroupBy<name> for name {\n            type Output = diesel::expression::is_contained_in_group_by::Yes;\n        }\n        impl<T> diesel::EqAll<T> for name\n        where\n            T: diesel::expression::AsExpression<Text>,\n            diesel::dsl::Eq<\n                name,\n                T::Expression,\n            >: diesel::Expression<SqlType = diesel::sql_types::Bool>,\n        {\n            type Output = diesel::dsl::Eq<Self, T::Expression>;\n            fn eq_all(self, __diesel_internal_rhs: T) -> Self::Output {\n                use diesel::expression_methods::ExpressionMethods;\n                self.eq(__diesel_internal_rhs)\n            }\n        }\n        impl diesel::query_source::Column for name {\n            type Table = super::table;\n            const NAME: &\'static str = \"name\";\n        }\n        impl diesel::expression::IsContainedInGroupBy<id> for name {\n            type Output = diesel::expression::is_contained_in_group_by::No;\n        }\n        impl diesel::expression::IsContainedInGroupBy<name> for id {\n            type Output = diesel::expression::is_contained_in_group_by::Yes;\n        }\n    }\n}\n```\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/table.md")))]
1445#[proc_macro]
1446pub fn table_proc(input: TokenStream) -> TokenStream {
1447    table_proc_inner(input.into()).into()
1448}
1449
1450/// Allow two or more tables which are otherwise unrelated to be used together
1451/// in a query.
1452///
1453/// This macro must be invoked any time two tables need to appear in the same
1454/// query either because they are being joined together, or because one appears
1455/// in a subselect. When this macro is invoked with more than 2 tables, every
1456/// combination of those tables will be allowed to appear together.
1457///
1458/// If you are using `diesel print-schema`, an invocation of
1459/// this macro will be generated for you for all tables in your schema.
1460///
1461/// # Example
1462///
1463/// ```
1464/// # use diesel::{allow_tables_to_appear_in_same_query, table};
1465/// #
1466/// // This would be required to do `users.inner_join(posts.inner_join(comments))`
1467/// allow_tables_to_appear_in_same_query!(comments, posts, users);
1468///
1469/// table! {
1470///     comments {
1471///         id -> Integer,
1472///         post_id -> Integer,
1473///         body -> VarChar,
1474///     }
1475/// }
1476///
1477/// table! {
1478///    posts {
1479///        id -> Integer,
1480///        user_id -> Integer,
1481///        title -> VarChar,
1482///    }
1483/// }
1484///
1485/// table! {
1486///     users {
1487///        id -> Integer,
1488///        name -> VarChar,
1489///     }
1490/// }
1491/// ```
1492///
1493/// When more than two tables are passed, the relevant code is generated for
1494/// every combination of those tables. This code would be equivalent to the
1495/// previous example.
1496///
1497/// ```
1498/// # use diesel::{allow_tables_to_appear_in_same_query, table};
1499/// # table! {
1500/// #    comments {
1501/// #        id -> Integer,
1502/// #        post_id -> Integer,
1503/// #        body -> VarChar,
1504/// #    }
1505/// # }
1506/// #
1507/// # table! {
1508/// #    posts {
1509/// #        id -> Integer,
1510/// #        user_id -> Integer,
1511/// #        title -> VarChar,
1512/// #    }
1513/// # }
1514/// #
1515/// # table! {
1516/// #     users {
1517/// #        id -> Integer,
1518/// #        name -> VarChar,
1519/// #     }
1520/// # }
1521/// #
1522/// allow_tables_to_appear_in_same_query!(comments, posts);
1523/// allow_tables_to_appear_in_same_query!(comments, users);
1524/// allow_tables_to_appear_in_same_query!(posts, users);
1525/// #
1526/// # fn main() {}
1527/// ```
1528///
1529#[cfg_attr(diesel_docsrs, doc = "\n# Expanded Code\n\n<details>\n<summary> Expanded Code </summary>\n\n\n### Simple example\n\n\n\n#### Input\n\n```rust,ignore\nallow_tables_to_appear_in_same_query! {\n    users, posts, comments\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nimpl ::diesel::query_source::TableNotEqual<posts::table> for users::table {}\nimpl ::diesel::query_source::TableNotEqual<users::table> for posts::table {}\nimpl ::diesel::query_source::TableNotEqual<comments::table> for users::table {}\nimpl ::diesel::query_source::TableNotEqual<users::table> for comments::table {}\nimpl ::diesel::query_source::TableNotEqual<comments::table> for posts::table {}\nimpl ::diesel::query_source::TableNotEqual<posts::table> for comments::table {}\n```\n\n\n### With paths\n\n\n\n#### Input\n\n```rust,ignore\nallow_tables_to_appear_in_same_query! {\n    schema::users, schema::posts, comments\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nimpl ::diesel::query_source::TableNotEqual<schema::posts::table>\nfor schema::users::table {}\nimpl ::diesel::query_source::TableNotEqual<schema::users::table>\nfor schema::posts::table {}\nimpl ::diesel::query_source::TableNotEqual<comments::table> for schema::users::table {}\nimpl ::diesel::query_source::TableNotEqual<schema::users::table> for comments::table {}\nimpl ::diesel::query_source::TableNotEqual<comments::table> for schema::posts::table {}\nimpl ::diesel::query_source::TableNotEqual<schema::posts::table> for comments::table {}\n```\n\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/allow_tables_to_appear_in_same_query.md")))]
1530#[proc_macro]
1531pub fn allow_tables_to_appear_in_same_query(input: TokenStream) -> TokenStream {
1532    allow_tables_to_appear_in_same_query::expand(input.into()).into()
1533}
1534
1535fn table_proc_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
1536    self::table::query_source_macro(input, self::table::QuerySourceMacroKind::Table)
1537}
1538
1539/// Specifies that a view exists, and what fields it has. This will create a
1540/// new public module, with the same name, as the name of the view. In this
1541/// module, you will find a unit struct named `view`, and a unit struct with the
1542/// name of each field.
1543///
1544/// The macro and the generated code closely mirror the [`table!`](table_proc) macro.
1545///
1546/// By default, this allows a maximum of 32 columns per view.
1547/// You can increase this limit to 64 by enabling the `64-column-tables` feature.
1548/// You can increase it to 128 by enabling the `128-column-tables` feature.
1549/// You can decrease it to 16 columns,
1550/// which improves compilation time,
1551/// by disabling the default features of Diesel.
1552/// Note that enabling 64 column tables or larger will substantially increase
1553/// the compile time of Diesel.
1554///
1555/// Example usage
1556/// -------------
1557///
1558/// ```rust
1559/// # extern crate diesel;
1560///
1561/// diesel::view! {
1562///     users {
1563///         name -> VarChar,
1564///         favorite_color -> Nullable<VarChar>,
1565///     }
1566/// }
1567/// ```
1568///
1569/// If you are using types that aren't from Diesel's core types, you can specify
1570/// which types to import.
1571///
1572/// ```
1573/// # extern crate diesel;
1574/// # mod diesel_full_text_search {
1575/// #     #[derive(diesel::sql_types::SqlType)]
1576/// #     pub struct TsVector;
1577/// # }
1578///
1579/// diesel::view! {
1580///     use diesel::sql_types::*;
1581/// #    use crate::diesel_full_text_search::*;
1582/// # /*
1583///     use diesel_full_text_search::*;
1584/// # */
1585///
1586///     posts {
1587///         title -> Text,
1588///         keywords -> TsVector,
1589///     }
1590/// }
1591/// # fn main() {}
1592/// ```
1593///
1594/// If you want to add documentation to the generated code, you can use the
1595/// following syntax:
1596///
1597/// ```
1598/// # extern crate diesel;
1599///
1600/// diesel::view! {
1601///     /// The table containing all blog posts
1602///     posts {
1603///         /// The post's title
1604///         title -> Text,
1605///     }
1606/// }
1607/// ```
1608///
1609/// If you have a column with the same name as a Rust reserved keyword, you can use
1610/// the `sql_name` attribute like this:
1611///
1612/// ```
1613/// # extern crate diesel;
1614///
1615/// diesel::view! {
1616///     posts {
1617///         /// This column is named `mytype` but references the table `type` column.
1618///         #[sql_name = "type"]
1619///         mytype -> Text,
1620///     }
1621/// }
1622/// ```
1623///
1624/// This module will also contain several helper types:
1625///
1626/// dsl
1627/// ---
1628///
1629/// This simply re-exports the view, renamed to the same name as the module,
1630/// and each of the columns. This is useful to glob import when you're dealing
1631/// primarily with one table, to allow writing `users.filter(name.eq("Sean"))`
1632/// instead of `users::table.filter(users::name.eq("Sean"))`.
1633///
1634/// `all_columns`
1635/// -----------
1636///
1637/// A constant will be assigned called `all_columns`. This is what will be
1638/// selected if you don't otherwise specify a select clause. It's type will be
1639/// `view::AllColumns`. You can also get this value from the
1640/// `QueryRelation::all_columns` function.
1641///
1642/// star
1643/// ----
1644///
1645/// This will be the qualified "star" expression for this view (e.g.
1646/// `users.*`). Internally, we read columns by index, not by name, so this
1647/// column is not safe to read data out of, and it has had its SQL type set to
1648/// `()` to prevent accidentally using it as such. It is sometimes useful for
1649/// counting statements, however. It can also be accessed through the `Table.star()`
1650/// method.
1651///
1652/// `SqlType`
1653/// -------
1654///
1655/// A type alias called `SqlType` will be created. It will be the SQL type of
1656/// `all_columns`. The SQL type is needed for things like returning boxed
1657/// queries.
1658///
1659/// `BoxedQuery`
1660/// ----------
1661///
1662/// ```ignore
1663/// pub type BoxedQuery<'a, DB, ST = SqlType> = BoxedSelectStatement<'a, ST, view, DB>;
1664/// ```
1665///
1666#[cfg_attr(diesel_docsrs, doc = "\n# Expanded Code\n\n<details>\n<summary> Expanded Code </summary>\n\n\n\n#### Input\n\n```rust,ignore\nview! {\n    view { id -> Integer, name -> Text, }\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\n#[allow(unused_imports, dead_code, unreachable_pub, unused_qualifications)]\npub mod view {\n    use ::diesel;\n    pub use self::columns::*;\n    use diesel::sql_types::*;\n    #[doc = concat!(\n        \"Re-exports all of the columns of this \", \"view\", \", as well as the\"\n    )]\n    #[doc = concat!(\"view\", \" struct renamed to the module name. This is meant to be\")]\n    #[doc = concat!(\n        \"glob imported for functions which only deal with one \", \"view\", \".\"\n    )]\n    pub mod dsl {\n        pub use super::columns::id;\n        pub use super::columns::name;\n        pub use super::view as view;\n    }\n    #[allow(non_upper_case_globals, dead_code)]\n    #[doc = concat!(\"A tuple of all of the columns on this\", \"view\")]\n    pub const all_columns: (id, name) = (id, name);\n    #[allow(non_camel_case_types)]\n    #[derive(\n        Debug,\n        Clone,\n        Copy,\n        diesel::query_builder::QueryId,\n        Default,\n        PartialEq,\n        Eq,\n        PartialOrd,\n        Ord,\n        Hash\n    )]\n    #[doc = concat!(\"The actual \", \"view\", \" struct\")]\n    ///\n    /// This is the type which provides the base methods of the query\n    /// builder, such as `.select` and `.filter`.\n    pub struct view;\n    impl view {\n        #[allow(dead_code)]\n        #[doc = concat!(\n            \"Represents `\", \"view\", \"_name.*`, which is sometimes necessary\"\n        )]\n        /// for efficient count queries. It cannot be used in place of\n        /// `all_columns`\n        pub fn star(&self) -> star {\n            star\n        }\n    }\n    #[doc = concat!(\"The SQL type of all of the columns on this \", \"view\")]\n    pub type SqlType = (Integer, Text);\n    #[doc = concat!(\"Helper type for representing a boxed query from this \", \"view\")]\n    pub type BoxedQuery<\'a, DB, ST = SqlType> = diesel::internal::table_macro::BoxedSelectStatement<\n        \'a,\n        ST,\n        diesel::internal::table_macro::FromClause<view>,\n        DB,\n    >;\n    impl diesel::QuerySource for view {\n        type FromClause = diesel::internal::table_macro::StaticQueryFragmentInstance<\n            view,\n        >;\n        type DefaultSelection = <Self as diesel::query_source::QueryRelation>::AllColumns;\n        fn from_clause(&self) -> Self::FromClause {\n            diesel::internal::table_macro::StaticQueryFragmentInstance::new()\n        }\n        fn default_selection(&self) -> Self::DefaultSelection {\n            <Self as diesel::query_source::QueryRelation>::all_columns()\n        }\n    }\n    impl diesel::internal::table_macro::PlainQuerySource for view {}\n    impl<DB> diesel::query_builder::QueryFragment<DB> for view\n    where\n        DB: diesel::backend::Backend,\n        <Self as diesel::internal::table_macro::StaticQueryFragment>::Component: diesel::query_builder::QueryFragment<\n            DB,\n        >,\n    {\n        fn walk_ast<\'b>(\n            &\'b self,\n            __diesel_internal_pass: diesel::query_builder::AstPass<\'_, \'b, DB>,\n        ) -> diesel::result::QueryResult<()> {\n            <Self as diesel::internal::table_macro::StaticQueryFragment>::STATIC_COMPONENT\n                .walk_ast(__diesel_internal_pass)\n        }\n    }\n    impl diesel::internal::table_macro::StaticQueryFragment for view {\n        type Component = diesel::internal::table_macro::Identifier<\'static>;\n        const STATIC_COMPONENT: &\'static Self::Component = &diesel::internal::table_macro::Identifier(\n            \"view\",\n        );\n    }\n    impl diesel::query_builder::AsQuery for view {\n        type SqlType = SqlType;\n        type Query = diesel::internal::table_macro::SelectStatement<\n            diesel::internal::table_macro::FromClause<Self>,\n        >;\n        fn as_query(self) -> Self::Query {\n            diesel::internal::table_macro::SelectStatement::simple(self)\n        }\n    }\n    #[doc(hidden)]\n    pub use self::view as table;\n    impl diesel::query_source::QueryRelation for view {\n        type AllColumns = (id, name);\n        fn all_columns() -> Self::AllColumns {\n            (id, name)\n        }\n    }\n    impl diesel::internal::table_macro::Sealed for view {}\n    impl diesel::query_source::View for view {}\n    impl diesel::query_source::AppearsInFromClause<Self> for view {\n        type Count = diesel::query_source::Once;\n    }\n    impl<S> diesel::internal::table_macro::AliasAppearsInFromClause<S, Self> for view\n    where\n        S: diesel::query_source::AliasSource<Target = Self>,\n    {\n        type Count = diesel::query_source::Never;\n    }\n    impl<\n        S1,\n        S2,\n    > diesel::internal::table_macro::AliasAliasAppearsInFromClause<Self, S2, S1> for view\n    where\n        S1: diesel::query_source::AliasSource<Target = Self>,\n        S2: diesel::query_source::AliasSource<Target = Self>,\n        S1: diesel::internal::table_macro::AliasAliasAppearsInFromClauseSameTable<\n            S2,\n            Self,\n        >,\n    {\n        type Count = <S1 as diesel::internal::table_macro::AliasAliasAppearsInFromClauseSameTable<\n            S2,\n            Self,\n        >>::Count;\n    }\n    impl<S> diesel::query_source::AppearsInFromClause<diesel::query_source::Alias<S>>\n    for view\n    where\n        S: diesel::query_source::AliasSource,\n    {\n        type Count = diesel::query_source::Never;\n    }\n    impl<\n        S,\n        C,\n    > diesel::internal::table_macro::FieldAliasMapperAssociatedTypesDisjointnessTrick<\n        Self,\n        S,\n        C,\n    > for view\n    where\n        S: diesel::query_source::AliasSource<Target = Self> + ::std::clone::Clone,\n        C: diesel::query_source::QueryRelationField<QueryRelation = Self>,\n    {\n        type Out = diesel::query_source::AliasedField<S, C>;\n        fn map(\n            __diesel_internal_column: C,\n            __diesel_internal_alias: &diesel::query_source::Alias<S>,\n        ) -> Self::Out {\n            __diesel_internal_alias.field(__diesel_internal_column)\n        }\n    }\n    impl diesel::query_source::AppearsInFromClause<view>\n    for diesel::internal::table_macro::NoFromClause {\n        type Count = diesel::query_source::Never;\n    }\n    impl<\n        Left,\n        Right,\n        Kind,\n    > diesel::JoinTo<diesel::internal::table_macro::Join<Left, Right, Kind>> for view\n    where\n        diesel::internal::table_macro::Join<Left, Right, Kind>: diesel::JoinTo<Self>,\n        Left: diesel::query_source::QuerySource,\n        Right: diesel::query_source::QuerySource,\n    {\n        type FromClause = diesel::internal::table_macro::Join<Left, Right, Kind>;\n        type OnClause = <diesel::internal::table_macro::Join<\n            Left,\n            Right,\n            Kind,\n        > as diesel::JoinTo<Self>>::OnClause;\n        fn join_target(\n            __diesel_internal_rhs: diesel::internal::table_macro::Join<Left, Right, Kind>,\n        ) -> (Self::FromClause, Self::OnClause) {\n            let (_, __diesel_internal_on_clause) = diesel::internal::table_macro::Join::join_target(\n                Self,\n            );\n            (__diesel_internal_rhs, __diesel_internal_on_clause)\n        }\n    }\n    impl<Join, On> diesel::JoinTo<diesel::internal::table_macro::JoinOn<Join, On>>\n    for view\n    where\n        diesel::internal::table_macro::JoinOn<Join, On>: diesel::JoinTo<Self>,\n    {\n        type FromClause = diesel::internal::table_macro::JoinOn<Join, On>;\n        type OnClause = <diesel::internal::table_macro::JoinOn<\n            Join,\n            On,\n        > as diesel::JoinTo<Self>>::OnClause;\n        fn join_target(\n            __diesel_internal_rhs: diesel::internal::table_macro::JoinOn<Join, On>,\n        ) -> (Self::FromClause, Self::OnClause) {\n            let (_, __diesel_internal_on_clause) = diesel::internal::table_macro::JoinOn::join_target(\n                Self,\n            );\n            (__diesel_internal_rhs, __diesel_internal_on_clause)\n        }\n    }\n    impl<\n        F,\n        S,\n        D,\n        W,\n        O,\n        L,\n        Of,\n        G,\n    > diesel::JoinTo<\n        diesel::internal::table_macro::SelectStatement<\n            diesel::internal::table_macro::FromClause<F>,\n            S,\n            D,\n            W,\n            O,\n            L,\n            Of,\n            G,\n        >,\n    > for view\n    where\n        diesel::internal::table_macro::SelectStatement<\n            diesel::internal::table_macro::FromClause<F>,\n            S,\n            D,\n            W,\n            O,\n            L,\n            Of,\n            G,\n        >: diesel::JoinTo<Self>,\n        F: diesel::query_source::QuerySource,\n    {\n        type FromClause = diesel::internal::table_macro::SelectStatement<\n            diesel::internal::table_macro::FromClause<F>,\n            S,\n            D,\n            W,\n            O,\n            L,\n            Of,\n            G,\n        >;\n        type OnClause = <diesel::internal::table_macro::SelectStatement<\n            diesel::internal::table_macro::FromClause<F>,\n            S,\n            D,\n            W,\n            O,\n            L,\n            Of,\n            G,\n        > as diesel::JoinTo<Self>>::OnClause;\n        fn join_target(\n            __diesel_internal_rhs: diesel::internal::table_macro::SelectStatement<\n                diesel::internal::table_macro::FromClause<F>,\n                S,\n                D,\n                W,\n                O,\n                L,\n                Of,\n                G,\n            >,\n        ) -> (Self::FromClause, Self::OnClause) {\n            let (_, __diesel_internal_on_clause) = diesel::internal::table_macro::SelectStatement::join_target(\n                Self,\n            );\n            (__diesel_internal_rhs, __diesel_internal_on_clause)\n        }\n    }\n    impl<\n        \'a,\n        QS,\n        ST,\n        DB,\n    > diesel::JoinTo<\n        diesel::internal::table_macro::BoxedSelectStatement<\n            \'a,\n            diesel::internal::table_macro::FromClause<QS>,\n            ST,\n            DB,\n        >,\n    > for view\n    where\n        diesel::internal::table_macro::BoxedSelectStatement<\n            \'a,\n            diesel::internal::table_macro::FromClause<QS>,\n            ST,\n            DB,\n        >: diesel::JoinTo<Self>,\n        QS: diesel::query_source::QuerySource,\n    {\n        type FromClause = diesel::internal::table_macro::BoxedSelectStatement<\n            \'a,\n            diesel::internal::table_macro::FromClause<QS>,\n            ST,\n            DB,\n        >;\n        type OnClause = <diesel::internal::table_macro::BoxedSelectStatement<\n            \'a,\n            diesel::internal::table_macro::FromClause<QS>,\n            ST,\n            DB,\n        > as diesel::JoinTo<Self>>::OnClause;\n        fn join_target(\n            __diesel_internal_rhs: diesel::internal::table_macro::BoxedSelectStatement<\n                \'a,\n                diesel::internal::table_macro::FromClause<QS>,\n                ST,\n                DB,\n            >,\n        ) -> (Self::FromClause, Self::OnClause) {\n            let (_, __diesel_internal_on_clause) = diesel::internal::table_macro::BoxedSelectStatement::join_target(\n                Self,\n            );\n            (__diesel_internal_rhs, __diesel_internal_on_clause)\n        }\n    }\n    impl<S> diesel::JoinTo<diesel::query_source::Alias<S>> for view\n    where\n        diesel::query_source::Alias<S>: diesel::JoinTo<Self>,\n    {\n        type FromClause = diesel::query_source::Alias<S>;\n        type OnClause = <diesel::query_source::Alias<\n            S,\n        > as diesel::JoinTo<Self>>::OnClause;\n        fn join_target(\n            __diesel_internal_rhs: diesel::query_source::Alias<S>,\n        ) -> (Self::FromClause, Self::OnClause) {\n            let (_, __diesel_internal_on_clause) = diesel::query_source::Alias::<\n                S,\n            >::join_target(Self);\n            (__diesel_internal_rhs, __diesel_internal_on_clause)\n        }\n    }\n    #[doc = concat!(\"Contains all of the columns of this \", \"view\")]\n    pub mod columns {\n        use ::diesel;\n        use super::view;\n        use diesel::sql_types::*;\n        #[allow(non_camel_case_types, dead_code)]\n        #[derive(\n            Debug,\n            Clone,\n            Copy,\n            diesel::query_builder::QueryId,\n            PartialEq,\n            Eq,\n            PartialOrd,\n            Ord,\n            Hash\n        )]\n        #[doc = concat!(\n            \"Represents `\", \"view\", \"_name.*`, which is sometimes needed for\"\n        )]\n        /// efficient count queries. It cannot be used in place of\n        /// `all_columns`, and has a `SqlType` of `()` to prevent it\n        /// being used that way\n        pub struct star;\n        impl<__GB> diesel::expression::ValidGrouping<__GB> for star\n        where\n            (id, name): diesel::expression::ValidGrouping<__GB>,\n        {\n            type IsAggregate = <(\n                id,\n                name,\n            ) as diesel::expression::ValidGrouping<__GB>>::IsAggregate;\n        }\n        impl diesel::Expression for star {\n            type SqlType = diesel::expression::expression_types::NotSelectable;\n        }\n        impl<DB: diesel::backend::Backend> diesel::query_builder::QueryFragment<DB>\n        for star\n        where\n            <view as diesel::QuerySource>::FromClause: diesel::query_builder::QueryFragment<\n                DB,\n            >,\n        {\n            #[allow(non_snake_case)]\n            fn walk_ast<\'b>(\n                &\'b self,\n                mut __diesel_internal_out: diesel::query_builder::AstPass<\'_, \'b, DB>,\n            ) -> diesel::result::QueryResult<()> {\n                use diesel::QuerySource;\n                if !__diesel_internal_out.should_skip_from() {\n                    const FROM_CLAUSE: diesel::internal::table_macro::StaticQueryFragmentInstance<\n                        view,\n                    > = diesel::internal::table_macro::StaticQueryFragmentInstance::new();\n                    FROM_CLAUSE.walk_ast(__diesel_internal_out.reborrow())?;\n                    __diesel_internal_out.push_sql(\".\");\n                }\n                __diesel_internal_out.push_sql(\"*\");\n                Ok(())\n            }\n        }\n        impl diesel::SelectableExpression<view> for star {}\n        impl diesel::AppearsOnTable<view> for star {}\n        #[allow(non_camel_case_types, dead_code)]\n        #[derive(\n            Debug,\n            Clone,\n            Copy,\n            diesel::query_builder::QueryId,\n            Default,\n            PartialEq,\n            Eq,\n            PartialOrd,\n            Ord,\n            Hash\n        )]\n        pub struct id;\n        impl diesel::expression::Expression for id {\n            type SqlType = Integer;\n        }\n        impl<DB> diesel::query_builder::QueryFragment<DB> for id\n        where\n            DB: diesel::backend::Backend,\n            diesel::internal::table_macro::StaticQueryFragmentInstance<\n                view,\n            >: diesel::query_builder::QueryFragment<DB>,\n        {\n            #[allow(non_snake_case)]\n            fn walk_ast<\'b>(\n                &\'b self,\n                mut __diesel_internal_out: diesel::query_builder::AstPass<\'_, \'b, DB>,\n            ) -> diesel::result::QueryResult<()> {\n                if !__diesel_internal_out.should_skip_from() {\n                    const FROM_CLAUSE: diesel::internal::table_macro::StaticQueryFragmentInstance<\n                        view,\n                    > = diesel::internal::table_macro::StaticQueryFragmentInstance::new();\n                    FROM_CLAUSE.walk_ast(__diesel_internal_out.reborrow())?;\n                    __diesel_internal_out.push_sql(\".\");\n                }\n                __diesel_internal_out.push_identifier(\"id\")\n            }\n        }\n        impl diesel::SelectableExpression<super::view> for id {}\n        impl<QS> diesel::AppearsOnTable<QS> for id\n        where\n            QS: diesel::query_source::AppearsInFromClause<\n                super::view,\n                Count = diesel::query_source::Once,\n            >,\n        {}\n        impl<\n            Left,\n            Right,\n        > diesel::SelectableExpression<\n            diesel::internal::table_macro::Join<\n                Left,\n                Right,\n                diesel::internal::table_macro::LeftOuter,\n            >,\n        > for id\n        where\n            id: diesel::AppearsOnTable<\n                diesel::internal::table_macro::Join<\n                    Left,\n                    Right,\n                    diesel::internal::table_macro::LeftOuter,\n                >,\n            >,\n            Self: diesel::SelectableExpression<Left>,\n            Right: diesel::query_source::AppearsInFromClause<\n                    super::view,\n                    Count = diesel::query_source::Never,\n                > + diesel::query_source::QuerySource,\n            Left: diesel::query_source::QuerySource,\n        {}\n        impl<\n            Left,\n            Right,\n        > diesel::SelectableExpression<\n            diesel::internal::table_macro::Join<\n                Left,\n                Right,\n                diesel::internal::table_macro::Inner,\n            >,\n        > for id\n        where\n            id: diesel::AppearsOnTable<\n                diesel::internal::table_macro::Join<\n                    Left,\n                    Right,\n                    diesel::internal::table_macro::Inner,\n                >,\n            >,\n            Left: diesel::query_source::AppearsInFromClause<super::view>\n                + diesel::query_source::QuerySource,\n            Right: diesel::query_source::AppearsInFromClause<super::view>\n                + diesel::query_source::QuerySource,\n            (\n                Left::Count,\n                Right::Count,\n            ): diesel::internal::table_macro::Pick<Left, Right>,\n            Self: diesel::SelectableExpression<\n                <(\n                    Left::Count,\n                    Right::Count,\n                ) as diesel::internal::table_macro::Pick<Left, Right>>::Selection,\n            >,\n        {}\n        impl<\n            Join,\n            On,\n        > diesel::SelectableExpression<diesel::internal::table_macro::JoinOn<Join, On>>\n        for id\n        where\n            id: diesel::SelectableExpression<Join>\n                + diesel::AppearsOnTable<\n                    diesel::internal::table_macro::JoinOn<Join, On>,\n                >,\n        {}\n        impl<\n            From,\n        > diesel::SelectableExpression<\n            diesel::internal::table_macro::SelectStatement<\n                diesel::internal::table_macro::FromClause<From>,\n            >,\n        > for id\n        where\n            From: diesel::query_source::QuerySource,\n            id: diesel::SelectableExpression<From>\n                + diesel::AppearsOnTable<\n                    diesel::internal::table_macro::SelectStatement<\n                        diesel::internal::table_macro::FromClause<From>,\n                    >,\n                >,\n        {}\n        impl<__GB> diesel::expression::ValidGrouping<__GB> for id\n        where\n            __GB: diesel::expression::IsContainedInGroupBy<\n                id,\n                Output = diesel::expression::is_contained_in_group_by::Yes,\n            >,\n        {\n            type IsAggregate = diesel::expression::is_aggregate::Yes;\n        }\n        impl diesel::expression::ValidGrouping<()> for id {\n            type IsAggregate = diesel::expression::is_aggregate::No;\n        }\n        impl diesel::expression::IsContainedInGroupBy<id> for id {\n            type Output = diesel::expression::is_contained_in_group_by::Yes;\n        }\n        impl<T> diesel::EqAll<T> for id\n        where\n            T: diesel::expression::AsExpression<Integer>,\n            diesel::dsl::Eq<\n                id,\n                T::Expression,\n            >: diesel::Expression<SqlType = diesel::sql_types::Bool>,\n        {\n            type Output = diesel::dsl::Eq<Self, T::Expression>;\n            fn eq_all(self, __diesel_internal_rhs: T) -> Self::Output {\n                use diesel::expression_methods::ExpressionMethods;\n                self.eq(__diesel_internal_rhs)\n            }\n        }\n        impl<Rhs> ::std::ops::Add<Rhs> for id\n        where\n            Rhs: diesel::expression::AsExpression<\n                <<id as diesel::Expression>::SqlType as diesel::sql_types::ops::Add>::Rhs,\n            >,\n        {\n            type Output = diesel::internal::table_macro::ops::Add<Self, Rhs::Expression>;\n            fn add(self, __diesel_internal_rhs: Rhs) -> Self::Output {\n                diesel::internal::table_macro::ops::Add::new(\n                    self,\n                    __diesel_internal_rhs.as_expression(),\n                )\n            }\n        }\n        impl<Rhs> ::std::ops::Sub<Rhs> for id\n        where\n            Rhs: diesel::expression::AsExpression<\n                <<id as diesel::Expression>::SqlType as diesel::sql_types::ops::Sub>::Rhs,\n            >,\n        {\n            type Output = diesel::internal::table_macro::ops::Sub<Self, Rhs::Expression>;\n            fn sub(self, __diesel_internal_rhs: Rhs) -> Self::Output {\n                diesel::internal::table_macro::ops::Sub::new(\n                    self,\n                    __diesel_internal_rhs.as_expression(),\n                )\n            }\n        }\n        impl<Rhs> ::std::ops::Div<Rhs> for id\n        where\n            Rhs: diesel::expression::AsExpression<\n                <<id as diesel::Expression>::SqlType as diesel::sql_types::ops::Div>::Rhs,\n            >,\n        {\n            type Output = diesel::internal::table_macro::ops::Div<Self, Rhs::Expression>;\n            fn div(self, __diesel_internal_rhs: Rhs) -> Self::Output {\n                diesel::internal::table_macro::ops::Div::new(\n                    self,\n                    __diesel_internal_rhs.as_expression(),\n                )\n            }\n        }\n        impl<Rhs> ::std::ops::Mul<Rhs> for id\n        where\n            Rhs: diesel::expression::AsExpression<\n                <<id as diesel::Expression>::SqlType as diesel::sql_types::ops::Mul>::Rhs,\n            >,\n        {\n            type Output = diesel::internal::table_macro::ops::Mul<Self, Rhs::Expression>;\n            fn mul(self, __diesel_internal_rhs: Rhs) -> Self::Output {\n                diesel::internal::table_macro::ops::Mul::new(\n                    self,\n                    __diesel_internal_rhs.as_expression(),\n                )\n            }\n        }\n        impl diesel::query_source::QueryRelationField for id {\n            type QueryRelation = super::view;\n            const NAME: &\'static str = \"id\";\n        }\n        #[allow(non_camel_case_types, dead_code)]\n        #[derive(\n            Debug,\n            Clone,\n            Copy,\n            diesel::query_builder::QueryId,\n            Default,\n            PartialEq,\n            Eq,\n            PartialOrd,\n            Ord,\n            Hash\n        )]\n        pub struct name;\n        impl diesel::expression::Expression for name {\n            type SqlType = Text;\n        }\n        impl<DB> diesel::query_builder::QueryFragment<DB> for name\n        where\n            DB: diesel::backend::Backend,\n            diesel::internal::table_macro::StaticQueryFragmentInstance<\n                view,\n            >: diesel::query_builder::QueryFragment<DB>,\n        {\n            #[allow(non_snake_case)]\n            fn walk_ast<\'b>(\n                &\'b self,\n                mut __diesel_internal_out: diesel::query_builder::AstPass<\'_, \'b, DB>,\n            ) -> diesel::result::QueryResult<()> {\n                if !__diesel_internal_out.should_skip_from() {\n                    const FROM_CLAUSE: diesel::internal::table_macro::StaticQueryFragmentInstance<\n                        view,\n                    > = diesel::internal::table_macro::StaticQueryFragmentInstance::new();\n                    FROM_CLAUSE.walk_ast(__diesel_internal_out.reborrow())?;\n                    __diesel_internal_out.push_sql(\".\");\n                }\n                __diesel_internal_out.push_identifier(\"name\")\n            }\n        }\n        impl diesel::SelectableExpression<super::view> for name {}\n        impl<QS> diesel::AppearsOnTable<QS> for name\n        where\n            QS: diesel::query_source::AppearsInFromClause<\n                super::view,\n                Count = diesel::query_source::Once,\n            >,\n        {}\n        impl<\n            Left,\n            Right,\n        > diesel::SelectableExpression<\n            diesel::internal::table_macro::Join<\n                Left,\n                Right,\n                diesel::internal::table_macro::LeftOuter,\n            >,\n        > for name\n        where\n            name: diesel::AppearsOnTable<\n                diesel::internal::table_macro::Join<\n                    Left,\n                    Right,\n                    diesel::internal::table_macro::LeftOuter,\n                >,\n            >,\n            Self: diesel::SelectableExpression<Left>,\n            Right: diesel::query_source::AppearsInFromClause<\n                    super::view,\n                    Count = diesel::query_source::Never,\n                > + diesel::query_source::QuerySource,\n            Left: diesel::query_source::QuerySource,\n        {}\n        impl<\n            Left,\n            Right,\n        > diesel::SelectableExpression<\n            diesel::internal::table_macro::Join<\n                Left,\n                Right,\n                diesel::internal::table_macro::Inner,\n            >,\n        > for name\n        where\n            name: diesel::AppearsOnTable<\n                diesel::internal::table_macro::Join<\n                    Left,\n                    Right,\n                    diesel::internal::table_macro::Inner,\n                >,\n            >,\n            Left: diesel::query_source::AppearsInFromClause<super::view>\n                + diesel::query_source::QuerySource,\n            Right: diesel::query_source::AppearsInFromClause<super::view>\n                + diesel::query_source::QuerySource,\n            (\n                Left::Count,\n                Right::Count,\n            ): diesel::internal::table_macro::Pick<Left, Right>,\n            Self: diesel::SelectableExpression<\n                <(\n                    Left::Count,\n                    Right::Count,\n                ) as diesel::internal::table_macro::Pick<Left, Right>>::Selection,\n            >,\n        {}\n        impl<\n            Join,\n            On,\n        > diesel::SelectableExpression<diesel::internal::table_macro::JoinOn<Join, On>>\n        for name\n        where\n            name: diesel::SelectableExpression<Join>\n                + diesel::AppearsOnTable<\n                    diesel::internal::table_macro::JoinOn<Join, On>,\n                >,\n        {}\n        impl<\n            From,\n        > diesel::SelectableExpression<\n            diesel::internal::table_macro::SelectStatement<\n                diesel::internal::table_macro::FromClause<From>,\n            >,\n        > for name\n        where\n            From: diesel::query_source::QuerySource,\n            name: diesel::SelectableExpression<From>\n                + diesel::AppearsOnTable<\n                    diesel::internal::table_macro::SelectStatement<\n                        diesel::internal::table_macro::FromClause<From>,\n                    >,\n                >,\n        {}\n        impl<__GB> diesel::expression::ValidGrouping<__GB> for name\n        where\n            __GB: diesel::expression::IsContainedInGroupBy<\n                name,\n                Output = diesel::expression::is_contained_in_group_by::Yes,\n            >,\n        {\n            type IsAggregate = diesel::expression::is_aggregate::Yes;\n        }\n        impl diesel::expression::ValidGrouping<()> for name {\n            type IsAggregate = diesel::expression::is_aggregate::No;\n        }\n        impl diesel::expression::IsContainedInGroupBy<name> for name {\n            type Output = diesel::expression::is_contained_in_group_by::Yes;\n        }\n        impl<T> diesel::EqAll<T> for name\n        where\n            T: diesel::expression::AsExpression<Text>,\n            diesel::dsl::Eq<\n                name,\n                T::Expression,\n            >: diesel::Expression<SqlType = diesel::sql_types::Bool>,\n        {\n            type Output = diesel::dsl::Eq<Self, T::Expression>;\n            fn eq_all(self, __diesel_internal_rhs: T) -> Self::Output {\n                use diesel::expression_methods::ExpressionMethods;\n                self.eq(__diesel_internal_rhs)\n            }\n        }\n        impl diesel::query_source::QueryRelationField for name {\n            type QueryRelation = super::view;\n            const NAME: &\'static str = \"name\";\n        }\n        impl diesel::expression::IsContainedInGroupBy<id> for name {\n            type Output = diesel::expression::is_contained_in_group_by::No;\n        }\n        impl diesel::expression::IsContainedInGroupBy<name> for id {\n            type Output = diesel::expression::is_contained_in_group_by::Yes;\n        }\n    }\n}\n```\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/view.md")))]
1667#[proc_macro]
1668pub fn view_proc(input: TokenStream) -> TokenStream {
1669    view_proc_inner(input.into()).into()
1670}
1671
1672fn view_proc_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
1673    self::table::query_source_macro(input, self::table::QuerySourceMacroKind::View)
1674}
1675
1676/// This derives implements `diesel::Connection` and related traits for an enum of
1677/// connections to different databases.
1678///
1679/// By applying this derive to such an enum, you can use the enum as a connection type in
1680/// any location all the inner connections are valid. This derive supports enum
1681/// variants containing a single tuple field. Each tuple field type must implement
1682/// `diesel::Connection` and a number of related traits. Connection types form Diesel itself
1683/// as well as third party connection types are supported by this derive.
1684///
1685/// The implementation of `diesel::Connection::establish` tries to establish
1686/// a new connection with the given connection string in the order the connections
1687/// are specified in the enum. If one connection fails, it tries the next one and so on.
1688/// That means that as soon as more than one connection type accepts a certain connection
1689/// string the first matching type in your enum will always establish the connection. This
1690/// is especially important if one of the connection types is `diesel::SqliteConnection`
1691/// as this connection type accepts arbitrary paths. It should normally place as last entry
1692/// in your enum. If you want control of which connection type is created, just construct the
1693/// corresponding enum manually by first establishing the connection via the inner type and then
1694/// wrap the result into the enum.
1695///
1696/// # Example
1697/// ```
1698/// # extern crate diesel;
1699/// # use diesel::result::QueryResult;
1700/// use diesel::prelude::*;
1701///
1702/// #[derive(diesel::MultiConnection)]
1703/// pub enum AnyConnection {
1704/// #   #[cfg(feature = "postgres")]
1705///     Postgresql(diesel::PgConnection),
1706/// #   #[cfg(feature = "mysql")]
1707///     Mysql(diesel::MysqlConnection),
1708/// #   #[cfg(feature = "sqlite")]
1709///     Sqlite(diesel::SqliteConnection),
1710/// }
1711///
1712/// diesel::table! {
1713///     users {
1714///         id -> Integer,
1715///         name -> Text,
1716///     }
1717/// }
1718///
1719/// fn use_multi(conn: &mut AnyConnection) -> QueryResult<()> {
1720///     // Use the connection enum as any other connection type
1721///     // for inserting/updating/loading/…
1722///     diesel::insert_into(users::table)
1723///         .values(users::name.eq("Sean"))
1724///         .execute(conn)?;
1725///
1726///     let users = users::table.load::<(i32, String)>(conn)?;
1727///
1728///     // Match on the connection type to access
1729///     // the inner connection. This allows us then to use
1730///     // backend specific methods.
1731/// #    #[cfg(feature = "postgres")]
1732///     if let AnyConnection::Postgresql(ref mut conn) = conn {
1733///         // perform a postgresql specific query here
1734///         let users = users::table.load::<(i32, String)>(conn)?;
1735///     }
1736///
1737///     Ok(())
1738/// }
1739///
1740/// # fn main() {}
1741/// ```
1742///
1743/// # Limitations
1744///
1745/// The derived connection implementation can only cover the common subset of
1746/// all inner connection types. So, if one backend doesn't support certain SQL features,
1747/// like for example, returning clauses, the whole connection implementation doesn't
1748/// support this feature. In addition, only a limited set of SQL types is supported:
1749///
1750/// * `diesel::sql_types::SmallInt`
1751/// * `diesel::sql_types::Integer`
1752/// * `diesel::sql_types::BigInt`
1753/// * `diesel::sql_types::Double`
1754/// * `diesel::sql_types::Float`
1755/// * `diesel::sql_types::Text`
1756/// * `diesel::sql_types::Date`
1757/// * `diesel::sql_types::Time`
1758/// * `diesel::sql_types::Timestamp`
1759///
1760/// Support for additional types can be added by providing manual implementations of
1761/// `HasSqlType`, `FromSql` and `ToSql` for the corresponding type, all databases included
1762/// in your enum, and the backend generated by this derive called `MultiBackend`.
1763/// For example to support a custom enum `MyEnum` with the custom SQL type `MyInteger`:
1764/// ```
1765/// extern crate diesel;
1766/// use diesel::backend::Backend;
1767/// use diesel::deserialize::{self, FromSql, FromSqlRow};
1768/// use diesel::serialize::{self, IsNull, ToSql};
1769/// use diesel::AsExpression;
1770/// use diesel::sql_types::{HasSqlType, SqlType};
1771/// use diesel::prelude::*;
1772///
1773/// #[derive(diesel::MultiConnection)]
1774/// pub enum AnyConnection {
1775/// #   #[cfg(feature = "postgres")]
1776///     Postgresql(diesel::PgConnection),
1777/// #   #[cfg(feature = "mysql")]
1778///     Mysql(diesel::MysqlConnection),
1779/// #   #[cfg(feature = "sqlite")]
1780///     Sqlite(diesel::SqliteConnection),
1781/// }
1782///
1783/// // defining an custom SQL type is optional
1784/// // you can also use types from `diesel::sql_types`
1785/// #[derive(Copy, Clone, Debug, SqlType)]
1786/// #[diesel(postgres_type(name = "Int4"))]
1787/// #[diesel(mysql_type(name = "Long"))]
1788/// #[diesel(sqlite_type(name = "Integer"))]
1789/// struct MyInteger;
1790///
1791///
1792/// // our custom enum
1793/// #[repr(i32)]
1794/// #[derive(Debug, Clone, Copy, AsExpression, FromSqlRow)]
1795/// #[diesel(sql_type = MyInteger)]
1796/// pub enum MyEnum {
1797///     A = 1,
1798///     B = 2,
1799/// }
1800///
1801/// // The `MultiBackend` type is generated by `#[derive(diesel::MultiConnection)]`
1802/// // This part is only required if you define a custom sql type
1803/// impl HasSqlType<MyInteger> for MultiBackend {
1804///    fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {
1805///        // The `lookup_sql_type` function is exposed by the `MultiBackend` type
1806///        MultiBackend::lookup_sql_type::<MyInteger>(lookup)
1807///    }
1808/// }
1809///
1810/// impl FromSql<MyInteger, MultiBackend> for MyEnum {
1811///    fn from_sql(bytes: <MultiBackend as Backend>::RawValue<'_>) -> deserialize::Result<Self> {
1812///        // The `from_sql` function is exposed by the `RawValue` type of the
1813///        // `MultiBackend` type
1814///        // This requires a `FromSql` impl for each backend
1815///        bytes.from_sql::<MyEnum, MyInteger>()
1816///    }
1817/// }
1818///
1819/// impl ToSql<MyInteger, MultiBackend> for MyEnum {
1820///    fn to_sql<'b>(&'b self, out: &mut serialize::Output<'b, '_, MultiBackend>) -> serialize::Result {
1821///        /// `set_value` expects a tuple consisting of the target SQL type
1822///        /// and self for `MultiBackend`
1823///        /// This requires a `ToSql` impl for each backend
1824///        out.set_value((MyInteger, self));
1825///        Ok(IsNull::No)
1826///    }
1827/// }
1828/// # #[cfg(feature = "postgres")]
1829/// # impl ToSql<MyInteger, diesel::pg::Pg> for MyEnum {
1830/// #    fn to_sql<'b>(&'b self, out: &mut serialize::Output<'b, '_, diesel::pg::Pg>) -> serialize::Result { todo!() }
1831/// # }
1832/// # #[cfg(feature = "mysql")]
1833/// # impl ToSql<MyInteger, diesel::mysql::Mysql> for MyEnum {
1834/// #    fn to_sql<'b>(&'b self, out: &mut serialize::Output<'b, '_, diesel::mysql::Mysql>) -> serialize::Result { todo!() }
1835/// # }
1836/// # #[cfg(feature = "sqlite")]
1837/// # impl ToSql<MyInteger, diesel::sqlite::Sqlite> for MyEnum {
1838/// #    fn to_sql<'b>(&'b self, out: &mut serialize::Output<'b, '_, diesel::sqlite::Sqlite>) -> serialize::Result { todo!() }
1839/// # }
1840/// # #[cfg(feature = "postgres")]
1841/// # impl FromSql<MyInteger, diesel::pg::Pg> for MyEnum {
1842/// #    fn from_sql(bytes: <diesel::pg::Pg as Backend>::RawValue<'_>) -> deserialize::Result<Self> { todo!() }
1843/// # }
1844/// # #[cfg(feature = "mysql")]
1845/// # impl FromSql<MyInteger, diesel::mysql::Mysql> for MyEnum {
1846/// #    fn from_sql(bytes: <diesel::mysql::Mysql as Backend>::RawValue<'_>) -> deserialize::Result<Self> { todo!() }
1847/// # }
1848/// # #[cfg(feature = "sqlite")]
1849/// # impl FromSql<MyInteger, diesel::sqlite::Sqlite> for MyEnum {
1850/// #    fn from_sql(bytes: <diesel::sqlite::Sqlite as Backend>::RawValue<'_>) -> deserialize::Result<Self> { todo!() }
1851/// # }
1852/// # fn main() {}
1853/// ```
1854///
1855#[cfg_attr(diesel_docsrs, doc = "\n# Expanded Code\n\n<details>\n<summary> Expanded Code </summary>\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(MultiConnection)]\nenum DbConnection {\n    Pg(PgConnection),\n    Sqlite(diesel::SqliteConnection),\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nmod multi_connection_impl {\n    use super::*;\n    mod backend {\n        use super::*;\n        pub enum MultiBackend {\n            Pg(<PgConnection as diesel::Connection>::Backend),\n            Sqlite(<diesel::SqliteConnection as diesel::Connection>::Backend),\n        }\n        impl MultiBackend {\n            pub(super) fn pg(&self) -> &<PgConnection as diesel::Connection>::Backend {\n                match self {\n                    Self::Pg(b) => b,\n                    _ => unreachable!(),\n                }\n            }\n            pub(super) fn sqlite(\n                &self,\n            ) -> &<diesel::SqliteConnection as diesel::Connection>::Backend {\n                match self {\n                    Self::Sqlite(b) => b,\n                    _ => unreachable!(),\n                }\n            }\n            pub fn lookup_sql_type<ST>(\n                lookup: &mut dyn std::any::Any,\n            ) -> MultiTypeMetadata\n            where\n                <PgConnection as diesel::Connection>::Backend: diesel::sql_types::HasSqlType<\n                    ST,\n                >,\n                <diesel::SqliteConnection as diesel::Connection>::Backend: diesel::sql_types::HasSqlType<\n                    ST,\n                >,\n            {\n                let mut ret = MultiTypeMetadata::default();\n                if let Some(lookup) = <PgConnection as diesel::internal::derives::multiconnection::MultiConnectionHelper>::from_any(\n                    lookup,\n                ) {\n                    ret.Pg = Some(\n                        <<PgConnection as diesel::Connection>::Backend as diesel::sql_types::HasSqlType<\n                            ST,\n                        >>::metadata(lookup),\n                    );\n                }\n                if let Some(lookup) = <diesel::SqliteConnection as diesel::internal::derives::multiconnection::MultiConnectionHelper>::from_any(\n                    lookup,\n                ) {\n                    ret.Sqlite = Some(\n                        <<diesel::SqliteConnection as diesel::Connection>::Backend as diesel::sql_types::HasSqlType<\n                            ST,\n                        >>::metadata(lookup),\n                    );\n                }\n                ret\n            }\n        }\n        impl MultiBackend {\n            pub fn walk_variant_ast<\'b, T>(\n                ast_node: &\'b T,\n                pass: diesel::query_builder::AstPass<\'_, \'b, Self>,\n            ) -> diesel::QueryResult<()>\n            where\n                T: diesel::query_builder::QueryFragment<\n                    <PgConnection as diesel::Connection>::Backend,\n                >,\n                T: diesel::query_builder::QueryFragment<\n                    <diesel::SqliteConnection as diesel::Connection>::Backend,\n                >,\n            {\n                use diesel::internal::derives::multiconnection::AstPassHelper;\n                match pass.backend() {\n                    super::backend::MultiBackend::Pg(_) => {\n                        <T as diesel::query_builder::QueryFragment<\n                            <PgConnection as diesel::connection::Connection>::Backend,\n                        >>::walk_ast(\n                            ast_node,\n                            pass\n                                .cast_database(\n                                    super::bind_collector::MultiBindCollector::pg,\n                                    super::query_builder::MultiQueryBuilder::pg,\n                                    super::backend::MultiBackend::pg,\n                                    |l| {\n                                        <PgConnection as diesel::internal::derives::multiconnection::MultiConnectionHelper>::from_any(\n                                                l,\n                                            )\n                                            .expect(\n                                                \"It\'s possible to downcast the metadata lookup type to the correct type\",\n                                            )\n                                    },\n                                ),\n                        )\n                    }\n                    super::backend::MultiBackend::Sqlite(_) => {\n                        <T as diesel::query_builder::QueryFragment<\n                            <diesel::SqliteConnection as diesel::connection::Connection>::Backend,\n                        >>::walk_ast(\n                            ast_node,\n                            pass\n                                .cast_database(\n                                    super::bind_collector::MultiBindCollector::sqlite,\n                                    super::query_builder::MultiQueryBuilder::sqlite,\n                                    super::backend::MultiBackend::sqlite,\n                                    |l| {\n                                        <diesel::SqliteConnection as diesel::internal::derives::multiconnection::MultiConnectionHelper>::from_any(\n                                                l,\n                                            )\n                                            .expect(\n                                                \"It\'s possible to downcast the metadata lookup type to the correct type\",\n                                            )\n                                    },\n                                ),\n                        )\n                    }\n                }\n            }\n        }\n        pub enum MultiRawValue<\'a> {\n            Pg(\n                <<PgConnection as diesel::Connection>::Backend as diesel::backend::Backend>::RawValue<\n                    \'a,\n                >,\n            ),\n            Sqlite(\n                <<diesel::SqliteConnection as diesel::Connection>::Backend as diesel::backend::Backend>::RawValue<\n                    \'a,\n                >,\n            ),\n        }\n        impl MultiRawValue<\'_> {\n            pub fn from_sql<T, ST>(self) -> diesel::deserialize::Result<T>\n            where\n                T: diesel::deserialize::FromSql<\n                    ST,\n                    <PgConnection as diesel::Connection>::Backend,\n                >,\n                T: diesel::deserialize::FromSql<\n                    ST,\n                    <diesel::SqliteConnection as diesel::Connection>::Backend,\n                >,\n            {\n                match self {\n                    Self::Pg(b) => {\n                        <T as diesel::deserialize::FromSql<\n                            ST,\n                            <PgConnection as diesel::Connection>::Backend,\n                        >>::from_sql(b)\n                    }\n                    Self::Sqlite(b) => {\n                        <T as diesel::deserialize::FromSql<\n                            ST,\n                            <diesel::SqliteConnection as diesel::Connection>::Backend,\n                        >>::from_sql(b)\n                    }\n                }\n            }\n        }\n        impl diesel::backend::Backend for MultiBackend {\n            type QueryBuilder = super::query_builder::MultiQueryBuilder;\n            type RawValue<\'a> = MultiRawValue<\'a>;\n            type BindCollector<\'a> = super::bind_collector::MultiBindCollector<\'a>;\n        }\n        #[derive(Default)]\n        #[allow(non_snake_case)]\n        pub struct MultiTypeMetadata {\n            pub(super) Pg: Option<\n                <<PgConnection as diesel::Connection>::Backend as diesel::sql_types::TypeMetadata>::TypeMetadata,\n            >,\n            pub(super) Sqlite: Option<\n                <<diesel::SqliteConnection as diesel::Connection>::Backend as diesel::sql_types::TypeMetadata>::TypeMetadata,\n            >,\n        }\n        impl diesel::sql_types::TypeMetadata for MultiBackend {\n            type TypeMetadata = MultiTypeMetadata;\n            type MetadataLookup = dyn std::any::Any;\n        }\n        pub struct MultiReturningClause;\n        pub struct MultiInsertWithDefaultKeyword;\n        pub struct MultiBatchInsertSupport;\n        pub struct MultiDefaultValueClauseForInsert;\n        pub struct MultiEmptyFromClauseSyntax;\n        pub struct MultiExistsSyntax;\n        pub struct MultiArrayComparisonSyntax;\n        pub struct MultiConcatClauseSyntax;\n        pub struct MultiSelectStatementSyntax;\n        pub struct MultiAliasSyntax;\n        pub struct MultiWindowFrameClauseGroupSupport;\n        pub struct MultiWindowFrameExclusionSupport;\n        pub struct MultiAggregateFunctionExpressions;\n        pub struct MultiBuiltInWindowFunctionRequireOrder;\n        impl diesel::backend::SqlDialect for MultiBackend {\n            type ReturningClause = MultiReturningClause;\n            type OnConflictClause = diesel::internal::derives::multiconnection::sql_dialect::on_conflict_clause::DoesNotSupportOnConflictClause;\n            type InsertWithDefaultKeyword = MultiInsertWithDefaultKeyword;\n            type BatchInsertSupport = MultiBatchInsertSupport;\n            type DefaultValueClauseForInsert = MultiDefaultValueClauseForInsert;\n            type EmptyFromClauseSyntax = MultiEmptyFromClauseSyntax;\n            type ExistsSyntax = MultiExistsSyntax;\n            type ArrayComparison = MultiArrayComparisonSyntax;\n            type ConcatClause = MultiConcatClauseSyntax;\n            type SelectStatementSyntax = MultiSelectStatementSyntax;\n            type AliasSyntax = MultiAliasSyntax;\n            type WindowFrameClauseGroupSupport = MultiWindowFrameClauseGroupSupport;\n            type WindowFrameExclusionSupport = MultiWindowFrameExclusionSupport;\n            type AggregateFunctionExpressions = MultiAggregateFunctionExpressions;\n            type BuiltInWindowFunctionRequireOrder = MultiBuiltInWindowFunctionRequireOrder;\n        }\n        impl diesel::internal::derives::multiconnection::TrustedBackend\n        for MultiBackend {}\n        impl diesel::internal::derives::multiconnection::DieselReserveSpecialization\n        for MultiBackend {}\n        impl diesel::sql_types::HasSqlType<diesel::sql_types::SmallInt>\n        for super::MultiBackend {\n            fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {\n                Self::lookup_sql_type::<diesel::sql_types::SmallInt>(lookup)\n            }\n        }\n        impl diesel::sql_types::HasSqlType<diesel::sql_types::Integer>\n        for super::MultiBackend {\n            fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {\n                Self::lookup_sql_type::<diesel::sql_types::Integer>(lookup)\n            }\n        }\n        impl diesel::sql_types::HasSqlType<diesel::sql_types::BigInt>\n        for super::MultiBackend {\n            fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {\n                Self::lookup_sql_type::<diesel::sql_types::BigInt>(lookup)\n            }\n        }\n        impl diesel::sql_types::HasSqlType<diesel::sql_types::Double>\n        for super::MultiBackend {\n            fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {\n                Self::lookup_sql_type::<diesel::sql_types::Double>(lookup)\n            }\n        }\n        impl diesel::sql_types::HasSqlType<diesel::sql_types::Float>\n        for super::MultiBackend {\n            fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {\n                Self::lookup_sql_type::<diesel::sql_types::Float>(lookup)\n            }\n        }\n        impl diesel::sql_types::HasSqlType<diesel::sql_types::Text>\n        for super::MultiBackend {\n            fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {\n                Self::lookup_sql_type::<diesel::sql_types::Text>(lookup)\n            }\n        }\n        impl diesel::sql_types::HasSqlType<diesel::sql_types::Binary>\n        for super::MultiBackend {\n            fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {\n                Self::lookup_sql_type::<diesel::sql_types::Binary>(lookup)\n            }\n        }\n        impl diesel::sql_types::HasSqlType<diesel::sql_types::Date>\n        for super::MultiBackend {\n            fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {\n                Self::lookup_sql_type::<diesel::sql_types::Date>(lookup)\n            }\n        }\n        impl diesel::sql_types::HasSqlType<diesel::sql_types::Time>\n        for super::MultiBackend {\n            fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {\n                Self::lookup_sql_type::<diesel::sql_types::Time>(lookup)\n            }\n        }\n        impl diesel::sql_types::HasSqlType<diesel::sql_types::Timestamp>\n        for super::MultiBackend {\n            fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {\n                Self::lookup_sql_type::<diesel::sql_types::Timestamp>(lookup)\n            }\n        }\n        impl diesel::sql_types::HasSqlType<diesel::sql_types::Bool>\n        for super::MultiBackend {\n            fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {\n                Self::lookup_sql_type::<diesel::sql_types::Bool>(lookup)\n            }\n        }\n        impl diesel::sql_types::HasSqlType<diesel::sql_types::Numeric>\n        for super::MultiBackend {\n            fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {\n                Self::lookup_sql_type::<diesel::sql_types::Numeric>(lookup)\n            }\n        }\n    }\n    mod query_builder {\n        use super::*;\n        pub enum MultiQueryBuilder {\n            Pg(\n                <<PgConnection as diesel::Connection>::Backend as diesel::backend::Backend>::QueryBuilder,\n            ),\n            Sqlite(\n                <<diesel::SqliteConnection as diesel::Connection>::Backend as diesel::backend::Backend>::QueryBuilder,\n            ),\n        }\n        impl MultiQueryBuilder {\n            pub(super) fn duplicate(&self) -> Self {\n                match self {\n                    Self::Pg(_) => Self::Pg(Default::default()),\n                    Self::Sqlite(_) => Self::Sqlite(Default::default()),\n                }\n            }\n        }\n        impl MultiQueryBuilder {\n            pub(super) fn pg(\n                &mut self,\n            ) -> &mut <<PgConnection as diesel::Connection>::Backend as diesel::backend::Backend>::QueryBuilder {\n                match self {\n                    Self::Pg(qb) => qb,\n                    _ => unreachable!(),\n                }\n            }\n            pub(super) fn sqlite(\n                &mut self,\n            ) -> &mut <<diesel::SqliteConnection as diesel::Connection>::Backend as diesel::backend::Backend>::QueryBuilder {\n                match self {\n                    Self::Sqlite(qb) => qb,\n                    _ => unreachable!(),\n                }\n            }\n        }\n        impl diesel::query_builder::QueryBuilder<super::MultiBackend>\n        for MultiQueryBuilder {\n            fn push_sql(&mut self, sql: &str) {\n                match self {\n                    Self::Pg(q) => q.push_sql(sql),\n                    Self::Sqlite(q) => q.push_sql(sql),\n                }\n            }\n            fn push_identifier(&mut self, identifier: &str) -> diesel::QueryResult<()> {\n                match self {\n                    Self::Pg(q) => q.push_identifier(identifier),\n                    Self::Sqlite(q) => q.push_identifier(identifier),\n                }\n            }\n            fn push_bind_param(&mut self) {\n                match self {\n                    Self::Pg(q) => q.push_bind_param(),\n                    Self::Sqlite(q) => q.push_bind_param(),\n                }\n            }\n            fn finish(self) -> String {\n                match self {\n                    Self::Pg(q) => q.finish(),\n                    Self::Sqlite(q) => q.finish(),\n                }\n            }\n        }\n        impl<L, O> diesel::query_builder::QueryFragment<super::backend::MultiBackend>\n        for diesel::internal::derives::multiconnection::LimitOffsetClause<L, O>\n        where\n            Self: diesel::query_builder::QueryFragment<\n                    <PgConnection as diesel::connection::Connection>::Backend,\n                >\n                + diesel::query_builder::QueryFragment<\n                    <diesel::SqliteConnection as diesel::connection::Connection>::Backend,\n                >,\n        {\n            fn walk_ast<\'b>(\n                &\'b self,\n                pass: diesel::query_builder::AstPass<\'_, \'b, MultiBackend>,\n            ) -> diesel::QueryResult<()> {\n                super::backend::MultiBackend::walk_variant_ast(self, pass)\n            }\n        }\n        impl<\n            L,\n            R,\n        > diesel::query_builder::QueryFragment<\n            super::backend::MultiBackend,\n            super::backend::MultiConcatClauseSyntax,\n        > for diesel::internal::derives::multiconnection::Concat<L, R>\n        where\n            Self: diesel::query_builder::QueryFragment<\n                    <PgConnection as diesel::connection::Connection>::Backend,\n                >\n                + diesel::query_builder::QueryFragment<\n                    <diesel::SqliteConnection as diesel::connection::Connection>::Backend,\n                >,\n        {\n            fn walk_ast<\'b>(\n                &\'b self,\n                pass: diesel::query_builder::AstPass<\'_, \'b, MultiBackend>,\n            ) -> diesel::QueryResult<()> {\n                super::backend::MultiBackend::walk_variant_ast(self, pass)\n            }\n        }\n        impl<\n            T,\n            U,\n        > diesel::query_builder::QueryFragment<\n            super::backend::MultiBackend,\n            super::backend::MultiArrayComparisonSyntax,\n        > for diesel::internal::derives::multiconnection::array_comparison::In<T, U>\n        where\n            Self: diesel::query_builder::QueryFragment<\n                    <PgConnection as diesel::connection::Connection>::Backend,\n                >\n                + diesel::query_builder::QueryFragment<\n                    <diesel::SqliteConnection as diesel::connection::Connection>::Backend,\n                >,\n        {\n            fn walk_ast<\'b>(\n                &\'b self,\n                pass: diesel::query_builder::AstPass<\'_, \'b, MultiBackend>,\n            ) -> diesel::QueryResult<()> {\n                super::backend::MultiBackend::walk_variant_ast(self, pass)\n            }\n        }\n        impl<\n            T,\n            U,\n        > diesel::query_builder::QueryFragment<\n            super::backend::MultiBackend,\n            super::backend::MultiArrayComparisonSyntax,\n        > for diesel::internal::derives::multiconnection::array_comparison::NotIn<T, U>\n        where\n            Self: diesel::query_builder::QueryFragment<\n                    <PgConnection as diesel::connection::Connection>::Backend,\n                >\n                + diesel::query_builder::QueryFragment<\n                    <diesel::SqliteConnection as diesel::connection::Connection>::Backend,\n                >,\n        {\n            fn walk_ast<\'b>(\n                &\'b self,\n                pass: diesel::query_builder::AstPass<\'_, \'b, MultiBackend>,\n            ) -> diesel::QueryResult<()> {\n                super::backend::MultiBackend::walk_variant_ast(self, pass)\n            }\n        }\n        impl<\n            ST,\n            I,\n        > diesel::query_builder::QueryFragment<\n            super::backend::MultiBackend,\n            super::backend::MultiArrayComparisonSyntax,\n        > for diesel::internal::derives::multiconnection::array_comparison::Many<ST, I>\n        where\n            Self: diesel::query_builder::QueryFragment<\n                    <PgConnection as diesel::connection::Connection>::Backend,\n                >\n                + diesel::query_builder::QueryFragment<\n                    <diesel::SqliteConnection as diesel::connection::Connection>::Backend,\n                >,\n        {\n            fn walk_ast<\'b>(\n                &\'b self,\n                pass: diesel::query_builder::AstPass<\'_, \'b, MultiBackend>,\n            ) -> diesel::QueryResult<()> {\n                super::backend::MultiBackend::walk_variant_ast(self, pass)\n            }\n        }\n        impl<\n            T,\n        > diesel::query_builder::QueryFragment<\n            super::backend::MultiBackend,\n            super::backend::MultiExistsSyntax,\n        > for diesel::internal::derives::multiconnection::Exists<T>\n        where\n            Self: diesel::query_builder::QueryFragment<\n                    <PgConnection as diesel::connection::Connection>::Backend,\n                >\n                + diesel::query_builder::QueryFragment<\n                    <diesel::SqliteConnection as diesel::connection::Connection>::Backend,\n                >,\n        {\n            fn walk_ast<\'b>(\n                &\'b self,\n                pass: diesel::query_builder::AstPass<\'_, \'b, MultiBackend>,\n            ) -> diesel::QueryResult<()> {\n                super::backend::MultiBackend::walk_variant_ast(self, pass)\n            }\n        }\n        impl diesel::query_builder::QueryFragment<\n            super::backend::MultiBackend,\n            super::backend::MultiEmptyFromClauseSyntax,\n        > for diesel::internal::derives::multiconnection::NoFromClause\n        where\n            Self: diesel::query_builder::QueryFragment<\n                    <PgConnection as diesel::connection::Connection>::Backend,\n                >\n                + diesel::query_builder::QueryFragment<\n                    <diesel::SqliteConnection as diesel::connection::Connection>::Backend,\n                >,\n        {\n            fn walk_ast<\'b>(\n                &\'b self,\n                pass: diesel::query_builder::AstPass<\'_, \'b, MultiBackend>,\n            ) -> diesel::QueryResult<()> {\n                super::backend::MultiBackend::walk_variant_ast(self, pass)\n            }\n        }\n        impl diesel::query_builder::QueryFragment<\n            super::backend::MultiBackend,\n            super::backend::MultiDefaultValueClauseForInsert,\n        > for diesel::internal::derives::multiconnection::DefaultValues\n        where\n            Self: diesel::query_builder::QueryFragment<\n                    <PgConnection as diesel::connection::Connection>::Backend,\n                >\n                + diesel::query_builder::QueryFragment<\n                    <diesel::SqliteConnection as diesel::connection::Connection>::Backend,\n                >,\n        {\n            fn walk_ast<\'b>(\n                &\'b self,\n                pass: diesel::query_builder::AstPass<\'_, \'b, MultiBackend>,\n            ) -> diesel::QueryResult<()> {\n                super::backend::MultiBackend::walk_variant_ast(self, pass)\n            }\n        }\n        impl<\n            Expr,\n        > diesel::query_builder::QueryFragment<\n            super::backend::MultiBackend,\n            super::backend::MultiReturningClause,\n        > for diesel::internal::derives::multiconnection::ReturningClause<Expr>\n        where\n            Self: diesel::query_builder::QueryFragment<\n                    <PgConnection as diesel::connection::Connection>::Backend,\n                >\n                + diesel::query_builder::QueryFragment<\n                    <diesel::SqliteConnection as diesel::connection::Connection>::Backend,\n                >,\n        {\n            fn walk_ast<\'b>(\n                &\'b self,\n                pass: diesel::query_builder::AstPass<\'_, \'b, MultiBackend>,\n            ) -> diesel::QueryResult<()> {\n                super::backend::MultiBackend::walk_variant_ast(self, pass)\n            }\n        }\n        impl<\n            Expr,\n        > diesel::query_builder::QueryFragment<\n            super::backend::MultiBackend,\n            super::backend::MultiInsertWithDefaultKeyword,\n        > for diesel::insertable::DefaultableColumnInsertValue<Expr>\n        where\n            Self: diesel::query_builder::QueryFragment<\n                    <PgConnection as diesel::connection::Connection>::Backend,\n                >\n                + diesel::query_builder::QueryFragment<\n                    <diesel::SqliteConnection as diesel::connection::Connection>::Backend,\n                >,\n        {\n            fn walk_ast<\'b>(\n                &\'b self,\n                pass: diesel::query_builder::AstPass<\'_, \'b, MultiBackend>,\n            ) -> diesel::QueryResult<()> {\n                super::backend::MultiBackend::walk_variant_ast(self, pass)\n            }\n        }\n        impl<\n            Tab,\n            V,\n            QId,\n            const HAS_STATIC_QUERY_ID: bool,\n        > diesel::query_builder::QueryFragment<\n            super::backend::MultiBackend,\n            super::backend::MultiBatchInsertSupport,\n        >\n        for diesel::internal::derives::multiconnection::BatchInsert<\n            V,\n            Tab,\n            QId,\n            HAS_STATIC_QUERY_ID,\n        >\n        where\n            Self: diesel::query_builder::QueryFragment<\n                    <PgConnection as diesel::connection::Connection>::Backend,\n                >\n                + diesel::query_builder::QueryFragment<\n                    <diesel::SqliteConnection as diesel::connection::Connection>::Backend,\n                >,\n        {\n            fn walk_ast<\'b>(\n                &\'b self,\n                pass: diesel::query_builder::AstPass<\'_, \'b, MultiBackend>,\n            ) -> diesel::QueryResult<()> {\n                super::backend::MultiBackend::walk_variant_ast(self, pass)\n            }\n        }\n        impl<\n            S,\n        > diesel::query_builder::QueryFragment<\n            super::backend::MultiBackend,\n            super::backend::MultiAliasSyntax,\n        > for diesel::query_source::Alias<S>\n        where\n            Self: diesel::query_builder::QueryFragment<\n                    <PgConnection as diesel::connection::Connection>::Backend,\n                >\n                + diesel::query_builder::QueryFragment<\n                    <diesel::SqliteConnection as diesel::connection::Connection>::Backend,\n                >,\n        {\n            fn walk_ast<\'b>(\n                &\'b self,\n                pass: diesel::query_builder::AstPass<\'_, \'b, MultiBackend>,\n            ) -> diesel::QueryResult<()> {\n                super::backend::MultiBackend::walk_variant_ast(self, pass)\n            }\n        }\n        impl<\n            F,\n            S,\n            D,\n            W,\n            O,\n            LOf,\n            G,\n            H,\n            LC,\n        > diesel::query_builder::QueryFragment<\n            super::backend::MultiBackend,\n            super::backend::MultiSelectStatementSyntax,\n        >\n        for diesel::internal::derives::multiconnection::SelectStatement<\n            F,\n            S,\n            D,\n            W,\n            O,\n            LOf,\n            G,\n            H,\n            LC,\n        >\n        where\n            S: diesel::query_builder::QueryFragment<super::backend::MultiBackend>,\n            F: diesel::query_builder::QueryFragment<super::backend::MultiBackend>,\n            D: diesel::query_builder::QueryFragment<super::backend::MultiBackend>,\n            W: diesel::query_builder::QueryFragment<super::backend::MultiBackend>,\n            O: diesel::query_builder::QueryFragment<super::backend::MultiBackend>,\n            LOf: diesel::query_builder::QueryFragment<super::backend::MultiBackend>,\n            G: diesel::query_builder::QueryFragment<super::backend::MultiBackend>,\n            H: diesel::query_builder::QueryFragment<super::backend::MultiBackend>,\n            LC: diesel::query_builder::QueryFragment<super::backend::MultiBackend>,\n        {\n            fn walk_ast<\'b>(\n                &\'b self,\n                mut out: diesel::query_builder::AstPass<\'_, \'b, MultiBackend>,\n            ) -> diesel::QueryResult<()> {\n                use diesel::internal::derives::multiconnection::SelectStatementAccessor;\n                out.push_sql(\"SELECT \");\n                self.distinct_clause().walk_ast(out.reborrow())?;\n                self.select_clause().walk_ast(out.reborrow())?;\n                self.from_clause().walk_ast(out.reborrow())?;\n                self.where_clause().walk_ast(out.reborrow())?;\n                self.group_by_clause().walk_ast(out.reborrow())?;\n                self.having_clause().walk_ast(out.reborrow())?;\n                self.order_clause().walk_ast(out.reborrow())?;\n                self.limit_offset_clause().walk_ast(out.reborrow())?;\n                self.locking_clause().walk_ast(out.reborrow())?;\n                Ok(())\n            }\n        }\n        impl<\n            \'a,\n            ST,\n            QS,\n            GB,\n        > diesel::query_builder::QueryFragment<\n            super::backend::MultiBackend,\n            super::backend::MultiSelectStatementSyntax,\n        >\n        for diesel::internal::derives::multiconnection::BoxedSelectStatement<\n            \'a,\n            ST,\n            QS,\n            super::backend::MultiBackend,\n            GB,\n        >\n        where\n            QS: diesel::query_builder::QueryFragment<super::backend::MultiBackend>,\n        {\n            fn walk_ast<\'b>(\n                &\'b self,\n                pass: diesel::query_builder::AstPass<\'_, \'b, MultiBackend>,\n            ) -> diesel::QueryResult<()> {\n                use diesel::internal::derives::multiconnection::BoxedQueryHelper;\n                self.build_query(pass, |where_clause, pass| where_clause.walk_ast(pass))\n            }\n        }\n        impl diesel::query_builder::QueryFragment<super::backend::MultiBackend>\n        for diesel::internal::derives::multiconnection::BoxedLimitOffsetClause<\n            \'_,\n            super::backend::MultiBackend,\n        > {\n            fn walk_ast<\'b>(\n                &\'b self,\n                mut pass: diesel::query_builder::AstPass<\'_, \'b, MultiBackend>,\n            ) -> diesel::QueryResult<()> {\n                if let Some(ref limit) = self.limit {\n                    limit.walk_ast(pass.reborrow())?;\n                }\n                if let Some(ref offset) = self.offset {\n                    offset.walk_ast(pass.reborrow())?;\n                }\n                Ok(())\n            }\n        }\n        impl<\n            \'a,\n        > diesel::query_builder::IntoBoxedClause<\n            \'a,\n            super::multi_connection_impl::backend::MultiBackend,\n        >\n        for diesel::internal::derives::multiconnection::LimitOffsetClause<\n            diesel::internal::derives::multiconnection::NoLimitClause,\n            diesel::internal::derives::multiconnection::NoOffsetClause,\n        > {\n            type BoxedClause = diesel::internal::derives::multiconnection::BoxedLimitOffsetClause<\n                \'a,\n                super::multi_connection_impl::backend::MultiBackend,\n            >;\n            fn into_boxed(self) -> Self::BoxedClause {\n                diesel::internal::derives::multiconnection::BoxedLimitOffsetClause {\n                    limit: None,\n                    offset: None,\n                }\n            }\n        }\n        impl<\n            \'a,\n            L,\n        > diesel::query_builder::IntoBoxedClause<\n            \'a,\n            super::multi_connection_impl::backend::MultiBackend,\n        >\n        for diesel::internal::derives::multiconnection::LimitOffsetClause<\n            diesel::internal::derives::multiconnection::LimitClause<L>,\n            diesel::internal::derives::multiconnection::NoOffsetClause,\n        >\n        where\n            diesel::internal::derives::multiconnection::LimitClause<\n                L,\n            >: diesel::query_builder::QueryFragment<super::backend::MultiBackend> + Send\n                + \'static,\n        {\n            type BoxedClause = diesel::internal::derives::multiconnection::BoxedLimitOffsetClause<\n                \'a,\n                super::multi_connection_impl::backend::MultiBackend,\n            >;\n            fn into_boxed(self) -> Self::BoxedClause {\n                diesel::internal::derives::multiconnection::BoxedLimitOffsetClause {\n                    limit: Some(Box::new(self.limit_clause)),\n                    offset: None,\n                }\n            }\n        }\n        impl<\n            \'a,\n            O,\n        > diesel::query_builder::IntoBoxedClause<\n            \'a,\n            super::multi_connection_impl::backend::MultiBackend,\n        >\n        for diesel::internal::derives::multiconnection::LimitOffsetClause<\n            diesel::internal::derives::multiconnection::NoLimitClause,\n            diesel::internal::derives::multiconnection::OffsetClause<O>,\n        >\n        where\n            diesel::internal::derives::multiconnection::OffsetClause<\n                O,\n            >: diesel::query_builder::QueryFragment<super::backend::MultiBackend> + Send\n                + \'static,\n        {\n            type BoxedClause = diesel::internal::derives::multiconnection::BoxedLimitOffsetClause<\n                \'a,\n                super::multi_connection_impl::backend::MultiBackend,\n            >;\n            fn into_boxed(self) -> Self::BoxedClause {\n                diesel::internal::derives::multiconnection::BoxedLimitOffsetClause {\n                    limit: None,\n                    offset: Some(Box::new(self.offset_clause)),\n                }\n            }\n        }\n        impl<\n            \'a,\n            L,\n            O,\n        > diesel::query_builder::IntoBoxedClause<\n            \'a,\n            super::multi_connection_impl::backend::MultiBackend,\n        >\n        for diesel::internal::derives::multiconnection::LimitOffsetClause<\n            diesel::internal::derives::multiconnection::LimitClause<L>,\n            diesel::internal::derives::multiconnection::OffsetClause<O>,\n        >\n        where\n            diesel::internal::derives::multiconnection::LimitClause<\n                L,\n            >: diesel::query_builder::QueryFragment<super::backend::MultiBackend> + Send\n                + \'static,\n            diesel::internal::derives::multiconnection::OffsetClause<\n                O,\n            >: diesel::query_builder::QueryFragment<super::backend::MultiBackend> + Send\n                + \'static,\n        {\n            type BoxedClause = diesel::internal::derives::multiconnection::BoxedLimitOffsetClause<\n                \'a,\n                super::multi_connection_impl::backend::MultiBackend,\n            >;\n            fn into_boxed(self) -> Self::BoxedClause {\n                diesel::internal::derives::multiconnection::BoxedLimitOffsetClause {\n                    limit: Some(Box::new(self.limit_clause)),\n                    offset: Some(Box::new(self.offset_clause)),\n                }\n            }\n        }\n        impl<\n            Col,\n            Expr,\n        > diesel::insertable::InsertValues<\n            super::multi_connection_impl::backend::MultiBackend,\n            Col::Table,\n        >\n        for diesel::insertable::DefaultableColumnInsertValue<\n            diesel::insertable::ColumnInsertValue<Col, Expr>,\n        >\n        where\n            Col: diesel::prelude::Column,\n            Expr: diesel::prelude::Expression<SqlType = Col::SqlType>,\n            Expr: diesel::prelude::AppearsOnTable<\n                diesel::internal::derives::multiconnection::NoFromClause,\n            >,\n            Self: diesel::query_builder::QueryFragment<\n                super::multi_connection_impl::backend::MultiBackend,\n            >,\n            diesel::insertable::DefaultableColumnInsertValue<\n                diesel::insertable::ColumnInsertValue<Col, Expr>,\n            >: diesel::insertable::InsertValues<\n                <PgConnection as diesel::connection::Connection>::Backend,\n                Col::Table,\n            >,\n            diesel::insertable::DefaultableColumnInsertValue<\n                diesel::insertable::ColumnInsertValue<Col, Expr>,\n            >: diesel::insertable::InsertValues<\n                <diesel::SqliteConnection as diesel::connection::Connection>::Backend,\n                Col::Table,\n            >,\n        {\n            fn column_names(\n                &self,\n                mut out: diesel::query_builder::AstPass<\n                    \'_,\n                    \'_,\n                    super::multi_connection_impl::backend::MultiBackend,\n                >,\n            ) -> diesel::QueryResult<()> {\n                use diesel::internal::derives::multiconnection::AstPassHelper;\n                match out.backend() {\n                    super::backend::MultiBackend::Pg(_) => {\n                        <Self as diesel::insertable::InsertValues<\n                            <PgConnection as diesel::connection::Connection>::Backend,\n                            Col::Table,\n                        >>::column_names(\n                            &self,\n                            out\n                                .cast_database(\n                                    super::bind_collector::MultiBindCollector::pg,\n                                    super::query_builder::MultiQueryBuilder::pg,\n                                    super::backend::MultiBackend::pg,\n                                    |l| {\n                                        <PgConnection as diesel::internal::derives::multiconnection::MultiConnectionHelper>::from_any(\n                                                l,\n                                            )\n                                            .expect(\n                                                \"It\'s possible to downcast the metadata lookup type to the correct type\",\n                                            )\n                                    },\n                                ),\n                        )\n                    }\n                    super::backend::MultiBackend::Sqlite(_) => {\n                        <Self as diesel::insertable::InsertValues<\n                            <diesel::SqliteConnection as diesel::connection::Connection>::Backend,\n                            Col::Table,\n                        >>::column_names(\n                            &self,\n                            out\n                                .cast_database(\n                                    super::bind_collector::MultiBindCollector::sqlite,\n                                    super::query_builder::MultiQueryBuilder::sqlite,\n                                    super::backend::MultiBackend::sqlite,\n                                    |l| {\n                                        <diesel::SqliteConnection as diesel::internal::derives::multiconnection::MultiConnectionHelper>::from_any(\n                                                l,\n                                            )\n                                            .expect(\n                                                \"It\'s possible to downcast the metadata lookup type to the correct type\",\n                                            )\n                                    },\n                                ),\n                        )\n                    }\n                }\n            }\n        }\n    }\n    mod bind_collector {\n        use super::*;\n        pub enum MultiBindCollector<\'a> {\n            Pg(\n                <<PgConnection as diesel::connection::Connection>::Backend as diesel::backend::Backend>::BindCollector<\n                    \'a,\n                >,\n            ),\n            Sqlite(\n                <<diesel::SqliteConnection as diesel::connection::Connection>::Backend as diesel::backend::Backend>::BindCollector<\n                    \'a,\n                >,\n            ),\n        }\n        impl<\'a> MultiBindCollector<\'a> {\n            pub(super) fn pg(\n                &mut self,\n            ) -> &mut <<PgConnection as diesel::connection::Connection>::Backend as diesel::backend::Backend>::BindCollector<\n                \'a,\n            > {\n                match self {\n                    Self::Pg(bc) => bc,\n                    _ => unreachable!(),\n                }\n            }\n            pub(super) fn sqlite(\n                &mut self,\n            ) -> &mut <<diesel::SqliteConnection as diesel::connection::Connection>::Backend as diesel::backend::Backend>::BindCollector<\n                \'a,\n            > {\n                match self {\n                    Self::Sqlite(bc) => bc,\n                    _ => unreachable!(),\n                }\n            }\n        }\n        trait PushBoundValueToCollectorDB<DB: diesel::backend::Backend> {\n            fn push_bound_value<\'a: \'b, \'b>(\n                &self,\n                v: InnerBindValueKind<\'a>,\n                collector: &mut <DB as diesel::backend::Backend>::BindCollector<\'b>,\n                lookup: &mut <DB as diesel::sql_types::TypeMetadata>::MetadataLookup,\n            ) -> diesel::result::QueryResult<()>;\n        }\n        struct PushBoundValueToCollectorImpl<ST, T: ?Sized> {\n            p: std::marker::PhantomData<(ST, T)>,\n        }\n        impl<ST, T, DB> PushBoundValueToCollectorDB<DB>\n        for PushBoundValueToCollectorImpl<ST, T>\n        where\n            DB: diesel::backend::Backend + diesel::sql_types::HasSqlType<ST>,\n            T: diesel::serialize::ToSql<ST, DB> + \'static,\n            Option<\n                T,\n            >: diesel::serialize::ToSql<diesel::sql_types::Nullable<ST>, DB> + \'static,\n            ST: diesel::sql_types::SqlType,\n        {\n            fn push_bound_value<\'a: \'b, \'b>(\n                &self,\n                v: InnerBindValueKind<\'a>,\n                collector: &mut <DB as diesel::backend::Backend>::BindCollector<\'b>,\n                lookup: &mut <DB as diesel::sql_types::TypeMetadata>::MetadataLookup,\n            ) -> diesel::result::QueryResult<()> {\n                use diesel::query_builder::BindCollector;\n                match v {\n                    InnerBindValueKind::Sized(v) => {\n                        let v = v\n                            .downcast_ref::<T>()\n                            .expect(\"We know the type statically here\");\n                        collector.push_bound_value::<ST, T>(v, lookup)\n                    }\n                    InnerBindValueKind::Null => {\n                        collector\n                            .push_bound_value::<\n                                diesel::sql_types::Nullable<ST>,\n                                Option<T>,\n                            >(&None, lookup)\n                    }\n                    _ => {\n                        unreachable!(\n                            \"We set the value to `InnerBindValueKind::Sized` or `InnerBindValueKind::Null`\"\n                        )\n                    }\n                }\n            }\n        }\n        impl<DB> PushBoundValueToCollectorDB<DB>\n        for PushBoundValueToCollectorImpl<diesel::sql_types::Text, str>\n        where\n            DB: diesel::backend::Backend\n                + diesel::sql_types::HasSqlType<diesel::sql_types::Text>,\n            str: diesel::serialize::ToSql<diesel::sql_types::Text, DB> + \'static,\n        {\n            fn push_bound_value<\'a: \'b, \'b>(\n                &self,\n                v: InnerBindValueKind<\'a>,\n                collector: &mut <DB as diesel::backend::Backend>::BindCollector<\'b>,\n                lookup: &mut <DB as diesel::sql_types::TypeMetadata>::MetadataLookup,\n            ) -> diesel::result::QueryResult<()> {\n                use diesel::query_builder::BindCollector;\n                if let InnerBindValueKind::Str(v) = v {\n                    collector.push_bound_value::<diesel::sql_types::Text, str>(v, lookup)\n                } else {\n                    unreachable!(\"We set the value to `InnerBindValueKind::Str`\")\n                }\n            }\n        }\n        impl<DB> PushBoundValueToCollectorDB<DB>\n        for PushBoundValueToCollectorImpl<diesel::sql_types::Binary, [u8]>\n        where\n            DB: diesel::backend::Backend\n                + diesel::sql_types::HasSqlType<diesel::sql_types::Binary>,\n            [u8]: diesel::serialize::ToSql<diesel::sql_types::Binary, DB> + \'static,\n        {\n            fn push_bound_value<\'a: \'b, \'b>(\n                &self,\n                v: InnerBindValueKind<\'a>,\n                collector: &mut <DB as diesel::backend::Backend>::BindCollector<\'b>,\n                lookup: &mut <DB as diesel::sql_types::TypeMetadata>::MetadataLookup,\n            ) -> diesel::result::QueryResult<()> {\n                use diesel::query_builder::BindCollector;\n                if let InnerBindValueKind::Bytes(v) = v {\n                    collector\n                        .push_bound_value::<diesel::sql_types::Binary, [u8]>(v, lookup)\n                } else {\n                    unreachable!(\"We set the value to `InnerBindValueKind::Binary`\")\n                }\n            }\n        }\n        trait PushBoundValueToCollector: PushBoundValueToCollectorDB<\n                <PgConnection as diesel::Connection>::Backend,\n            > + PushBoundValueToCollectorDB<\n                <diesel::SqliteConnection as diesel::Connection>::Backend,\n            > {}\n        impl<T> PushBoundValueToCollector for T\n        where\n            T: PushBoundValueToCollectorDB<<PgConnection as diesel::Connection>::Backend>\n                + PushBoundValueToCollectorDB<\n                    <diesel::SqliteConnection as diesel::Connection>::Backend,\n                >,\n        {}\n        #[derive(Default)]\n        pub struct BindValue<\'a> {\n            inner: Option<InnerBindValue<\'a>>,\n        }\n        struct InnerBindValue<\'a> {\n            value: InnerBindValueKind<\'a>,\n            push_bound_value_to_collector: &\'static dyn PushBoundValueToCollector,\n        }\n        enum InnerBindValueKind<\'a> {\n            Sized(&\'a (dyn std::any::Any + std::marker::Send + std::marker::Sync)),\n            Str(&\'a str),\n            Bytes(&\'a [u8]),\n            Null,\n        }\n        impl<\'a> From<(diesel::sql_types::Text, &\'a str)> for BindValue<\'a> {\n            fn from((_, v): (diesel::sql_types::Text, &\'a str)) -> Self {\n                Self {\n                    inner: Some(InnerBindValue {\n                        value: InnerBindValueKind::Str(v),\n                        push_bound_value_to_collector: &PushBoundValueToCollectorImpl {\n                            p: std::marker::PhantomData::<(diesel::sql_types::Text, str)>,\n                        },\n                    }),\n                }\n            }\n        }\n        impl<\'a> From<(diesel::sql_types::Binary, &\'a [u8])> for BindValue<\'a> {\n            fn from((_, v): (diesel::sql_types::Binary, &\'a [u8])) -> Self {\n                Self {\n                    inner: Some(InnerBindValue {\n                        value: InnerBindValueKind::Bytes(v),\n                        push_bound_value_to_collector: &PushBoundValueToCollectorImpl {\n                            p: std::marker::PhantomData::<\n                                (diesel::sql_types::Binary, [u8]),\n                            >,\n                        },\n                    }),\n                }\n            }\n        }\n        impl<\'a, T, ST> From<(ST, &\'a T)> for BindValue<\'a>\n        where\n            T: std::any::Any\n                + diesel::serialize::ToSql<\n                    ST,\n                    <PgConnection as diesel::connection::Connection>::Backend,\n                >\n                + diesel::serialize::ToSql<\n                    ST,\n                    <diesel::SqliteConnection as diesel::connection::Connection>::Backend,\n                > + Send + Sync + \'static,\n            ST: Send\n                + diesel::sql_types::SqlType<\n                    IsNull = diesel::sql_types::is_nullable::NotNull,\n                > + \'static,\n            <PgConnection as diesel::connection::Connection>::Backend: diesel::sql_types::HasSqlType<\n                ST,\n            >,\n            <diesel::SqliteConnection as diesel::connection::Connection>::Backend: diesel::sql_types::HasSqlType<\n                ST,\n            >,\n        {\n            fn from((_, v): (ST, &\'a T)) -> Self {\n                Self {\n                    inner: Some(InnerBindValue {\n                        value: InnerBindValueKind::Sized(v),\n                        push_bound_value_to_collector: &PushBoundValueToCollectorImpl {\n                            p: std::marker::PhantomData::<(ST, T)>,\n                        },\n                    }),\n                }\n            }\n        }\n        impl<\'a> diesel::query_builder::BindCollector<\'a, MultiBackend>\n        for MultiBindCollector<\'a> {\n            type Buffer = multi_connection_impl::bind_collector::BindValue<\'a>;\n            fn push_bound_value<T, U>(\n                &mut self,\n                bind: &\'a U,\n                metadata_lookup: &mut (dyn std::any::Any + \'static),\n            ) -> diesel::QueryResult<()>\n            where\n                MultiBackend: diesel::sql_types::HasSqlType<T>,\n                U: diesel::serialize::ToSql<T, MultiBackend> + ?Sized + \'a,\n            {\n                let out = {\n                    let out = multi_connection_impl::bind_collector::BindValue::default();\n                    let mut out = diesel::serialize::Output::<\n                        MultiBackend,\n                    >::new(out, metadata_lookup);\n                    let bind_is_null = bind\n                        .to_sql(&mut out)\n                        .map_err(diesel::result::Error::SerializationError)?;\n                    if matches!(bind_is_null, diesel::serialize::IsNull::Yes) {\n                        let metadata = <MultiBackend as diesel::sql_types::HasSqlType<\n                            T,\n                        >>::metadata(metadata_lookup);\n                        match (self, metadata) {\n                            (\n                                Self::Pg(ref mut bc),\n                                super::backend::MultiTypeMetadata { Pg: Some(metadata), .. },\n                            ) => {\n                                bc.push_null_value(metadata)?;\n                            }\n                            (\n                                Self::Sqlite(ref mut bc),\n                                super::backend::MultiTypeMetadata {\n                                    Sqlite: Some(metadata),\n                                    ..\n                                },\n                            ) => {\n                                bc.push_null_value(metadata)?;\n                            }\n                            _ => unreachable!(\"We have matching metadata\"),\n                        }\n                        return Ok(());\n                    } else {\n                        out.into_inner()\n                    }\n                };\n                match self {\n                    Self::Pg(ref mut bc) => {\n                        let out = out\n                            .inner\n                            .expect(\n                                \"This inner value is set via our custom `ToSql` impls\",\n                            );\n                        let callback = out.push_bound_value_to_collector;\n                        let value = out.value;\n                        <_ as PushBoundValueToCollectorDB<\n                            <PgConnection as diesel::Connection>::Backend,\n                        >>::push_bound_value(\n                            callback,\n                            value,\n                            bc,\n                            <PgConnection as diesel::internal::derives::multiconnection::MultiConnectionHelper>::from_any(\n                                    metadata_lookup,\n                                )\n                                .expect(\n                                    \"We can downcast the metadata lookup to the right type\",\n                                ),\n                        )?\n                    }\n                    Self::Sqlite(ref mut bc) => {\n                        let out = out\n                            .inner\n                            .expect(\n                                \"This inner value is set via our custom `ToSql` impls\",\n                            );\n                        let callback = out.push_bound_value_to_collector;\n                        let value = out.value;\n                        <_ as PushBoundValueToCollectorDB<\n                            <diesel::SqliteConnection as diesel::Connection>::Backend,\n                        >>::push_bound_value(\n                            callback,\n                            value,\n                            bc,\n                            <diesel::SqliteConnection as diesel::internal::derives::multiconnection::MultiConnectionHelper>::from_any(\n                                    metadata_lookup,\n                                )\n                                .expect(\n                                    \"We can downcast the metadata lookup to the right type\",\n                                ),\n                        )?\n                    }\n                }\n                Ok(())\n            }\n            fn push_null_value(\n                &mut self,\n                metadata: super::backend::MultiTypeMetadata,\n            ) -> diesel::QueryResult<()> {\n                match (self, metadata) {\n                    (\n                        Self::Pg(ref mut bc),\n                        super::backend::MultiTypeMetadata { Pg: Some(metadata), .. },\n                    ) => {\n                        bc.push_null_value(metadata)?;\n                    }\n                    (\n                        Self::Sqlite(ref mut bc),\n                        super::backend::MultiTypeMetadata { Sqlite: Some(metadata), .. },\n                    ) => {\n                        bc.push_null_value(metadata)?;\n                    }\n                    _ => unreachable!(\"We have matching metadata\"),\n                }\n                Ok(())\n            }\n        }\n        impl diesel::serialize::ToSql<diesel::sql_types::SmallInt, super::MultiBackend>\n        for i16 {\n            fn to_sql<\'b>(\n                &\'b self,\n                out: &mut diesel::serialize::Output<\'b, \'_, super::MultiBackend>,\n            ) -> diesel::serialize::Result {\n                out.set_value((diesel::sql_types::SmallInt, self));\n                Ok(diesel::serialize::IsNull::No)\n            }\n        }\n        impl diesel::serialize::ToSql<diesel::sql_types::Integer, super::MultiBackend>\n        for i32 {\n            fn to_sql<\'b>(\n                &\'b self,\n                out: &mut diesel::serialize::Output<\'b, \'_, super::MultiBackend>,\n            ) -> diesel::serialize::Result {\n                out.set_value((diesel::sql_types::Integer, self));\n                Ok(diesel::serialize::IsNull::No)\n            }\n        }\n        impl diesel::serialize::ToSql<diesel::sql_types::BigInt, super::MultiBackend>\n        for i64 {\n            fn to_sql<\'b>(\n                &\'b self,\n                out: &mut diesel::serialize::Output<\'b, \'_, super::MultiBackend>,\n            ) -> diesel::serialize::Result {\n                out.set_value((diesel::sql_types::BigInt, self));\n                Ok(diesel::serialize::IsNull::No)\n            }\n        }\n        impl diesel::serialize::ToSql<diesel::sql_types::Double, super::MultiBackend>\n        for f64 {\n            fn to_sql<\'b>(\n                &\'b self,\n                out: &mut diesel::serialize::Output<\'b, \'_, super::MultiBackend>,\n            ) -> diesel::serialize::Result {\n                out.set_value((diesel::sql_types::Double, self));\n                Ok(diesel::serialize::IsNull::No)\n            }\n        }\n        impl diesel::serialize::ToSql<diesel::sql_types::Float, super::MultiBackend>\n        for f32 {\n            fn to_sql<\'b>(\n                &\'b self,\n                out: &mut diesel::serialize::Output<\'b, \'_, super::MultiBackend>,\n            ) -> diesel::serialize::Result {\n                out.set_value((diesel::sql_types::Float, self));\n                Ok(diesel::serialize::IsNull::No)\n            }\n        }\n        impl diesel::serialize::ToSql<diesel::sql_types::Text, super::MultiBackend>\n        for str {\n            fn to_sql<\'b>(\n                &\'b self,\n                out: &mut diesel::serialize::Output<\'b, \'_, super::MultiBackend>,\n            ) -> diesel::serialize::Result {\n                out.set_value((diesel::sql_types::Text, self));\n                Ok(diesel::serialize::IsNull::No)\n            }\n        }\n        impl diesel::serialize::ToSql<diesel::sql_types::Binary, super::MultiBackend>\n        for [u8] {\n            fn to_sql<\'b>(\n                &\'b self,\n                out: &mut diesel::serialize::Output<\'b, \'_, super::MultiBackend>,\n            ) -> diesel::serialize::Result {\n                out.set_value((diesel::sql_types::Binary, self));\n                Ok(diesel::serialize::IsNull::No)\n            }\n        }\n        impl diesel::serialize::ToSql<diesel::sql_types::Bool, super::MultiBackend>\n        for bool {\n            fn to_sql<\'b>(\n                &\'b self,\n                out: &mut diesel::serialize::Output<\'b, \'_, super::MultiBackend>,\n            ) -> diesel::serialize::Result {\n                out.set_value((diesel::sql_types::Bool, self));\n                Ok(diesel::serialize::IsNull::No)\n            }\n        }\n        impl diesel::serialize::ToSql<diesel::sql_types::Numeric, super::MultiBackend>\n        for diesel::internal::derives::multiconnection::bigdecimal::BigDecimal {\n            fn to_sql<\'b>(\n                &\'b self,\n                out: &mut diesel::serialize::Output<\'b, \'_, super::MultiBackend>,\n            ) -> diesel::serialize::Result {\n                out.set_value((diesel::sql_types::Numeric, self));\n                Ok(diesel::serialize::IsNull::No)\n            }\n        }\n        impl diesel::serialize::ToSql<diesel::sql_types::Timestamp, super::MultiBackend>\n        for diesel::internal::derives::multiconnection::chrono::NaiveDateTime {\n            fn to_sql<\'b>(\n                &\'b self,\n                out: &mut diesel::serialize::Output<\'b, \'_, super::MultiBackend>,\n            ) -> diesel::serialize::Result {\n                out.set_value((diesel::sql_types::Timestamp, self));\n                Ok(diesel::serialize::IsNull::No)\n            }\n        }\n        impl diesel::serialize::ToSql<diesel::sql_types::Date, super::MultiBackend>\n        for diesel::internal::derives::multiconnection::chrono::NaiveDate {\n            fn to_sql<\'b>(\n                &\'b self,\n                out: &mut diesel::serialize::Output<\'b, \'_, super::MultiBackend>,\n            ) -> diesel::serialize::Result {\n                out.set_value((diesel::sql_types::Date, self));\n                Ok(diesel::serialize::IsNull::No)\n            }\n        }\n        impl diesel::serialize::ToSql<diesel::sql_types::Time, super::MultiBackend>\n        for diesel::internal::derives::multiconnection::chrono::NaiveTime {\n            fn to_sql<\'b>(\n                &\'b self,\n                out: &mut diesel::serialize::Output<\'b, \'_, super::MultiBackend>,\n            ) -> diesel::serialize::Result {\n                out.set_value((diesel::sql_types::Time, self));\n                Ok(diesel::serialize::IsNull::No)\n            }\n        }\n        impl diesel::serialize::ToSql<diesel::sql_types::Timestamp, super::MultiBackend>\n        for diesel::internal::derives::multiconnection::time::PrimitiveDateTime {\n            fn to_sql<\'b>(\n                &\'b self,\n                out: &mut diesel::serialize::Output<\'b, \'_, super::MultiBackend>,\n            ) -> diesel::serialize::Result {\n                out.set_value((diesel::sql_types::Timestamp, self));\n                Ok(diesel::serialize::IsNull::No)\n            }\n        }\n        impl diesel::serialize::ToSql<diesel::sql_types::Time, super::MultiBackend>\n        for diesel::internal::derives::multiconnection::time::Time {\n            fn to_sql<\'b>(\n                &\'b self,\n                out: &mut diesel::serialize::Output<\'b, \'_, super::MultiBackend>,\n            ) -> diesel::serialize::Result {\n                out.set_value((diesel::sql_types::Time, self));\n                Ok(diesel::serialize::IsNull::No)\n            }\n        }\n        impl diesel::serialize::ToSql<diesel::sql_types::Date, super::MultiBackend>\n        for diesel::internal::derives::multiconnection::time::Date {\n            fn to_sql<\'b>(\n                &\'b self,\n                out: &mut diesel::serialize::Output<\'b, \'_, super::MultiBackend>,\n            ) -> diesel::serialize::Result {\n                out.set_value((diesel::sql_types::Date, self));\n                Ok(diesel::serialize::IsNull::No)\n            }\n        }\n        impl diesel::deserialize::FromSql<\n            diesel::sql_types::SmallInt,\n            super::MultiBackend,\n        > for i16 {\n            fn from_sql(\n                bytes: <super::MultiBackend as diesel::backend::Backend>::RawValue<\'_>,\n            ) -> diesel::deserialize::Result<Self> {\n                bytes.from_sql::<Self, diesel::sql_types::SmallInt>()\n            }\n        }\n        impl diesel::deserialize::FromSql<\n            diesel::sql_types::Integer,\n            super::MultiBackend,\n        > for i32 {\n            fn from_sql(\n                bytes: <super::MultiBackend as diesel::backend::Backend>::RawValue<\'_>,\n            ) -> diesel::deserialize::Result<Self> {\n                bytes.from_sql::<Self, diesel::sql_types::Integer>()\n            }\n        }\n        impl diesel::deserialize::FromSql<diesel::sql_types::BigInt, super::MultiBackend>\n        for i64 {\n            fn from_sql(\n                bytes: <super::MultiBackend as diesel::backend::Backend>::RawValue<\'_>,\n            ) -> diesel::deserialize::Result<Self> {\n                bytes.from_sql::<Self, diesel::sql_types::BigInt>()\n            }\n        }\n        impl diesel::deserialize::FromSql<diesel::sql_types::Double, super::MultiBackend>\n        for f64 {\n            fn from_sql(\n                bytes: <super::MultiBackend as diesel::backend::Backend>::RawValue<\'_>,\n            ) -> diesel::deserialize::Result<Self> {\n                bytes.from_sql::<Self, diesel::sql_types::Double>()\n            }\n        }\n        impl diesel::deserialize::FromSql<diesel::sql_types::Float, super::MultiBackend>\n        for f32 {\n            fn from_sql(\n                bytes: <super::MultiBackend as diesel::backend::Backend>::RawValue<\'_>,\n            ) -> diesel::deserialize::Result<Self> {\n                bytes.from_sql::<Self, diesel::sql_types::Float>()\n            }\n        }\n        impl diesel::deserialize::FromSql<diesel::sql_types::Text, super::MultiBackend>\n        for String {\n            fn from_sql(\n                bytes: <super::MultiBackend as diesel::backend::Backend>::RawValue<\'_>,\n            ) -> diesel::deserialize::Result<Self> {\n                bytes.from_sql::<Self, diesel::sql_types::Text>()\n            }\n        }\n        impl diesel::deserialize::FromSql<diesel::sql_types::Binary, super::MultiBackend>\n        for Vec<u8> {\n            fn from_sql(\n                bytes: <super::MultiBackend as diesel::backend::Backend>::RawValue<\'_>,\n            ) -> diesel::deserialize::Result<Self> {\n                bytes.from_sql::<Self, diesel::sql_types::Binary>()\n            }\n        }\n        impl diesel::deserialize::FromSql<diesel::sql_types::Bool, super::MultiBackend>\n        for bool {\n            fn from_sql(\n                bytes: <super::MultiBackend as diesel::backend::Backend>::RawValue<\'_>,\n            ) -> diesel::deserialize::Result<Self> {\n                bytes.from_sql::<Self, diesel::sql_types::Bool>()\n            }\n        }\n        impl diesel::deserialize::FromSql<\n            diesel::sql_types::Numeric,\n            super::MultiBackend,\n        > for diesel::internal::derives::multiconnection::bigdecimal::BigDecimal {\n            fn from_sql(\n                bytes: <super::MultiBackend as diesel::backend::Backend>::RawValue<\'_>,\n            ) -> diesel::deserialize::Result<Self> {\n                bytes.from_sql::<Self, diesel::sql_types::Numeric>()\n            }\n        }\n        impl diesel::deserialize::FromSql<\n            diesel::sql_types::Timestamp,\n            super::MultiBackend,\n        > for diesel::internal::derives::multiconnection::chrono::NaiveDateTime {\n            fn from_sql(\n                bytes: <super::MultiBackend as diesel::backend::Backend>::RawValue<\'_>,\n            ) -> diesel::deserialize::Result<Self> {\n                bytes.from_sql::<Self, diesel::sql_types::Timestamp>()\n            }\n        }\n        impl diesel::deserialize::FromSql<diesel::sql_types::Date, super::MultiBackend>\n        for diesel::internal::derives::multiconnection::chrono::NaiveDate {\n            fn from_sql(\n                bytes: <super::MultiBackend as diesel::backend::Backend>::RawValue<\'_>,\n            ) -> diesel::deserialize::Result<Self> {\n                bytes.from_sql::<Self, diesel::sql_types::Date>()\n            }\n        }\n        impl diesel::deserialize::FromSql<diesel::sql_types::Time, super::MultiBackend>\n        for diesel::internal::derives::multiconnection::chrono::NaiveTime {\n            fn from_sql(\n                bytes: <super::MultiBackend as diesel::backend::Backend>::RawValue<\'_>,\n            ) -> diesel::deserialize::Result<Self> {\n                bytes.from_sql::<Self, diesel::sql_types::Time>()\n            }\n        }\n        impl diesel::deserialize::FromSql<\n            diesel::sql_types::Timestamp,\n            super::MultiBackend,\n        > for diesel::internal::derives::multiconnection::time::PrimitiveDateTime {\n            fn from_sql(\n                bytes: <super::MultiBackend as diesel::backend::Backend>::RawValue<\'_>,\n            ) -> diesel::deserialize::Result<Self> {\n                bytes.from_sql::<Self, diesel::sql_types::Timestamp>()\n            }\n        }\n        impl diesel::deserialize::FromSql<diesel::sql_types::Time, super::MultiBackend>\n        for diesel::internal::derives::multiconnection::time::Time {\n            fn from_sql(\n                bytes: <super::MultiBackend as diesel::backend::Backend>::RawValue<\'_>,\n            ) -> diesel::deserialize::Result<Self> {\n                bytes.from_sql::<Self, diesel::sql_types::Time>()\n            }\n        }\n        impl diesel::deserialize::FromSql<diesel::sql_types::Date, super::MultiBackend>\n        for diesel::internal::derives::multiconnection::time::Date {\n            fn from_sql(\n                bytes: <super::MultiBackend as diesel::backend::Backend>::RawValue<\'_>,\n            ) -> diesel::deserialize::Result<Self> {\n                bytes.from_sql::<Self, diesel::sql_types::Date>()\n            }\n        }\n    }\n    mod row {\n        use super::*;\n        pub enum MultiRow<\'conn, \'query> {\n            Pg(<PgConnection as diesel::connection::LoadConnection>::Row<\'conn, \'query>),\n            Sqlite(\n                <diesel::SqliteConnection as diesel::connection::LoadConnection>::Row<\n                    \'conn,\n                    \'query,\n                >,\n            ),\n        }\n        impl<\'conn, \'query> diesel::internal::derives::multiconnection::RowSealed\n        for MultiRow<\'conn, \'query> {}\n        pub enum MultiField<\'conn: \'query, \'query> {\n            Pg(\n                <<PgConnection as diesel::connection::LoadConnection>::Row<\n                    \'conn,\n                    \'query,\n                > as diesel::row::Row<\n                    \'conn,\n                    <PgConnection as diesel::connection::Connection>::Backend,\n                >>::Field<\'query>,\n            ),\n            Sqlite(\n                <<diesel::SqliteConnection as diesel::connection::LoadConnection>::Row<\n                    \'conn,\n                    \'query,\n                > as diesel::row::Row<\n                    \'conn,\n                    <diesel::SqliteConnection as diesel::connection::Connection>::Backend,\n                >>::Field<\'query>,\n            ),\n        }\n        impl<\'conn, \'query> diesel::row::Field<\'conn, super::MultiBackend>\n        for MultiField<\'conn, \'query> {\n            fn field_name(&self) -> Option<&str> {\n                use diesel::row::Field;\n                match self {\n                    Self::Pg(f) => f.field_name(),\n                    Self::Sqlite(f) => f.field_name(),\n                }\n            }\n            fn value(\n                &self,\n            ) -> Option<\n                <super::MultiBackend as diesel::backend::Backend>::RawValue<\'_>,\n            > {\n                use diesel::row::Field;\n                match self {\n                    Self::Pg(f) => f.value().map(super::MultiRawValue::Pg),\n                    Self::Sqlite(f) => f.value().map(super::MultiRawValue::Sqlite),\n                }\n            }\n        }\n        impl<\'conn, \'query, \'c> diesel::row::RowIndex<&\'c str>\n        for MultiRow<\'conn, \'query> {\n            fn idx(&self, idx: &\'c str) -> Option<usize> {\n                use diesel::row::RowIndex;\n                match self {\n                    Self::Pg(r) => r.idx(idx),\n                    Self::Sqlite(r) => r.idx(idx),\n                }\n            }\n        }\n        impl<\'conn, \'query> diesel::row::RowIndex<usize> for MultiRow<\'conn, \'query> {\n            fn idx(&self, idx: usize) -> Option<usize> {\n                use diesel::row::RowIndex;\n                match self {\n                    Self::Pg(r) => r.idx(idx),\n                    Self::Sqlite(r) => r.idx(idx),\n                }\n            }\n        }\n        impl<\'conn, \'query> diesel::row::Row<\'conn, super::MultiBackend>\n        for MultiRow<\'conn, \'query> {\n            type Field<\'a> = MultiField<\'a, \'a> where \'conn: \'a, Self: \'a;\n            type InnerPartialRow = Self;\n            fn field_count(&self) -> usize {\n                use diesel::row::Row;\n                match self {\n                    Self::Pg(r) => r.field_count(),\n                    Self::Sqlite(r) => r.field_count(),\n                }\n            }\n            fn get<\'b, I>(&\'b self, idx: I) -> Option<Self::Field<\'b>>\n            where\n                \'conn: \'b,\n                Self: diesel::row::RowIndex<I>,\n            {\n                use diesel::row::{RowIndex, Row};\n                let idx = self.idx(idx)?;\n                match self {\n                    Self::Pg(r) => r.get(idx).map(MultiField::Pg),\n                    Self::Sqlite(r) => r.get(idx).map(MultiField::Sqlite),\n                }\n            }\n            fn partial_row(\n                &self,\n                range: std::ops::Range<usize>,\n            ) -> diesel::internal::derives::multiconnection::PartialRow<\n                \'_,\n                Self::InnerPartialRow,\n            > {\n                diesel::internal::derives::multiconnection::PartialRow::new(self, range)\n            }\n        }\n        pub enum MultiCursor<\'conn, \'query> {\n            Pg(\n                <PgConnection as diesel::connection::LoadConnection>::Cursor<\n                    \'conn,\n                    \'query,\n                >,\n            ),\n            Sqlite(\n                <diesel::SqliteConnection as diesel::connection::LoadConnection>::Cursor<\n                    \'conn,\n                    \'query,\n                >,\n            ),\n        }\n        impl<\'conn, \'query> Iterator for MultiCursor<\'conn, \'query> {\n            type Item = diesel::QueryResult<MultiRow<\'conn, \'query>>;\n            fn next(&mut self) -> Option<Self::Item> {\n                match self {\n                    Self::Pg(r) => Some(r.next()?.map(MultiRow::Pg)),\n                    Self::Sqlite(r) => Some(r.next()?.map(MultiRow::Sqlite)),\n                }\n            }\n        }\n    }\n    mod connection {\n        use super::*;\n        use diesel::connection::*;\n        pub(super) use super::DbConnection as MultiConnection;\n        impl SimpleConnection for MultiConnection {\n            fn batch_execute(&mut self, query: &str) -> diesel::result::QueryResult<()> {\n                match self {\n                    Self::Pg(conn) => conn.batch_execute(query),\n                    Self::Sqlite(conn) => conn.batch_execute(query),\n                }\n            }\n        }\n        impl diesel::internal::derives::multiconnection::ConnectionSealed\n        for MultiConnection {}\n        struct SerializedQuery<T, C> {\n            inner: T,\n            backend: MultiBackend,\n            query_builder: super::query_builder::MultiQueryBuilder,\n            p: std::marker::PhantomData<C>,\n        }\n        trait BindParamHelper: Connection {\n            fn handle_inner_pass<\'a, \'b: \'a>(\n                collector: &mut <Self::Backend as diesel::backend::Backend>::BindCollector<\n                    \'a,\n                >,\n                lookup: &mut <Self::Backend as diesel::sql_types::TypeMetadata>::MetadataLookup,\n                backend: &\'b MultiBackend,\n                q: &\'b impl diesel::query_builder::QueryFragment<MultiBackend>,\n            ) -> diesel::QueryResult<()>;\n        }\n        impl BindParamHelper for PgConnection {\n            fn handle_inner_pass<\'a, \'b: \'a>(\n                outer_collector: &mut <Self::Backend as diesel::backend::Backend>::BindCollector<\n                    \'a,\n                >,\n                lookup: &mut <Self::Backend as diesel::sql_types::TypeMetadata>::MetadataLookup,\n                backend: &\'b MultiBackend,\n                q: &\'b impl diesel::query_builder::QueryFragment<MultiBackend>,\n            ) -> diesel::QueryResult<()> {\n                use diesel::internal::derives::multiconnection::MultiConnectionHelper;\n                let mut collector = super::bind_collector::MultiBindCollector::Pg(\n                    Default::default(),\n                );\n                let lookup = Self::to_any(lookup);\n                q.collect_binds(&mut collector, lookup, backend)?;\n                if let super::bind_collector::MultiBindCollector::Pg(collector) = collector {\n                    *outer_collector = collector;\n                }\n                Ok(())\n            }\n        }\n        impl BindParamHelper for diesel::SqliteConnection {\n            fn handle_inner_pass<\'a, \'b: \'a>(\n                outer_collector: &mut <Self::Backend as diesel::backend::Backend>::BindCollector<\n                    \'a,\n                >,\n                lookup: &mut <Self::Backend as diesel::sql_types::TypeMetadata>::MetadataLookup,\n                backend: &\'b MultiBackend,\n                q: &\'b impl diesel::query_builder::QueryFragment<MultiBackend>,\n            ) -> diesel::QueryResult<()> {\n                use diesel::internal::derives::multiconnection::MultiConnectionHelper;\n                let mut collector = super::bind_collector::MultiBindCollector::Sqlite(\n                    Default::default(),\n                );\n                let lookup = Self::to_any(lookup);\n                q.collect_binds(&mut collector, lookup, backend)?;\n                if let super::bind_collector::MultiBindCollector::Sqlite(collector) = collector {\n                    *outer_collector = collector;\n                }\n                Ok(())\n            }\n        }\n        impl<T, DB, C> diesel::query_builder::QueryFragment<DB> for SerializedQuery<T, C>\n        where\n            DB: diesel::backend::Backend + \'static,\n            T: diesel::query_builder::QueryFragment<MultiBackend>,\n            C: diesel::connection::Connection<Backend = DB> + BindParamHelper\n                + diesel::internal::derives::multiconnection::MultiConnectionHelper,\n        {\n            fn walk_ast<\'b>(\n                &\'b self,\n                mut pass: diesel::query_builder::AstPass<\'_, \'b, DB>,\n            ) -> diesel::QueryResult<()> {\n                use diesel::query_builder::QueryBuilder;\n                use diesel::internal::derives::multiconnection::AstPassHelper;\n                let mut query_builder = self.query_builder.duplicate();\n                self.inner.to_sql(&mut query_builder, &self.backend)?;\n                pass.push_sql(&query_builder.finish());\n                if !self.inner.is_safe_to_cache_prepared(&self.backend)? {\n                    pass.unsafe_to_cache_prepared();\n                }\n                if let Some((outer_collector, lookup)) = pass.bind_collector() {\n                    C::handle_inner_pass(\n                        outer_collector,\n                        lookup,\n                        &self.backend,\n                        &self.inner,\n                    )?;\n                }\n                if let Some((formatter, _backend)) = pass.debug_binds() {\n                    let pass = diesel::query_builder::AstPass::<\n                        MultiBackend,\n                    >::collect_debug_binds_pass(formatter, &self.backend);\n                    self.inner.walk_ast(pass)?;\n                }\n                Ok(())\n            }\n        }\n        impl<T, C> diesel::query_builder::QueryId for SerializedQuery<T, C>\n        where\n            T: diesel::query_builder::QueryId,\n        {\n            type QueryId = <T as diesel::query_builder::QueryId>::QueryId;\n            const HAS_STATIC_QUERY_ID: bool = <T as diesel::query_builder::QueryId>::HAS_STATIC_QUERY_ID;\n        }\n        impl<T, C> diesel::query_builder::Query for SerializedQuery<T, C>\n        where\n            T: diesel::query_builder::Query,\n        {\n            type SqlType = diesel::sql_types::Untyped;\n        }\n        impl Connection for MultiConnection {\n            type Backend = super::MultiBackend;\n            type TransactionManager = Self;\n            fn establish(database_url: &str) -> diesel::ConnectionResult<Self> {\n                if let Ok(conn) = PgConnection::establish(database_url) {\n                    return Ok(Self::Pg(conn));\n                }\n                if let Ok(conn) = diesel::SqliteConnection::establish(database_url) {\n                    return Ok(Self::Sqlite(conn));\n                }\n                Err(\n                    diesel::ConnectionError::BadConnection(\n                        \"Invalid connection url for multiconnection\".into(),\n                    ),\n                )\n            }\n            fn execute_returning_count<T>(\n                &mut self,\n                source: &T,\n            ) -> diesel::result::QueryResult<usize>\n            where\n                T: diesel::query_builder::QueryFragment<Self::Backend>\n                    + diesel::query_builder::QueryId,\n            {\n                match self {\n                    Self::Pg(conn) => {\n                        let query = SerializedQuery {\n                            inner: source,\n                            backend: MultiBackend::Pg(Default::default()),\n                            query_builder: super::query_builder::MultiQueryBuilder::Pg(\n                                Default::default(),\n                            ),\n                            p: std::marker::PhantomData::<PgConnection>,\n                        };\n                        conn.execute_returning_count(&query)\n                    }\n                    Self::Sqlite(conn) => {\n                        let query = SerializedQuery {\n                            inner: source,\n                            backend: MultiBackend::Sqlite(Default::default()),\n                            query_builder: super::query_builder::MultiQueryBuilder::Sqlite(\n                                Default::default(),\n                            ),\n                            p: std::marker::PhantomData::<diesel::SqliteConnection>,\n                        };\n                        conn.execute_returning_count(&query)\n                    }\n                }\n            }\n            fn transaction_state(\n                &mut self,\n            ) -> &mut <Self::TransactionManager as TransactionManager<\n                Self,\n            >>::TransactionStateData {\n                self\n            }\n            fn instrumentation(\n                &mut self,\n            ) -> &mut dyn diesel::connection::Instrumentation {\n                match self {\n                    DbConnection::Pg(conn) => {\n                        diesel::connection::Connection::instrumentation(conn)\n                    }\n                    DbConnection::Sqlite(conn) => {\n                        diesel::connection::Connection::instrumentation(conn)\n                    }\n                }\n            }\n            fn set_instrumentation(\n                &mut self,\n                instrumentation: impl diesel::connection::Instrumentation,\n            ) {\n                match self {\n                    DbConnection::Pg(conn) => {\n                        diesel::connection::Connection::set_instrumentation(\n                            conn,\n                            instrumentation,\n                        );\n                    }\n                    DbConnection::Sqlite(conn) => {\n                        diesel::connection::Connection::set_instrumentation(\n                            conn,\n                            instrumentation,\n                        );\n                    }\n                }\n            }\n            fn set_prepared_statement_cache_size(\n                &mut self,\n                size: diesel::connection::CacheSize,\n            ) {\n                match self {\n                    DbConnection::Pg(conn) => {\n                        diesel::connection::Connection::set_prepared_statement_cache_size(\n                            conn,\n                            size,\n                        );\n                    }\n                    DbConnection::Sqlite(conn) => {\n                        diesel::connection::Connection::set_prepared_statement_cache_size(\n                            conn,\n                            size,\n                        );\n                    }\n                }\n            }\n            fn begin_test_transaction(&mut self) -> diesel::QueryResult<()> {\n                match self {\n                    Self::Pg(conn) => conn.begin_test_transaction(),\n                    Self::Sqlite(conn) => conn.begin_test_transaction(),\n                }\n            }\n        }\n        impl LoadConnection for MultiConnection {\n            type Cursor<\'conn, \'query> = super::row::MultiCursor<\'conn, \'query>;\n            type Row<\'conn, \'query> = super::MultiRow<\'conn, \'query>;\n            fn load<\'conn, \'query, T>(\n                &\'conn mut self,\n                source: T,\n            ) -> diesel::result::QueryResult<Self::Cursor<\'conn, \'query>>\n            where\n                T: diesel::query_builder::Query\n                    + diesel::query_builder::QueryFragment<Self::Backend>\n                    + diesel::query_builder::QueryId + \'query,\n                Self::Backend: diesel::expression::QueryMetadata<T::SqlType>,\n            {\n                match self {\n                    DbConnection::Pg(conn) => {\n                        let query = SerializedQuery {\n                            inner: source,\n                            backend: MultiBackend::Pg(Default::default()),\n                            query_builder: super::query_builder::MultiQueryBuilder::Pg(\n                                Default::default(),\n                            ),\n                            p: std::marker::PhantomData::<PgConnection>,\n                        };\n                        let r = <PgConnection as diesel::connection::LoadConnection>::load(\n                            conn,\n                            query,\n                        )?;\n                        Ok(super::row::MultiCursor::Pg(r))\n                    }\n                    DbConnection::Sqlite(conn) => {\n                        let query = SerializedQuery {\n                            inner: source,\n                            backend: MultiBackend::Sqlite(Default::default()),\n                            query_builder: super::query_builder::MultiQueryBuilder::Sqlite(\n                                Default::default(),\n                            ),\n                            p: std::marker::PhantomData::<diesel::SqliteConnection>,\n                        };\n                        let r = <diesel::SqliteConnection as diesel::connection::LoadConnection>::load(\n                            conn,\n                            query,\n                        )?;\n                        Ok(super::row::MultiCursor::Sqlite(r))\n                    }\n                }\n            }\n        }\n        impl TransactionManager<MultiConnection> for MultiConnection {\n            type TransactionStateData = Self;\n            fn begin_transaction(conn: &mut MultiConnection) -> diesel::QueryResult<()> {\n                match conn {\n                    Self::Pg(conn) => {\n                        <PgConnection as Connection>::TransactionManager::begin_transaction(\n                            conn,\n                        )\n                    }\n                    Self::Sqlite(conn) => {\n                        <diesel::SqliteConnection as Connection>::TransactionManager::begin_transaction(\n                            conn,\n                        )\n                    }\n                }\n            }\n            fn rollback_transaction(\n                conn: &mut MultiConnection,\n            ) -> diesel::QueryResult<()> {\n                match conn {\n                    Self::Pg(conn) => {\n                        <PgConnection as Connection>::TransactionManager::rollback_transaction(\n                            conn,\n                        )\n                    }\n                    Self::Sqlite(conn) => {\n                        <diesel::SqliteConnection as Connection>::TransactionManager::rollback_transaction(\n                            conn,\n                        )\n                    }\n                }\n            }\n            fn commit_transaction(\n                conn: &mut MultiConnection,\n            ) -> diesel::QueryResult<()> {\n                match conn {\n                    Self::Pg(conn) => {\n                        <PgConnection as Connection>::TransactionManager::commit_transaction(\n                            conn,\n                        )\n                    }\n                    Self::Sqlite(conn) => {\n                        <diesel::SqliteConnection as Connection>::TransactionManager::commit_transaction(\n                            conn,\n                        )\n                    }\n                }\n            }\n            fn transaction_manager_status_mut(\n                conn: &mut MultiConnection,\n            ) -> &mut diesel::connection::TransactionManagerStatus {\n                match conn {\n                    Self::Pg(conn) => {\n                        <PgConnection as Connection>::TransactionManager::transaction_manager_status_mut(\n                            conn,\n                        )\n                    }\n                    Self::Sqlite(conn) => {\n                        <diesel::SqliteConnection as Connection>::TransactionManager::transaction_manager_status_mut(\n                            conn,\n                        )\n                    }\n                }\n            }\n            fn is_broken_transaction_manager(conn: &mut MultiConnection) -> bool {\n                match conn {\n                    Self::Pg(conn) => {\n                        <PgConnection as Connection>::TransactionManager::is_broken_transaction_manager(\n                            conn,\n                        )\n                    }\n                    Self::Sqlite(conn) => {\n                        <diesel::SqliteConnection as Connection>::TransactionManager::is_broken_transaction_manager(\n                            conn,\n                        )\n                    }\n                }\n            }\n        }\n        impl diesel::migration::MigrationConnection for MultiConnection {\n            fn setup(&mut self) -> diesel::QueryResult<usize> {\n                match self {\n                    Self::Pg(conn) => {\n                        use diesel::migration::MigrationConnection;\n                        conn.setup()\n                    }\n                    Self::Sqlite(conn) => {\n                        use diesel::migration::MigrationConnection;\n                        conn.setup()\n                    }\n                }\n            }\n        }\n        impl diesel::r2d2::R2D2Connection for MultiConnection {\n            fn ping(&mut self) -> diesel::QueryResult<()> {\n                use diesel::r2d2::R2D2Connection;\n                match self {\n                    Self::Pg(conn) => conn.ping(),\n                    Self::Sqlite(conn) => conn.ping(),\n                }\n            }\n            fn is_broken(&mut self) -> bool {\n                use diesel::r2d2::R2D2Connection;\n                match self {\n                    Self::Pg(conn) => conn.is_broken(),\n                    Self::Sqlite(conn) => conn.is_broken(),\n                }\n            }\n        }\n    }\n    pub use self::backend::{MultiBackend, MultiRawValue};\n    pub use self::row::{MultiRow, MultiField};\n}\npub use self::multi_connection_impl::{MultiBackend, MultiRow, MultiRawValue, MultiField};\n```\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/multiconnection.md")))]
1856#[proc_macro_derive(MultiConnection)]
1857pub fn derive_multiconnection(input: TokenStream) -> TokenStream {
1858    derive_multiconnection_inner(input.into()).into()
1859}
1860
1861fn derive_multiconnection_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
1862    syn::parse2(input)
1863        .map(multiconnection::derive)
1864        .unwrap_or_else(syn::Error::into_compile_error)
1865}
1866
1867/// Automatically annotates return type of a query fragment function
1868///
1869/// This may be useful when factoring out common query fragments into functions.
1870/// If not using this, it would typically involve explicitly writing the full
1871/// type of the query fragment function, which depending on the length of said
1872/// query fragment can be quite difficult (especially to maintain) and verbose.
1873///
1874/// # Example
1875///
1876/// ```rust
1877/// # extern crate diesel;
1878/// # include!("../../diesel/src/doctest_setup.rs");
1879/// # use schema::{users, posts};
1880/// use diesel::dsl;
1881///
1882/// # fn main() {
1883/// #     run_test().unwrap();
1884/// # }
1885/// #
1886/// # fn run_test() -> QueryResult<()> {
1887/// #     let conn = &mut establish_connection();
1888/// #
1889/// #[dsl::auto_type]
1890/// fn user_has_post() -> _ {
1891///     dsl::exists(posts::table.filter(posts::user_id.eq(users::id)))
1892/// }
1893///
1894/// let users_with_posts: Vec<String> = users::table
1895///     .filter(user_has_post())
1896///     .select(users::name)
1897///     .load(conn)?;
1898///
1899/// assert_eq!(
1900///     &["Sean", "Tess"] as &[_],
1901///     users_with_posts
1902///         .iter()
1903///         .map(|s| s.as_str())
1904///         .collect::<Vec<_>>()
1905/// );
1906/// #     Ok(())
1907/// # }
1908/// ```
1909/// # Limitations
1910///
1911/// While this attribute tries to support as much of diesels built-in DSL as possible it's
1912/// unfortunately not possible to support everything. Notable unsupported types are:
1913///
1914/// * Update statements
1915/// * Insert from select statements
1916/// * Query constructed by `diesel::sql_query`
1917/// * Expressions using `diesel::dsl::sql`
1918///
1919/// For these cases a manual type annotation is required. See the "Annotating Types" section below
1920/// for details.
1921///
1922///
1923/// # Advanced usage
1924///
1925/// By default, the macro will:
1926///  - Generate a type alias for the return type of the function, named the
1927///    exact same way as the function itself.
1928///  - Assume that functions, unless otherwise annotated, have a type alias for
1929///    their return type available at the same path as the function itself
1930///    (including case). (e.g. for the `dsl::not(x)` call, it expects that there
1931///    is a `dsl::not<X>` type alias available)
1932///  - Assume that methods, unless otherwise annotated, have a type alias
1933///    available as `diesel::dsl::PascalCaseOfMethodName` (e.g. for the
1934///    `x.and(y)` call, it expects that there is a `diesel::dsl::And<X, Y>` type
1935///    alias available)
1936///
1937/// The defaults can be changed by passing the following attributes to the
1938/// macro:
1939/// - `#[auto_type(no_type_alias)]` to disable the generation of the type alias.
1940/// - `#[auto_type(dsl_path = "path::to::dsl")]` to change the path where the
1941///   macro will look for type aliases for methods. This is required if you mix your own
1942///   custom query dsl extensions with diesel types. In that case, you may use this argument to
1943///   reference a module defined like so:
1944///   ```ignore
1945///   mod dsl {
1946///       /// export all of diesel dsl
1947///       pub use diesel::dsl::*;
1948///
1949///       /// Export your extension types here
1950///       pub use crate::your_extension::dsl::YourType;
1951///    }
1952///    ```
1953/// - `#[auto_type(type_case = "snake_case")]` to change the case of the
1954///   method type alias.
1955///
1956/// The `dsl_path` attribute in particular may be used to declare an
1957/// intermediate module where you would define the few additional needed type
1958/// aliases that can't be inferred automatically.
1959///
1960/// ## Annotating types
1961///
1962/// Sometimes the macro can't infer the type of a particular sub-expression. In
1963/// that case, you can annotate the type of the sub-expression:
1964///
1965/// ```rust
1966/// # extern crate diesel;
1967/// # include!("../../diesel/src/doctest_setup.rs");
1968/// # use schema::{users, posts};
1969/// use diesel::dsl;
1970///
1971/// # fn main() {
1972/// #     run_test().unwrap();
1973/// # }
1974/// #
1975/// # fn run_test() -> QueryResult<()> {
1976/// #     let conn = &mut establish_connection();
1977/// #
1978/// // This will generate a `user_has_post_with_id_greater_than` type alias
1979/// #[dsl::auto_type]
1980/// fn user_has_post_with_id_greater_than(id_greater_than: i32) -> _ {
1981///     dsl::exists(
1982///         posts::table
1983///             .filter(posts::user_id.eq(users::id))
1984///             .filter(posts::id.gt(id_greater_than)),
1985///     )
1986/// }
1987///
1988/// #[dsl::auto_type]
1989/// fn users_with_posts_with_id_greater_than(id_greater_than: i32) -> _ {
1990///     // If we didn't specify the type for this query fragment, the macro would infer it as
1991///     // `user_has_post_with_id_greater_than<i32>`, which would be incorrect because there is
1992///     // no generic parameter.
1993///     let filter: user_has_post_with_id_greater_than =
1994///         user_has_post_with_id_greater_than(id_greater_than);
1995///     // The macro inferring that it has to pass generic parameters is still the convention
1996///     // because it's the most general case, as well as the common case within Diesel itself,
1997///     // and because annotating this way is reasonably simple, while the other way around
1998///     // would be hard.
1999///
2000///     users::table.filter(filter).select(users::name)
2001/// }
2002///
2003/// let users_with_posts: Vec<String> = users_with_posts_with_id_greater_than(2).load(conn)?;
2004///
2005/// assert_eq!(
2006///     &["Tess"] as &[_],
2007///     users_with_posts
2008///         .iter()
2009///         .map(|s| s.as_str())
2010///         .collect::<Vec<_>>()
2011/// );
2012/// #     Ok(())
2013/// # }
2014/// ```
2015///
2016#[cfg_attr(diesel_docsrs, doc = "\n# Expanded Code\n\n<details>\n<summary> Expanded Code </summary>\n\n\n\n#### Input\n\n```rust,ignore\n#[diesel::dsl::auto_type]\nfn foo() -> _ {\n    users::table.select(users::id)\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\n#[allow(non_camel_case_types)]\ntype foo = diesel::dsl::Select<users::table, users::id>;\n#[allow(clippy::needless_lifetimes)]\nfn foo() -> foo {\n    users::table.select(users::id)\n}\n```\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/auto_type.md")))]
2017#[proc_macro_attribute]
2018pub fn auto_type(
2019    attr: proc_macro::TokenStream,
2020    input: proc_macro::TokenStream,
2021) -> proc_macro::TokenStream {
2022    auto_type_inner(attr.into(), input.into()).into()
2023}
2024
2025fn auto_type_inner(
2026    attr: proc_macro2::TokenStream,
2027    input: proc_macro2::TokenStream,
2028) -> proc_macro2::TokenStream {
2029    dsl_auto_type::auto_type_proc_macro_attribute(
2030        attr,
2031        input,
2032        dsl_auto_type::DeriveSettings::builder()
2033            .default_dsl_path(::syn::__private::parse_quote({
        let mut _s = ::quote::__private::TokenStream::new();
        ::quote::__private::push_ident(&mut _s, "diesel");
        ::quote::__private::push_colon2(&mut _s);
        ::quote::__private::push_ident(&mut _s, "dsl");
        _s
    })parse_quote!(diesel::dsl))
2034            .default_generate_type_alias(true)
2035            .default_method_type_case(AUTO_TYPE_DEFAULT_METHOD_TYPE_CASE)
2036            .default_function_type_case(AUTO_TYPE_DEFAULT_FUNCTION_TYPE_CASE)
2037            .build(),
2038    )
2039}
2040
2041const AUTO_TYPE_DEFAULT_METHOD_TYPE_CASE: dsl_auto_type::Case = dsl_auto_type::Case::UpperCamel;
2042const AUTO_TYPE_DEFAULT_FUNCTION_TYPE_CASE: dsl_auto_type::Case = dsl_auto_type::Case::DoNotChange;
2043
2044/// Declare a sql function for use in your code.
2045///
2046/// Diesel only provides support for a very small number of SQL functions.
2047/// This macro enables you to add additional functions from the SQL standard,
2048/// as well as any custom functions your application might have.
2049///
2050/// The syntax for this attribute macro is designed to be applied to `extern "SQL"` blocks
2051/// with function definitions. These function typically use types
2052/// from [`diesel::sql_types`](../diesel/sql_types/index.html) as arguments and return types.
2053/// You can use such definitions to declare bindings to unsupported SQL functions.
2054///
2055/// For each function in this `extern` block the macro will generate two items.
2056/// A function with the name that you've given, and a module with a helper type
2057/// representing the return type of your function. For example, this invocation:
2058///
2059/// ```ignore
2060/// #[declare_sql_function]
2061/// extern "SQL" {
2062///     fn lower(x: Text) -> Text
2063/// }
2064/// ```
2065///
2066/// will generate this code:
2067///
2068/// ```ignore
2069/// pub fn lower<X>(x: X) -> lower<X> {
2070///     ...
2071/// }
2072///
2073/// pub type lower<X> = ...;
2074/// ```
2075///
2076/// Most attributes given to this macro will be put on the generated function
2077/// (including doc comments).
2078///
2079/// If the `generate_return_type_helpers` attribute is specified, an additional module named
2080/// `return_type_helpers` will be generated, containing all return type helpers. For more
2081/// information, refer to the `Helper types generation` section.
2082///
2083/// # Adding Doc Comments
2084///
2085/// ```no_run
2086/// # extern crate diesel;
2087/// # use diesel::*;
2088/// # use diesel::expression::functions::declare_sql_function;
2089/// #
2090/// # table! { crates { id -> Integer, name -> VarChar, } }
2091/// #
2092/// use diesel::sql_types::Text;
2093///
2094/// #[declare_sql_function]
2095/// extern "SQL" {
2096///     /// Represents the `canon_crate_name` SQL function, created in
2097///     /// migration ....
2098///     fn canon_crate_name(a: Text) -> Text;
2099/// }
2100///
2101/// # fn main() {
2102/// # use self::crates::dsl::*;
2103/// let target_name = "diesel";
2104/// crates.filter(canon_crate_name(name).eq(canon_crate_name(target_name)));
2105/// // This will generate the following SQL
2106/// // SELECT * FROM crates WHERE canon_crate_name(crates.name) = canon_crate_name($1)
2107/// # }
2108/// ```
2109///
2110/// # Special Attributes
2111///
2112/// There are a handful of special attributes that Diesel will recognize. They
2113/// are:
2114///
2115/// - `#[aggregate]`
2116///   - Indicates that this is an aggregate function, and that `NonAggregate`
2117///     shouldn't be implemented.
2118/// - `#[sql_name = "name"]`
2119///   - The SQL to be generated is different from the Rust name of the function.
2120///     This can be used to represent functions which can take many argument
2121///     types, or to capitalize function names.
2122/// - `#[variadic(argument_count)]`
2123///   - Indicates that this is a variadic function, where `argument_count` is a
2124///     nonnegative integer representing the number of variadic arguments the
2125///     function accepts.
2126///
2127/// Functions can also be generic. Take the definition of `sum`, for example:
2128///
2129/// ```no_run
2130/// # extern crate diesel;
2131/// # use diesel::*;
2132/// # use diesel::expression::functions::declare_sql_function;
2133/// #
2134/// # table! { crates { id -> Integer, name -> VarChar, } }
2135/// #
2136/// use diesel::sql_types::Foldable;
2137///
2138/// #[declare_sql_function]
2139/// extern "SQL" {
2140///     #[aggregate]
2141///     #[sql_name = "SUM"]
2142///     fn sum<ST: Foldable>(expr: ST) -> ST::Sum;
2143/// }
2144///
2145/// # fn main() {
2146/// # use self::crates::dsl::*;
2147/// crates.select(sum(id));
2148/// # }
2149/// ```
2150///
2151/// # SQL Functions without Arguments
2152///
2153/// A common example is ordering a query using the `RANDOM()` sql function,
2154/// which can be implemented using `define_sql_function!` like this:
2155///
2156/// ```rust
2157/// # extern crate diesel;
2158/// # use diesel::*;
2159/// # use diesel::expression::functions::declare_sql_function;
2160/// #
2161/// # table! { crates { id -> Integer, name -> VarChar, } }
2162/// #
2163/// #[declare_sql_function]
2164/// extern "SQL" {
2165///     fn random() -> Text;
2166/// }
2167///
2168/// # fn main() {
2169/// # use self::crates::dsl::*;
2170/// crates.order(random());
2171/// # }
2172/// ```
2173///
2174/// # Use with SQLite
2175///
2176/// On most backends, the implementation of the function is defined in a
2177/// migration using `CREATE FUNCTION`. On SQLite, the function is implemented in
2178/// Rust instead. You must call `register_impl` or
2179/// `register_nondeterministic_impl` (in the generated function's `_internals`
2180/// module) with every connection before you can use the function.
2181///
2182/// These functions will only be generated if the `sqlite` feature is enabled,
2183/// and the function is not generic.
2184/// SQLite doesn't support generic functions and variadic functions.
2185///
2186/// ```rust
2187/// # extern crate diesel;
2188/// # use diesel::*;
2189/// # use diesel::expression::functions::declare_sql_function;
2190/// #
2191/// # #[cfg(feature = "sqlite")]
2192/// # fn main() {
2193/// #     run_test().unwrap();
2194/// # }
2195/// #
2196/// # #[cfg(not(feature = "sqlite"))]
2197/// # fn main() {
2198/// # }
2199/// #
2200/// use diesel::sql_types::{Double, Integer};
2201///
2202/// #[declare_sql_function]
2203/// extern "SQL" {
2204///     fn add_mul(x: Integer, y: Integer, z: Double) -> Double;
2205/// }
2206///
2207/// # #[cfg(feature = "sqlite")]
2208/// # fn run_test() -> Result<(), Box<dyn std::error::Error>> {
2209/// let connection = &mut SqliteConnection::establish(":memory:")?;
2210///
2211/// add_mul_utils::register_impl(connection, |x: i32, y: i32, z: f64| (x + y) as f64 * z)?;
2212///
2213/// let result = select(add_mul(1, 2, 1.5)).get_result::<f64>(connection)?;
2214/// assert_eq!(4.5, result);
2215/// #     Ok(())
2216/// # }
2217/// ```
2218///
2219/// ## Panics
2220///
2221/// If an implementation of the custom function panics and unwinding is enabled, the panic is
2222/// caught and the function returns to libsqlite with an error. It can't propagate the panics due
2223/// to the FFI boundary.
2224///
2225/// This is the same for [custom aggregate functions](#custom-aggregate-functions).
2226///
2227/// ## Custom Aggregate Functions
2228///
2229/// Custom aggregate functions can be created in SQLite by adding an `#[aggregate]`
2230/// attribute inside `define_sql_function`. `register_impl` (in the generated function's `_utils`
2231/// module) needs to be called with a type implementing the
2232/// [SqliteAggregateFunction](../diesel/sqlite/trait.SqliteAggregateFunction.html)
2233/// trait as a type parameter as shown in the examples below.
2234///
2235/// ```rust
2236/// # extern crate diesel;
2237/// # use diesel::*;
2238/// # use diesel::expression::functions::declare_sql_function;
2239/// #
2240/// # #[cfg(feature = "sqlite")]
2241/// # fn main() {
2242/// #   run().unwrap();
2243/// # }
2244/// #
2245/// # #[cfg(not(feature = "sqlite"))]
2246/// # fn main() {
2247/// # }
2248/// use diesel::sql_types::Integer;
2249/// # #[cfg(feature = "sqlite")]
2250/// use diesel::sqlite::SqliteAggregateFunction;
2251///
2252/// #[declare_sql_function]
2253/// extern "SQL" {
2254///     #[aggregate]
2255///     fn my_sum(x: Integer) -> Integer;
2256/// }
2257///
2258/// #[derive(Default)]
2259/// struct MySum { sum: i32 }
2260///
2261/// # #[cfg(feature = "sqlite")]
2262/// impl SqliteAggregateFunction<i32> for MySum {
2263///     type Output = i32;
2264///
2265///     fn step(&mut self, expr: i32) {
2266///         self.sum += expr;
2267///     }
2268///
2269///     fn finalize(aggregator: Option<Self>) -> Self::Output {
2270///         aggregator.map(|a| a.sum).unwrap_or_default()
2271///     }
2272/// }
2273/// # table! {
2274/// #     players {
2275/// #         id -> Integer,
2276/// #         score -> Integer,
2277/// #     }
2278/// # }
2279///
2280/// # #[cfg(feature = "sqlite")]
2281/// fn run() -> Result<(), Box<dyn (::std::error::Error)>> {
2282/// #    use self::players::dsl::*;
2283///     let connection = &mut SqliteConnection::establish(":memory:")?;
2284/// #    diesel::sql_query("create table players (id integer primary key autoincrement, score integer)")
2285/// #        .execute(connection)
2286/// #        .unwrap();
2287/// #    diesel::sql_query("insert into players (score) values (10), (20), (30)")
2288/// #        .execute(connection)
2289/// #        .unwrap();
2290///
2291///     my_sum_utils::register_impl::<MySum, _>(connection)?;
2292///
2293///     let total_score = players.select(my_sum(score))
2294///         .get_result::<i32>(connection)?;
2295///
2296///     println!("The total score of all the players is: {}", total_score);
2297///
2298/// #    assert_eq!(60, total_score);
2299///     Ok(())
2300/// }
2301/// ```
2302///
2303/// With multiple function arguments, the arguments are passed as a tuple to `SqliteAggregateFunction`
2304///
2305/// ```rust
2306/// # extern crate diesel;
2307/// # use diesel::*;
2308/// # use diesel::expression::functions::declare_sql_function;
2309/// #
2310/// # #[cfg(feature = "sqlite")]
2311/// # fn main() {
2312/// #   run().unwrap();
2313/// # }
2314/// #
2315/// # #[cfg(not(feature = "sqlite"))]
2316/// # fn main() {
2317/// # }
2318/// use diesel::sql_types::{Float, Nullable};
2319/// # #[cfg(feature = "sqlite")]
2320/// use diesel::sqlite::SqliteAggregateFunction;
2321///
2322/// #[declare_sql_function]
2323/// extern "SQL" {
2324///     #[aggregate]
2325///     fn range_max(x0: Float, x1: Float) -> Nullable<Float>;
2326/// }
2327///
2328/// #[derive(Default)]
2329/// struct RangeMax<T> { max_value: Option<T> }
2330///
2331/// # #[cfg(feature = "sqlite")]
2332/// impl<T: Default + PartialOrd + Copy + Clone> SqliteAggregateFunction<(T, T)> for RangeMax<T> {
2333///     type Output = Option<T>;
2334///
2335///     fn step(&mut self, (x0, x1): (T, T)) {
2336/// #        let max = if x0 >= x1 {
2337/// #            x0
2338/// #        } else {
2339/// #            x1
2340/// #        };
2341/// #
2342/// #        self.max_value = match self.max_value {
2343/// #            Some(current_max_value) if max > current_max_value => Some(max),
2344/// #            None => Some(max),
2345/// #            _ => self.max_value,
2346/// #        };
2347///         // Compare self.max_value to x0 and x1
2348///     }
2349///
2350///     fn finalize(aggregator: Option<Self>) -> Self::Output {
2351///         aggregator?.max_value
2352///     }
2353/// }
2354/// # table! {
2355/// #     student_avgs {
2356/// #         id -> Integer,
2357/// #         s1_avg -> Float,
2358/// #         s2_avg -> Float,
2359/// #     }
2360/// # }
2361///
2362/// # #[cfg(feature = "sqlite")]
2363/// fn run() -> Result<(), Box<dyn (::std::error::Error)>> {
2364/// #    use self::student_avgs::dsl::*;
2365///     let connection = &mut SqliteConnection::establish(":memory:")?;
2366/// #    diesel::sql_query("create table student_avgs (id integer primary key autoincrement, s1_avg float, s2_avg float)")
2367/// #       .execute(connection)
2368/// #       .unwrap();
2369/// #    diesel::sql_query("insert into student_avgs (s1_avg, s2_avg) values (85.5, 90), (79.8, 80.1)")
2370/// #        .execute(connection)
2371/// #        .unwrap();
2372///
2373///     range_max_utils::register_impl::<RangeMax<f32>, _, _>(connection)?;
2374///
2375///     let result = student_avgs.select(range_max(s1_avg, s2_avg))
2376///         .get_result::<Option<f32>>(connection)?;
2377///
2378///     if let Some(max_semester_avg) = result {
2379///         println!("The largest semester average is: {}", max_semester_avg);
2380///     }
2381///
2382/// #    assert_eq!(Some(90f32), result);
2383///     Ok(())
2384/// }
2385/// ```
2386///
2387/// ## Variadic functions
2388///
2389/// Since Rust does not support variadic functions, the SQL variadic functions are
2390/// handled differently. For example, consider the variadic function `json_array`.
2391/// To add support for it, you can use the `#[variadic]` attribute:
2392///
2393/// ```rust
2394/// # extern crate diesel;
2395/// # use diesel::sql_types::*;
2396/// # use diesel::expression::functions::declare_sql_function;
2397/// #
2398/// # fn main() {
2399/// #   // Without the main function this code will be wrapped in the auto-generated
2400/// #   // `main` function and `#[declare_sql_function]` won't work properly.
2401/// # }
2402///
2403/// # #[cfg(feature = "sqlite")]
2404/// #[declare_sql_function]
2405/// extern "SQL" {
2406///     #[variadic(1)]
2407///     fn json_array<V: SqlType + SingleValue>(value: V) -> Json;
2408/// }
2409/// ```
2410///
2411/// This will generate multiple implementations, one for each possible argument
2412/// count (up to a predefined limit). For instance, it will generate functions like
2413/// `json_array_0`, `json_array_1`, and so on, which are equivalent to:
2414///
2415/// ```rust
2416/// # extern crate diesel;
2417/// # use diesel::sql_types::*;
2418/// # use diesel::expression::functions::declare_sql_function;
2419/// #
2420/// # fn main() {
2421/// #   // Without the main function this code will be wrapped in the auto-generated
2422/// #   // `main` function and `#[declare_sql_function]` won't work properly.
2423/// # }
2424///
2425/// # #[cfg(feature = "sqlite")]
2426/// #[declare_sql_function]
2427/// extern "SQL" {
2428///     #[sql_name = "json_array"]
2429///     fn json_array_0() -> Json;
2430///
2431///     #[sql_name = "json_array"]
2432///     fn json_array_1<V1: SqlType + SingleValue>(value_1: V1) -> Json;
2433///
2434///     #[sql_name = "json_array"]
2435///     fn json_array_2<V1: SqlType + SingleValue, V2: SqlType + SingleValue>(
2436///         value_1: V1,
2437///         value_2: V2,
2438///     ) -> Json;
2439///
2440///     // ...
2441/// }
2442/// ```
2443///
2444/// The argument to the `variadic` attribute specifies the number of trailing arguments to repeat.
2445/// For example, if you have a variadic function `foo(a: A, b: B, c: C)` and want `b: B` and `c: C`
2446/// to repeat, you would write:
2447///
2448/// ```ignore
2449/// #[declare_sql_function]
2450/// extern "SQL" {
2451///     #[variadic(2)]
2452///     fn foo<A, B, C>(a: A, b: B, c: C) -> Text;
2453/// }
2454/// ```
2455///
2456/// Which will be equivalent to
2457///
2458/// ```ignore
2459/// #[declare_sql_function]
2460/// extern "SQL" {
2461///     #[sql_name = "foo"]
2462///     fn foo_0<A>(a: A) -> Text;
2463///
2464///     #[sql_name = "foo"]
2465///     fn foo_1<A, B1, C1>(a: A, b_1: B1, c_1: C1) -> Text;
2466///
2467///     #[sql_name = "foo"]
2468///     fn foo_2<A, B1, C1, B2, C2>(a: A, b_1: B1, c_1: C1, b_2: B2, c_2: C2) -> Text;
2469///
2470///     ...
2471/// }
2472/// ```
2473///
2474/// Optionally, a second named boolean argument `skip_zero_argument_variant` can be provided to
2475/// control whether the 0-argument variant is generated. By default, (omitted or `false`),
2476/// the 0-argument variant is included. Set it to `true` to skip generating the 0-argument
2477/// variant for functions that require at least one variadic argument. If you specify the boolean
2478/// argument, the first argument has to be named `last_arguments` for clarity.
2479///
2480/// Example:
2481///
2482/// ```ignore
2483/// #[declare_sql_function]
2484/// extern "SQL" {
2485///     #[variadic(last_arguments = 2, skip_zero_argument_variant = true)]
2486///     fn foo<A, B, C>(a: A, b: B, c: C) -> Text;
2487/// }
2488/// ```
2489///
2490/// Which will be equivalent to
2491///
2492/// ```ignore
2493/// #[declare_sql_function]
2494/// extern "SQL" {
2495///     #[sql_name = "foo"]
2496///     fn foo_1<A, B1, C1>(a: A, b_1: B1, c_1: C1) -> Text;
2497///
2498///     #[sql_name = "foo"]
2499///     fn foo_2<A, B1, C1, B2, C2>(a: A, b_1: B1, c_1: C1, b_2: B2, c_2: C2) -> Text;
2500///
2501///     ...
2502/// }
2503/// ```
2504///
2505/// ### Controlling the generation of variadic function variants
2506///
2507/// By default, only variants with 0, 1, and 2 repetitions of variadic arguments are generated. To
2508/// generate more variants, set the `DIESEL_VARIADIC_FUNCTION_ARGS` environment variable to the
2509/// desired number of variants.
2510///
2511/// • The boolean only affects whether the 0 variant is generated; the total number of variants
2512/// (e.g., up to N) still follows DIESEL_VARIADIC_FUNCTION_ARGS or the default.
2513///
2514/// For a greater convenience this environment variable can also be set in a `.cargo/config.toml`
2515/// file as described in the [cargo documentation](https://doc.rust-lang.org/cargo/reference/config.html#env).
2516///
2517/// ## Helper types generation
2518///
2519/// When the `generate_return_type_helpers` attribute is specified, for each function defined inside
2520/// an `extern "SQL"` block, a return type alias with the same name as the function is created and
2521/// placed in the `return_type_helpers` module:
2522///
2523/// ```rust
2524/// # extern crate diesel;
2525/// # use diesel::expression::functions::declare_sql_function;
2526/// # use diesel::sql_types::*;
2527/// #
2528/// # fn main() {
2529/// #   // Without the main function this code will be wrapped in the auto-generated
2530/// #   // `main` function and `#[declare_sql_function]` won't work properly.
2531/// # }
2532/// #
2533/// #[declare_sql_function(generate_return_type_helpers = true)]
2534/// extern "SQL" {
2535///     fn f<V: SqlType + SingleValue>(arg: V);
2536/// }
2537///
2538/// type return_type_helper_for_f<V> = return_type_helpers::f<V>;
2539/// ```
2540///
2541/// If you want to skip generating a type alias for a specific function, you can use the
2542/// `#[skip_return_type_helper]` attribute, like this:
2543///
2544/// ```compile_fail
2545/// # extern crate diesel;
2546/// # use diesel::expression::functions::declare_sql_function;
2547/// #
2548/// # fn main() {
2549/// #   // Without the main function this code will be wrapped in the auto-generated
2550/// #   // `main` function and `#[declare_sql_function]` won't work properly.
2551/// # }
2552/// #
2553/// #[declare_sql_function(generate_return_type_helpers = true)]
2554/// extern "SQL" {
2555///     #[skip_return_type_helper]
2556///     fn f();
2557/// }
2558///
2559/// # type skipped_type = return_type_helpers::f;
2560/// ```
2561///
2562#[cfg_attr(diesel_docsrs, doc = "\n# Expanded Code\n\n<details>\n<summary> Expanded Code </summary>\n\n\n\n#### Input\n\n```rust,ignore\n#[diesel::declare_sql_function]\nextern \"SQL\" {\n    fn lower(input: Text) -> Text;\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\n#[allow(non_camel_case_types)]\npub fn lower<input>(input: input) -> lower<input>\nwhere\n    input: diesel::expression::AsExpression<Text>,\n{\n    lower_utils::lower {\n        input: input.as_expression(),\n    }\n}\n#[allow(non_camel_case_types, non_snake_case)]\n///The return type of [`lower()`](fn@lower)\npub type lower<input> = lower_utils::lower<\n    <input as diesel::expression::AsExpression<Text>>::Expression,\n>;\n#[doc(hidden)]\n#[allow(non_camel_case_types, non_snake_case, unused_imports)]\npub(crate) mod lower_utils {\n    use diesel::{self, QueryResult};\n    use diesel::expression::{\n        AsExpression, Expression, SelectableExpression, AppearsOnTable, ValidGrouping,\n    };\n    use diesel::query_builder::{QueryFragment, AstPass};\n    use diesel::sql_types::*;\n    use diesel::internal::sql_functions::*;\n    use super::*;\n    #[derive(Debug, Clone, Copy, diesel::query_builder::QueryId)]\n    #[derive(diesel::sql_types::DieselNumericOps)]\n    pub struct lower<input> {\n        pub(super) input: input,\n    }\n    ///The return type of [`lower()`](fn@lower)\n    pub type HelperType<input> = lower<<input as AsExpression<Text>>::Expression>;\n    impl<input> Expression for lower<input>\n    where\n        (input): Expression,\n    {\n        type SqlType = Text;\n    }\n    impl<input, __DieselInternal> SelectableExpression<__DieselInternal> for lower<input>\n    where\n        input: SelectableExpression<__DieselInternal>,\n        Self: AppearsOnTable<__DieselInternal>,\n    {}\n    impl<input, __DieselInternal> AppearsOnTable<__DieselInternal> for lower<input>\n    where\n        input: AppearsOnTable<__DieselInternal>,\n        Self: Expression,\n    {}\n    impl<input, __DieselInternal> FunctionFragment<__DieselInternal> for lower<input>\n    where\n        __DieselInternal: diesel::backend::Backend,\n        input: QueryFragment<__DieselInternal>,\n    {\n        const FUNCTION_NAME: &\'static str = \"lower\";\n        #[allow(unused_assignments)]\n        fn walk_arguments<\'__b>(\n            &\'__b self,\n            mut out: AstPass<\'_, \'__b, __DieselInternal>,\n        ) -> QueryResult<()> {\n            let mut needs_comma = false;\n            if !self.input.is_noop(out.backend())? {\n                if needs_comma {\n                    out.push_sql(\", \");\n                }\n                self.input.walk_ast(out.reborrow())?;\n                needs_comma = true;\n            }\n            Ok(())\n        }\n    }\n    impl<input, __DieselInternal> QueryFragment<__DieselInternal> for lower<input>\n    where\n        __DieselInternal: diesel::backend::Backend,\n        input: QueryFragment<__DieselInternal>,\n    {\n        fn walk_ast<\'__b>(\n            &\'__b self,\n            mut out: AstPass<\'_, \'__b, __DieselInternal>,\n        ) -> QueryResult<()> {\n            out.push_sql(<Self as FunctionFragment<__DieselInternal>>::FUNCTION_NAME);\n            out.push_sql(\"(\");\n            self.walk_arguments(out.reborrow())?;\n            out.push_sql(\")\");\n            Ok(())\n        }\n    }\n    #[derive(ValidGrouping)]\n    pub struct __Derived<input>(input);\n    impl<input, __DieselInternal> ValidGrouping<__DieselInternal> for lower<input>\n    where\n        __Derived<input>: ValidGrouping<__DieselInternal>,\n    {\n        type IsAggregate = <__Derived<\n            input,\n        > as ValidGrouping<__DieselInternal>>::IsAggregate;\n    }\n    use diesel::sqlite::{Sqlite, SqliteConnection};\n    use diesel::serialize::ToSql;\n    use diesel::deserialize::{FromSqlRow, StaticallySizedRow};\n    #[allow(dead_code)]\n    /// Registers an implementation for this function on the given connection\n    ///\n    /// This function must be called for every `SqliteConnection` before\n    /// this SQL function can be used on SQLite. The implementation must be\n    /// deterministic (returns the same result given the same arguments). If\n    /// the function is nondeterministic, call\n    /// `register_nondeterministic_impl` instead.\n    pub fn register_impl<F, Ret, input>(\n        conn: &mut SqliteConnection,\n        f: F,\n    ) -> QueryResult<()>\n    where\n        F: Fn(input) -> Ret + std::panic::UnwindSafe + Send + \'static,\n        (input,): FromSqlRow<(Text,), Sqlite> + StaticallySizedRow<(Text,), Sqlite>,\n        Ret: ToSql<Text, Sqlite>,\n    {\n        conn.register_sql_function::<\n                (Text,),\n                Text,\n                _,\n                _,\n                _,\n            >(\"lower\", true, move |(input,)| f(input))\n    }\n    #[allow(dead_code)]\n    /// Registers an implementation for this function on the given connection\n    ///\n    /// This function must be called for every `SqliteConnection` before\n    /// this SQL function can be used on SQLite.\n    /// `register_nondeterministic_impl` should only be used if your\n    /// function can return different results with the same arguments (e.g.\n    /// `random`). If your function is deterministic, you should call\n    /// `register_impl` instead.\n    pub fn register_nondeterministic_impl<F, Ret, input>(\n        conn: &mut SqliteConnection,\n        mut f: F,\n    ) -> QueryResult<()>\n    where\n        F: FnMut(input) -> Ret + std::panic::UnwindSafe + Send + \'static,\n        (input,): FromSqlRow<(Text,), Sqlite> + StaticallySizedRow<(Text,), Sqlite>,\n        Ret: ToSql<Text, Sqlite>,\n    {\n        conn.register_sql_function::<\n                (Text,),\n                Text,\n                _,\n                _,\n                _,\n            >(\"lower\", false, move |(input,)| f(input))\n    }\n}\n```\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/declare_sql_function.md")))]
2563#[proc_macro_attribute]
2564pub fn declare_sql_function(
2565    attr: proc_macro::TokenStream,
2566    input: proc_macro::TokenStream,
2567) -> proc_macro::TokenStream {
2568    declare_sql_function_inner(attr.into(), input.into()).into()
2569}
2570
2571fn declare_sql_function_inner(
2572    attr: proc_macro2::TokenStream,
2573    input: proc_macro2::TokenStream,
2574) -> proc_macro2::TokenStream {
2575    let attr = crate::sql_function::DeclareSqlFunctionArgs::parse_from_macro_input(attr);
2576
2577    let result = syn::parse2::<ExternSqlBlock>(input.clone()).map(|res| {
2578        sql_function::expand(
2579            res.function_decls,
2580            false,
2581            attr.as_ref()
2582                .map(|attr| attr.generate_return_type_helpers)
2583                .unwrap_or(true),
2584        )
2585    });
2586
2587    let mut output = match result {
2588        Ok(token_stream) => token_stream,
2589        Err(e) => {
2590            let mut output = input;
2591            output.extend(e.into_compile_error());
2592            output
2593        }
2594    };
2595    if let Err(e) = attr {
2596        output.extend(e.into_compile_error());
2597    }
2598    output
2599}
2600
2601/// Implements `HasQuery`
2602///
2603/// This derive implements a common entry point for building queries
2604/// based on a model like Rust struct. It enables you to always have a certain base query
2605/// associated with a given type. This derive is designed to easily couple your query with
2606/// your Rust type. It's important to note that for Diesel this mapping happens always
2607/// on query and not on table level, which enables you to write several queries related to the
2608/// same table, while a single query could be related to zero or multiple tables.
2609///
2610/// By default this derive will use the equivalent of `SELECT your, fields FROM your_types`
2611/// which implies that it needs to know the corresponding table type. As with any other
2612/// diesel derive it uses the `snake_case` type name with an added `s` if no other
2613/// name is specified.
2614/// It is possible to change this default by using `#[diesel(table_name = something)]`.
2615///
2616/// If you would like to use a more complex query as base query you can overwrite the standard
2617/// query by using the `#[diesel(base_query = your_type::table.filter(your_type::is_admin.eq(true)))]`
2618/// attribute to overwrite the automatically generated base query. This derive will still apply
2619/// a select clause that matches your type. By default it also tries to infer the correct
2620/// type of that query. This type can be overwritten by using the `#[diesel(base_query_type)]`
2621/// attribute.
2622///
2623/// This derive will internally implement the following traits:
2624///
2625/// * `HasQuery`
2626/// * `Selectable` (for building the selection)
2627/// * `Queryable` (for allowing to load results from the database)
2628///
2629/// For the later two traits see their corresponding derives for supported options:
2630///
2631/// * [Queryable]
2632/// * [Selectable]
2633///
2634/// Any option documented there is also supported by this derive
2635///
2636/// In contrast to `#[derive(Selectable)]` this derive automatically enables
2637/// `#[diesel(check_for_backend(_))]` with all backends enabled at compile time
2638/// if no explicit `#[diesel(check_for_backend(_))]` attribute is given. This
2639/// will lead to better error messages. You
2640/// can use `#[diesel(check_for_backend(disable = true))]` to disable this behaviour
2641/// for that particular instance.
2642///
2643/// # Attributes
2644///
2645/// ## Optional Type attributes
2646///
2647/// * `#[diesel(base_query = _)]`  specifies a base query associated with this type.
2648///   It may be used in conjunction with `base_query_type` (described below)
2649/// * `#[diesel(base_query_type = _)]` the Rust type described by the `base_query`
2650///   attribute. Usually diesel is able to infer this type, but for complex types such an
2651///   annotation might be required. This will be required if  a custom
2652///   function call that doesn't have the corresponding associated type defined at the same path
2653///   appears in your query.
2654/// * `#[diesel(table_name = path::to::table)]`, specifies a path to the table for which the
2655///   current type is selectable. The path is relative to the current module.
2656///   If this attribute is not used, the type name converted to
2657///   `snake_case` with an added `s` is used as table name.
2658/// * `#[diesel(check_for_backend(diesel::pg::Pg, diesel::mysql::Mysql))]`, instructs
2659///   the derive to generate additional code to identify potential type mismatches.
2660///   It accepts a list of backend types to check the types against. If this option
2661///   is not set this derive automatically uses all backends enabled at compile time
2662///   for this check. You can disable this behaviour via `#[diesel(check_for_backend(disable = true))]`
2663///
2664/// ## Optional Field Attributes
2665///
2666/// * `#[diesel(column_name = some_column)]`, overrides the column name for
2667///   a given field. If not set, the name of the field is used as column
2668///   name.
2669/// * `#[diesel(embed)]`, specifies that the current field maps not only
2670///   a single database column, but is a type that implements
2671///   `Selectable` on its own
2672/// * `#[diesel(select_expression = some_custom_select_expression)]`, overrides
2673///   the entire select expression for the given field. It may be used to select with
2674///   custom tuples, or specify `select_expression = my_table::some_field.is_not_null()`,
2675///   or separate tables...
2676///   It may be used in conjunction with `select_expression_type` (described below)
2677/// * `#[diesel(select_expression_type = the_custom_select_expression_type]`, should be used
2678///   in conjunction with `select_expression` (described above) if the type is too complex
2679///   for diesel to infer it automatically. This will be required if select_expression is a custom
2680///   function call that doesn't have the corresponding associated type defined at the same path.
2681///   Example use (this would actually be inferred):
2682///   `#[diesel(select_expression_type = dsl::IsNotNull<my_table::some_field>)]`
2683/// * `#[diesel(deserialize_as = Type)]`, instead of deserializing directly
2684///   into the field type, the implementation will deserialize into `Type`.
2685///   Then `Type` is converted via
2686///   [`.try_into`](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into)
2687///   into the field type. By default, this derive will deserialize directly into the field type
2688///
2689/// # Examples
2690///
2691/// ## Basic usage
2692///
2693///
2694/// ```rust
2695/// # extern crate diesel;
2696/// # extern crate dotenvy;
2697/// # include!("../../diesel/src/doctest_setup.rs");
2698/// #
2699///
2700/// // it's important to have the right table in scope
2701/// use schema::users;
2702///
2703/// #[derive(HasQuery, PartialEq, Debug)]
2704/// struct User {
2705///     id: i32,
2706///     name: String,
2707/// }
2708///
2709/// # fn main() -> QueryResult<()> {
2710/// #
2711/// #     let connection = &mut establish_connection();
2712/// // equivalent to `users::table.select(User::as_select()).first(connection)?;
2713/// let first_user = User::query().first(connection)?;
2714/// let expected = User { id: 1, name: "Sean".into() };
2715/// assert_eq!(expected, first_user);
2716///
2717/// #     Ok(())
2718/// # }
2719/// ```
2720///
2721/// ## Custom base query
2722///
2723/// ```rust
2724/// # extern crate diesel;
2725/// # extern crate dotenvy;
2726/// # include!("../../diesel/src/doctest_setup.rs");
2727/// #
2728///
2729/// // it's important to have the right table in scope
2730/// use schema::{users, posts};
2731///
2732/// #[derive(HasQuery, PartialEq, Debug)]
2733/// struct Post {
2734///    id: i32,
2735///    user_id: i32,
2736///    title: String,
2737/// }
2738///
2739/// #[derive(HasQuery, PartialEq, Debug)]
2740/// #[diesel(base_query = users::table.inner_join(posts::table).order_by(users::id))]
2741/// // that's required to let the derive understand
2742/// // from which table the columns should be selected
2743/// #[diesel(table_name = users)]
2744/// struct UserWithPost {
2745///     id: i32,
2746///     name: String,
2747///     #[diesel(embed)]
2748///     post: Post,
2749/// }
2750///
2751/// # fn main() -> QueryResult<()> {
2752/// #
2753/// #     let connection = &mut establish_connection();
2754/// // equivalent to users::table.inner_join(posts::table)
2755/// //               .order_by(users::id)
2756/// //               .select(UserWithPost::as_select()).first(connection)?;
2757/// let first_user = UserWithPost::query().first(connection)?;
2758/// let expected = UserWithPost { id: 1, name: "Sean".into(), post: Post {id: 1, user_id: 1, title: "My first post".into() } };
2759/// assert_eq!(expected, first_user);
2760///
2761/// #     Ok(())
2762/// # }
2763/// ```
2764///
2765#[cfg_attr(diesel_docsrs, doc = "\n# Expanded Code\n\n<details>\n<summary> Expanded Code </summary>\n\n\n### SQLite\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(HasQuery)]\nstruct User {\n    id: i32,\n    name: String,\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n    use diesel;\n    impl<__DB: diesel::backend::Backend> diesel::HasQuery<__DB> for User {\n        type BaseQuery = <users::table as diesel::query_builder::AsQuery>::Query;\n        fn base_query() -> Self::BaseQuery {\n            diesel::query_builder::AsQuery::as_query(users::table)\n        }\n    }\n};\nconst _: () = {\n    use diesel;\n    use diesel::expression::Selectable;\n    impl<__DB: diesel::backend::Backend> Selectable<__DB> for User {\n        type SelectExpression = (users::r#id, users::r#name);\n        fn construct_selection() -> Self::SelectExpression {\n            (users::r#id, users::r#name)\n        }\n    }\n    fn _check_field_compatibility()\n    where\n        i32: diesel::deserialize::FromSqlRow<\n            diesel::dsl::SqlTypeOf<users::r#id>,\n            diesel::sqlite::Sqlite,\n        >,\n        String: diesel::deserialize::FromSqlRow<\n            diesel::dsl::SqlTypeOf<users::r#name>,\n            diesel::sqlite::Sqlite,\n        >,\n    {}\n};\nconst _: () = {\n    use diesel;\n    use diesel::row::{Row as _, Field as _};\n    impl<\n        __DB: diesel::backend::Backend,\n        __ST0,\n        __ST1,\n    > diesel::deserialize::Queryable<(__ST0, __ST1), __DB> for User\n    where\n        (i32, String): diesel::deserialize::FromStaticSqlRow<(__ST0, __ST1), __DB>,\n    {\n        type Row = (i32, String);\n        fn build(row: (i32, String)) -> diesel::deserialize::Result<Self> {\n            use std::convert::TryInto;\n            diesel::deserialize::Result::Ok(Self {\n                id: row.0.try_into()?,\n                name: row.1.try_into()?,\n            })\n        }\n    }\n};\n```\n\n\n### PostgreSQL\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(HasQuery)]\nstruct User {\n    id: i32,\n    name: String,\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n    use diesel;\n    impl<__DB: diesel::backend::Backend> diesel::HasQuery<__DB> for User {\n        type BaseQuery = <users::table as diesel::query_builder::AsQuery>::Query;\n        fn base_query() -> Self::BaseQuery {\n            diesel::query_builder::AsQuery::as_query(users::table)\n        }\n    }\n};\nconst _: () = {\n    use diesel;\n    use diesel::expression::Selectable;\n    impl<__DB: diesel::backend::Backend> Selectable<__DB> for User {\n        type SelectExpression = (users::r#id, users::r#name);\n        fn construct_selection() -> Self::SelectExpression {\n            (users::r#id, users::r#name)\n        }\n    }\n    fn _check_field_compatibility()\n    where\n        i32: diesel::deserialize::FromSqlRow<\n            diesel::dsl::SqlTypeOf<users::r#id>,\n            diesel::pg::Pg,\n        >,\n        String: diesel::deserialize::FromSqlRow<\n            diesel::dsl::SqlTypeOf<users::r#name>,\n            diesel::pg::Pg,\n        >,\n    {}\n};\nconst _: () = {\n    use diesel;\n    use diesel::row::{Row as _, Field as _};\n    impl<\n        __DB: diesel::backend::Backend,\n        __ST0,\n        __ST1,\n    > diesel::deserialize::Queryable<(__ST0, __ST1), __DB> for User\n    where\n        (i32, String): diesel::deserialize::FromStaticSqlRow<(__ST0, __ST1), __DB>,\n    {\n        type Row = (i32, String);\n        fn build(row: (i32, String)) -> diesel::deserialize::Result<Self> {\n            use std::convert::TryInto;\n            diesel::deserialize::Result::Ok(Self {\n                id: row.0.try_into()?,\n                name: row.1.try_into()?,\n            })\n        }\n    }\n};\n```\n\n\n### MySQL\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(HasQuery)]\nstruct User {\n    id: i32,\n    name: String,\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n    use diesel;\n    impl<__DB: diesel::backend::Backend> diesel::HasQuery<__DB> for User {\n        type BaseQuery = <users::table as diesel::query_builder::AsQuery>::Query;\n        fn base_query() -> Self::BaseQuery {\n            diesel::query_builder::AsQuery::as_query(users::table)\n        }\n    }\n};\nconst _: () = {\n    use diesel;\n    use diesel::expression::Selectable;\n    impl<__DB: diesel::backend::Backend> Selectable<__DB> for User {\n        type SelectExpression = (users::r#id, users::r#name);\n        fn construct_selection() -> Self::SelectExpression {\n            (users::r#id, users::r#name)\n        }\n    }\n    fn _check_field_compatibility()\n    where\n        i32: diesel::deserialize::FromSqlRow<\n            diesel::dsl::SqlTypeOf<users::r#id>,\n            diesel::mysql::Mysql,\n        >,\n        String: diesel::deserialize::FromSqlRow<\n            diesel::dsl::SqlTypeOf<users::r#name>,\n            diesel::mysql::Mysql,\n        >,\n    {}\n};\nconst _: () = {\n    use diesel;\n    use diesel::row::{Row as _, Field as _};\n    impl<\n        __DB: diesel::backend::Backend,\n        __ST0,\n        __ST1,\n    > diesel::deserialize::Queryable<(__ST0, __ST1), __DB> for User\n    where\n        (i32, String): diesel::deserialize::FromStaticSqlRow<(__ST0, __ST1), __DB>,\n    {\n        type Row = (i32, String);\n        fn build(row: (i32, String)) -> diesel::deserialize::Result<Self> {\n            use std::convert::TryInto;\n            diesel::deserialize::Result::Ok(Self {\n                id: row.0.try_into()?,\n                name: row.1.try_into()?,\n            })\n        }\n    }\n};\n```\n\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/has_query.md")))]
2766#[proc_macro_derive(HasQuery, attributes(diesel))]
2767pub fn derive_has_query(input: TokenStream) -> TokenStream {
2768    derive_has_query_inner(input.into()).into()
2769}
2770
2771fn derive_has_query_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
2772    syn::parse2(input)
2773        .and_then(has_query::derive)
2774        .unwrap_or_else(syn::Error::into_compile_error)
2775}