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