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))]
1819extern crate diesel_table_macro_syntax;
20extern crate proc_macro;
21extern crate proc_macro2;
22extern crate quote;
23extern crate syn;
2425use proc_macro::TokenStream;
26use sql_function::ExternSqlBlock;
27use syn::parse_quote;
2829mod allow_tables_to_appear_in_same_query;
30mod field;
31mod model;
32mod util;
3334mod 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;
5657/// 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 {
132derive_as_changeset_inner(input.into()).into()
133}
134135fn 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}
140141/// 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\n#### Input\n\n```rust,ignore\n#[derive(AsExpression)]\n#[diesel(sql_type = diesel::sql_type::Integer)]\nenum Foo {\n Bar,\n Baz,\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n use diesel;\n impl<\'__expr> diesel::expression::AsExpression<diesel::sql_type::Integer>\n for &\'__expr Foo {\n type Expression = diesel::internal::derives::as_expression::Bound<\n diesel::sql_type::Integer,\n Self,\n >;\n fn as_expression(\n self,\n ) -> <Self as diesel::expression::AsExpression<\n diesel::sql_type::Integer,\n >>::Expression {\n diesel::internal::derives::as_expression::Bound::new(self)\n }\n }\n #[diagnostic::do_not_recommend]\n impl<\n \'__expr,\n > diesel::expression::AsExpression<\n diesel::sql_types::Nullable<diesel::sql_type::Integer>,\n > for &\'__expr Foo {\n type Expression = diesel::internal::derives::as_expression::Bound<\n diesel::sql_types::Nullable<diesel::sql_type::Integer>,\n Self,\n >;\n fn as_expression(\n self,\n ) -> <Self as diesel::expression::AsExpression<\n diesel::sql_types::Nullable<diesel::sql_type::Integer>,\n >>::Expression {\n diesel::internal::derives::as_expression::Bound::new(self)\n }\n }\n #[diagnostic::do_not_recommend]\n impl<\'__expr, \'__expr2> diesel::expression::AsExpression<diesel::sql_type::Integer>\n for &\'__expr2 &\'__expr Foo {\n type Expression = diesel::internal::derives::as_expression::Bound<\n diesel::sql_type::Integer,\n Self,\n >;\n fn as_expression(\n self,\n ) -> <Self as diesel::expression::AsExpression<\n diesel::sql_type::Integer,\n >>::Expression {\n diesel::internal::derives::as_expression::Bound::new(self)\n }\n }\n #[diagnostic::do_not_recommend]\n impl<\n \'__expr,\n \'__expr2,\n > diesel::expression::AsExpression<\n diesel::sql_types::Nullable<diesel::sql_type::Integer>,\n > for &\'__expr2 &\'__expr Foo {\n type Expression = diesel::internal::derives::as_expression::Bound<\n diesel::sql_types::Nullable<diesel::sql_type::Integer>,\n Self,\n >;\n fn as_expression(\n self,\n ) -> <Self as diesel::expression::AsExpression<\n diesel::sql_types::Nullable<diesel::sql_type::Integer>,\n >>::Expression {\n diesel::internal::derives::as_expression::Bound::new(self)\n }\n }\n impl<\n __DB,\n > diesel::serialize::ToSql<\n diesel::sql_types::Nullable<diesel::sql_type::Integer>,\n __DB,\n > for Foo\n where\n __DB: diesel::backend::Backend,\n Self: diesel::serialize::ToSql<diesel::sql_type::Integer, __DB>,\n {\n fn to_sql<\'__b>(\n &\'__b self,\n out: &mut diesel::serialize::Output<\'__b, \'_, __DB>,\n ) -> diesel::serialize::Result {\n diesel::serialize::ToSql::<\n diesel::sql_type::Integer,\n __DB,\n >::to_sql(self, out)\n }\n }\n impl diesel::expression::AsExpression<diesel::sql_type::Integer> for Foo {\n type Expression = diesel::internal::derives::as_expression::Bound<\n diesel::sql_type::Integer,\n Self,\n >;\n fn as_expression(\n self,\n ) -> <Self as diesel::expression::AsExpression<\n diesel::sql_type::Integer,\n >>::Expression {\n diesel::internal::derives::as_expression::Bound::new(self)\n }\n }\n impl diesel::expression::AsExpression<\n diesel::sql_types::Nullable<diesel::sql_type::Integer>,\n > for Foo {\n type Expression = diesel::internal::derives::as_expression::Bound<\n diesel::sql_types::Nullable<diesel::sql_type::Integer>,\n Self,\n >;\n fn as_expression(\n self,\n ) -> <Self as diesel::expression::AsExpression<\n diesel::sql_types::Nullable<diesel::sql_type::Integer>,\n >>::Expression {\n diesel::internal::derives::as_expression::Bound::new(self)\n }\n }\n};\n```\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/as_expression.md")))]
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 {
195derive_as_expression_inner(input.into()).into()
196}
197198fn 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}
203204/// 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 {
249derive_associations_inner(input.into()).into()
250}
251252fn 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}
257258/// Implement numeric operators for the current query node
259#[proc_macro_derive(DieselNumericOps)]
260pub fn derive_diesel_numeric_ops(input: TokenStream) -> TokenStream {
261derive_diesel_numeric_ops_inner(input.into()).into()
262}
263264fn 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}
269270/// 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 {
280derive_from_sql_row_inner(input.into()).into()
281}
282283fn 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}
288289/// 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 {
336derive_identifiable_inner(input.into()).into()
337}
338339fn 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}
344345/// 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\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 {
482derive_insertable_inner(input.into()).into()
483}
484485fn 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}
490491/// 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 {
529derive_query_id_inner(input.into()).into()
530}
531532fn 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}
537538/// 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 {
728derive_queryable_inner(input.into()).into()
729}
730731fn 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}
736737/// 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\n#### Input\n\n```rust,ignore\n#[derive(QueryableByName)]\nstruct User {\n id: i32,\n name: String,\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n use diesel;\n impl<__DB: diesel::backend::Backend> diesel::deserialize::QueryableByName<__DB>\n for User\n where\n i32: diesel::deserialize::FromSql<diesel::dsl::SqlTypeOf<users::r#id>, __DB>,\n String: diesel::deserialize::FromSql<\n diesel::dsl::SqlTypeOf<users::r#name>,\n __DB,\n >,\n {\n fn build<\'__a>(\n row: &impl diesel::row::NamedRow<\'__a, __DB>,\n ) -> diesel::deserialize::Result<Self> {\n let mut id = {\n let field = diesel::row::NamedRow::get::<\n diesel::dsl::SqlTypeOf<users::r#id>,\n i32,\n >(row, \"id\")?;\n <i32 as ::core::convert::Into<i32>>::into(field)\n };\n let mut name = {\n let field = diesel::row::NamedRow::get::<\n diesel::dsl::SqlTypeOf<users::r#name>,\n String,\n >(row, \"name\")?;\n <String as ::core::convert::Into<String>>::into(field)\n };\n diesel::deserialize::Result::Ok(Self { id: id, name: name })\n }\n }\n};\n```\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/queryable_by_name.md")))]
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 {
941derive_queryable_by_name_inner(input.into()).into()
942}
943944fn 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}
949950/// 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 {
1013derive_selectable_inner(input.into()).into()
1014}
10151016fn 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}
10211022/// 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 SQLite, specify which variant of `SqliteType` should be used
1041/// by adding `#[diesel(sqlite_type(name = "Variant"))]`.
1042///
1043/// # Attributes
1044///
1045/// ## Type attributes
1046///
1047/// * `#[diesel(postgres_type(name = "TypeName", schema = "public"))]` specifies support for
1048/// a postgresql type with the name `TypeName` in the schema `public`. Prefer this variant
1049/// for types with no stable OID (== everything but the builtin types). It is possible to leaf
1050/// of the `schema` part. In that case, Diesel defaults to the default postgres search path.
1051/// * `#[diesel(postgres_type(oid = 42, array_oid = 142))]`, specifies support for a
1052/// postgresql type with the given `oid` and `array_oid`. This variant
1053/// should only be used with types that have a stable OID.
1054/// * `#[diesel(sqlite_type(name = "TypeName"))]`, specifies support for a sqlite type
1055/// with the given name. `TypeName` needs to be one of the possible values
1056/// in `SqliteType`
1057/// * `#[diesel(mysql_type(name = "TypeName"))]`, specifies support for a mysql type
1058/// with the given name. `TypeName` needs to be one of the possible values
1059/// in `MysqlType`
1060///
1061#[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")))]
1062#[cfg_attr(
1063 all(not(feature = "without-deprecated"), feature = "with-deprecated"),
1064 proc_macro_derive(SqlType, attributes(diesel, postgres, sqlite_type, mysql_type))
1065)]
1066#[cfg_attr(
1067 any(feature = "without-deprecated", not(feature = "with-deprecated")),
1068 proc_macro_derive(SqlType, attributes(diesel))
1069)]
1070pub fn derive_sql_type(input: TokenStream) -> TokenStream {
1071derive_sql_type_inner(input.into()).into()
1072}
10731074fn derive_sql_type_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
1075 syn::parse2(input)
1076 .and_then(sql_type::derive)
1077 .unwrap_or_else(syn::Error::into_compile_error)
1078}
10791080/// Implements `ValidGrouping`
1081///
1082/// This trait can be automatically derived for structs with no type parameters
1083/// which are never aggregate, as well as for structs which are `NonAggregate`
1084/// when all type parameters are `NonAggregate`. For example:
1085///
1086/// ```ignore
1087/// #[derive(ValidGrouping)]
1088/// struct LiteralOne;
1089///
1090/// #[derive(ValidGrouping)]
1091/// struct Plus<Lhs, Rhs>(Lhs, Rhs);
1092///
1093/// // The following impl will be generated:
1094///
1095/// impl<GroupByClause> ValidGrouping<GroupByClause> for LiteralOne {
1096/// type IsAggregate = is_aggregate::Never;
1097/// }
1098///
1099/// impl<Lhs, Rhs, GroupByClause> ValidGrouping<GroupByClause> for Plus<Lhs, Rhs>
1100/// where
1101/// Lhs: ValidGrouping<GroupByClause>,
1102/// Rhs: ValidGrouping<GroupByClause>,
1103/// Lhs::IsAggregate: MixedAggregates<Rhs::IsAggregate>,
1104/// {
1105/// type IsAggregate = <Lhs::IsAggregate as MixedAggregates<Rhs::IsAggregate>>::Output;
1106/// }
1107/// ```
1108///
1109/// For types which are always considered aggregate (such as an aggregate
1110/// function), annotate your struct with `#[diesel(aggregate)]` to set `IsAggregate`
1111/// explicitly to `is_aggregate::Yes`.
1112///
1113/// # Attributes
1114///
1115/// ## Optional container attributes
1116///
1117/// * `#[diesel(aggregate)]` for cases where the type represents an aggregating
1118/// SQL expression
1119///
1120#[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")))]
1121#[proc_macro_derive(ValidGrouping, attributes(diesel))]
1122pub fn derive_valid_grouping(input: TokenStream) -> TokenStream {
1123derive_valid_grouping_inner(input.into()).into()
1124}
11251126fn derive_valid_grouping_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
1127 syn::parse2(input)
1128 .and_then(valid_grouping::derive)
1129 .unwrap_or_else(syn::Error::into_compile_error)
1130}
11311132/// Declare a sql function for use in your code.
1133///
1134/// Diesel only provides support for a very small number of SQL functions.
1135/// This macro enables you to add additional functions from the SQL standard,
1136/// as well as any custom functions your application might have.
1137///
1138/// This is a legacy variant of the [`#[declare_sql_function]`] attribute macro, which
1139/// should be preferred instead. It will generate the same code as the attribute macro
1140/// and also it will accept the same syntax as the other macro.
1141///
1142/// The syntax for this macro is very similar to that of a normal Rust function,
1143/// except the argument and return types will be the SQL types being used.
1144/// Typically, these types will come from [`diesel::sql_types`](../diesel/sql_types/index.html)
1145///
1146/// This macro will generate two items. A function with the name that you've
1147/// given, and a module with a helper type representing the return type of your
1148/// function. For example, this invocation:
1149///
1150/// ```ignore
1151/// define_sql_function!(fn lower(x: Text) -> Text);
1152/// ```
1153///
1154/// will generate this code:
1155///
1156/// ```ignore
1157/// pub fn lower<X>(x: X) -> lower<X> {
1158/// ...
1159/// }
1160///
1161/// pub type lower<X> = ...;
1162/// ```
1163///
1164/// Most attributes given to this macro will be put on the generated function
1165/// (including doc comments).
1166///
1167/// # Adding Doc Comments
1168///
1169/// ```no_run
1170/// # extern crate diesel;
1171/// # use diesel::*;
1172/// #
1173/// # table! { crates { id -> Integer, name -> VarChar, } }
1174/// #
1175/// use diesel::sql_types::Text;
1176///
1177/// define_sql_function! {
1178/// /// Represents the `canon_crate_name` SQL function, created in
1179/// /// migration ....
1180/// fn canon_crate_name(a: Text) -> Text;
1181/// }
1182///
1183/// # fn main() {
1184/// # use self::crates::dsl::*;
1185/// let target_name = "diesel";
1186/// crates.filter(canon_crate_name(name).eq(canon_crate_name(target_name)));
1187/// // This will generate the following SQL
1188/// // SELECT * FROM crates WHERE canon_crate_name(crates.name) = canon_crate_name($1)
1189/// # }
1190/// ```
1191///
1192/// # Special Attributes
1193///
1194/// There are a handful of special attributes that Diesel will recognize. They
1195/// are:
1196///
1197/// - `#[aggregate]`
1198/// - Indicates that this is an aggregate function, and that `NonAggregate`
1199/// shouldn't be implemented.
1200/// - `#[sql_name = "name"]`
1201/// - The SQL to be generated is different from the Rust name of the function.
1202/// This can be used to represent functions which can take many argument
1203/// types, or to capitalize function names.
1204///
1205#[cfg_attr(diesel_docsrs, doc = "\n# Expanded Code\n\n<details>\n<summary> Expanded Code </summary>\n\n\n\n#### Input\n\n```rust,ignore\ndefine_sql_function! {\n fn lower(input : Text) -> Text;\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\n#[allow(non_camel_case_types)]\npub fn lower<input>(input: input) -> lower<input>\nwhere\n input: diesel::expression::AsExpression<Text>,\n{\n lower_utils::lower {\n input: input.as_expression(),\n }\n}\n#[allow(non_camel_case_types, non_snake_case)]\n///The return type of [`lower()`](fn@lower)\npub type lower<input> = lower_utils::lower<\n <input as diesel::expression::AsExpression<Text>>::Expression,\n>;\n#[doc(hidden)]\n#[allow(non_camel_case_types, non_snake_case, unused_imports)]\npub(crate) mod lower_utils {\n use diesel::{self, QueryResult};\n use diesel::expression::{\n AsExpression, Expression, SelectableExpression, AppearsOnTable, ValidGrouping,\n };\n use diesel::query_builder::{QueryFragment, AstPass};\n use diesel::sql_types::*;\n use diesel::internal::sql_functions::*;\n use super::*;\n #[derive(Debug, Clone, Copy, diesel::query_builder::QueryId)]\n #[derive(diesel::sql_types::DieselNumericOps)]\n pub struct lower<input> {\n pub(super) input: input,\n }\n ///The return type of [`lower()`](fn@lower)\n pub type HelperType<input> = lower<<input as AsExpression<Text>>::Expression>;\n impl<input> Expression for lower<input>\n where\n (input): Expression,\n {\n type SqlType = Text;\n }\n impl<input, __DieselInternal> SelectableExpression<__DieselInternal> for lower<input>\n where\n input: SelectableExpression<__DieselInternal>,\n Self: AppearsOnTable<__DieselInternal>,\n {}\n impl<input, __DieselInternal> AppearsOnTable<__DieselInternal> for lower<input>\n where\n input: AppearsOnTable<__DieselInternal>,\n Self: Expression,\n {}\n impl<input, __DieselInternal> FunctionFragment<__DieselInternal> for lower<input>\n where\n __DieselInternal: diesel::backend::Backend,\n input: QueryFragment<__DieselInternal>,\n {\n const FUNCTION_NAME: &\'static str = \"lower\";\n #[allow(unused_assignments)]\n fn walk_arguments<\'__b>(\n &\'__b self,\n mut out: AstPass<\'_, \'__b, __DieselInternal>,\n ) -> QueryResult<()> {\n let mut needs_comma = false;\n if !self.input.is_noop(out.backend())? {\n if needs_comma {\n out.push_sql(\", \");\n }\n self.input.walk_ast(out.reborrow())?;\n needs_comma = true;\n }\n Ok(())\n }\n }\n impl<input, __DieselInternal> QueryFragment<__DieselInternal> for lower<input>\n where\n __DieselInternal: diesel::backend::Backend,\n input: QueryFragment<__DieselInternal>,\n {\n fn walk_ast<\'__b>(\n &\'__b self,\n mut out: AstPass<\'_, \'__b, __DieselInternal>,\n ) -> QueryResult<()> {\n out.push_sql(<Self as FunctionFragment<__DieselInternal>>::FUNCTION_NAME);\n out.push_sql(\"(\");\n self.walk_arguments(out.reborrow())?;\n out.push_sql(\")\");\n Ok(())\n }\n }\n #[derive(ValidGrouping)]\n pub struct __Derived<input>(input);\n impl<input, __DieselInternal> ValidGrouping<__DieselInternal> for lower<input>\n where\n __Derived<input>: ValidGrouping<__DieselInternal>,\n {\n type IsAggregate = <__Derived<\n input,\n > as ValidGrouping<__DieselInternal>>::IsAggregate;\n }\n #[allow(dead_code)]\n /// Registers an implementation for this function on the given connection.\n ///\n /// This function must be called for every `SqliteConnection` before\n /// this SQL function can be used on SQLite. The implementation must be\n /// deterministic (returns the same result given the same arguments). If\n /// the function is nondeterministic, call\n /// [`register_nondeterministic_impl`](self::register_nondeterministic_impl)\n /// instead, or [`register_impl_with_behavior`](self::register_impl_with_behavior)\n /// for full control over the SQLite behavior flags.\n pub fn register_impl<F, Ret, input>(\n conn: &mut diesel::sqlite::SqliteConnection,\n f: F,\n ) -> diesel::result::QueryResult<()>\n where\n F: Fn(input) -> Ret + ::core::panic::UnwindSafe + Send + \'static,\n (\n input,\n ): diesel::deserialize::FromSqlRow<(Text,), diesel::sqlite::Sqlite>\n + diesel::deserialize::StaticallySizedRow<(Text,), diesel::sqlite::Sqlite>,\n Ret: diesel::serialize::ToSql<Text, diesel::sqlite::Sqlite>,\n {\n register_impl_with_behavior(\n conn,\n diesel::sqlite::SqliteFunctionBehavior::DETERMINISTIC,\n f,\n )\n }\n #[allow(dead_code)]\n /// Registers a nondeterministic implementation for this function on the\n /// given connection.\n ///\n /// This function must be called for every `SqliteConnection` before\n /// this SQL function can be used on SQLite.\n /// `register_nondeterministic_impl` should only be used if your\n /// function can return different results with the same arguments (e.g.\n /// `random`). If your function is deterministic, you should call\n /// [`register_impl`](self::register_impl) instead. For full control over\n /// the SQLite behavior flags, use\n /// [`register_impl_with_behavior`](self::register_impl_with_behavior).\n pub fn register_nondeterministic_impl<F, Ret, input>(\n conn: &mut diesel::sqlite::SqliteConnection,\n f: F,\n ) -> diesel::result::QueryResult<()>\n where\n F: FnMut(input) -> Ret + ::core::panic::UnwindSafe + Send + \'static,\n (\n input,\n ): diesel::deserialize::FromSqlRow<(Text,), diesel::sqlite::Sqlite>\n + diesel::deserialize::StaticallySizedRow<(Text,), diesel::sqlite::Sqlite>,\n Ret: diesel::serialize::ToSql<Text, diesel::sqlite::Sqlite>,\n {\n register_impl_with_behavior(\n conn,\n diesel::sqlite::SqliteFunctionBehavior::empty(),\n f,\n )\n }\n #[allow(dead_code)]\n /// Registers an implementation for this function on the given connection,\n /// with explicit control over the SQLite behavior flags.\n ///\n /// This function must be called for every `SqliteConnection` before\n /// this SQL function can be used on SQLite. Prefer\n /// [`register_impl`](self::register_impl) (deterministic) or\n /// [`register_nondeterministic_impl`](self::register_nondeterministic_impl)\n /// unless you need to set behavior flags explicitly. See\n /// [`SqliteFunctionBehavior`] for the available flags.\n pub fn register_impl_with_behavior<F, Ret, input>(\n conn: &mut diesel::sqlite::SqliteConnection,\n behavior: diesel::sqlite::SqliteFunctionBehavior,\n mut f: F,\n ) -> diesel::result::QueryResult<()>\n where\n F: FnMut(input) -> Ret + ::core::panic::UnwindSafe + Send + \'static,\n (\n input,\n ): diesel::deserialize::FromSqlRow<(Text,), diesel::sqlite::Sqlite>\n + diesel::deserialize::StaticallySizedRow<(Text,), diesel::sqlite::Sqlite>,\n Ret: diesel::serialize::ToSql<Text, diesel::sqlite::Sqlite>,\n {\n conn.register_sql_function::<\n (Text,),\n Text,\n _,\n _,\n _,\n >(\"lower\", behavior, move |(input,)| f(input))\n }\n}\n```\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/define_sql_function.md")))]
1206#[proc_macro]
1207pub fn define_sql_function(input: TokenStream) -> TokenStream {
1208define_sql_function_inner(input.into()).into()
1209}
12101211fn define_sql_function_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
1212 syn::parse2(input)
1213 .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))
1214 .unwrap_or_else(syn::Error::into_compile_error)
1215}
12161217/// A legacy version of [`define_sql_function!`].
1218///
1219/// The difference is that it makes the helper type available in a module named the exact same as
1220/// the function:
1221///
1222/// ```ignore
1223/// sql_function!(fn lower(x: Text) -> Text);
1224/// ```
1225///
1226/// will generate this code:
1227///
1228/// ```ignore
1229/// pub fn lower<X>(x: X) -> lower::HelperType<X> {
1230/// ...
1231/// }
1232///
1233/// pub(crate) mod lower {
1234/// pub type HelperType<X> = ...;
1235/// }
1236/// ```
1237///
1238/// This turned out to be an issue for the support of the `auto_type` feature, which is why
1239/// [`define_sql_function!`] was introduced (and why this is deprecated).
1240///
1241/// SQL functions declared with this version of the macro will not be usable with `#[auto_type]`
1242/// or `Selectable` `select_expression` type inference.
1243#[deprecated(since = "2.2.0", note = "Use [`define_sql_function`] instead")]
1244#[proc_macro]
1245#[cfg(all(feature = "with-deprecated", not(feature = "without-deprecated")))]
1246pub fn sql_function_proc(input: TokenStream) -> TokenStream {
1247sql_function_proc_inner(input.into()).into()
1248}
12491250#[cfg(all(feature = "with-deprecated", not(feature = "without-deprecated")))]
1251fn sql_function_proc_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
1252 syn::parse2(input)
1253 .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))
1254 .unwrap_or_else(syn::Error::into_compile_error)
1255}
12561257/// This is an internal diesel macro that
1258/// helps to implement all traits for tuples of
1259/// various sizes
1260#[doc(hidden)]
1261#[proc_macro]
1262pub fn __diesel_for_each_tuple(input: TokenStream) -> TokenStream {
1263__diesel_for_each_tuple_inner(input.into()).into()
1264}
12651266fn __diesel_for_each_tuple_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
1267 syn::parse2(input)
1268 .map(diesel_for_each_tuple::expand)
1269 .unwrap_or_else(syn::Error::into_compile_error)
1270}
12711272/// This is an internal diesel macro that
1273/// helps to restrict the visibility of an item based
1274/// on a feature flag
1275#[doc(hidden)]
1276#[proc_macro_attribute]
1277pub fn __diesel_public_if(attrs: TokenStream, input: TokenStream) -> TokenStream {
1278__diesel_public_if_inner(attrs.into(), input.into()).into()
1279}
12801281fn __diesel_public_if_inner(
1282 attrs: proc_macro2::TokenStream,
1283 input: proc_macro2::TokenStream,
1284) -> proc_macro2::TokenStream {
1285 syn::parse2(input)
1286 .and_then(|input| syn::parse2(attrs).map(|a| (a, input)))
1287 .map(|(a, i)| diesel_public_if::expand(a, i))
1288 .unwrap_or_else(syn::Error::into_compile_error)
1289}
12901291/// Specifies that a table exists, and what columns it has. This will create a
1292/// new public module, with the same name, as the name of the table. In this
1293/// module, you will find a unit struct named `table`, and a unit struct with the
1294/// name of each column.
1295///
1296/// By default, this allows a maximum of 32 columns per table.
1297/// You can increase this limit to 64 by enabling the `64-column-tables` feature.
1298/// You can increase it to 128 by enabling the `128-column-tables` feature.
1299/// You can decrease it to 16 columns,
1300/// which improves compilation time,
1301/// by disabling the default features of Diesel.
1302/// Note that enabling 64 column tables or larger will substantially increase
1303/// the compile time of Diesel.
1304///
1305/// Example usage
1306/// -------------
1307///
1308/// ```rust
1309/// # extern crate diesel;
1310///
1311/// diesel::table! {
1312/// users {
1313/// id -> Integer,
1314/// name -> VarChar,
1315/// favorite_color -> Nullable<VarChar>,
1316/// }
1317/// }
1318/// ```
1319///
1320/// You may also specify a primary key if it is called something other than `id`.
1321/// Tables with no primary key aren't supported.
1322///
1323/// ```rust
1324/// # extern crate diesel;
1325///
1326/// diesel::table! {
1327/// users (non_standard_primary_key) {
1328/// non_standard_primary_key -> Integer,
1329/// name -> VarChar,
1330/// favorite_color -> Nullable<VarChar>,
1331/// }
1332/// }
1333/// ```
1334///
1335/// For tables with composite primary keys, list all the columns in the primary key.
1336///
1337/// ```rust
1338/// # extern crate diesel;
1339///
1340/// diesel::table! {
1341/// followings (user_id, post_id) {
1342/// user_id -> Integer,
1343/// post_id -> Integer,
1344/// favorited -> Bool,
1345/// }
1346/// }
1347/// # fn main() {
1348/// # use diesel::prelude::Table;
1349/// # use self::followings::dsl::*;
1350/// # // Poor man's assert_eq! -- since this is type level this would fail
1351/// # // to compile if the wrong primary key were generated
1352/// # let (user_id {}, post_id {}) = followings.primary_key();
1353/// # }
1354/// ```
1355///
1356/// If you are using types that aren't from Diesel's core types, you can specify
1357/// which types to import.
1358///
1359/// ```
1360/// # extern crate diesel;
1361/// # mod diesel_full_text_search {
1362/// # #[derive(diesel::sql_types::SqlType)]
1363/// # pub struct TsVector;
1364/// # }
1365///
1366/// diesel::table! {
1367/// use diesel::sql_types::*;
1368/// # use crate::diesel_full_text_search::*;
1369/// # /*
1370/// use diesel_full_text_search::*;
1371/// # */
1372///
1373/// posts {
1374/// id -> Integer,
1375/// title -> Text,
1376/// keywords -> TsVector,
1377/// }
1378/// }
1379/// # fn main() {}
1380/// ```
1381///
1382/// If you want to add documentation to the generated code, you can use the
1383/// following syntax:
1384///
1385/// ```
1386/// # extern crate diesel;
1387///
1388/// diesel::table! {
1389/// /// The table containing all blog posts
1390/// posts {
1391/// /// The post's unique id
1392/// id -> Integer,
1393/// /// The post's title
1394/// title -> Text,
1395/// }
1396/// }
1397/// ```
1398///
1399/// If you have a column with the same name as a Rust reserved keyword, you can use
1400/// the `sql_name` attribute like this:
1401///
1402/// ```
1403/// # extern crate diesel;
1404///
1405/// diesel::table! {
1406/// posts {
1407/// id -> Integer,
1408/// /// This column is named `mytype` but references the table `type` column.
1409/// #[sql_name = "type"]
1410/// mytype -> Text,
1411/// }
1412/// }
1413/// ```
1414///
1415/// Individual columns may be guarded by a `#[cfg(...)]` attribute, so a table
1416/// whose columns vary by enabled crate features can live in a single `table!`
1417/// block instead of duplicated feature gated modules.
1418///
1419/// ```
1420/// # extern crate diesel;
1421///
1422/// diesel::table! {
1423/// users {
1424/// id -> Integer,
1425/// name -> Text,
1426/// #[cfg(feature = "chrono")]
1427/// created_at -> Timestamp,
1428/// }
1429/// }
1430/// ```
1431///
1432/// The primary key itself cannot be feature gated this way: if a feature flag
1433/// changes which columns form the primary key, the whole `table!` block still
1434/// needs to be duplicated behind the relevant `#[cfg(...)]` attributes.
1435///
1436/// This module will also contain several helper types:
1437///
1438/// dsl
1439/// ---
1440///
1441/// This simply re-exports the table, renamed to the same name as the module,
1442/// and each of the columns. This is useful to glob import when you're dealing
1443/// primarily with one table, to allow writing `users.filter(name.eq("Sean"))`
1444/// instead of `users::table.filter(users::name.eq("Sean"))`.
1445///
1446/// `all_columns`
1447/// -----------
1448///
1449/// A constant will be assigned called `all_columns`. This is what will be
1450/// selected if you don't otherwise specify a select clause. It's type will be
1451/// `table::AllColumns`. You can also get this value from the
1452/// `Table::all_columns` function.
1453///
1454/// star
1455/// ----
1456///
1457/// This will be the qualified "star" expression for this table (e.g.
1458/// `users.*`). Internally, we read columns by index, not by name, so this
1459/// column is not safe to read data out of, and it has had its SQL type set to
1460/// `()` to prevent accidentally using it as such. It is sometimes useful for
1461/// counting statements, however. It can also be accessed through the `Table.star()`
1462/// method.
1463///
1464/// `SqlType`
1465/// -------
1466///
1467/// A type alias called `SqlType` will be created. It will be the SQL type of
1468/// `all_columns`. The SQL type is needed for things like returning boxed
1469/// queries.
1470///
1471/// `BoxedQuery`
1472/// ----------
1473///
1474/// ```ignore
1475/// pub type BoxedQuery<'a, DB, ST = SqlType> = BoxedSelectStatement<'a, ST, table, DB>;
1476/// ```
1477///
1478#[cfg_attr(diesel_docsrs, doc = "\n# Expanded Code\n\n<details>\n<summary> Expanded Code </summary>\n\n\n\n#### Input\n\n```rust,ignore\ntable! {\n users { id -> Integer, name -> Text, }\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\n#[allow(unused_imports, dead_code, unreachable_pub, unused_qualifications)]\npub mod users {\n const _: () = {\n assert!(\n 2u16 <= diesel::internal::table_macro::MAX_COLUMN_COUNT,\n \"`users` contains 2 columns, which is more than the supported maximum number of columns\\nTry enabling a crate level feature to support more columns\"\n );\n };\n use ::diesel;\n pub use self::columns::*;\n use diesel::sql_types::*;\n #[doc = concat!(\n \"Re-exports all of the columns of this \", \"table\", \", as well as the\"\n )]\n #[doc = concat!(\"table\", \" struct renamed to the module name. This is meant to be\")]\n #[doc = concat!(\n \"glob imported for functions which only deal with one \", \"table\", \".\"\n )]\n pub mod dsl {\n pub use super::columns::id;\n pub use super::columns::name;\n pub use super::table as users;\n }\n #[allow(non_upper_case_globals, dead_code)]\n #[doc = concat!(\"A tuple of all of the columns on this\", \"table\")]\n pub const all_columns: AllColumns = (id, name);\n #[allow(non_camel_case_types)]\n #[derive(\n Debug,\n Clone,\n Copy,\n diesel::query_builder::QueryId,\n Default,\n PartialEq,\n Eq,\n PartialOrd,\n Ord,\n Hash\n )]\n #[doc = concat!(\"The actual \", \"table\", \" struct\")]\n ///\n /// This is the type which provides the base methods of the query\n /// builder, such as `.select` and `.filter`.\n pub struct table;\n impl table {\n #[allow(dead_code)]\n #[doc = concat!(\n \"Represents `\", \"table\", \"_name.*`, which is sometimes necessary\"\n )]\n /// for efficient count queries. It cannot be used in place of\n /// `all_columns`\n pub fn star(&self) -> star {\n star\n }\n }\n #[allow(non_camel_case_types, dead_code)]\n #[doc = concat!(\"The tuple of all column structs on this \", \"table\")]\n pub type AllColumns = (id, name);\n #[doc = concat!(\"The SQL type of all of the columns on this \", \"table\")]\n pub type SqlType = <AllColumns as diesel::Expression>::SqlType;\n #[doc = concat!(\"Helper type for representing a boxed query from this \", \"table\")]\n pub type BoxedQuery<\'a, DB, ST = SqlType> = diesel::internal::table_macro::BoxedSelectStatement<\n \'a,\n ST,\n diesel::internal::table_macro::FromClause<table>,\n DB,\n >;\n impl diesel::QuerySource for table {\n type FromClause = diesel::internal::table_macro::StaticQueryFragmentInstance<\n table,\n >;\n type DefaultSelection = <Self as diesel::query_source::QueryRelation>::AllColumns;\n fn from_clause(&self) -> Self::FromClause {\n diesel::internal::table_macro::StaticQueryFragmentInstance::new()\n }\n fn default_selection(&self) -> Self::DefaultSelection {\n <Self as diesel::query_source::QueryRelation>::all_columns()\n }\n }\n impl diesel::internal::table_macro::PlainQuerySource for table {}\n impl<DB> diesel::query_builder::QueryFragment<DB> for table\n where\n DB: diesel::backend::Backend,\n <Self as diesel::internal::table_macro::StaticQueryFragment>::Component: diesel::query_builder::QueryFragment<\n DB,\n >,\n {\n fn walk_ast<\'b>(\n &\'b self,\n __diesel_internal_pass: diesel::query_builder::AstPass<\'_, \'b, DB>,\n ) -> diesel::result::QueryResult<()> {\n <Self as diesel::internal::table_macro::StaticQueryFragment>::STATIC_COMPONENT\n .walk_ast(__diesel_internal_pass)\n }\n }\n impl diesel::internal::table_macro::StaticQueryFragment for table {\n type Component = diesel::internal::table_macro::Identifier<\'static>;\n const STATIC_COMPONENT: &\'static Self::Component = &diesel::internal::table_macro::Identifier(\n \"users\",\n );\n }\n impl diesel::query_builder::AsQuery for table {\n type SqlType = SqlType;\n type Query = diesel::internal::table_macro::SelectStatement<\n diesel::internal::table_macro::FromClause<Self>,\n >;\n fn as_query(self) -> Self::Query {\n diesel::internal::table_macro::SelectStatement::simple(self)\n }\n }\n impl diesel::Table for table {\n type PrimaryKey = id;\n type AllColumns = AllColumns;\n fn primary_key(&self) -> Self::PrimaryKey {\n id\n }\n fn all_columns() -> Self::AllColumns {\n all_columns\n }\n }\n impl diesel::associations::HasTable for table {\n type Table = Self;\n fn table() -> Self::Table {\n table\n }\n }\n impl diesel::query_builder::IntoUpdateTarget for table {\n type WhereClause = <<Self as diesel::query_builder::AsQuery>::Query as diesel::query_builder::IntoUpdateTarget>::WhereClause;\n fn into_update_target(\n self,\n ) -> diesel::query_builder::UpdateTarget<Self::Table, Self::WhereClause> {\n use diesel::query_builder::AsQuery;\n let q: diesel::internal::table_macro::SelectStatement<\n diesel::internal::table_macro::FromClause<table>,\n > = self.as_query();\n q.into_update_target()\n }\n }\n impl<T> diesel::insertable::Insertable<T> for table\n where\n <table as diesel::query_builder::AsQuery>::Query: diesel::insertable::Insertable<\n T,\n >,\n {\n type Values = <<table as diesel::query_builder::AsQuery>::Query as diesel::insertable::Insertable<\n T,\n >>::Values;\n fn values(self) -> Self::Values {\n use diesel::query_builder::AsQuery;\n self.as_query().values()\n }\n }\n impl<\'a, T> diesel::insertable::Insertable<T> for &\'a table\n where\n table: diesel::insertable::Insertable<T>,\n {\n type Values = <table as diesel::insertable::Insertable<T>>::Values;\n fn values(self) -> Self::Values {\n (*self).values()\n }\n }\n impl diesel::query_source::AppearsInFromClause<Self> for table {\n type Count = diesel::query_source::Once;\n }\n impl<S> diesel::internal::table_macro::AliasAppearsInFromClause<S, Self> for table\n where\n S: diesel::query_source::AliasSource<Target = Self>,\n {\n type Count = diesel::query_source::Never;\n }\n impl<\n S1,\n S2,\n > diesel::internal::table_macro::AliasAliasAppearsInFromClause<Self, S2, S1>\n for table\n where\n S1: diesel::query_source::AliasSource<Target = Self>,\n S2: diesel::query_source::AliasSource<Target = Self>,\n S1: diesel::internal::table_macro::AliasAliasAppearsInFromClauseSameTable<\n S2,\n Self,\n >,\n {\n type Count = <S1 as diesel::internal::table_macro::AliasAliasAppearsInFromClauseSameTable<\n S2,\n Self,\n >>::Count;\n }\n impl<S> diesel::query_source::AppearsInFromClause<diesel::query_source::Alias<S>>\n for table\n where\n S: diesel::query_source::AliasSource,\n {\n type Count = diesel::query_source::Never;\n }\n impl<\n S,\n C,\n > diesel::internal::table_macro::FieldAliasMapperAssociatedTypesDisjointnessTrick<\n Self,\n S,\n C,\n > for table\n where\n S: diesel::query_source::AliasSource<Target = Self> + ::core::clone::Clone,\n C: diesel::query_source::QueryRelationField<QueryRelation = Self>,\n {\n type Out = diesel::query_source::AliasedField<S, C>;\n fn map(\n __diesel_internal_column: C,\n __diesel_internal_alias: &diesel::query_source::Alias<S>,\n ) -> Self::Out {\n __diesel_internal_alias.field(__diesel_internal_column)\n }\n }\n impl<StmtKind> diesel::query_source::AppearsInFromClause<table>\n for diesel::internal::table_macro::returning::ReturningQuerySource<StmtKind, table> {\n type Count = diesel::query_source::Once;\n }\n impl<\n StmtKind,\n T,\n > diesel::query_source::AppearsInFromClause<\n diesel::internal::table_macro::returning::ReturningQuerySource<StmtKind, T>,\n > for table {\n type Count = diesel::query_source::Never;\n }\n impl diesel::query_source::AppearsInFromClause<table>\n for diesel::internal::table_macro::NoFromClause {\n type Count = diesel::query_source::Never;\n }\n impl<\n Left,\n Right,\n Kind,\n > diesel::JoinTo<diesel::internal::table_macro::Join<Left, Right, Kind>> for table\n where\n diesel::internal::table_macro::Join<Left, Right, Kind>: diesel::JoinTo<Self>,\n Left: diesel::query_source::QuerySource,\n Right: diesel::query_source::QuerySource,\n {\n type FromClause = diesel::internal::table_macro::Join<Left, Right, Kind>;\n type OnClause = <diesel::internal::table_macro::Join<\n Left,\n Right,\n Kind,\n > as diesel::JoinTo<Self>>::OnClause;\n fn join_target(\n __diesel_internal_rhs: diesel::internal::table_macro::Join<Left, Right, Kind>,\n ) -> (Self::FromClause, Self::OnClause) {\n let (_, __diesel_internal_on_clause) = diesel::internal::table_macro::Join::join_target(\n Self,\n );\n (__diesel_internal_rhs, __diesel_internal_on_clause)\n }\n }\n impl<Join, On> diesel::JoinTo<diesel::internal::table_macro::JoinOn<Join, On>>\n for table\n where\n diesel::internal::table_macro::JoinOn<Join, On>: diesel::JoinTo<Self>,\n {\n type FromClause = diesel::internal::table_macro::JoinOn<Join, On>;\n type OnClause = <diesel::internal::table_macro::JoinOn<\n Join,\n On,\n > as diesel::JoinTo<Self>>::OnClause;\n fn join_target(\n __diesel_internal_rhs: diesel::internal::table_macro::JoinOn<Join, On>,\n ) -> (Self::FromClause, Self::OnClause) {\n let (_, __diesel_internal_on_clause) = diesel::internal::table_macro::JoinOn::join_target(\n Self,\n );\n (__diesel_internal_rhs, __diesel_internal_on_clause)\n }\n }\n impl<\n F,\n S,\n D,\n W,\n O,\n L,\n Of,\n G,\n > diesel::JoinTo<\n diesel::internal::table_macro::SelectStatement<\n diesel::internal::table_macro::FromClause<F>,\n S,\n D,\n W,\n O,\n L,\n Of,\n G,\n >,\n > for table\n where\n diesel::internal::table_macro::SelectStatement<\n diesel::internal::table_macro::FromClause<F>,\n S,\n D,\n W,\n O,\n L,\n Of,\n G,\n >: diesel::JoinTo<Self>,\n F: diesel::query_source::QuerySource,\n {\n type FromClause = diesel::internal::table_macro::SelectStatement<\n diesel::internal::table_macro::FromClause<F>,\n S,\n D,\n W,\n O,\n L,\n Of,\n G,\n >;\n type OnClause = <diesel::internal::table_macro::SelectStatement<\n diesel::internal::table_macro::FromClause<F>,\n S,\n D,\n W,\n O,\n L,\n Of,\n G,\n > as diesel::JoinTo<Self>>::OnClause;\n fn join_target(\n __diesel_internal_rhs: diesel::internal::table_macro::SelectStatement<\n diesel::internal::table_macro::FromClause<F>,\n S,\n D,\n W,\n O,\n L,\n Of,\n G,\n >,\n ) -> (Self::FromClause, Self::OnClause) {\n let (_, __diesel_internal_on_clause) = diesel::internal::table_macro::SelectStatement::join_target(\n Self,\n );\n (__diesel_internal_rhs, __diesel_internal_on_clause)\n }\n }\n impl<\n \'a,\n QS,\n ST,\n DB,\n > diesel::JoinTo<\n diesel::internal::table_macro::BoxedSelectStatement<\n \'a,\n diesel::internal::table_macro::FromClause<QS>,\n ST,\n DB,\n >,\n > for table\n where\n diesel::internal::table_macro::BoxedSelectStatement<\n \'a,\n diesel::internal::table_macro::FromClause<QS>,\n ST,\n DB,\n >: diesel::JoinTo<Self>,\n QS: diesel::query_source::QuerySource,\n {\n type FromClause = diesel::internal::table_macro::BoxedSelectStatement<\n \'a,\n diesel::internal::table_macro::FromClause<QS>,\n ST,\n DB,\n >;\n type OnClause = <diesel::internal::table_macro::BoxedSelectStatement<\n \'a,\n diesel::internal::table_macro::FromClause<QS>,\n ST,\n DB,\n > as diesel::JoinTo<Self>>::OnClause;\n fn join_target(\n __diesel_internal_rhs: diesel::internal::table_macro::BoxedSelectStatement<\n \'a,\n diesel::internal::table_macro::FromClause<QS>,\n ST,\n DB,\n >,\n ) -> (Self::FromClause, Self::OnClause) {\n let (_, __diesel_internal_on_clause) = diesel::internal::table_macro::BoxedSelectStatement::join_target(\n Self,\n );\n (__diesel_internal_rhs, __diesel_internal_on_clause)\n }\n }\n impl<S> diesel::JoinTo<diesel::query_source::Alias<S>> for table\n where\n diesel::query_source::Alias<S>: diesel::JoinTo<Self>,\n {\n type FromClause = diesel::query_source::Alias<S>;\n type OnClause = <diesel::query_source::Alias<\n S,\n > as diesel::JoinTo<Self>>::OnClause;\n fn join_target(\n __diesel_internal_rhs: diesel::query_source::Alias<S>,\n ) -> (Self::FromClause, Self::OnClause) {\n let (_, __diesel_internal_on_clause) = diesel::query_source::Alias::<\n S,\n >::join_target(Self);\n (__diesel_internal_rhs, __diesel_internal_on_clause)\n }\n }\n\n\n\n\n\n\n #[doc = concat!(\"Contains all of the columns of this \", \"table\")]\n pub mod columns {\n use ::diesel;\n use super::table;\n use diesel::sql_types::*;\n #[allow(non_camel_case_types, dead_code)]\n #[derive(\n Debug,\n Clone,\n Copy,\n diesel::query_builder::QueryId,\n PartialEq,\n Eq,\n PartialOrd,\n Ord,\n Hash\n )]\n #[doc = concat!(\n \"Represents `\", \"table\", \"_name.*`, which is sometimes needed for\"\n )]\n /// efficient count queries. It cannot be used in place of\n /// `all_columns`, and has a `SqlType` of `()` to prevent it\n /// being used that way\n pub struct star;\n impl<__GB> diesel::expression::ValidGrouping<__GB> for star\n where\n super::AllColumns: diesel::expression::ValidGrouping<__GB>,\n {\n type IsAggregate = <super::AllColumns as diesel::expression::ValidGrouping<\n __GB,\n >>::IsAggregate;\n }\n impl diesel::Expression for star {\n type SqlType = diesel::expression::expression_types::NotSelectable;\n }\n impl<DB: diesel::backend::Backend> diesel::query_builder::QueryFragment<DB>\n for star\n where\n <table as diesel::QuerySource>::FromClause: diesel::query_builder::QueryFragment<\n DB,\n >,\n {\n #[allow(non_snake_case)]\n fn walk_ast<\'b>(\n &\'b self,\n mut __diesel_internal_out: diesel::query_builder::AstPass<\'_, \'b, DB>,\n ) -> diesel::result::QueryResult<()> {\n use diesel::QuerySource;\n if !__diesel_internal_out.should_skip_from() {\n const FROM_CLAUSE: diesel::internal::table_macro::StaticQueryFragmentInstance<\n table,\n > = diesel::internal::table_macro::StaticQueryFragmentInstance::new();\n FROM_CLAUSE.walk_ast(__diesel_internal_out.reborrow())?;\n __diesel_internal_out.push_sql(\".\");\n }\n __diesel_internal_out.push_sql(\"*\");\n Ok(())\n }\n }\n impl diesel::SelectableExpression<table> for star {}\n impl diesel::AppearsOnTable<table> for star {}\n #[allow(non_camel_case_types, dead_code)]\n #[derive(\n Debug,\n Clone,\n Copy,\n diesel::query_builder::QueryId,\n Default,\n PartialEq,\n Eq,\n PartialOrd,\n Ord,\n Hash\n )]\n pub struct id;\n impl diesel::expression::Expression for id {\n type SqlType = Integer;\n }\n impl<DB> diesel::query_builder::QueryFragment<DB> for id\n where\n DB: diesel::backend::Backend,\n diesel::internal::table_macro::StaticQueryFragmentInstance<\n table,\n >: diesel::query_builder::QueryFragment<DB>,\n {\n #[allow(non_snake_case)]\n fn walk_ast<\'b>(\n &\'b self,\n mut __diesel_internal_out: diesel::query_builder::AstPass<\'_, \'b, DB>,\n ) -> diesel::result::QueryResult<()> {\n if !__diesel_internal_out.should_skip_from() {\n const FROM_CLAUSE: diesel::internal::table_macro::StaticQueryFragmentInstance<\n table,\n > = diesel::internal::table_macro::StaticQueryFragmentInstance::new();\n FROM_CLAUSE.walk_ast(__diesel_internal_out.reborrow())?;\n __diesel_internal_out.push_sql(\".\");\n }\n __diesel_internal_out.push_identifier(\"id\")\n }\n }\n impl diesel::SelectableExpression<super::table> for id {}\n impl<\n __StmtKind,\n > diesel::SelectableExpression<\n diesel::internal::table_macro::returning::ReturningQuerySource<\n __StmtKind,\n super::table,\n >,\n > for id {}\n impl<QS> diesel::AppearsOnTable<QS> for id\n where\n QS: diesel::query_source::AppearsInFromClause<\n super::table,\n Count = diesel::query_source::Once,\n >,\n {}\n impl<\n Left,\n Right,\n > diesel::SelectableExpression<\n diesel::internal::table_macro::Join<\n Left,\n Right,\n diesel::internal::table_macro::LeftOuter,\n >,\n > for id\n where\n id: diesel::AppearsOnTable<\n diesel::internal::table_macro::Join<\n Left,\n Right,\n diesel::internal::table_macro::LeftOuter,\n >,\n >,\n Self: diesel::SelectableExpression<Left>,\n Right: diesel::query_source::AppearsInFromClause<\n super::table,\n Count = diesel::query_source::Never,\n > + diesel::query_source::QuerySource,\n Left: diesel::query_source::QuerySource,\n {}\n impl<\n Left,\n Right,\n > diesel::SelectableExpression<\n diesel::internal::table_macro::Join<\n Left,\n Right,\n diesel::internal::table_macro::Inner,\n >,\n > for id\n where\n id: diesel::AppearsOnTable<\n diesel::internal::table_macro::Join<\n Left,\n Right,\n diesel::internal::table_macro::Inner,\n >,\n >,\n Left: diesel::query_source::AppearsInFromClause<super::table>\n + diesel::query_source::QuerySource,\n Right: diesel::query_source::AppearsInFromClause<super::table>\n + diesel::query_source::QuerySource,\n (\n Left::Count,\n Right::Count,\n ): diesel::internal::table_macro::Pick<Left, Right>,\n Self: diesel::SelectableExpression<\n <(\n Left::Count,\n Right::Count,\n ) as diesel::internal::table_macro::Pick<Left, Right>>::Selection,\n >,\n {}\n impl<\n Join,\n On,\n > diesel::SelectableExpression<diesel::internal::table_macro::JoinOn<Join, On>>\n for id\n where\n id: diesel::SelectableExpression<Join>\n + diesel::AppearsOnTable<\n diesel::internal::table_macro::JoinOn<Join, On>,\n >,\n {}\n impl<\n From,\n > diesel::SelectableExpression<\n diesel::internal::table_macro::SelectStatement<\n diesel::internal::table_macro::FromClause<From>,\n >,\n > for id\n where\n From: diesel::query_source::QuerySource,\n id: diesel::SelectableExpression<From>\n + diesel::AppearsOnTable<\n diesel::internal::table_macro::SelectStatement<\n diesel::internal::table_macro::FromClause<From>,\n >,\n >,\n {}\n impl<__GB> diesel::expression::ValidGrouping<__GB> for id\n where\n __GB: diesel::expression::IsContainedInGroupBy<\n id,\n Output = diesel::expression::is_contained_in_group_by::Yes,\n >,\n {\n type IsAggregate = diesel::expression::is_aggregate::Yes;\n }\n impl diesel::expression::ValidGrouping<()> for id {\n type IsAggregate = diesel::expression::is_aggregate::No;\n }\n impl diesel::expression::IsContainedInGroupBy<id> for id {\n type Output = diesel::expression::is_contained_in_group_by::Yes;\n }\n impl<T> diesel::EqAll<T> for id\n where\n T: diesel::expression::AsExpression<Integer>,\n diesel::dsl::Eq<\n id,\n T::Expression,\n >: diesel::Expression<SqlType = diesel::sql_types::Bool>,\n {\n type Output = diesel::dsl::Eq<Self, T::Expression>;\n fn eq_all(self, __diesel_internal_rhs: T) -> Self::Output {\n use diesel::expression_methods::ExpressionMethods;\n self.eq(__diesel_internal_rhs)\n }\n }\n impl<Rhs> ::core::ops::Add<Rhs> for id\n where\n Rhs: diesel::expression::AsExpression<\n <<id as diesel::Expression>::SqlType as diesel::sql_types::ops::Add>::Rhs,\n >,\n {\n type Output = diesel::internal::table_macro::ops::Add<Self, Rhs::Expression>;\n fn add(self, __diesel_internal_rhs: Rhs) -> Self::Output {\n diesel::internal::table_macro::ops::Add::new(\n self,\n __diesel_internal_rhs.as_expression(),\n )\n }\n }\n impl<Rhs> ::core::ops::Sub<Rhs> for id\n where\n Rhs: diesel::expression::AsExpression<\n <<id as diesel::Expression>::SqlType as diesel::sql_types::ops::Sub>::Rhs,\n >,\n {\n type Output = diesel::internal::table_macro::ops::Sub<Self, Rhs::Expression>;\n fn sub(self, __diesel_internal_rhs: Rhs) -> Self::Output {\n diesel::internal::table_macro::ops::Sub::new(\n self,\n __diesel_internal_rhs.as_expression(),\n )\n }\n }\n impl<Rhs> ::core::ops::Div<Rhs> for id\n where\n Rhs: diesel::expression::AsExpression<\n <<id as diesel::Expression>::SqlType as diesel::sql_types::ops::Div>::Rhs,\n >,\n {\n type Output = diesel::internal::table_macro::ops::Div<Self, Rhs::Expression>;\n fn div(self, __diesel_internal_rhs: Rhs) -> Self::Output {\n diesel::internal::table_macro::ops::Div::new(\n self,\n __diesel_internal_rhs.as_expression(),\n )\n }\n }\n impl<Rhs> ::core::ops::Mul<Rhs> for id\n where\n Rhs: diesel::expression::AsExpression<\n <<id as diesel::Expression>::SqlType as diesel::sql_types::ops::Mul>::Rhs,\n >,\n {\n type Output = diesel::internal::table_macro::ops::Mul<Self, Rhs::Expression>;\n fn mul(self, __diesel_internal_rhs: Rhs) -> Self::Output {\n diesel::internal::table_macro::ops::Mul::new(\n self,\n __diesel_internal_rhs.as_expression(),\n )\n }\n }\n\n\n\n\n impl diesel::query_source::Column for id {\n type Table = super::table;\n const NAME: &\'static str = \"id\";\n }\n #[allow(non_camel_case_types, dead_code)]\n #[derive(\n Debug,\n Clone,\n Copy,\n diesel::query_builder::QueryId,\n Default,\n PartialEq,\n Eq,\n PartialOrd,\n Ord,\n Hash\n )]\n pub struct name;\n impl diesel::expression::Expression for name {\n type SqlType = Text;\n }\n impl<DB> diesel::query_builder::QueryFragment<DB> for name\n where\n DB: diesel::backend::Backend,\n diesel::internal::table_macro::StaticQueryFragmentInstance<\n table,\n >: diesel::query_builder::QueryFragment<DB>,\n {\n #[allow(non_snake_case)]\n fn walk_ast<\'b>(\n &\'b self,\n mut __diesel_internal_out: diesel::query_builder::AstPass<\'_, \'b, DB>,\n ) -> diesel::result::QueryResult<()> {\n if !__diesel_internal_out.should_skip_from() {\n const FROM_CLAUSE: diesel::internal::table_macro::StaticQueryFragmentInstance<\n table,\n > = diesel::internal::table_macro::StaticQueryFragmentInstance::new();\n FROM_CLAUSE.walk_ast(__diesel_internal_out.reborrow())?;\n __diesel_internal_out.push_sql(\".\");\n }\n __diesel_internal_out.push_identifier(\"name\")\n }\n }\n impl diesel::SelectableExpression<super::table> for name {}\n impl<\n __StmtKind,\n > diesel::SelectableExpression<\n diesel::internal::table_macro::returning::ReturningQuerySource<\n __StmtKind,\n super::table,\n >,\n > for name {}\n impl<QS> diesel::AppearsOnTable<QS> for name\n where\n QS: diesel::query_source::AppearsInFromClause<\n super::table,\n Count = diesel::query_source::Once,\n >,\n {}\n impl<\n Left,\n Right,\n > diesel::SelectableExpression<\n diesel::internal::table_macro::Join<\n Left,\n Right,\n diesel::internal::table_macro::LeftOuter,\n >,\n > for name\n where\n name: diesel::AppearsOnTable<\n diesel::internal::table_macro::Join<\n Left,\n Right,\n diesel::internal::table_macro::LeftOuter,\n >,\n >,\n Self: diesel::SelectableExpression<Left>,\n Right: diesel::query_source::AppearsInFromClause<\n super::table,\n Count = diesel::query_source::Never,\n > + diesel::query_source::QuerySource,\n Left: diesel::query_source::QuerySource,\n {}\n impl<\n Left,\n Right,\n > diesel::SelectableExpression<\n diesel::internal::table_macro::Join<\n Left,\n Right,\n diesel::internal::table_macro::Inner,\n >,\n > for name\n where\n name: diesel::AppearsOnTable<\n diesel::internal::table_macro::Join<\n Left,\n Right,\n diesel::internal::table_macro::Inner,\n >,\n >,\n Left: diesel::query_source::AppearsInFromClause<super::table>\n + diesel::query_source::QuerySource,\n Right: diesel::query_source::AppearsInFromClause<super::table>\n + diesel::query_source::QuerySource,\n (\n Left::Count,\n Right::Count,\n ): diesel::internal::table_macro::Pick<Left, Right>,\n Self: diesel::SelectableExpression<\n <(\n Left::Count,\n Right::Count,\n ) as diesel::internal::table_macro::Pick<Left, Right>>::Selection,\n >,\n {}\n impl<\n Join,\n On,\n > diesel::SelectableExpression<diesel::internal::table_macro::JoinOn<Join, On>>\n for name\n where\n name: diesel::SelectableExpression<Join>\n + diesel::AppearsOnTable<\n diesel::internal::table_macro::JoinOn<Join, On>,\n >,\n {}\n impl<\n From,\n > diesel::SelectableExpression<\n diesel::internal::table_macro::SelectStatement<\n diesel::internal::table_macro::FromClause<From>,\n >,\n > for name\n where\n From: diesel::query_source::QuerySource,\n name: diesel::SelectableExpression<From>\n + diesel::AppearsOnTable<\n diesel::internal::table_macro::SelectStatement<\n diesel::internal::table_macro::FromClause<From>,\n >,\n >,\n {}\n impl<__GB> diesel::expression::ValidGrouping<__GB> for name\n where\n __GB: diesel::expression::IsContainedInGroupBy<\n name,\n Output = diesel::expression::is_contained_in_group_by::Yes,\n >,\n {\n type IsAggregate = diesel::expression::is_aggregate::Yes;\n }\n impl diesel::expression::ValidGrouping<()> for name {\n type IsAggregate = diesel::expression::is_aggregate::No;\n }\n impl diesel::expression::IsContainedInGroupBy<name> for name {\n type Output = diesel::expression::is_contained_in_group_by::Yes;\n }\n impl<T> diesel::EqAll<T> for name\n where\n T: diesel::expression::AsExpression<Text>,\n diesel::dsl::Eq<\n name,\n T::Expression,\n >: diesel::Expression<SqlType = diesel::sql_types::Bool>,\n {\n type Output = diesel::dsl::Eq<Self, T::Expression>;\n fn eq_all(self, __diesel_internal_rhs: T) -> Self::Output {\n use diesel::expression_methods::ExpressionMethods;\n self.eq(__diesel_internal_rhs)\n }\n }\n\n\n\n\n impl diesel::query_source::Column for name {\n type Table = super::table;\n const NAME: &\'static str = \"name\";\n }\n impl diesel::expression::IsContainedInGroupBy<id> for name {\n type Output = diesel::expression::is_contained_in_group_by::No;\n }\n impl diesel::expression::IsContainedInGroupBy<name> for id {\n type Output = diesel::expression::is_contained_in_group_by::Yes;\n }\n }\n}\n```\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/table.md")))]
1479#[proc_macro]
1480pub fn table_proc(input: TokenStream) -> TokenStream {
1481table_proc_inner(input.into()).into()
1482}
14831484/// Allow two or more tables which are otherwise unrelated to be used together
1485/// in a query.
1486///
1487/// This macro must be invoked any time two tables need to appear in the same
1488/// query either because they are being joined together, or because one appears
1489/// in a subselect. When this macro is invoked with more than 2 tables, every
1490/// combination of those tables will be allowed to appear together.
1491///
1492/// If you are using `diesel print-schema`, an invocation of
1493/// this macro will be generated for you for all tables in your schema.
1494///
1495/// # Example
1496///
1497/// ```
1498/// # use diesel::{allow_tables_to_appear_in_same_query, table};
1499/// #
1500/// // This would be required to do `users.inner_join(posts.inner_join(comments))`
1501/// allow_tables_to_appear_in_same_query!(comments, posts, users);
1502///
1503/// table! {
1504/// comments {
1505/// id -> Integer,
1506/// post_id -> Integer,
1507/// body -> VarChar,
1508/// }
1509/// }
1510///
1511/// table! {
1512/// posts {
1513/// id -> Integer,
1514/// user_id -> Integer,
1515/// title -> VarChar,
1516/// }
1517/// }
1518///
1519/// table! {
1520/// users {
1521/// id -> Integer,
1522/// name -> VarChar,
1523/// }
1524/// }
1525/// ```
1526///
1527/// When more than two tables are passed, the relevant code is generated for
1528/// every combination of those tables. This code would be equivalent to the
1529/// previous example.
1530///
1531/// ```
1532/// # use diesel::{allow_tables_to_appear_in_same_query, table};
1533/// # table! {
1534/// # comments {
1535/// # id -> Integer,
1536/// # post_id -> Integer,
1537/// # body -> VarChar,
1538/// # }
1539/// # }
1540/// #
1541/// # table! {
1542/// # posts {
1543/// # id -> Integer,
1544/// # user_id -> Integer,
1545/// # title -> VarChar,
1546/// # }
1547/// # }
1548/// #
1549/// # table! {
1550/// # users {
1551/// # id -> Integer,
1552/// # name -> VarChar,
1553/// # }
1554/// # }
1555/// #
1556/// allow_tables_to_appear_in_same_query!(comments, posts);
1557/// allow_tables_to_appear_in_same_query!(comments, users);
1558/// allow_tables_to_appear_in_same_query!(posts, users);
1559/// #
1560/// # fn main() {}
1561/// ```
1562///
1563#[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")))]
1564#[proc_macro]
1565pub fn allow_tables_to_appear_in_same_query(input: TokenStream) -> TokenStream {
1566 allow_tables_to_appear_in_same_query::expand(input.into()).into()
1567}
15681569fn table_proc_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
1570self::table::query_source_macro(input, self::table::QuerySourceMacroKind::Table)
1571}
15721573/// Specifies that a view exists, and what fields it has. This will create a
1574/// new public module, with the same name, as the name of the view. In this
1575/// module, you will find a unit struct named `view`, and a unit struct with the
1576/// name of each field.
1577///
1578/// The macro and the generated code closely mirror the [`table!`](table_proc) macro.
1579///
1580/// By default, this allows a maximum of 32 columns per view.
1581/// You can increase this limit to 64 by enabling the `64-column-tables` feature.
1582/// You can increase it to 128 by enabling the `128-column-tables` feature.
1583/// You can decrease it to 16 columns,
1584/// which improves compilation time,
1585/// by disabling the default features of Diesel.
1586/// Note that enabling 64 column tables or larger will substantially increase
1587/// the compile time of Diesel.
1588///
1589/// Example usage
1590/// -------------
1591///
1592/// ```rust
1593/// # extern crate diesel;
1594///
1595/// diesel::view! {
1596/// users {
1597/// name -> VarChar,
1598/// favorite_color -> Nullable<VarChar>,
1599/// }
1600/// }
1601/// ```
1602///
1603/// If you are using types that aren't from Diesel's core types, you can specify
1604/// which types to import.
1605///
1606/// ```
1607/// # extern crate diesel;
1608/// # mod diesel_full_text_search {
1609/// # #[derive(diesel::sql_types::SqlType)]
1610/// # pub struct TsVector;
1611/// # }
1612///
1613/// diesel::view! {
1614/// use diesel::sql_types::*;
1615/// # use crate::diesel_full_text_search::*;
1616/// # /*
1617/// use diesel_full_text_search::*;
1618/// # */
1619///
1620/// posts {
1621/// title -> Text,
1622/// keywords -> TsVector,
1623/// }
1624/// }
1625/// # fn main() {}
1626/// ```
1627///
1628/// If you want to add documentation to the generated code, you can use the
1629/// following syntax:
1630///
1631/// ```
1632/// # extern crate diesel;
1633///
1634/// diesel::view! {
1635/// /// The table containing all blog posts
1636/// posts {
1637/// /// The post's title
1638/// title -> Text,
1639/// }
1640/// }
1641/// ```
1642///
1643/// If you have a column with the same name as a Rust reserved keyword, you can use
1644/// the `sql_name` attribute like this:
1645///
1646/// ```
1647/// # extern crate diesel;
1648///
1649/// diesel::view! {
1650/// posts {
1651/// /// This column is named `mytype` but references the table `type` column.
1652/// #[sql_name = "type"]
1653/// mytype -> Text,
1654/// }
1655/// }
1656/// ```
1657///
1658/// This module will also contain several helper types:
1659///
1660/// dsl
1661/// ---
1662///
1663/// This simply re-exports the view, renamed to the same name as the module,
1664/// and each of the columns. This is useful to glob import when you're dealing
1665/// primarily with one table, to allow writing `users.filter(name.eq("Sean"))`
1666/// instead of `users::table.filter(users::name.eq("Sean"))`.
1667///
1668/// `all_columns`
1669/// -----------
1670///
1671/// A constant will be assigned called `all_columns`. This is what will be
1672/// selected if you don't otherwise specify a select clause. It's type will be
1673/// `view::AllColumns`. You can also get this value from the
1674/// `QueryRelation::all_columns` function.
1675///
1676/// star
1677/// ----
1678///
1679/// This will be the qualified "star" expression for this view (e.g.
1680/// `users.*`). Internally, we read columns by index, not by name, so this
1681/// column is not safe to read data out of, and it has had its SQL type set to
1682/// `()` to prevent accidentally using it as such. It is sometimes useful for
1683/// counting statements, however. It can also be accessed through the `Table.star()`
1684/// method.
1685///
1686/// `SqlType`
1687/// -------
1688///
1689/// A type alias called `SqlType` will be created. It will be the SQL type of
1690/// `all_columns`. The SQL type is needed for things like returning boxed
1691/// queries.
1692///
1693/// `BoxedQuery`
1694/// ----------
1695///
1696/// ```ignore
1697/// pub type BoxedQuery<'a, DB, ST = SqlType> = BoxedSelectStatement<'a, ST, view, DB>;
1698/// ```
1699///
1700#[cfg_attr(diesel_docsrs, doc = "\n# Expanded Code\n\n<details>\n<summary> Expanded Code </summary>\n\n\n\n#### Input\n\n```rust,ignore\nview! {\n view { id -> Integer, name -> Text, }\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\n#[allow(unused_imports, dead_code, unreachable_pub, unused_qualifications)]\npub mod view {\n const _: () = {\n assert!(\n 2u16 <= diesel::internal::table_macro::MAX_COLUMN_COUNT,\n \"`view` contains 2 columns, which is more than the supported maximum number of columns\\nTry enabling a crate level feature to support more columns\"\n );\n };\n use ::diesel;\n pub use self::columns::*;\n use diesel::sql_types::*;\n #[doc = concat!(\n \"Re-exports all of the columns of this \", \"view\", \", as well as the\"\n )]\n #[doc = concat!(\"view\", \" struct renamed to the module name. This is meant to be\")]\n #[doc = concat!(\n \"glob imported for functions which only deal with one \", \"view\", \".\"\n )]\n pub mod dsl {\n pub use super::columns::id;\n pub use super::columns::name;\n pub use super::view as view;\n }\n #[allow(non_upper_case_globals, dead_code)]\n #[doc = concat!(\"A tuple of all of the columns on this\", \"view\")]\n pub const all_columns: AllColumns = (id, name);\n #[allow(non_camel_case_types)]\n #[derive(\n Debug,\n Clone,\n Copy,\n diesel::query_builder::QueryId,\n Default,\n PartialEq,\n Eq,\n PartialOrd,\n Ord,\n Hash\n )]\n #[doc = concat!(\"The actual \", \"view\", \" struct\")]\n ///\n /// This is the type which provides the base methods of the query\n /// builder, such as `.select` and `.filter`.\n pub struct view;\n impl view {\n #[allow(dead_code)]\n #[doc = concat!(\n \"Represents `\", \"view\", \"_name.*`, which is sometimes necessary\"\n )]\n /// for efficient count queries. It cannot be used in place of\n /// `all_columns`\n pub fn star(&self) -> star {\n star\n }\n }\n #[allow(non_camel_case_types, dead_code)]\n #[doc = concat!(\"The tuple of all column structs on this \", \"view\")]\n pub type AllColumns = (id, name);\n #[doc = concat!(\"The SQL type of all of the columns on this \", \"view\")]\n pub type SqlType = <AllColumns as diesel::Expression>::SqlType;\n #[doc = concat!(\"Helper type for representing a boxed query from this \", \"view\")]\n pub type BoxedQuery<\'a, DB, ST = SqlType> = diesel::internal::table_macro::BoxedSelectStatement<\n \'a,\n ST,\n diesel::internal::table_macro::FromClause<view>,\n DB,\n >;\n impl diesel::QuerySource for view {\n type FromClause = diesel::internal::table_macro::StaticQueryFragmentInstance<\n view,\n >;\n type DefaultSelection = <Self as diesel::query_source::QueryRelation>::AllColumns;\n fn from_clause(&self) -> Self::FromClause {\n diesel::internal::table_macro::StaticQueryFragmentInstance::new()\n }\n fn default_selection(&self) -> Self::DefaultSelection {\n <Self as diesel::query_source::QueryRelation>::all_columns()\n }\n }\n impl diesel::internal::table_macro::PlainQuerySource for view {}\n impl<DB> diesel::query_builder::QueryFragment<DB> for view\n where\n DB: diesel::backend::Backend,\n <Self as diesel::internal::table_macro::StaticQueryFragment>::Component: diesel::query_builder::QueryFragment<\n DB,\n >,\n {\n fn walk_ast<\'b>(\n &\'b self,\n __diesel_internal_pass: diesel::query_builder::AstPass<\'_, \'b, DB>,\n ) -> diesel::result::QueryResult<()> {\n <Self as diesel::internal::table_macro::StaticQueryFragment>::STATIC_COMPONENT\n .walk_ast(__diesel_internal_pass)\n }\n }\n impl diesel::internal::table_macro::StaticQueryFragment for view {\n type Component = diesel::internal::table_macro::Identifier<\'static>;\n const STATIC_COMPONENT: &\'static Self::Component = &diesel::internal::table_macro::Identifier(\n \"view\",\n );\n }\n impl diesel::query_builder::AsQuery for view {\n type SqlType = SqlType;\n type Query = diesel::internal::table_macro::SelectStatement<\n diesel::internal::table_macro::FromClause<Self>,\n >;\n fn as_query(self) -> Self::Query {\n diesel::internal::table_macro::SelectStatement::simple(self)\n }\n }\n #[doc(hidden)]\n pub use self::view as table;\n impl diesel::query_source::QueryRelation for view {\n type AllColumns = AllColumns;\n fn all_columns() -> Self::AllColumns {\n all_columns\n }\n }\n impl diesel::internal::table_macro::Sealed for view {}\n impl diesel::query_source::View for view {}\n impl diesel::query_source::AppearsInFromClause<Self> for view {\n type Count = diesel::query_source::Once;\n }\n impl<S> diesel::internal::table_macro::AliasAppearsInFromClause<S, Self> for view\n where\n S: diesel::query_source::AliasSource<Target = Self>,\n {\n type Count = diesel::query_source::Never;\n }\n impl<\n S1,\n S2,\n > diesel::internal::table_macro::AliasAliasAppearsInFromClause<Self, S2, S1> for view\n where\n S1: diesel::query_source::AliasSource<Target = Self>,\n S2: diesel::query_source::AliasSource<Target = Self>,\n S1: diesel::internal::table_macro::AliasAliasAppearsInFromClauseSameTable<\n S2,\n Self,\n >,\n {\n type Count = <S1 as diesel::internal::table_macro::AliasAliasAppearsInFromClauseSameTable<\n S2,\n Self,\n >>::Count;\n }\n impl<S> diesel::query_source::AppearsInFromClause<diesel::query_source::Alias<S>>\n for view\n where\n S: diesel::query_source::AliasSource,\n {\n type Count = diesel::query_source::Never;\n }\n impl<\n S,\n C,\n > diesel::internal::table_macro::FieldAliasMapperAssociatedTypesDisjointnessTrick<\n Self,\n S,\n C,\n > for view\n where\n S: diesel::query_source::AliasSource<Target = Self> + ::core::clone::Clone,\n C: diesel::query_source::QueryRelationField<QueryRelation = Self>,\n {\n type Out = diesel::query_source::AliasedField<S, C>;\n fn map(\n __diesel_internal_column: C,\n __diesel_internal_alias: &diesel::query_source::Alias<S>,\n ) -> Self::Out {\n __diesel_internal_alias.field(__diesel_internal_column)\n }\n }\n impl<StmtKind> diesel::query_source::AppearsInFromClause<view>\n for diesel::internal::table_macro::returning::ReturningQuerySource<StmtKind, view> {\n type Count = diesel::query_source::Once;\n }\n impl<\n StmtKind,\n T,\n > diesel::query_source::AppearsInFromClause<\n diesel::internal::table_macro::returning::ReturningQuerySource<StmtKind, T>,\n > for view {\n type Count = diesel::query_source::Never;\n }\n impl diesel::query_source::AppearsInFromClause<view>\n for diesel::internal::table_macro::NoFromClause {\n type Count = diesel::query_source::Never;\n }\n impl<\n Left,\n Right,\n Kind,\n > diesel::JoinTo<diesel::internal::table_macro::Join<Left, Right, Kind>> for view\n where\n diesel::internal::table_macro::Join<Left, Right, Kind>: diesel::JoinTo<Self>,\n Left: diesel::query_source::QuerySource,\n Right: diesel::query_source::QuerySource,\n {\n type FromClause = diesel::internal::table_macro::Join<Left, Right, Kind>;\n type OnClause = <diesel::internal::table_macro::Join<\n Left,\n Right,\n Kind,\n > as diesel::JoinTo<Self>>::OnClause;\n fn join_target(\n __diesel_internal_rhs: diesel::internal::table_macro::Join<Left, Right, Kind>,\n ) -> (Self::FromClause, Self::OnClause) {\n let (_, __diesel_internal_on_clause) = diesel::internal::table_macro::Join::join_target(\n Self,\n );\n (__diesel_internal_rhs, __diesel_internal_on_clause)\n }\n }\n impl<Join, On> diesel::JoinTo<diesel::internal::table_macro::JoinOn<Join, On>>\n for view\n where\n diesel::internal::table_macro::JoinOn<Join, On>: diesel::JoinTo<Self>,\n {\n type FromClause = diesel::internal::table_macro::JoinOn<Join, On>;\n type OnClause = <diesel::internal::table_macro::JoinOn<\n Join,\n On,\n > as diesel::JoinTo<Self>>::OnClause;\n fn join_target(\n __diesel_internal_rhs: diesel::internal::table_macro::JoinOn<Join, On>,\n ) -> (Self::FromClause, Self::OnClause) {\n let (_, __diesel_internal_on_clause) = diesel::internal::table_macro::JoinOn::join_target(\n Self,\n );\n (__diesel_internal_rhs, __diesel_internal_on_clause)\n }\n }\n impl<\n F,\n S,\n D,\n W,\n O,\n L,\n Of,\n G,\n > diesel::JoinTo<\n diesel::internal::table_macro::SelectStatement<\n diesel::internal::table_macro::FromClause<F>,\n S,\n D,\n W,\n O,\n L,\n Of,\n G,\n >,\n > for view\n where\n diesel::internal::table_macro::SelectStatement<\n diesel::internal::table_macro::FromClause<F>,\n S,\n D,\n W,\n O,\n L,\n Of,\n G,\n >: diesel::JoinTo<Self>,\n F: diesel::query_source::QuerySource,\n {\n type FromClause = diesel::internal::table_macro::SelectStatement<\n diesel::internal::table_macro::FromClause<F>,\n S,\n D,\n W,\n O,\n L,\n Of,\n G,\n >;\n type OnClause = <diesel::internal::table_macro::SelectStatement<\n diesel::internal::table_macro::FromClause<F>,\n S,\n D,\n W,\n O,\n L,\n Of,\n G,\n > as diesel::JoinTo<Self>>::OnClause;\n fn join_target(\n __diesel_internal_rhs: diesel::internal::table_macro::SelectStatement<\n diesel::internal::table_macro::FromClause<F>,\n S,\n D,\n W,\n O,\n L,\n Of,\n G,\n >,\n ) -> (Self::FromClause, Self::OnClause) {\n let (_, __diesel_internal_on_clause) = diesel::internal::table_macro::SelectStatement::join_target(\n Self,\n );\n (__diesel_internal_rhs, __diesel_internal_on_clause)\n }\n }\n impl<\n \'a,\n QS,\n ST,\n DB,\n > diesel::JoinTo<\n diesel::internal::table_macro::BoxedSelectStatement<\n \'a,\n diesel::internal::table_macro::FromClause<QS>,\n ST,\n DB,\n >,\n > for view\n where\n diesel::internal::table_macro::BoxedSelectStatement<\n \'a,\n diesel::internal::table_macro::FromClause<QS>,\n ST,\n DB,\n >: diesel::JoinTo<Self>,\n QS: diesel::query_source::QuerySource,\n {\n type FromClause = diesel::internal::table_macro::BoxedSelectStatement<\n \'a,\n diesel::internal::table_macro::FromClause<QS>,\n ST,\n DB,\n >;\n type OnClause = <diesel::internal::table_macro::BoxedSelectStatement<\n \'a,\n diesel::internal::table_macro::FromClause<QS>,\n ST,\n DB,\n > as diesel::JoinTo<Self>>::OnClause;\n fn join_target(\n __diesel_internal_rhs: diesel::internal::table_macro::BoxedSelectStatement<\n \'a,\n diesel::internal::table_macro::FromClause<QS>,\n ST,\n DB,\n >,\n ) -> (Self::FromClause, Self::OnClause) {\n let (_, __diesel_internal_on_clause) = diesel::internal::table_macro::BoxedSelectStatement::join_target(\n Self,\n );\n (__diesel_internal_rhs, __diesel_internal_on_clause)\n }\n }\n impl<S> diesel::JoinTo<diesel::query_source::Alias<S>> for view\n where\n diesel::query_source::Alias<S>: diesel::JoinTo<Self>,\n {\n type FromClause = diesel::query_source::Alias<S>;\n type OnClause = <diesel::query_source::Alias<\n S,\n > as diesel::JoinTo<Self>>::OnClause;\n fn join_target(\n __diesel_internal_rhs: diesel::query_source::Alias<S>,\n ) -> (Self::FromClause, Self::OnClause) {\n let (_, __diesel_internal_on_clause) = diesel::query_source::Alias::<\n S,\n >::join_target(Self);\n (__diesel_internal_rhs, __diesel_internal_on_clause)\n }\n }\n #[doc = concat!(\"Contains all of the columns of this \", \"view\")]\n pub mod columns {\n use ::diesel;\n use super::view;\n use diesel::sql_types::*;\n #[allow(non_camel_case_types, dead_code)]\n #[derive(\n Debug,\n Clone,\n Copy,\n diesel::query_builder::QueryId,\n PartialEq,\n Eq,\n PartialOrd,\n Ord,\n Hash\n )]\n #[doc = concat!(\n \"Represents `\", \"view\", \"_name.*`, which is sometimes needed for\"\n )]\n /// efficient count queries. It cannot be used in place of\n /// `all_columns`, and has a `SqlType` of `()` to prevent it\n /// being used that way\n pub struct star;\n impl<__GB> diesel::expression::ValidGrouping<__GB> for star\n where\n super::AllColumns: diesel::expression::ValidGrouping<__GB>,\n {\n type IsAggregate = <super::AllColumns as diesel::expression::ValidGrouping<\n __GB,\n >>::IsAggregate;\n }\n impl diesel::Expression for star {\n type SqlType = diesel::expression::expression_types::NotSelectable;\n }\n impl<DB: diesel::backend::Backend> diesel::query_builder::QueryFragment<DB>\n for star\n where\n <view as diesel::QuerySource>::FromClause: diesel::query_builder::QueryFragment<\n DB,\n >,\n {\n #[allow(non_snake_case)]\n fn walk_ast<\'b>(\n &\'b self,\n mut __diesel_internal_out: diesel::query_builder::AstPass<\'_, \'b, DB>,\n ) -> diesel::result::QueryResult<()> {\n use diesel::QuerySource;\n if !__diesel_internal_out.should_skip_from() {\n const FROM_CLAUSE: diesel::internal::table_macro::StaticQueryFragmentInstance<\n view,\n > = diesel::internal::table_macro::StaticQueryFragmentInstance::new();\n FROM_CLAUSE.walk_ast(__diesel_internal_out.reborrow())?;\n __diesel_internal_out.push_sql(\".\");\n }\n __diesel_internal_out.push_sql(\"*\");\n Ok(())\n }\n }\n impl diesel::SelectableExpression<view> for star {}\n impl diesel::AppearsOnTable<view> for star {}\n #[allow(non_camel_case_types, dead_code)]\n #[derive(\n Debug,\n Clone,\n Copy,\n diesel::query_builder::QueryId,\n Default,\n PartialEq,\n Eq,\n PartialOrd,\n Ord,\n Hash\n )]\n pub struct id;\n impl diesel::expression::Expression for id {\n type SqlType = Integer;\n }\n impl<DB> diesel::query_builder::QueryFragment<DB> for id\n where\n DB: diesel::backend::Backend,\n diesel::internal::table_macro::StaticQueryFragmentInstance<\n view,\n >: diesel::query_builder::QueryFragment<DB>,\n {\n #[allow(non_snake_case)]\n fn walk_ast<\'b>(\n &\'b self,\n mut __diesel_internal_out: diesel::query_builder::AstPass<\'_, \'b, DB>,\n ) -> diesel::result::QueryResult<()> {\n if !__diesel_internal_out.should_skip_from() {\n const FROM_CLAUSE: diesel::internal::table_macro::StaticQueryFragmentInstance<\n view,\n > = diesel::internal::table_macro::StaticQueryFragmentInstance::new();\n FROM_CLAUSE.walk_ast(__diesel_internal_out.reborrow())?;\n __diesel_internal_out.push_sql(\".\");\n }\n __diesel_internal_out.push_identifier(\"id\")\n }\n }\n impl diesel::SelectableExpression<super::view> for id {}\n impl<\n __StmtKind,\n > diesel::SelectableExpression<\n diesel::internal::table_macro::returning::ReturningQuerySource<\n __StmtKind,\n super::view,\n >,\n > for id {}\n impl<QS> diesel::AppearsOnTable<QS> for id\n where\n QS: diesel::query_source::AppearsInFromClause<\n super::view,\n Count = diesel::query_source::Once,\n >,\n {}\n impl<\n Left,\n Right,\n > diesel::SelectableExpression<\n diesel::internal::table_macro::Join<\n Left,\n Right,\n diesel::internal::table_macro::LeftOuter,\n >,\n > for id\n where\n id: diesel::AppearsOnTable<\n diesel::internal::table_macro::Join<\n Left,\n Right,\n diesel::internal::table_macro::LeftOuter,\n >,\n >,\n Self: diesel::SelectableExpression<Left>,\n Right: diesel::query_source::AppearsInFromClause<\n super::view,\n Count = diesel::query_source::Never,\n > + diesel::query_source::QuerySource,\n Left: diesel::query_source::QuerySource,\n {}\n impl<\n Left,\n Right,\n > diesel::SelectableExpression<\n diesel::internal::table_macro::Join<\n Left,\n Right,\n diesel::internal::table_macro::Inner,\n >,\n > for id\n where\n id: diesel::AppearsOnTable<\n diesel::internal::table_macro::Join<\n Left,\n Right,\n diesel::internal::table_macro::Inner,\n >,\n >,\n Left: diesel::query_source::AppearsInFromClause<super::view>\n + diesel::query_source::QuerySource,\n Right: diesel::query_source::AppearsInFromClause<super::view>\n + diesel::query_source::QuerySource,\n (\n Left::Count,\n Right::Count,\n ): diesel::internal::table_macro::Pick<Left, Right>,\n Self: diesel::SelectableExpression<\n <(\n Left::Count,\n Right::Count,\n ) as diesel::internal::table_macro::Pick<Left, Right>>::Selection,\n >,\n {}\n impl<\n Join,\n On,\n > diesel::SelectableExpression<diesel::internal::table_macro::JoinOn<Join, On>>\n for id\n where\n id: diesel::SelectableExpression<Join>\n + diesel::AppearsOnTable<\n diesel::internal::table_macro::JoinOn<Join, On>,\n >,\n {}\n impl<\n From,\n > diesel::SelectableExpression<\n diesel::internal::table_macro::SelectStatement<\n diesel::internal::table_macro::FromClause<From>,\n >,\n > for id\n where\n From: diesel::query_source::QuerySource,\n id: diesel::SelectableExpression<From>\n + diesel::AppearsOnTable<\n diesel::internal::table_macro::SelectStatement<\n diesel::internal::table_macro::FromClause<From>,\n >,\n >,\n {}\n impl<__GB> diesel::expression::ValidGrouping<__GB> for id\n where\n __GB: diesel::expression::IsContainedInGroupBy<\n id,\n Output = diesel::expression::is_contained_in_group_by::Yes,\n >,\n {\n type IsAggregate = diesel::expression::is_aggregate::Yes;\n }\n impl diesel::expression::ValidGrouping<()> for id {\n type IsAggregate = diesel::expression::is_aggregate::No;\n }\n impl diesel::expression::IsContainedInGroupBy<id> for id {\n type Output = diesel::expression::is_contained_in_group_by::Yes;\n }\n impl<T> diesel::EqAll<T> for id\n where\n T: diesel::expression::AsExpression<Integer>,\n diesel::dsl::Eq<\n id,\n T::Expression,\n >: diesel::Expression<SqlType = diesel::sql_types::Bool>,\n {\n type Output = diesel::dsl::Eq<Self, T::Expression>;\n fn eq_all(self, __diesel_internal_rhs: T) -> Self::Output {\n use diesel::expression_methods::ExpressionMethods;\n self.eq(__diesel_internal_rhs)\n }\n }\n impl<Rhs> ::core::ops::Add<Rhs> for id\n where\n Rhs: diesel::expression::AsExpression<\n <<id as diesel::Expression>::SqlType as diesel::sql_types::ops::Add>::Rhs,\n >,\n {\n type Output = diesel::internal::table_macro::ops::Add<Self, Rhs::Expression>;\n fn add(self, __diesel_internal_rhs: Rhs) -> Self::Output {\n diesel::internal::table_macro::ops::Add::new(\n self,\n __diesel_internal_rhs.as_expression(),\n )\n }\n }\n impl<Rhs> ::core::ops::Sub<Rhs> for id\n where\n Rhs: diesel::expression::AsExpression<\n <<id as diesel::Expression>::SqlType as diesel::sql_types::ops::Sub>::Rhs,\n >,\n {\n type Output = diesel::internal::table_macro::ops::Sub<Self, Rhs::Expression>;\n fn sub(self, __diesel_internal_rhs: Rhs) -> Self::Output {\n diesel::internal::table_macro::ops::Sub::new(\n self,\n __diesel_internal_rhs.as_expression(),\n )\n }\n }\n impl<Rhs> ::core::ops::Div<Rhs> for id\n where\n Rhs: diesel::expression::AsExpression<\n <<id as diesel::Expression>::SqlType as diesel::sql_types::ops::Div>::Rhs,\n >,\n {\n type Output = diesel::internal::table_macro::ops::Div<Self, Rhs::Expression>;\n fn div(self, __diesel_internal_rhs: Rhs) -> Self::Output {\n diesel::internal::table_macro::ops::Div::new(\n self,\n __diesel_internal_rhs.as_expression(),\n )\n }\n }\n impl<Rhs> ::core::ops::Mul<Rhs> for id\n where\n Rhs: diesel::expression::AsExpression<\n <<id as diesel::Expression>::SqlType as diesel::sql_types::ops::Mul>::Rhs,\n >,\n {\n type Output = diesel::internal::table_macro::ops::Mul<Self, Rhs::Expression>;\n fn mul(self, __diesel_internal_rhs: Rhs) -> Self::Output {\n diesel::internal::table_macro::ops::Mul::new(\n self,\n __diesel_internal_rhs.as_expression(),\n )\n }\n }\n impl diesel::query_source::QueryRelationField for id {\n type QueryRelation = super::view;\n const NAME: &\'static str = \"id\";\n }\n #[allow(non_camel_case_types, dead_code)]\n #[derive(\n Debug,\n Clone,\n Copy,\n diesel::query_builder::QueryId,\n Default,\n PartialEq,\n Eq,\n PartialOrd,\n Ord,\n Hash\n )]\n pub struct name;\n impl diesel::expression::Expression for name {\n type SqlType = Text;\n }\n impl<DB> diesel::query_builder::QueryFragment<DB> for name\n where\n DB: diesel::backend::Backend,\n diesel::internal::table_macro::StaticQueryFragmentInstance<\n view,\n >: diesel::query_builder::QueryFragment<DB>,\n {\n #[allow(non_snake_case)]\n fn walk_ast<\'b>(\n &\'b self,\n mut __diesel_internal_out: diesel::query_builder::AstPass<\'_, \'b, DB>,\n ) -> diesel::result::QueryResult<()> {\n if !__diesel_internal_out.should_skip_from() {\n const FROM_CLAUSE: diesel::internal::table_macro::StaticQueryFragmentInstance<\n view,\n > = diesel::internal::table_macro::StaticQueryFragmentInstance::new();\n FROM_CLAUSE.walk_ast(__diesel_internal_out.reborrow())?;\n __diesel_internal_out.push_sql(\".\");\n }\n __diesel_internal_out.push_identifier(\"name\")\n }\n }\n impl diesel::SelectableExpression<super::view> for name {}\n impl<\n __StmtKind,\n > diesel::SelectableExpression<\n diesel::internal::table_macro::returning::ReturningQuerySource<\n __StmtKind,\n super::view,\n >,\n > for name {}\n impl<QS> diesel::AppearsOnTable<QS> for name\n where\n QS: diesel::query_source::AppearsInFromClause<\n super::view,\n Count = diesel::query_source::Once,\n >,\n {}\n impl<\n Left,\n Right,\n > diesel::SelectableExpression<\n diesel::internal::table_macro::Join<\n Left,\n Right,\n diesel::internal::table_macro::LeftOuter,\n >,\n > for name\n where\n name: diesel::AppearsOnTable<\n diesel::internal::table_macro::Join<\n Left,\n Right,\n diesel::internal::table_macro::LeftOuter,\n >,\n >,\n Self: diesel::SelectableExpression<Left>,\n Right: diesel::query_source::AppearsInFromClause<\n super::view,\n Count = diesel::query_source::Never,\n > + diesel::query_source::QuerySource,\n Left: diesel::query_source::QuerySource,\n {}\n impl<\n Left,\n Right,\n > diesel::SelectableExpression<\n diesel::internal::table_macro::Join<\n Left,\n Right,\n diesel::internal::table_macro::Inner,\n >,\n > for name\n where\n name: diesel::AppearsOnTable<\n diesel::internal::table_macro::Join<\n Left,\n Right,\n diesel::internal::table_macro::Inner,\n >,\n >,\n Left: diesel::query_source::AppearsInFromClause<super::view>\n + diesel::query_source::QuerySource,\n Right: diesel::query_source::AppearsInFromClause<super::view>\n + diesel::query_source::QuerySource,\n (\n Left::Count,\n Right::Count,\n ): diesel::internal::table_macro::Pick<Left, Right>,\n Self: diesel::SelectableExpression<\n <(\n Left::Count,\n Right::Count,\n ) as diesel::internal::table_macro::Pick<Left, Right>>::Selection,\n >,\n {}\n impl<\n Join,\n On,\n > diesel::SelectableExpression<diesel::internal::table_macro::JoinOn<Join, On>>\n for name\n where\n name: diesel::SelectableExpression<Join>\n + diesel::AppearsOnTable<\n diesel::internal::table_macro::JoinOn<Join, On>,\n >,\n {}\n impl<\n From,\n > diesel::SelectableExpression<\n diesel::internal::table_macro::SelectStatement<\n diesel::internal::table_macro::FromClause<From>,\n >,\n > for name\n where\n From: diesel::query_source::QuerySource,\n name: diesel::SelectableExpression<From>\n + diesel::AppearsOnTable<\n diesel::internal::table_macro::SelectStatement<\n diesel::internal::table_macro::FromClause<From>,\n >,\n >,\n {}\n impl<__GB> diesel::expression::ValidGrouping<__GB> for name\n where\n __GB: diesel::expression::IsContainedInGroupBy<\n name,\n Output = diesel::expression::is_contained_in_group_by::Yes,\n >,\n {\n type IsAggregate = diesel::expression::is_aggregate::Yes;\n }\n impl diesel::expression::ValidGrouping<()> for name {\n type IsAggregate = diesel::expression::is_aggregate::No;\n }\n impl diesel::expression::IsContainedInGroupBy<name> for name {\n type Output = diesel::expression::is_contained_in_group_by::Yes;\n }\n impl<T> diesel::EqAll<T> for name\n where\n T: diesel::expression::AsExpression<Text>,\n diesel::dsl::Eq<\n name,\n T::Expression,\n >: diesel::Expression<SqlType = diesel::sql_types::Bool>,\n {\n type Output = diesel::dsl::Eq<Self, T::Expression>;\n fn eq_all(self, __diesel_internal_rhs: T) -> Self::Output {\n use diesel::expression_methods::ExpressionMethods;\n self.eq(__diesel_internal_rhs)\n }\n }\n impl diesel::query_source::QueryRelationField for name {\n type QueryRelation = super::view;\n const NAME: &\'static str = \"name\";\n }\n impl diesel::expression::IsContainedInGroupBy<id> for name {\n type Output = diesel::expression::is_contained_in_group_by::No;\n }\n impl diesel::expression::IsContainedInGroupBy<name> for id {\n type Output = diesel::expression::is_contained_in_group_by::Yes;\n }\n }\n}\n```\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/view.md")))]
1701#[proc_macro]
1702pub fn view_proc(input: TokenStream) -> TokenStream {
1703view_proc_inner(input.into()).into()
1704}
17051706fn view_proc_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
1707self::table::query_source_macro(input, self::table::QuerySourceMacroKind::View)
1708}
17091710/// This derives implements `diesel::Connection` and related traits for an enum of
1711/// connections to different databases.
1712///
1713/// By applying this derive to such an enum, you can use the enum as a connection type in
1714/// any location all the inner connections are valid. This derive supports enum
1715/// variants containing a single tuple field. Each tuple field type must implement
1716/// `diesel::Connection` and a number of related traits. Connection types form Diesel itself
1717/// as well as third party connection types are supported by this derive.
1718///
1719/// The implementation of `diesel::Connection::establish` tries to establish
1720/// a new connection with the given connection string in the order the connections
1721/// are specified in the enum. If one connection fails, it tries the next one and so on.
1722/// That means that as soon as more than one connection type accepts a certain connection
1723/// string the first matching type in your enum will always establish the connection. This
1724/// is especially important if one of the connection types is `diesel::SqliteConnection`
1725/// as this connection type accepts arbitrary paths. It should normally place as last entry
1726/// in your enum. If you want control of which connection type is created, just construct the
1727/// corresponding enum manually by first establishing the connection via the inner type and then
1728/// wrap the result into the enum.
1729///
1730/// ## Optional Container Attributes
1731///
1732/// This macro supports generating code for [`diesel-async`](https://docs.rs/diesel-async/latest/diesel_async/).
1733/// By adding the `#[diesel_async]` attribute, the macro instead derives
1734/// implements `diesel_async::AsyncConnection` and related traits
1735/// for an enum of connections to different databases.
1736/// This way each tuple field type must implement `diesel_async::AsyncConnection`.
1737/// It is possible to use `diesel-async`'s `SyncConnectionWrapper` as connection type.
1738/// The implementation of `diesel_async::AsyncConnection::establish` works similar to the sync variant.
1739///
1740/// The usual stability guarantees of `diesel` do not apply here.
1741/// When this attribute is used the generated code is only compatible to the `diesel-async` version supported,
1742/// by this `diesel` version.
1743///
1744/// Note: The associated types `LoadFuture` and `ExecuteFuture` in the implementation
1745/// of the trait [`AsyncConnectionCore`](https://docs.rs/diesel-async/latest/diesel_async/trait.AsyncConnectionCore.html)
1746/// must be bound by `'conn`.
1747///
1748///
1749/// # Example
1750/// ```
1751/// # extern crate diesel;
1752/// # use diesel::result::QueryResult;
1753/// use diesel::prelude::*;
1754///
1755/// #[derive(diesel::MultiConnection)]
1756/// pub enum AnyConnection {
1757/// # #[cfg(feature = "postgres")]
1758/// Postgresql(diesel::PgConnection),
1759/// # #[cfg(feature = "mysql")]
1760/// Mysql(diesel::MysqlConnection),
1761/// # #[cfg(feature = "sqlite")]
1762/// Sqlite(diesel::SqliteConnection),
1763/// }
1764///
1765/// diesel::table! {
1766/// users {
1767/// id -> Integer,
1768/// name -> Text,
1769/// }
1770/// }
1771///
1772/// fn use_multi(conn: &mut AnyConnection) -> QueryResult<()> {
1773/// // Use the connection enum as any other connection type
1774/// // for inserting/updating/loading/…
1775/// diesel::insert_into(users::table)
1776/// .values(users::name.eq("Sean"))
1777/// .execute(conn)?;
1778///
1779/// let users = users::table.load::<(i32, String)>(conn)?;
1780///
1781/// // Match on the connection type to access
1782/// // the inner connection. This allows us then to use
1783/// // backend specific methods.
1784/// # #[cfg(feature = "postgres")]
1785/// if let AnyConnection::Postgresql(conn) = conn {
1786/// // perform a postgresql specific query here
1787/// let users = users::table.load::<(i32, String)>(conn)?;
1788/// }
1789///
1790/// Ok(())
1791/// }
1792///
1793/// # fn main() {}
1794/// ```
1795///
1796/// # Limitations
1797///
1798/// The derived connection implementation can only cover the common subset of
1799/// all inner connection types. So, if one backend doesn't support certain SQL features,
1800/// like for example, returning clauses, the whole connection implementation doesn't
1801/// support this feature. In addition, only a limited set of SQL types is supported:
1802///
1803/// * `diesel::sql_types::SmallInt`
1804/// * `diesel::sql_types::Integer`
1805/// * `diesel::sql_types::BigInt`
1806/// * `diesel::sql_types::Double`
1807/// * `diesel::sql_types::Float`
1808/// * `diesel::sql_types::Text`
1809/// * `diesel::sql_types::Date`
1810/// * `diesel::sql_types::Time`
1811/// * `diesel::sql_types::Timestamp`
1812///
1813/// Support for additional types can be added by providing manual implementations of
1814/// `HasSqlType`, `FromSql` and `ToSql` for the corresponding type, all databases included
1815/// in your enum, and the backend generated by this derive called `MultiBackend`.
1816/// For example to support a custom enum `MyEnum` with the custom SQL type `MyInteger`:
1817/// ```
1818/// extern crate diesel;
1819/// use diesel::backend::Backend;
1820/// use diesel::deserialize::{self, FromSql, FromSqlRow};
1821/// use diesel::serialize::{self, IsNull, ToSql};
1822/// use diesel::AsExpression;
1823/// use diesel::sql_types::{HasSqlType, SqlType};
1824/// use diesel::prelude::*;
1825///
1826/// #[derive(diesel::MultiConnection)]
1827/// pub enum AnyConnection {
1828/// # #[cfg(feature = "postgres")]
1829/// Postgresql(diesel::PgConnection),
1830/// # #[cfg(feature = "mysql")]
1831/// Mysql(diesel::MysqlConnection),
1832/// # #[cfg(feature = "sqlite")]
1833/// Sqlite(diesel::SqliteConnection),
1834/// }
1835///
1836/// // defining an custom SQL type is optional
1837/// // you can also use types from `diesel::sql_types`
1838/// #[derive(Copy, Clone, Debug, SqlType)]
1839/// #[diesel(postgres_type(name = "Int4"))]
1840/// #[diesel(mysql_type(name = "Long"))]
1841/// #[diesel(sqlite_type(name = "Integer"))]
1842/// struct MyInteger;
1843///
1844///
1845/// // our custom enum
1846/// #[repr(i32)]
1847/// #[derive(Debug, Clone, Copy, AsExpression, FromSqlRow)]
1848/// #[diesel(sql_type = MyInteger)]
1849/// pub enum MyEnum {
1850/// A = 1,
1851/// B = 2,
1852/// }
1853///
1854/// // The `MultiBackend` type is generated by `#[derive(diesel::MultiConnection)]`
1855/// // This part is only required if you define a custom sql type
1856/// impl HasSqlType<MyInteger> for MultiBackend {
1857/// fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {
1858/// // The `lookup_sql_type` function is exposed by the `MultiBackend` type
1859/// MultiBackend::lookup_sql_type::<MyInteger>(lookup)
1860/// }
1861/// }
1862///
1863/// impl FromSql<MyInteger, MultiBackend> for MyEnum {
1864/// fn from_sql(bytes: <MultiBackend as Backend>::RawValue<'_>) -> deserialize::Result<Self> {
1865/// // The `from_sql` function is exposed by the `RawValue` type of the
1866/// // `MultiBackend` type
1867/// // This requires a `FromSql` impl for each backend
1868/// bytes.from_sql::<MyEnum, MyInteger>()
1869/// }
1870/// }
1871///
1872/// impl ToSql<MyInteger, MultiBackend> for MyEnum {
1873/// fn to_sql<'b>(&'b self, out: &mut serialize::Output<'b, '_, MultiBackend>) -> serialize::Result {
1874/// /// `set_value` expects a tuple consisting of the target SQL type
1875/// /// and self for `MultiBackend`
1876/// /// This requires a `ToSql` impl for each backend
1877/// out.set_value((MyInteger, self));
1878/// Ok(IsNull::No)
1879/// }
1880/// }
1881/// # #[cfg(feature = "postgres")]
1882/// # impl ToSql<MyInteger, diesel::pg::Pg> for MyEnum {
1883/// # fn to_sql<'b>(&'b self, out: &mut serialize::Output<'b, '_, diesel::pg::Pg>) -> serialize::Result { todo!() }
1884/// # }
1885/// # #[cfg(feature = "mysql")]
1886/// # impl ToSql<MyInteger, diesel::mysql::Mysql> for MyEnum {
1887/// # fn to_sql<'b>(&'b self, out: &mut serialize::Output<'b, '_, diesel::mysql::Mysql>) -> serialize::Result { todo!() }
1888/// # }
1889/// # #[cfg(feature = "sqlite")]
1890/// # impl ToSql<MyInteger, diesel::sqlite::Sqlite> for MyEnum {
1891/// # fn to_sql<'b>(&'b self, out: &mut serialize::Output<'b, '_, diesel::sqlite::Sqlite>) -> serialize::Result { todo!() }
1892/// # }
1893/// # #[cfg(feature = "postgres")]
1894/// # impl FromSql<MyInteger, diesel::pg::Pg> for MyEnum {
1895/// # fn from_sql(bytes: <diesel::pg::Pg as Backend>::RawValue<'_>) -> deserialize::Result<Self> { todo!() }
1896/// # }
1897/// # #[cfg(feature = "mysql")]
1898/// # impl FromSql<MyInteger, diesel::mysql::Mysql> for MyEnum {
1899/// # fn from_sql(bytes: <diesel::mysql::Mysql as Backend>::RawValue<'_>) -> deserialize::Result<Self> { todo!() }
1900/// # }
1901/// # #[cfg(feature = "sqlite")]
1902/// # impl FromSql<MyInteger, diesel::sqlite::Sqlite> for MyEnum {
1903/// # fn from_sql(bytes: <diesel::sqlite::Sqlite as Backend>::RawValue<'_>) -> deserialize::Result<Self> { todo!() }
1904/// # }
1905/// # fn main() {}
1906/// ```
1907///
1908#[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 MultiDefaultValueClauseForInsert;\n pub struct MultiEmptyFromClauseSyntax;\n pub struct MultiExistsSyntax;\n pub struct MultiArrayComparisonSyntax;\n pub struct MultiConcatClauseSyntax;\n pub struct MultiSelectStatementSyntax;\n pub struct MultiAliasSyntax;\n pub struct MultiWindowFrameClauseGroupSupport;\n pub struct MultiWindowFrameExclusionSupport;\n pub struct MultiAggregateFunctionExpressions;\n pub struct MultiBuiltInWindowFunctionRequireOrder;\n impl diesel::backend::SqlDialect for MultiBackend {\n type ReturningClause = MultiReturningClause;\n type OnConflictClause = diesel::internal::derives::multiconnection::sql_dialect::on_conflict_clause::DoesNotSupportOnConflictClause;\n type InsertWithDefaultKeyword = MultiInsertWithDefaultKeyword;\n type BatchInsertSupport = MultiBatchInsertSupport;\n type DefaultValueClauseForInsert = MultiDefaultValueClauseForInsert;\n type EmptyFromClauseSyntax = MultiEmptyFromClauseSyntax;\n type ExistsSyntax = MultiExistsSyntax;\n type ArrayComparison = MultiArrayComparisonSyntax;\n type ConcatClause = MultiConcatClauseSyntax;\n type SelectStatementSyntax = MultiSelectStatementSyntax;\n type AliasSyntax = MultiAliasSyntax;\n type WindowFrameClauseGroupSupport = MultiWindowFrameClauseGroupSupport;\n type WindowFrameExclusionSupport = MultiWindowFrameExclusionSupport;\n type AggregateFunctionExpressions = MultiAggregateFunctionExpressions;\n type BuiltInWindowFunctionRequireOrder = MultiBuiltInWindowFunctionRequireOrder;\n }\n impl diesel::internal::derives::multiconnection::TrustedBackend\n for MultiBackend {}\n impl diesel::internal::derives::multiconnection::DieselReserveSpecialization\n for MultiBackend {}\n impl diesel::sql_types::HasSqlType<diesel::sql_types::SmallInt>\n for super::MultiBackend {\n fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {\n Self::lookup_sql_type::<diesel::sql_types::SmallInt>(lookup)\n }\n }\n impl diesel::sql_types::HasSqlType<diesel::sql_types::Integer>\n for super::MultiBackend {\n fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {\n Self::lookup_sql_type::<diesel::sql_types::Integer>(lookup)\n }\n }\n impl diesel::sql_types::HasSqlType<diesel::sql_types::BigInt>\n for super::MultiBackend {\n fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {\n Self::lookup_sql_type::<diesel::sql_types::BigInt>(lookup)\n }\n }\n impl diesel::sql_types::HasSqlType<diesel::sql_types::Double>\n for super::MultiBackend {\n fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {\n Self::lookup_sql_type::<diesel::sql_types::Double>(lookup)\n }\n }\n impl diesel::sql_types::HasSqlType<diesel::sql_types::Float>\n for super::MultiBackend {\n fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {\n Self::lookup_sql_type::<diesel::sql_types::Float>(lookup)\n }\n }\n impl diesel::sql_types::HasSqlType<diesel::sql_types::Text>\n for super::MultiBackend {\n fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {\n Self::lookup_sql_type::<diesel::sql_types::Text>(lookup)\n }\n }\n impl diesel::sql_types::HasSqlType<diesel::sql_types::Binary>\n for super::MultiBackend {\n fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {\n Self::lookup_sql_type::<diesel::sql_types::Binary>(lookup)\n }\n }\n impl diesel::sql_types::HasSqlType<diesel::sql_types::Date>\n for super::MultiBackend {\n fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {\n Self::lookup_sql_type::<diesel::sql_types::Date>(lookup)\n }\n }\n impl diesel::sql_types::HasSqlType<diesel::sql_types::Time>\n for super::MultiBackend {\n fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {\n Self::lookup_sql_type::<diesel::sql_types::Time>(lookup)\n }\n }\n impl diesel::sql_types::HasSqlType<diesel::sql_types::Timestamp>\n for super::MultiBackend {\n fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {\n Self::lookup_sql_type::<diesel::sql_types::Timestamp>(lookup)\n }\n }\n impl diesel::sql_types::HasSqlType<diesel::sql_types::Bool>\n for super::MultiBackend {\n fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {\n Self::lookup_sql_type::<diesel::sql_types::Bool>(lookup)\n }\n }\n impl diesel::sql_types::HasSqlType<diesel::sql_types::Numeric>\n for super::MultiBackend {\n fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {\n Self::lookup_sql_type::<diesel::sql_types::Numeric>(lookup)\n }\n }\n }\n mod query_builder {\n use super::*;\n pub enum MultiQueryBuilder {\n Pg(\n <<PgConnection as diesel::connection::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 S,\n > diesel::query_builder::QueryFragment<\n super::backend::MultiBackend,\n super::backend::MultiAliasSyntax,\n > for diesel::query_source::Alias<S>\n where\n Self: diesel::query_builder::QueryFragment<\n <PgConnection as diesel::connection::Connection>::Backend,\n >\n + diesel::query_builder::QueryFragment<\n <diesel::SqliteConnection as diesel::connection::Connection>::Backend,\n >,\n {\n fn walk_ast<\'b>(\n &\'b self,\n pass: diesel::query_builder::AstPass<\'_, \'b, MultiBackend>,\n ) -> diesel::QueryResult<()> {\n super::backend::MultiBackend::walk_variant_ast(self, pass)\n }\n }\n impl<\n F,\n S,\n D,\n W,\n O,\n LOf,\n G,\n H,\n LC,\n > diesel::query_builder::QueryFragment<\n super::backend::MultiBackend,\n super::backend::MultiSelectStatementSyntax,\n >\n for diesel::internal::derives::multiconnection::SelectStatement<\n F,\n S,\n D,\n W,\n O,\n LOf,\n G,\n H,\n LC,\n >\n where\n S: diesel::query_builder::QueryFragment<super::backend::MultiBackend>,\n F: diesel::query_builder::QueryFragment<super::backend::MultiBackend>,\n D: diesel::query_builder::QueryFragment<super::backend::MultiBackend>,\n W: diesel::query_builder::QueryFragment<super::backend::MultiBackend>,\n O: diesel::query_builder::QueryFragment<super::backend::MultiBackend>,\n LOf: diesel::query_builder::QueryFragment<super::backend::MultiBackend>,\n G: diesel::query_builder::QueryFragment<super::backend::MultiBackend>,\n H: diesel::query_builder::QueryFragment<super::backend::MultiBackend>,\n LC: diesel::query_builder::QueryFragment<super::backend::MultiBackend>,\n {\n fn walk_ast<\'b>(\n &\'b self,\n mut out: diesel::query_builder::AstPass<\'_, \'b, MultiBackend>,\n ) -> diesel::QueryResult<()> {\n use diesel::internal::derives::multiconnection::SelectStatementAccessor;\n out.push_sql(\"SELECT \");\n self.distinct_clause().walk_ast(out.reborrow())?;\n self.select_clause().walk_ast(out.reborrow())?;\n self.from_clause().walk_ast(out.reborrow())?;\n self.where_clause().walk_ast(out.reborrow())?;\n self.group_by_clause().walk_ast(out.reborrow())?;\n self.having_clause().walk_ast(out.reborrow())?;\n self.order_clause().walk_ast(out.reborrow())?;\n self.limit_offset_clause().walk_ast(out.reborrow())?;\n self.locking_clause().walk_ast(out.reborrow())?;\n Ok(())\n }\n }\n impl<\n \'a,\n ST,\n QS,\n GB,\n > diesel::query_builder::QueryFragment<\n super::backend::MultiBackend,\n super::backend::MultiSelectStatementSyntax,\n >\n for diesel::internal::derives::multiconnection::BoxedSelectStatement<\n \'a,\n ST,\n QS,\n super::backend::MultiBackend,\n GB,\n >\n where\n QS: diesel::query_builder::QueryFragment<super::backend::MultiBackend>,\n {\n fn walk_ast<\'b>(\n &\'b self,\n pass: diesel::query_builder::AstPass<\'_, \'b, MultiBackend>,\n ) -> diesel::QueryResult<()> {\n use diesel::internal::derives::multiconnection::BoxedQueryHelper;\n self.build_query(pass, |where_clause, pass| where_clause.walk_ast(pass))\n }\n }\n impl diesel::query_builder::QueryFragment<super::backend::MultiBackend>\n for diesel::internal::derives::multiconnection::BoxedLimitOffsetClause<\n \'_,\n super::backend::MultiBackend,\n > {\n fn walk_ast<\'b>(\n &\'b self,\n mut pass: diesel::query_builder::AstPass<\'_, \'b, MultiBackend>,\n ) -> diesel::QueryResult<()> {\n if let Some(limit) = &self.limit {\n limit.walk_ast(pass.reborrow())?;\n }\n if let Some(offset) = &self.offset {\n offset.walk_ast(pass.reborrow())?;\n }\n Ok(())\n }\n }\n impl<\n \'a,\n > diesel::query_builder::IntoBoxedClause<\n \'a,\n super::multi_connection_impl::backend::MultiBackend,\n >\n for diesel::internal::derives::multiconnection::LimitOffsetClause<\n diesel::internal::derives::multiconnection::NoLimitClause,\n diesel::internal::derives::multiconnection::NoOffsetClause,\n > {\n type BoxedClause = diesel::internal::derives::multiconnection::BoxedLimitOffsetClause<\n \'a,\n super::multi_connection_impl::backend::MultiBackend,\n >;\n fn into_boxed(self) -> Self::BoxedClause {\n diesel::internal::derives::multiconnection::BoxedLimitOffsetClause {\n limit: None,\n offset: None,\n }\n }\n }\n impl<\n \'a,\n L,\n > diesel::query_builder::IntoBoxedClause<\n \'a,\n super::multi_connection_impl::backend::MultiBackend,\n >\n for diesel::internal::derives::multiconnection::LimitOffsetClause<\n diesel::internal::derives::multiconnection::LimitClause<L>,\n diesel::internal::derives::multiconnection::NoOffsetClause,\n >\n where\n diesel::internal::derives::multiconnection::LimitClause<\n L,\n >: diesel::query_builder::QueryFragment<super::backend::MultiBackend> + Send\n + \'static,\n {\n type BoxedClause = diesel::internal::derives::multiconnection::BoxedLimitOffsetClause<\n \'a,\n super::multi_connection_impl::backend::MultiBackend,\n >;\n fn into_boxed(self) -> Self::BoxedClause {\n diesel::internal::derives::multiconnection::BoxedLimitOffsetClause {\n limit: Some(Box::new(self.limit_clause)),\n offset: None,\n }\n }\n }\n impl<\n \'a,\n O,\n > diesel::query_builder::IntoBoxedClause<\n \'a,\n super::multi_connection_impl::backend::MultiBackend,\n >\n for diesel::internal::derives::multiconnection::LimitOffsetClause<\n diesel::internal::derives::multiconnection::NoLimitClause,\n diesel::internal::derives::multiconnection::OffsetClause<O>,\n >\n where\n diesel::internal::derives::multiconnection::OffsetClause<\n O,\n >: diesel::query_builder::QueryFragment<super::backend::MultiBackend> + Send\n + \'static,\n {\n type BoxedClause = diesel::internal::derives::multiconnection::BoxedLimitOffsetClause<\n \'a,\n super::multi_connection_impl::backend::MultiBackend,\n >;\n fn into_boxed(self) -> Self::BoxedClause {\n diesel::internal::derives::multiconnection::BoxedLimitOffsetClause {\n limit: None,\n offset: Some(Box::new(self.offset_clause)),\n }\n }\n }\n impl<\n \'a,\n L,\n O,\n > diesel::query_builder::IntoBoxedClause<\n \'a,\n super::multi_connection_impl::backend::MultiBackend,\n >\n for diesel::internal::derives::multiconnection::LimitOffsetClause<\n diesel::internal::derives::multiconnection::LimitClause<L>,\n diesel::internal::derives::multiconnection::OffsetClause<O>,\n >\n where\n diesel::internal::derives::multiconnection::LimitClause<\n L,\n >: diesel::query_builder::QueryFragment<super::backend::MultiBackend> + Send\n + \'static,\n diesel::internal::derives::multiconnection::OffsetClause<\n O,\n >: diesel::query_builder::QueryFragment<super::backend::MultiBackend> + Send\n + \'static,\n {\n type BoxedClause = diesel::internal::derives::multiconnection::BoxedLimitOffsetClause<\n \'a,\n super::multi_connection_impl::backend::MultiBackend,\n >;\n fn into_boxed(self) -> Self::BoxedClause {\n diesel::internal::derives::multiconnection::BoxedLimitOffsetClause {\n limit: Some(Box::new(self.limit_clause)),\n offset: Some(Box::new(self.offset_clause)),\n }\n }\n }\n impl<\n Col,\n Expr,\n > diesel::insertable::InsertValues<\n super::multi_connection_impl::backend::MultiBackend,\n Col::Table,\n >\n for diesel::insertable::DefaultableColumnInsertValue<\n diesel::insertable::ColumnInsertValue<Col, Expr>,\n >\n where\n Col: diesel::prelude::Column,\n Expr: diesel::prelude::Expression<SqlType = Col::SqlType>,\n Expr: diesel::prelude::AppearsOnTable<\n diesel::internal::derives::multiconnection::NoFromClause,\n >,\n Self: diesel::query_builder::QueryFragment<\n super::multi_connection_impl::backend::MultiBackend,\n >,\n diesel::insertable::DefaultableColumnInsertValue<\n diesel::insertable::ColumnInsertValue<Col, Expr>,\n >: diesel::insertable::InsertValues<\n <PgConnection as diesel::connection::Connection>::Backend,\n Col::Table,\n >,\n diesel::insertable::DefaultableColumnInsertValue<\n diesel::insertable::ColumnInsertValue<Col, Expr>,\n >: diesel::insertable::InsertValues<\n <diesel::SqliteConnection as diesel::connection::Connection>::Backend,\n Col::Table,\n >,\n {\n fn column_names(\n &self,\n mut out: diesel::query_builder::AstPass<\n \'_,\n \'_,\n super::multi_connection_impl::backend::MultiBackend,\n >,\n ) -> diesel::QueryResult<()> {\n use diesel::internal::derives::multiconnection::AstPassHelper;\n match out.backend() {\n super::backend::MultiBackend::Pg(_) => {\n <Self as diesel::insertable::InsertValues<\n <PgConnection as diesel::connection::Connection>::Backend,\n Col::Table,\n >>::column_names(\n &self,\n out\n .cast_database(\n super::bind_collector::MultiBindCollector::pg,\n super::query_builder::MultiQueryBuilder::pg,\n super::backend::MultiBackend::pg,\n |l| {\n <PgConnection as diesel::internal::derives::multiconnection::MultiConnectionHelper>::from_any(\n l,\n )\n .expect(\n \"It\'s possible to downcast the metadata lookup type to the correct type\",\n )\n },\n ),\n )\n }\n super::backend::MultiBackend::Sqlite(_) => {\n <Self as diesel::insertable::InsertValues<\n <diesel::SqliteConnection as diesel::connection::Connection>::Backend,\n Col::Table,\n >>::column_names(\n &self,\n out\n .cast_database(\n super::bind_collector::MultiBindCollector::sqlite,\n super::query_builder::MultiQueryBuilder::sqlite,\n super::backend::MultiBackend::sqlite,\n |l| {\n <diesel::SqliteConnection as diesel::internal::derives::multiconnection::MultiConnectionHelper>::from_any(\n l,\n )\n .expect(\n \"It\'s possible to downcast the metadata lookup type to the correct type\",\n )\n },\n ),\n )\n }\n }\n }\n }\n }\n mod bind_collector {\n use super::*;\n pub enum MultiBindCollector<\'a> {\n Pg(\n <<PgConnection as diesel::connection::Connection>::Backend as diesel::backend::Backend>::BindCollector<\n \'a,\n >,\n ),\n Sqlite(\n <<diesel::SqliteConnection as diesel::connection::Connection>::Backend as diesel::backend::Backend>::BindCollector<\n \'a,\n >,\n ),\n }\n impl<\'a> MultiBindCollector<\'a> {\n pub(super) fn pg(\n &mut self,\n ) -> &mut <<PgConnection as diesel::connection::Connection>::Backend as diesel::backend::Backend>::BindCollector<\n \'a,\n > {\n match self {\n Self::Pg(bc) => bc,\n _ => unreachable!(),\n }\n }\n pub(super) fn sqlite(\n &mut self,\n ) -> &mut <<diesel::SqliteConnection as diesel::connection::Connection>::Backend as diesel::backend::Backend>::BindCollector<\n \'a,\n > {\n match self {\n Self::Sqlite(bc) => bc,\n _ => unreachable!(),\n }\n }\n }\n trait PushBoundValueToCollectorDB<DB: diesel::backend::Backend> {\n fn push_bound_value<\'a: \'b, \'b>(\n &self,\n v: InnerBindValueKind<\'a>,\n collector: &mut <DB as diesel::backend::Backend>::BindCollector<\'b>,\n lookup: &mut <DB as diesel::sql_types::TypeMetadata>::MetadataLookup,\n ) -> diesel::result::QueryResult<()>;\n }\n struct PushBoundValueToCollectorImpl<ST, T: ?Sized> {\n p: std::marker::PhantomData<(ST, T)>,\n }\n impl<ST, T, DB> PushBoundValueToCollectorDB<DB>\n for PushBoundValueToCollectorImpl<ST, T>\n where\n DB: diesel::backend::Backend + diesel::sql_types::HasSqlType<ST>,\n T: diesel::serialize::ToSql<ST, DB> + \'static,\n Option<\n T,\n >: diesel::serialize::ToSql<diesel::sql_types::Nullable<ST>, DB> + \'static,\n ST: diesel::sql_types::SqlType,\n {\n fn push_bound_value<\'a: \'b, \'b>(\n &self,\n v: InnerBindValueKind<\'a>,\n collector: &mut <DB as diesel::backend::Backend>::BindCollector<\'b>,\n lookup: &mut <DB as diesel::sql_types::TypeMetadata>::MetadataLookup,\n ) -> diesel::result::QueryResult<()> {\n use diesel::query_builder::BindCollector;\n match v {\n InnerBindValueKind::Sized(v) => {\n let v = v\n .downcast_ref::<T>()\n .expect(\"We know the type statically here\");\n collector.push_bound_value::<ST, T>(v, lookup)\n }\n InnerBindValueKind::Null => {\n collector\n .push_bound_value::<\n diesel::sql_types::Nullable<ST>,\n Option<T>,\n >(&None, lookup)\n }\n _ => {\n unreachable!(\n \"We set the value to `InnerBindValueKind::Sized` or `InnerBindValueKind::Null`\"\n )\n }\n }\n }\n }\n impl<DB> PushBoundValueToCollectorDB<DB>\n for PushBoundValueToCollectorImpl<diesel::sql_types::Text, str>\n where\n DB: diesel::backend::Backend\n + diesel::sql_types::HasSqlType<diesel::sql_types::Text>,\n str: diesel::serialize::ToSql<diesel::sql_types::Text, DB> + \'static,\n {\n fn push_bound_value<\'a: \'b, \'b>(\n &self,\n v: InnerBindValueKind<\'a>,\n collector: &mut <DB as diesel::backend::Backend>::BindCollector<\'b>,\n lookup: &mut <DB as diesel::sql_types::TypeMetadata>::MetadataLookup,\n ) -> diesel::result::QueryResult<()> {\n use diesel::query_builder::BindCollector;\n if let InnerBindValueKind::Str(v) = v {\n collector.push_bound_value::<diesel::sql_types::Text, str>(v, lookup)\n } else {\n unreachable!(\"We set the value to `InnerBindValueKind::Str`\")\n }\n }\n }\n impl<DB> PushBoundValueToCollectorDB<DB>\n for PushBoundValueToCollectorImpl<diesel::sql_types::Binary, [u8]>\n where\n DB: diesel::backend::Backend\n + diesel::sql_types::HasSqlType<diesel::sql_types::Binary>,\n [u8]: diesel::serialize::ToSql<diesel::sql_types::Binary, DB> + \'static,\n {\n fn push_bound_value<\'a: \'b, \'b>(\n &self,\n v: InnerBindValueKind<\'a>,\n collector: &mut <DB as diesel::backend::Backend>::BindCollector<\'b>,\n lookup: &mut <DB as diesel::sql_types::TypeMetadata>::MetadataLookup,\n ) -> diesel::result::QueryResult<()> {\n use diesel::query_builder::BindCollector;\n if let InnerBindValueKind::Bytes(v) = v {\n collector\n .push_bound_value::<diesel::sql_types::Binary, [u8]>(v, lookup)\n } else {\n unreachable!(\"We set the value to `InnerBindValueKind::Binary`\")\n }\n }\n }\n trait PushBoundValueToCollector: PushBoundValueToCollectorDB<\n <PgConnection as diesel::connection::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 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")))]
1909#[proc_macro_derive(MultiConnection, attributes(diesel_async))]
1910pub fn derive_multiconnection(input: TokenStream) -> TokenStream {
1911derive_multiconnection_inner(input.into()).into()
1912}
19131914fn derive_multiconnection_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
1915 syn::parse2(input)
1916 .map(multiconnection::derive)
1917 .unwrap_or_else(syn::Error::into_compile_error)
1918}
19191920/// Automatically annotates return type of a query fragment function
1921///
1922/// This may be useful when factoring out common query fragments into functions.
1923/// If not using this, it would typically involve explicitly writing the full
1924/// type of the query fragment function, which depending on the length of said
1925/// query fragment can be quite difficult (especially to maintain) and verbose.
1926///
1927/// # Example
1928///
1929/// ```rust
1930/// # extern crate diesel;
1931/// # include!("../../diesel/src/doctest_setup.rs");
1932/// # use schema::{users, posts};
1933/// use diesel::dsl;
1934///
1935/// # fn main() {
1936/// # run_test().unwrap();
1937/// # }
1938/// #
1939/// # fn run_test() -> QueryResult<()> {
1940/// # let conn = &mut establish_connection();
1941/// #
1942/// #[dsl::auto_type]
1943/// fn user_has_post() -> _ {
1944/// dsl::exists(posts::table.filter(posts::user_id.eq(users::id)))
1945/// }
1946///
1947/// let users_with_posts: Vec<String> = users::table
1948/// .filter(user_has_post())
1949/// .select(users::name)
1950/// .load(conn)?;
1951///
1952/// assert_eq!(
1953/// &["Sean", "Tess"] as &[_],
1954/// users_with_posts
1955/// .iter()
1956/// .map(|s| s.as_str())
1957/// .collect::<Vec<_>>()
1958/// );
1959/// # Ok(())
1960/// # }
1961/// ```
1962/// # Limitations
1963///
1964/// While this attribute tries to support as much of diesels built-in DSL as possible it's
1965/// unfortunately not possible to support everything. Notable unsupported types are:
1966///
1967/// * Update statements
1968/// * Insert from select statements
1969/// * Query constructed by `diesel::sql_query`
1970/// * Expressions using `diesel::dsl::sql`
1971///
1972/// For these cases a manual type annotation is required. See the "Annotating Types" section below
1973/// for details.
1974///
1975///
1976/// # Advanced usage
1977///
1978/// By default, the macro will:
1979/// - Generate a type alias for the return type of the function, named the
1980/// exact same way as the function itself.
1981/// - Assume that functions, unless otherwise annotated, have a type alias for
1982/// their return type available at the same path as the function itself
1983/// (including case). (e.g. for the `dsl::not(x)` call, it expects that there
1984/// is a `dsl::not<X>` type alias available)
1985/// - Assume that methods, unless otherwise annotated, have a type alias
1986/// available as `diesel::dsl::PascalCaseOfMethodName` (e.g. for the
1987/// `x.and(y)` call, it expects that there is a `diesel::dsl::And<X, Y>` type
1988/// alias available)
1989///
1990/// The defaults can be changed by passing the following attributes to the
1991/// macro:
1992/// - `#[auto_type(no_type_alias)]` to disable the generation of the type alias.
1993/// - `#[auto_type(dsl_path = "path::to::dsl")]` to change the path where the
1994/// macro will look for type aliases for methods. This is required if you mix your own
1995/// custom query dsl extensions with diesel types. In that case, you may use this argument to
1996/// reference a module defined like so:
1997/// ```ignore
1998/// mod dsl {
1999/// /// export all of diesel dsl
2000/// pub use diesel::dsl::*;
2001///
2002/// /// Export your extension types here
2003/// pub use crate::your_extension::dsl::YourType;
2004/// }
2005/// ```
2006/// - `#[auto_type(type_case = "snake_case")]` to change the case of the
2007/// method type alias.
2008///
2009/// The `dsl_path` attribute in particular may be used to declare an
2010/// intermediate module where you would define the few additional needed type
2011/// aliases that can't be inferred automatically.
2012///
2013/// ## Annotating types
2014///
2015/// Sometimes the macro can't infer the type of a particular sub-expression. In
2016/// that case, you can annotate the type of the sub-expression:
2017///
2018/// ```rust
2019/// # extern crate diesel;
2020/// # include!("../../diesel/src/doctest_setup.rs");
2021/// # use schema::{users, posts};
2022/// use diesel::dsl;
2023///
2024/// # fn main() {
2025/// # run_test().unwrap();
2026/// # }
2027/// #
2028/// # fn run_test() -> QueryResult<()> {
2029/// # let conn = &mut establish_connection();
2030/// #
2031/// // This will generate a `user_has_post_with_id_greater_than` type alias
2032/// #[dsl::auto_type]
2033/// fn user_has_post_with_id_greater_than(id_greater_than: i32) -> _ {
2034/// dsl::exists(
2035/// posts::table
2036/// .filter(posts::user_id.eq(users::id))
2037/// .filter(posts::id.gt(id_greater_than)),
2038/// )
2039/// }
2040///
2041/// #[dsl::auto_type]
2042/// fn users_with_posts_with_id_greater_than(id_greater_than: i32) -> _ {
2043/// // If we didn't specify the type for this query fragment, the macro would infer it as
2044/// // `user_has_post_with_id_greater_than<i32>`, which would be incorrect because there is
2045/// // no generic parameter.
2046/// let filter: user_has_post_with_id_greater_than =
2047/// user_has_post_with_id_greater_than(id_greater_than);
2048/// // The macro inferring that it has to pass generic parameters is still the convention
2049/// // because it's the most general case, as well as the common case within Diesel itself,
2050/// // and because annotating this way is reasonably simple, while the other way around
2051/// // would be hard.
2052///
2053/// users::table.filter(filter).select(users::name)
2054/// }
2055///
2056/// let users_with_posts: Vec<String> = users_with_posts_with_id_greater_than(2).load(conn)?;
2057///
2058/// assert_eq!(
2059/// &["Tess"] as &[_],
2060/// users_with_posts
2061/// .iter()
2062/// .map(|s| s.as_str())
2063/// .collect::<Vec<_>>()
2064/// );
2065/// # Ok(())
2066/// # }
2067/// ```
2068///
2069#[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")))]
2070#[proc_macro_attribute]
2071pub fn auto_type(
2072 attr: proc_macro::TokenStream,
2073 input: proc_macro::TokenStream,
2074) -> proc_macro::TokenStream {
2075auto_type_inner(attr.into(), input.into()).into()
2076}
20772078fn auto_type_inner(
2079 attr: proc_macro2::TokenStream,
2080 input: proc_macro2::TokenStream,
2081) -> proc_macro2::TokenStream {
2082 dsl_auto_type::auto_type_proc_macro_attribute(
2083attr,
2084input,
2085 dsl_auto_type::DeriveSettings::builder()
2086 .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))
2087 .default_generate_type_alias(true)
2088 .default_method_type_case(AUTO_TYPE_DEFAULT_METHOD_TYPE_CASE)
2089 .default_function_type_case(AUTO_TYPE_DEFAULT_FUNCTION_TYPE_CASE)
2090 .build(),
2091 )
2092}
20932094const AUTO_TYPE_DEFAULT_METHOD_TYPE_CASE: dsl_auto_type::Case = dsl_auto_type::Case::UpperCamel;
2095const AUTO_TYPE_DEFAULT_FUNCTION_TYPE_CASE: dsl_auto_type::Case = dsl_auto_type::Case::DoNotChange;
20962097/// Declare a sql function for use in your code.
2098///
2099/// Diesel only provides support for a very small number of SQL functions.
2100/// This macro enables you to add additional functions from the SQL standard,
2101/// as well as any custom functions your application might have.
2102///
2103/// The syntax for this attribute macro is designed to be applied to `extern "SQL"` blocks
2104/// with function definitions. These function typically use types
2105/// from [`diesel::sql_types`](../diesel/sql_types/index.html) as arguments and return types.
2106/// You can use such definitions to declare bindings to unsupported SQL functions.
2107///
2108/// For each function in this `extern` block the macro will generate two items.
2109/// A function with the name that you've given, and a module with a helper type
2110/// representing the return type of your function. For example, this invocation:
2111///
2112/// ```ignore
2113/// #[declare_sql_function]
2114/// extern "SQL" {
2115/// fn lower(x: Text) -> Text
2116/// }
2117/// ```
2118///
2119/// will generate this code:
2120///
2121/// ```ignore
2122/// pub fn lower<X>(x: X) -> lower<X> {
2123/// ...
2124/// }
2125///
2126/// pub type lower<X> = ...;
2127/// ```
2128///
2129/// Most attributes given to this macro will be put on the generated function
2130/// (including doc comments).
2131///
2132/// If the `generate_return_type_helpers` attribute is specified, an additional module named
2133/// `return_type_helpers` will be generated, containing all return type helpers. For more
2134/// information, refer to the `Helper types generation` section.
2135///
2136/// # Adding Doc Comments
2137///
2138/// ```no_run
2139/// # extern crate diesel;
2140/// # use diesel::*;
2141/// # use diesel::expression::functions::declare_sql_function;
2142/// #
2143/// # table! { crates { id -> Integer, name -> VarChar, } }
2144/// #
2145/// use diesel::sql_types::Text;
2146///
2147/// #[declare_sql_function]
2148/// extern "SQL" {
2149/// /// Represents the `canon_crate_name` SQL function, created in
2150/// /// migration ....
2151/// fn canon_crate_name(a: Text) -> Text;
2152/// }
2153///
2154/// # fn main() {
2155/// # use self::crates::dsl::*;
2156/// let target_name = "diesel";
2157/// crates.filter(canon_crate_name(name).eq(canon_crate_name(target_name)));
2158/// // This will generate the following SQL
2159/// // SELECT * FROM crates WHERE canon_crate_name(crates.name) = canon_crate_name($1)
2160/// # }
2161/// ```
2162///
2163/// # Special Attributes
2164///
2165/// There are a handful of special attributes that Diesel will recognize. They
2166/// are:
2167///
2168/// - `#[aggregate]`
2169/// - Indicates that this is an aggregate function, and that `NonAggregate`
2170/// shouldn't be implemented.
2171/// - `#[sql_name = "name"]`
2172/// - The SQL to be generated is different from the Rust name of the function.
2173/// This can be used to represent functions which can take many argument
2174/// types, or to capitalize function names.
2175/// - `#[variadic(argument_count)]`
2176/// - Indicates that this is a variadic function, where `argument_count` is a
2177/// nonnegative integer representing the number of variadic arguments the
2178/// function accepts.
2179///
2180/// Functions can also be generic. Take the definition of `sum`, for example:
2181///
2182/// ```no_run
2183/// # extern crate diesel;
2184/// # use diesel::*;
2185/// # use diesel::expression::functions::declare_sql_function;
2186/// #
2187/// # table! { crates { id -> Integer, name -> VarChar, } }
2188/// #
2189/// use diesel::sql_types::Foldable;
2190///
2191/// #[declare_sql_function]
2192/// extern "SQL" {
2193/// #[aggregate]
2194/// #[sql_name = "SUM"]
2195/// fn sum<ST: Foldable>(expr: ST) -> ST::Sum;
2196/// }
2197///
2198/// # fn main() {
2199/// # use self::crates::dsl::*;
2200/// crates.select(sum(id));
2201/// # }
2202/// ```
2203///
2204/// # SQL Functions without Arguments
2205///
2206/// A common example is ordering a query using the `RANDOM()` sql function,
2207/// which can be implemented using `define_sql_function!` like this:
2208///
2209/// ```rust
2210/// # extern crate diesel;
2211/// # use diesel::*;
2212/// # use diesel::expression::functions::declare_sql_function;
2213/// #
2214/// # table! { crates { id -> Integer, name -> VarChar, } }
2215/// #
2216/// #[declare_sql_function]
2217/// extern "SQL" {
2218/// fn random() -> Text;
2219/// }
2220///
2221/// # fn main() {
2222/// # use self::crates::dsl::*;
2223/// crates.order(random());
2224/// # }
2225/// ```
2226///
2227/// # Use with SQLite
2228///
2229/// On most backends, the implementation of the function is defined in a
2230/// migration using `CREATE FUNCTION`. On SQLite, the function is implemented in
2231/// Rust instead. You must call `register_impl` (in the generated function's
2232/// `_utils` module) with every connection before you can use the function.
2233///
2234/// Three registration functions are generated in the `_utils` module:
2235///
2236/// - `register_impl`: registers a deterministic function (takes an `Fn`).
2237/// - `register_nondeterministic_impl`: registers a function that may return
2238/// different results for the same inputs, e.g. `random` (takes an `FnMut`).
2239/// - `register_impl_with_behavior`: registers a function with an explicit
2240/// [`SqliteFunctionBehavior`] for full control over how SQLite treats the
2241/// function:
2242///
2243/// - `SqliteFunctionBehavior::DETERMINISTIC`: The function always returns the
2244/// same result given the same inputs. Allows SQLite to optimize queries.
2245/// - `SqliteFunctionBehavior::INNOCUOUS`: The function is safe to call from
2246/// schema objects (views, triggers, etc.) when `set_trusted_schema(false)`.
2247/// - `SqliteFunctionBehavior::DIRECTONLY`: The function cannot be called from
2248/// schema objects. Use for functions with side effects.
2249/// - `SqliteFunctionBehavior::empty()`: Non-deterministic function.
2250///
2251/// To register the implementation automatically for every new SQLite connection
2252/// opened in the process, instead of manually per connection, see
2253/// [`register_auto_extension`](../diesel/sqlite/fn.register_auto_extension.html).
2254///
2255/// These functions will only be generated if the `sqlite` feature is enabled,
2256/// and the function is not generic.
2257/// SQLite doesn't support generic functions and variadic functions.
2258///
2259/// [`SqliteFunctionBehavior`]: ../diesel/sqlite/struct.SqliteFunctionBehavior.html
2260///
2261/// ```rust
2262/// # extern crate diesel;
2263/// # use diesel::*;
2264/// # use diesel::expression::functions::declare_sql_function;
2265/// #
2266/// # #[cfg(feature = "sqlite")]
2267/// # fn main() {
2268/// # run_test().unwrap();
2269/// # }
2270/// #
2271/// # #[cfg(not(feature = "sqlite"))]
2272/// # fn main() {
2273/// # }
2274/// #
2275/// use diesel::sql_types::{Double, Integer};
2276///
2277/// #[declare_sql_function]
2278/// extern "SQL" {
2279/// fn add_mul(x: Integer, y: Integer, z: Double) -> Double;
2280/// }
2281///
2282/// # #[cfg(feature = "sqlite")]
2283/// # fn run_test() -> Result<(), Box<dyn std::error::Error>> {
2284/// let connection = &mut SqliteConnection::establish(":memory:")?;
2285///
2286/// add_mul_utils::register_impl(connection, |x: i32, y: i32, z: f64| (x + y) as f64 * z)?;
2287///
2288/// let result = select(add_mul(1, 2, 1.5)).get_result::<f64>(connection)?;
2289/// assert_eq!(4.5, result);
2290/// # Ok(())
2291/// # }
2292/// ```
2293///
2294/// ## Panics
2295///
2296/// If an implementation of the custom function panics and unwinding is enabled, the panic is
2297/// caught and the function returns to libsqlite with an error. It can't propagate the panics due
2298/// to the FFI boundary.
2299///
2300/// This is the same for [custom aggregate functions](#custom-aggregate-functions).
2301///
2302/// ## Custom Aggregate Functions
2303///
2304/// Custom aggregate functions can be created in SQLite by adding an `#[aggregate]`
2305/// attribute inside `define_sql_function`. `register_impl` (in the generated function's `_utils`
2306/// module) needs to be called with a type implementing the
2307/// [SqliteAggregateFunction](../diesel/sqlite/trait.SqliteAggregateFunction.html)
2308/// trait as a type parameter as shown in the examples below.
2309///
2310/// ```rust
2311/// # extern crate diesel;
2312/// # use diesel::*;
2313/// # use diesel::expression::functions::declare_sql_function;
2314/// #
2315/// # #[cfg(feature = "sqlite")]
2316/// # fn main() {
2317/// # run().unwrap();
2318/// # }
2319/// #
2320/// # #[cfg(not(feature = "sqlite"))]
2321/// # fn main() {
2322/// # }
2323/// use diesel::sql_types::Integer;
2324/// # #[cfg(feature = "sqlite")]
2325/// use diesel::sqlite::SqliteAggregateFunction;
2326///
2327/// #[declare_sql_function]
2328/// extern "SQL" {
2329/// #[aggregate]
2330/// fn my_sum(x: Integer) -> Integer;
2331/// }
2332///
2333/// #[derive(Default)]
2334/// struct MySum { sum: i32 }
2335///
2336/// # #[cfg(feature = "sqlite")]
2337/// impl SqliteAggregateFunction<i32> for MySum {
2338/// type Output = i32;
2339///
2340/// fn step(&mut self, expr: i32) {
2341/// self.sum += expr;
2342/// }
2343///
2344/// fn finalize(aggregator: Option<Self>) -> Self::Output {
2345/// aggregator.map(|a| a.sum).unwrap_or_default()
2346/// }
2347/// }
2348/// # table! {
2349/// # players {
2350/// # id -> Integer,
2351/// # score -> Integer,
2352/// # }
2353/// # }
2354///
2355/// # #[cfg(feature = "sqlite")]
2356/// fn run() -> Result<(), Box<dyn (::std::error::Error)>> {
2357/// # use self::players::dsl::*;
2358/// let connection = &mut SqliteConnection::establish(":memory:")?;
2359/// # diesel::sql_query("create table players (id integer primary key autoincrement, score integer)")
2360/// # .execute(connection)
2361/// # .unwrap();
2362/// # diesel::sql_query("insert into players (score) values (10), (20), (30)")
2363/// # .execute(connection)
2364/// # .unwrap();
2365///
2366/// my_sum_utils::register_impl::<MySum, _>(connection)?;
2367///
2368/// let total_score = players.select(my_sum(score))
2369/// .get_result::<i32>(connection)?;
2370///
2371/// println!("The total score of all the players is: {}", total_score);
2372///
2373/// # assert_eq!(60, total_score);
2374/// Ok(())
2375/// }
2376/// ```
2377///
2378/// With multiple function arguments, the arguments are passed as a tuple to `SqliteAggregateFunction`
2379///
2380/// ```rust
2381/// # extern crate diesel;
2382/// # use diesel::*;
2383/// # use diesel::expression::functions::declare_sql_function;
2384/// #
2385/// # #[cfg(feature = "sqlite")]
2386/// # fn main() {
2387/// # run().unwrap();
2388/// # }
2389/// #
2390/// # #[cfg(not(feature = "sqlite"))]
2391/// # fn main() {
2392/// # }
2393/// use diesel::sql_types::{Float, Nullable};
2394/// # #[cfg(feature = "sqlite")]
2395/// use diesel::sqlite::SqliteAggregateFunction;
2396///
2397/// #[declare_sql_function]
2398/// extern "SQL" {
2399/// #[aggregate]
2400/// fn range_max(x0: Float, x1: Float) -> Nullable<Float>;
2401/// }
2402///
2403/// #[derive(Default)]
2404/// struct RangeMax<T> { max_value: Option<T> }
2405///
2406/// # #[cfg(feature = "sqlite")]
2407/// impl<T: Default + PartialOrd + Copy + Clone> SqliteAggregateFunction<(T, T)> for RangeMax<T> {
2408/// type Output = Option<T>;
2409///
2410/// fn step(&mut self, (x0, x1): (T, T)) {
2411/// # let max = if x0 >= x1 {
2412/// # x0
2413/// # } else {
2414/// # x1
2415/// # };
2416/// #
2417/// # self.max_value = match self.max_value {
2418/// # Some(current_max_value) if max > current_max_value => Some(max),
2419/// # None => Some(max),
2420/// # _ => self.max_value,
2421/// # };
2422/// // Compare self.max_value to x0 and x1
2423/// }
2424///
2425/// fn finalize(aggregator: Option<Self>) -> Self::Output {
2426/// aggregator?.max_value
2427/// }
2428/// }
2429/// # table! {
2430/// # student_avgs {
2431/// # id -> Integer,
2432/// # s1_avg -> Float,
2433/// # s2_avg -> Float,
2434/// # }
2435/// # }
2436///
2437/// # #[cfg(feature = "sqlite")]
2438/// fn run() -> Result<(), Box<dyn (::std::error::Error)>> {
2439/// # use self::student_avgs::dsl::*;
2440/// let connection = &mut SqliteConnection::establish(":memory:")?;
2441/// # diesel::sql_query("create table student_avgs (id integer primary key autoincrement, s1_avg float, s2_avg float)")
2442/// # .execute(connection)
2443/// # .unwrap();
2444/// # diesel::sql_query("insert into student_avgs (s1_avg, s2_avg) values (85.5, 90), (79.8, 80.1)")
2445/// # .execute(connection)
2446/// # .unwrap();
2447///
2448/// range_max_utils::register_impl::<RangeMax<f32>, _, _>(connection)?;
2449///
2450/// let result = student_avgs.select(range_max(s1_avg, s2_avg))
2451/// .get_result::<Option<f32>>(connection)?;
2452///
2453/// if let Some(max_semester_avg) = result {
2454/// println!("The largest semester average is: {}", max_semester_avg);
2455/// }
2456///
2457/// # assert_eq!(Some(90f32), result);
2458/// Ok(())
2459/// }
2460/// ```
2461///
2462/// ## Variadic functions
2463///
2464/// Since Rust does not support variadic functions, the SQL variadic functions are
2465/// handled differently. For example, consider the variadic function `json_array`.
2466/// To add support for it, you can use the `#[variadic]` attribute:
2467///
2468/// ```rust
2469/// # extern crate diesel;
2470/// # use diesel::sql_types::*;
2471/// # use diesel::expression::functions::declare_sql_function;
2472/// #
2473/// # fn main() {
2474/// # // Without the main function this code will be wrapped in the auto-generated
2475/// # // `main` function and `#[declare_sql_function]` won't work properly.
2476/// # }
2477///
2478/// # #[cfg(feature = "sqlite")]
2479/// #[declare_sql_function]
2480/// extern "SQL" {
2481/// #[variadic(1)]
2482/// fn json_array<V: SqlType + SingleValue>(value: V) -> Json;
2483/// }
2484/// ```
2485///
2486/// This will generate multiple implementations, one for each possible argument
2487/// count (up to a predefined limit). For instance, it will generate functions like
2488/// `json_array_0`, `json_array_1`, and so on, which are equivalent to:
2489///
2490/// ```rust
2491/// # extern crate diesel;
2492/// # use diesel::sql_types::*;
2493/// # use diesel::expression::functions::declare_sql_function;
2494/// #
2495/// # fn main() {
2496/// # // Without the main function this code will be wrapped in the auto-generated
2497/// # // `main` function and `#[declare_sql_function]` won't work properly.
2498/// # }
2499///
2500/// # #[cfg(feature = "sqlite")]
2501/// #[declare_sql_function]
2502/// extern "SQL" {
2503/// #[sql_name = "json_array"]
2504/// fn json_array_0() -> Json;
2505///
2506/// #[sql_name = "json_array"]
2507/// fn json_array_1<V1: SqlType + SingleValue>(value_1: V1) -> Json;
2508///
2509/// #[sql_name = "json_array"]
2510/// fn json_array_2<V1: SqlType + SingleValue, V2: SqlType + SingleValue>(
2511/// value_1: V1,
2512/// value_2: V2,
2513/// ) -> Json;
2514///
2515/// // ...
2516/// }
2517/// ```
2518///
2519/// The argument to the `variadic` attribute specifies the number of trailing arguments to repeat.
2520/// For example, if you have a variadic function `foo(a: A, b: B, c: C)` and want `b: B` and `c: C`
2521/// to repeat, you would write:
2522///
2523/// ```ignore
2524/// #[declare_sql_function]
2525/// extern "SQL" {
2526/// #[variadic(2)]
2527/// fn foo<A, B, C>(a: A, b: B, c: C) -> Text;
2528/// }
2529/// ```
2530///
2531/// Which will be equivalent to
2532///
2533/// ```ignore
2534/// #[declare_sql_function]
2535/// extern "SQL" {
2536/// #[sql_name = "foo"]
2537/// fn foo_0<A>(a: A) -> Text;
2538///
2539/// #[sql_name = "foo"]
2540/// fn foo_1<A, B1, C1>(a: A, b_1: B1, c_1: C1) -> Text;
2541///
2542/// #[sql_name = "foo"]
2543/// fn foo_2<A, B1, C1, B2, C2>(a: A, b_1: B1, c_1: C1, b_2: B2, c_2: C2) -> Text;
2544///
2545/// ...
2546/// }
2547/// ```
2548///
2549/// Optionally, a second named boolean argument `skip_zero_argument_variant` can be provided to
2550/// control whether the 0-argument variant is generated. By default, (omitted or `false`),
2551/// the 0-argument variant is included. Set it to `true` to skip generating the 0-argument
2552/// variant for functions that require at least one variadic argument. If you specify the boolean
2553/// argument, the first argument has to be named `last_arguments` for clarity.
2554///
2555/// Example:
2556///
2557/// ```ignore
2558/// #[declare_sql_function]
2559/// extern "SQL" {
2560/// #[variadic(last_arguments = 2, skip_zero_argument_variant = true)]
2561/// fn foo<A, B, C>(a: A, b: B, c: C) -> Text;
2562/// }
2563/// ```
2564///
2565/// Which will be equivalent to
2566///
2567/// ```ignore
2568/// #[declare_sql_function]
2569/// extern "SQL" {
2570/// #[sql_name = "foo"]
2571/// fn foo_1<A, B1, C1>(a: A, b_1: B1, c_1: C1) -> Text;
2572///
2573/// #[sql_name = "foo"]
2574/// fn foo_2<A, B1, C1, B2, C2>(a: A, b_1: B1, c_1: C1, b_2: B2, c_2: C2) -> Text;
2575///
2576/// ...
2577/// }
2578/// ```
2579///
2580/// ### Controlling the generation of variadic function variants
2581///
2582/// By default, only variants with 0, 1, and 2 repetitions of variadic arguments are generated. To
2583/// generate more variants, set the `DIESEL_VARIADIC_FUNCTION_ARGS` environment variable to the
2584/// desired number of variants.
2585///
2586/// • The boolean only affects whether the 0 variant is generated; the total number of variants
2587/// (e.g., up to N) still follows DIESEL_VARIADIC_FUNCTION_ARGS or the default.
2588///
2589/// For a greater convenience this environment variable can also be set in a `.cargo/config.toml`
2590/// file as described in the [cargo documentation](https://doc.rust-lang.org/cargo/reference/config.html#env).
2591///
2592/// ## Helper types generation
2593///
2594/// When the `generate_return_type_helpers` attribute is specified, for each function defined inside
2595/// an `extern "SQL"` block, a return type alias with the same name as the function is created and
2596/// placed in the `return_type_helpers` module:
2597///
2598/// ```rust
2599/// # extern crate diesel;
2600/// # use diesel::expression::functions::declare_sql_function;
2601/// # use diesel::sql_types::*;
2602/// #
2603/// # fn main() {
2604/// # // Without the main function this code will be wrapped in the auto-generated
2605/// # // `main` function and `#[declare_sql_function]` won't work properly.
2606/// # }
2607/// #
2608/// #[declare_sql_function(generate_return_type_helpers = true)]
2609/// extern "SQL" {
2610/// fn f<V: SqlType + SingleValue>(arg: V);
2611/// }
2612///
2613/// type return_type_helper_for_f<V> = return_type_helpers::f<V>;
2614/// ```
2615///
2616/// If you want to skip generating a type alias for a specific function, you can use the
2617/// `#[skip_return_type_helper]` attribute, like this:
2618///
2619/// ```compile_fail
2620/// # extern crate diesel;
2621/// # use diesel::expression::functions::declare_sql_function;
2622/// #
2623/// # fn main() {
2624/// # // Without the main function this code will be wrapped in the auto-generated
2625/// # // `main` function and `#[declare_sql_function]` won't work properly.
2626/// # }
2627/// #
2628/// #[declare_sql_function(generate_return_type_helpers = true)]
2629/// extern "SQL" {
2630/// #[skip_return_type_helper]
2631/// fn f();
2632/// }
2633///
2634/// # type skipped_type = return_type_helpers::f;
2635/// ```
2636///
2637#[cfg_attr(diesel_docsrs, doc = "\n# Expanded Code\n\n<details>\n<summary> Expanded Code </summary>\n\n\n\n#### Input\n\n```rust,ignore\n#[diesel::declare_sql_function]\nextern \"SQL\" {\n fn lower(input: Text) -> Text;\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\n#[allow(non_camel_case_types)]\npub fn lower<input>(input: input) -> lower<input>\nwhere\n input: diesel::expression::AsExpression<Text>,\n{\n lower_utils::lower {\n input: input.as_expression(),\n }\n}\n#[allow(non_camel_case_types, non_snake_case)]\n///The return type of [`lower()`](fn@lower)\npub type lower<input> = lower_utils::lower<\n <input as diesel::expression::AsExpression<Text>>::Expression,\n>;\n#[doc(hidden)]\n#[allow(non_camel_case_types, non_snake_case, unused_imports)]\npub(crate) mod lower_utils {\n use diesel::{self, QueryResult};\n use diesel::expression::{\n AsExpression, Expression, SelectableExpression, AppearsOnTable, ValidGrouping,\n };\n use diesel::query_builder::{QueryFragment, AstPass};\n use diesel::sql_types::*;\n use diesel::internal::sql_functions::*;\n use super::*;\n #[derive(Debug, Clone, Copy, diesel::query_builder::QueryId)]\n #[derive(diesel::sql_types::DieselNumericOps)]\n pub struct lower<input> {\n pub(super) input: input,\n }\n ///The return type of [`lower()`](fn@lower)\n pub type HelperType<input> = lower<<input as AsExpression<Text>>::Expression>;\n impl<input> Expression for lower<input>\n where\n (input): Expression,\n {\n type SqlType = Text;\n }\n impl<input, __DieselInternal> SelectableExpression<__DieselInternal> for lower<input>\n where\n input: SelectableExpression<__DieselInternal>,\n Self: AppearsOnTable<__DieselInternal>,\n {}\n impl<input, __DieselInternal> AppearsOnTable<__DieselInternal> for lower<input>\n where\n input: AppearsOnTable<__DieselInternal>,\n Self: Expression,\n {}\n impl<input, __DieselInternal> FunctionFragment<__DieselInternal> for lower<input>\n where\n __DieselInternal: diesel::backend::Backend,\n input: QueryFragment<__DieselInternal>,\n {\n const FUNCTION_NAME: &\'static str = \"lower\";\n #[allow(unused_assignments)]\n fn walk_arguments<\'__b>(\n &\'__b self,\n mut out: AstPass<\'_, \'__b, __DieselInternal>,\n ) -> QueryResult<()> {\n let mut needs_comma = false;\n if !self.input.is_noop(out.backend())? {\n if needs_comma {\n out.push_sql(\", \");\n }\n self.input.walk_ast(out.reborrow())?;\n needs_comma = true;\n }\n Ok(())\n }\n }\n impl<input, __DieselInternal> QueryFragment<__DieselInternal> for lower<input>\n where\n __DieselInternal: diesel::backend::Backend,\n input: QueryFragment<__DieselInternal>,\n {\n fn walk_ast<\'__b>(\n &\'__b self,\n mut out: AstPass<\'_, \'__b, __DieselInternal>,\n ) -> QueryResult<()> {\n out.push_sql(<Self as FunctionFragment<__DieselInternal>>::FUNCTION_NAME);\n out.push_sql(\"(\");\n self.walk_arguments(out.reborrow())?;\n out.push_sql(\")\");\n Ok(())\n }\n }\n #[derive(ValidGrouping)]\n pub struct __Derived<input>(input);\n impl<input, __DieselInternal> ValidGrouping<__DieselInternal> for lower<input>\n where\n __Derived<input>: ValidGrouping<__DieselInternal>,\n {\n type IsAggregate = <__Derived<\n input,\n > as ValidGrouping<__DieselInternal>>::IsAggregate;\n }\n #[allow(dead_code)]\n /// Registers an implementation for this function on the given connection.\n ///\n /// This function must be called for every `SqliteConnection` before\n /// this SQL function can be used on SQLite. The implementation must be\n /// deterministic (returns the same result given the same arguments). If\n /// the function is nondeterministic, call\n /// [`register_nondeterministic_impl`](self::register_nondeterministic_impl)\n /// instead, or [`register_impl_with_behavior`](self::register_impl_with_behavior)\n /// for full control over the SQLite behavior flags.\n pub fn register_impl<F, Ret, input>(\n conn: &mut diesel::sqlite::SqliteConnection,\n f: F,\n ) -> diesel::result::QueryResult<()>\n where\n F: Fn(input) -> Ret + ::core::panic::UnwindSafe + Send + \'static,\n (\n input,\n ): diesel::deserialize::FromSqlRow<(Text,), diesel::sqlite::Sqlite>\n + diesel::deserialize::StaticallySizedRow<(Text,), diesel::sqlite::Sqlite>,\n Ret: diesel::serialize::ToSql<Text, diesel::sqlite::Sqlite>,\n {\n register_impl_with_behavior(\n conn,\n diesel::sqlite::SqliteFunctionBehavior::DETERMINISTIC,\n f,\n )\n }\n #[allow(dead_code)]\n /// Registers a nondeterministic implementation for this function on the\n /// given connection.\n ///\n /// This function must be called for every `SqliteConnection` before\n /// this SQL function can be used on SQLite.\n /// `register_nondeterministic_impl` should only be used if your\n /// function can return different results with the same arguments (e.g.\n /// `random`). If your function is deterministic, you should call\n /// [`register_impl`](self::register_impl) instead. For full control over\n /// the SQLite behavior flags, use\n /// [`register_impl_with_behavior`](self::register_impl_with_behavior).\n pub fn register_nondeterministic_impl<F, Ret, input>(\n conn: &mut diesel::sqlite::SqliteConnection,\n f: F,\n ) -> diesel::result::QueryResult<()>\n where\n F: FnMut(input) -> Ret + ::core::panic::UnwindSafe + Send + \'static,\n (\n input,\n ): diesel::deserialize::FromSqlRow<(Text,), diesel::sqlite::Sqlite>\n + diesel::deserialize::StaticallySizedRow<(Text,), diesel::sqlite::Sqlite>,\n Ret: diesel::serialize::ToSql<Text, diesel::sqlite::Sqlite>,\n {\n register_impl_with_behavior(\n conn,\n diesel::sqlite::SqliteFunctionBehavior::empty(),\n f,\n )\n }\n #[allow(dead_code)]\n /// Registers an implementation for this function on the given connection,\n /// with explicit control over the SQLite behavior flags.\n ///\n /// This function must be called for every `SqliteConnection` before\n /// this SQL function can be used on SQLite. Prefer\n /// [`register_impl`](self::register_impl) (deterministic) or\n /// [`register_nondeterministic_impl`](self::register_nondeterministic_impl)\n /// unless you need to set behavior flags explicitly. See\n /// [`SqliteFunctionBehavior`] for the available flags.\n pub fn register_impl_with_behavior<F, Ret, input>(\n conn: &mut diesel::sqlite::SqliteConnection,\n behavior: diesel::sqlite::SqliteFunctionBehavior,\n mut f: F,\n ) -> diesel::result::QueryResult<()>\n where\n F: FnMut(input) -> Ret + ::core::panic::UnwindSafe + Send + \'static,\n (\n input,\n ): diesel::deserialize::FromSqlRow<(Text,), diesel::sqlite::Sqlite>\n + diesel::deserialize::StaticallySizedRow<(Text,), diesel::sqlite::Sqlite>,\n Ret: diesel::serialize::ToSql<Text, diesel::sqlite::Sqlite>,\n {\n conn.register_sql_function::<\n (Text,),\n Text,\n _,\n _,\n _,\n >(\"lower\", behavior, move |(input,)| f(input))\n }\n}\n```\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/declare_sql_function.md")))]
2638#[proc_macro_attribute]
2639pub fn declare_sql_function(
2640 attr: proc_macro::TokenStream,
2641 input: proc_macro::TokenStream,
2642) -> proc_macro::TokenStream {
2643declare_sql_function_inner(attr.into(), input.into()).into()
2644}
26452646fn declare_sql_function_inner(
2647 attr: proc_macro2::TokenStream,
2648 input: proc_macro2::TokenStream,
2649) -> proc_macro2::TokenStream {
2650let attr = crate::sql_function::DeclareSqlFunctionArgs::parse_from_macro_input(attr);
26512652let result = syn::parse2::<ExternSqlBlock>(input.clone()).map(|res| {
2653 sql_function::expand(
2654res.function_decls,
2655false,
2656attr.as_ref()
2657 .map(|attr| attr.generate_return_type_helpers)
2658 .unwrap_or(true),
2659 )
2660 });
26612662let mut output = match result {
2663Ok(token_stream) => token_stream,
2664Err(e) => {
2665let mut output = input;
2666output.extend(e.into_compile_error());
2667output2668 }
2669 };
2670if let Err(e) = attr {
2671output.extend(e.into_compile_error());
2672 }
2673output2674}
26752676/// Implements `HasQuery`
2677///
2678/// This derive implements a common entry point for building queries
2679/// based on a model like Rust struct. It enables you to always have a certain base query
2680/// associated with a given type. This derive is designed to easily couple your query with
2681/// your Rust type. It's important to note that for Diesel this mapping happens always
2682/// on query and not on table level, which enables you to write several queries related to the
2683/// same table, while a single query could be related to zero or multiple tables.
2684///
2685/// By default this derive will use the equivalent of `SELECT your, fields FROM your_types`
2686/// which implies that it needs to know the corresponding table type. As with any other
2687/// diesel derive it uses the `snake_case` type name with an added `s` if no other
2688/// name is specified.
2689/// It is possible to change this default by using `#[diesel(table_name = something)]`.
2690///
2691/// If you would like to use a more complex query as base query you can overwrite the standard
2692/// query by using the `#[diesel(base_query = your_type::table.filter(your_type::is_admin.eq(true)))]`
2693/// attribute to overwrite the automatically generated base query. This derive will still apply
2694/// a select clause that matches your type. By default it also tries to infer the correct
2695/// type of that query. This type can be overwritten by using the `#[diesel(base_query_type)]`
2696/// attribute.
2697///
2698/// This derive will internally implement the following traits:
2699///
2700/// * `HasQuery`
2701/// * `Selectable` (for building the selection)
2702/// * `Queryable` (for allowing to load results from the database)
2703///
2704/// For the later two traits see their corresponding derives for supported options:
2705///
2706/// * [Queryable]
2707/// * [Selectable]
2708///
2709/// Any option documented there is also supported by this derive
2710///
2711/// In contrast to `#[derive(Selectable)]` this derive automatically enables
2712/// `#[diesel(check_for_backend(_))]` with all backends enabled at compile time
2713/// if no explicit `#[diesel(check_for_backend(_))]` attribute is given. This
2714/// will lead to better error messages. You
2715/// can use `#[diesel(check_for_backend(disable = true))]` to disable this behaviour
2716/// for that particular instance.
2717///
2718/// # Attributes
2719///
2720/// ## Optional Type attributes
2721///
2722/// * `#[diesel(base_query = _)]` specifies a base query associated with this type.
2723/// It may be used in conjunction with `base_query_type` (described below)
2724/// * `#[diesel(base_query_type = _)]` the Rust type described by the `base_query`
2725/// attribute. Usually diesel is able to infer this type, but for complex types such an
2726/// annotation might be required. This will be required if a custom
2727/// function call that doesn't have the corresponding associated type defined at the same path
2728/// appears in your query.
2729/// * `#[diesel(table_name = path::to::table)]`, specifies a path to the table for which the
2730/// current type is selectable. The path is relative to the current module.
2731/// If this attribute is not used, the type name converted to
2732/// `snake_case` with an added `s` is used as table name.
2733/// * `#[diesel(check_for_backend(diesel::pg::Pg, diesel::mysql::Mysql))]`, instructs
2734/// the derive to generate additional code to identify potential type mismatches.
2735/// It accepts a list of backend types to check the types against. If this option
2736/// is not set this derive automatically uses all backends enabled at compile time
2737/// for this check. You can disable this behaviour via `#[diesel(check_for_backend(disable = true))]`
2738///
2739/// ## Optional Field Attributes
2740///
2741/// * `#[diesel(column_name = some_column)]`, overrides the column name for
2742/// a given field. If not set, the name of the field is used as column
2743/// name.
2744/// * `#[diesel(embed)]`, specifies that the current field maps not only
2745/// a single database column, but is a type that implements
2746/// `Selectable` on its own
2747/// * `#[diesel(select_expression = some_custom_select_expression)]`, overrides
2748/// the entire select expression for the given field. It may be used to select with
2749/// custom tuples, or specify `select_expression = my_table::some_field.is_not_null()`,
2750/// or separate tables...
2751/// It may be used in conjunction with `select_expression_type` (described below)
2752/// * `#[diesel(select_expression_type = the_custom_select_expression_type]`, should be used
2753/// in conjunction with `select_expression` (described above) if the type is too complex
2754/// for diesel to infer it automatically. This will be required if select_expression is a custom
2755/// function call that doesn't have the corresponding associated type defined at the same path.
2756/// Example use (this would actually be inferred):
2757/// `#[diesel(select_expression_type = dsl::IsNotNull<my_table::some_field>)]`
2758/// * `#[diesel(deserialize_as = Type)]`, instead of deserializing directly
2759/// into the field type, the implementation will deserialize into `Type`.
2760/// Then `Type` is converted via
2761/// [`.try_into`](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into)
2762/// into the field type. By default, this derive will deserialize directly into the field type
2763///
2764/// # Examples
2765///
2766/// ## Basic usage
2767///
2768///
2769/// ```rust
2770/// # extern crate diesel;
2771/// # extern crate dotenvy;
2772/// # include!("../../diesel/src/doctest_setup.rs");
2773/// #
2774///
2775/// // it's important to have the right table in scope
2776/// use schema::users;
2777///
2778/// #[derive(HasQuery, PartialEq, Debug)]
2779/// struct User {
2780/// id: i32,
2781/// name: String,
2782/// }
2783///
2784/// # fn main() -> QueryResult<()> {
2785/// #
2786/// # let connection = &mut establish_connection();
2787/// // equivalent to `users::table.select(User::as_select()).first(connection)?;
2788/// let first_user = User::query().first(connection)?;
2789/// let expected = User { id: 1, name: "Sean".into() };
2790/// assert_eq!(expected, first_user);
2791///
2792/// # Ok(())
2793/// # }
2794/// ```
2795///
2796/// ## Custom base query
2797///
2798/// ```rust
2799/// # extern crate diesel;
2800/// # extern crate dotenvy;
2801/// # include!("../../diesel/src/doctest_setup.rs");
2802/// #
2803///
2804/// // it's important to have the right table in scope
2805/// use schema::{users, posts};
2806///
2807/// #[derive(HasQuery, PartialEq, Debug)]
2808/// struct Post {
2809/// id: i32,
2810/// user_id: i32,
2811/// title: String,
2812/// }
2813///
2814/// #[derive(HasQuery, PartialEq, Debug)]
2815/// #[diesel(base_query = users::table.inner_join(posts::table).order_by(users::id))]
2816/// // that's required to let the derive understand
2817/// // from which table the columns should be selected
2818/// #[diesel(table_name = users)]
2819/// struct UserWithPost {
2820/// id: i32,
2821/// name: String,
2822/// #[diesel(embed)]
2823/// post: Post,
2824/// }
2825///
2826/// # fn main() -> QueryResult<()> {
2827/// #
2828/// # let connection = &mut establish_connection();
2829/// // equivalent to users::table.inner_join(posts::table)
2830/// // .order_by(users::id)
2831/// // .select(UserWithPost::as_select()).first(connection)?;
2832/// let first_user = UserWithPost::query().first(connection)?;
2833/// let expected = UserWithPost { id: 1, name: "Sean".into(), post: Post {id: 1, user_id: 1, title: "My first post".into() } };
2834/// assert_eq!(expected, first_user);
2835///
2836/// # Ok(())
2837/// # }
2838/// ```
2839///
2840#[cfg_attr(diesel_docsrs, doc = "\n# Expanded Code\n\n<details>\n<summary> Expanded Code </summary>\n\n\n### SQLite\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(HasQuery)]\nstruct User {\n id: i32,\n name: String,\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n use diesel;\n impl<__DB: diesel::backend::Backend> diesel::HasQuery<__DB> for User {\n type BaseQuery = <users::table as diesel::query_builder::AsQuery>::Query;\n fn base_query() -> Self::BaseQuery {\n diesel::query_builder::AsQuery::as_query(users::table)\n }\n }\n};\nconst _: () = {\n use diesel;\n use diesel::expression::Selectable;\n impl<__DB: diesel::backend::Backend> Selectable<__DB> for User {\n type SelectExpression = (users::r#id, users::r#name);\n fn construct_selection() -> Self::SelectExpression {\n (users::r#id, users::r#name)\n }\n }\n\n fn _check_field_compatibility_sqlite()\n where\n i32: diesel::deserialize::FromSqlRow<\n diesel::dsl::SqlTypeOf<users::r#id>,\n diesel::sqlite::Sqlite,\n >,\n String: diesel::deserialize::FromSqlRow<\n diesel::dsl::SqlTypeOf<users::r#name>,\n diesel::sqlite::Sqlite,\n >,\n {}\n\n};\nconst _: () = {\n use diesel;\n use diesel::row::{Row as _, Field as _};\n impl<\n __DB: diesel::backend::Backend,\n __ST0,\n __ST1,\n > diesel::deserialize::Queryable<(__ST0, __ST1), __DB> for User\n where\n (i32, String): diesel::deserialize::FromStaticSqlRow<(__ST0, __ST1), __DB>,\n {\n type Row = (i32, String);\n fn build(row: (i32, String)) -> diesel::deserialize::Result<Self> {\n use std::convert::TryInto;\n diesel::deserialize::Result::Ok(Self {\n id: row.0.try_into()?,\n name: row.1.try_into()?,\n })\n }\n }\n};\n```\n\n\n### PostgreSQL\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(HasQuery)]\nstruct User {\n id: i32,\n name: String,\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n use diesel;\n impl<__DB: diesel::backend::Backend> diesel::HasQuery<__DB> for User {\n type BaseQuery = <users::table as diesel::query_builder::AsQuery>::Query;\n fn base_query() -> Self::BaseQuery {\n diesel::query_builder::AsQuery::as_query(users::table)\n }\n }\n};\nconst _: () = {\n use diesel;\n use diesel::expression::Selectable;\n impl<__DB: diesel::backend::Backend> Selectable<__DB> for User {\n type SelectExpression = (users::r#id, users::r#name);\n fn construct_selection() -> Self::SelectExpression {\n (users::r#id, users::r#name)\n }\n }\n fn _check_field_compatibility_pg()\n where\n i32: diesel::deserialize::FromSqlRow<\n diesel::dsl::SqlTypeOf<users::r#id>,\n diesel::pg::Pg,\n >,\n String: diesel::deserialize::FromSqlRow<\n diesel::dsl::SqlTypeOf<users::r#name>,\n diesel::pg::Pg,\n >,\n {}\n\n\n};\nconst _: () = {\n use diesel;\n use diesel::row::{Row as _, Field as _};\n impl<\n __DB: diesel::backend::Backend,\n __ST0,\n __ST1,\n > diesel::deserialize::Queryable<(__ST0, __ST1), __DB> for User\n where\n (i32, String): diesel::deserialize::FromStaticSqlRow<(__ST0, __ST1), __DB>,\n {\n type Row = (i32, String);\n fn build(row: (i32, String)) -> diesel::deserialize::Result<Self> {\n use std::convert::TryInto;\n diesel::deserialize::Result::Ok(Self {\n id: row.0.try_into()?,\n name: row.1.try_into()?,\n })\n }\n }\n};\n```\n\n\n### MySQL\n\n\n\n#### Input\n\n```rust,ignore\n#[derive(HasQuery)]\nstruct User {\n id: i32,\n name: String,\n}\n```\n\n#### Expanded Code\n\n<div class=\"warning\">Expanded code might use diesel internal API\'s and is only shown for educational purpose</div>\n\nThe macro expands the input to the following Rust code:\n\n\n```rust,ignore\nconst _: () = {\n use diesel;\n impl<__DB: diesel::backend::Backend> diesel::HasQuery<__DB> for User {\n type BaseQuery = <users::table as diesel::query_builder::AsQuery>::Query;\n fn base_query() -> Self::BaseQuery {\n diesel::query_builder::AsQuery::as_query(users::table)\n }\n }\n};\nconst _: () = {\n use diesel;\n use diesel::expression::Selectable;\n impl<__DB: diesel::backend::Backend> Selectable<__DB> for User {\n type SelectExpression = (users::r#id, users::r#name);\n fn construct_selection() -> Self::SelectExpression {\n (users::r#id, users::r#name)\n }\n }\n\n\n fn _check_field_compatibility_mysql()\n where\n i32: diesel::deserialize::FromSqlRow<\n diesel::dsl::SqlTypeOf<users::r#id>,\n diesel::mysql::Mysql,\n >,\n String: diesel::deserialize::FromSqlRow<\n diesel::dsl::SqlTypeOf<users::r#name>,\n diesel::mysql::Mysql,\n >,\n {}\n};\nconst _: () = {\n use diesel;\n use diesel::row::{Row as _, Field as _};\n impl<\n __DB: diesel::backend::Backend,\n __ST0,\n __ST1,\n > diesel::deserialize::Queryable<(__ST0, __ST1), __DB> for User\n where\n (i32, String): diesel::deserialize::FromStaticSqlRow<(__ST0, __ST1), __DB>,\n {\n type Row = (i32, String);\n fn build(row: (i32, String)) -> diesel::deserialize::Result<Self> {\n use std::convert::TryInto;\n diesel::deserialize::Result::Ok(Self {\n id: row.0.try_into()?,\n name: row.1.try_into()?,\n })\n }\n }\n};\n```\n\n\n\n</details>\n"include_str!(concat!(env!("OUT_DIR"), "/has_query.md")))]
2841#[proc_macro_derive(HasQuery, attributes(diesel))]
2842pub fn derive_has_query(input: TokenStream) -> TokenStream {
2843derive_has_query_inner(input.into()).into()
2844}
28452846fn derive_has_query_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
2847 syn::parse2(input)
2848 .and_then(has_query::derive)
2849 .unwrap_or_else(syn::Error::into_compile_error)
2850}
28512852/// Implements `FromSql` and `ToSql` for enum types
2853///
2854/// This derive enables an enum (with unit-variants only) to be serialized to the database as
2855/// a byte-string and deserialized from the same representation from the database.
2856///
2857/// This derive generates `FromSql` and `ToSql` implementations for all backends based on the provided
2858/// SQL type. It currently supports the following SQL types:
2859///
2860/// * `diesel::sql_types::Integer`, `diesel::sql_types::SmallInt`, `diesel::sql_types::BigInt`, `diesel::sql_types::TinyInt`
2861/// and their unsigned variants for all backends to (de)serialize a Rust enum as integer values.
2862/// This requires annotating every variant with an explicit discriminant value
2863/// * `diesel::sql_types::Text` for all backend to (de)serialize a Rust enum as text values.
2864/// * Any custom SQL type marked with `#[diesel(enum_type)]`
2865///
2866/// Additional it internally generates the same implementations as `#[derive(FromSqlRow)]`
2867/// and `#[derive(AsExpression)]`
2868///
2869/// # Attributes
2870///
2871/// ## Required container attributes
2872///
2873/// * `#[diesel(sql_type = path::to::MyEnumType)]`, specifies the database type this enum represents, can appear several times
2874///
2875/// ## Optional container attributes
2876///
2877/// * `#[diesel(rename_all = "case")]` to rename all enum variants according the provided scheme. The following schemes are supported:
2878/// + `"lowercase"` to rename all variants to lower-case
2879/// + `"UPPERCASE"` to rename all variants to upper-case
2880/// + `"PascalCase"` to keep the provided Rust variant name
2881/// + `"camelCase"` to rename all variants to camel-case
2882/// + `"snake_case"` to rename all variants to snake-case
2883/// + `"SCREAMING_SNAKE_CASE"` to rename all variants to screaming snake case
2884/// + `"kebab-case"` to rename all variants to kebab-case
2885/// + `"SCREAMING-KEBAB-CASE"` to rename all variants to screaming kebab case
2886///
2887/// ## Optional variant attributes
2888///
2889/// * `#[diesel(rename = "newSqlName")]` to provide an explicit name for the SQL side variant
2890///
2891/// # Examples
2892///
2893/// ## Usage with database side Enums
2894///
2895/// ```rust
2896/// # extern crate diesel;
2897/// # extern crate dotenvy;
2898/// # include!("../../diesel/src/doctest_setup.rs");
2899/// #
2900/// #[derive(Debug, diesel::types::Enum, PartialEq)]
2901/// #[diesel(sql_type = schema::sql_types::Color)]
2902/// enum Color {
2903/// Red,
2904/// Green,
2905/// Blue
2906/// }
2907/// # #[cfg(feature = "postgres")]
2908/// # fn main() -> QueryResult<()> {
2909/// # let connection = &mut connection_no_data();
2910/// let r = diesel::select(Color::Red.into_sql::<schema::sql_types::Color>())
2911/// .get_result::<Color>(connection)?;
2912/// assert_eq!(r, Color::Red);
2913/// Ok(())
2914/// # }
2915/// # #[cfg(not(feature = "postgres"))]
2916/// # fn main() {}
2917/// ```
2918///
2919/// ## Usage with a database side integer column
2920///
2921/// ```rust
2922/// # extern crate diesel;
2923/// # extern crate dotenvy;
2924/// # include!("../../diesel/src/doctest_setup.rs");
2925/// #
2926/// #[derive(Debug, diesel::types::Enum, PartialEq)]
2927/// #[diesel(sql_type = diesel::sql_types::Integer)]
2928/// enum Color {
2929/// // Explicit discriminants are required here
2930/// Red = 1,
2931/// Green = 2,
2932/// Blue = 3
2933/// }
2934/// # fn main() -> QueryResult<()> {
2935/// # let connection = &mut connection_no_data();
2936/// let r = diesel::select(1.into_sql::<diesel::sql_types::Integer>())
2937/// .get_result::<Color>(connection)?;
2938/// assert_eq!(r, Color::Red);
2939/// Ok(())
2940/// # }
2941/// ```
2942///
2943/// ## Usage with a database side text column
2944///
2945/// ```rust
2946/// # extern crate diesel;
2947/// # extern crate dotenvy;
2948/// # include!("../../diesel/src/doctest_setup.rs");
2949/// #
2950/// #[derive(Debug, diesel::types::Enum, PartialEq)]
2951/// #[diesel(sql_type = diesel::sql_types::Text)]
2952/// #[diesel(rename_all = "SCREAMING_SNAKE_CASE")]
2953/// enum Color {
2954/// Red,
2955/// Green,
2956/// Blue,
2957/// }
2958/// # fn main() -> QueryResult<()> {
2959/// # let connection = &mut connection_no_data();
2960/// let r = diesel::select("RED".into_sql::<diesel::sql_types::Text>())
2961/// .get_result::<Color>(connection)?;
2962/// assert_eq!(r, Color::Red);
2963/// Ok(())
2964/// # }
2965/// ```
2966#[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")))]
2967#[proc_macro_derive(Enum, attributes(diesel))]
2968pub fn derive_enum(input: TokenStream) -> TokenStream {
2969derive_enum_inner(input.into()).into()
2970}
29712972fn derive_enum_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
2973 syn::parse2(input)
2974 .and_then(enum_::derive)
2975 .unwrap_or_else(syn::Error::into_compile_error)
2976}