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