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