Skip to main content

diesel_derives/
lib.rs

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