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