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