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