diesel_derives/
lib.rs

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))]
18
19extern crate diesel_table_macro_syntax;
20extern crate proc_macro;
21extern crate proc_macro2;
22extern crate quote;
23extern crate syn;
24
25use proc_macro::TokenStream;
26use sql_function::ExternSqlBlock;
27use syn::parse_quote;
28
29mod attrs;
30mod deprecated;
31mod field;
32mod model;
33mod parsers;
34mod util;
35
36mod 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;
57
58/// 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(docsrs, doc = 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 {
133    derive_as_changeset_inner(input.into()).into()
134}
135
136fn 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}
141
142/// 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(docsrs, doc = 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 {
182    derive_as_expression_inner(input.into()).into()
183}
184
185fn 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}
190
191/// 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(docsrs, doc = 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 {
236    derive_associations_inner(input.into()).into()
237}
238
239fn 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}
244
245/// Implement numeric operators for the current query node
246#[proc_macro_derive(DieselNumericOps)]
247pub fn derive_diesel_numeric_ops(input: TokenStream) -> TokenStream {
248    derive_diesel_numeric_ops_inner(input.into()).into()
249}
250
251fn 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}
256
257/// 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(docsrs, doc = 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 {
267    derive_from_sql_row_inner(input.into()).into()
268}
269
270fn 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}
275
276/// 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(docsrs, doc = 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 {
323    derive_identifiable_inner(input.into()).into()
324}
325
326fn 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}
331
332/// 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(docsrs, doc = 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 {
468    derive_insertable_inner(input.into()).into()
469}
470
471fn 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}
476
477/// 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(docsrs, doc = include_str!(concat!(env!("OUT_DIR"), "/query_id.md")))]
513#[proc_macro_derive(QueryId, attributes(diesel))]
514pub fn derive_query_id(input: TokenStream) -> TokenStream {
515    derive_query_id_inner(input.into()).into()
516}
517
518fn 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}
523
524/// 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(docsrs, doc = 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 {
714    derive_queryable_inner(input.into()).into()
715}
716
717fn 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}
722
723/// 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(docsrs, doc = 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 {
927    derive_queryable_by_name_inner(input.into()).into()
928}
929
930fn 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}
935
936/// 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(docsrs, doc = include_str!(concat!(env!("OUT_DIR"), "/selectable.md")))]
997#[proc_macro_derive(Selectable, attributes(diesel))]
998pub fn derive_selectable(input: TokenStream) -> TokenStream {
999    derive_selectable_inner(input.into()).into()
1000}
1001
1002fn 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}
1007
1008/// 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(docsrs, doc = 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 {
1057    derive_sql_type_inner(input.into()).into()
1058}
1059
1060fn 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}
1065
1066/// 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(docsrs, doc = include_str!(concat!(env!("OUT_DIR"), "/valid_grouping.md")))]
1107#[proc_macro_derive(ValidGrouping, attributes(diesel))]
1108pub fn derive_valid_grouping(input: TokenStream) -> TokenStream {
1109    derive_valid_grouping_inner(input.into()).into()
1110}
1111
1112fn 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}
1117
1118/// 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(docsrs, doc = include_str!(concat!(env!("OUT_DIR"), "/define_sql_function.md")))]
1192#[proc_macro]
1193pub fn define_sql_function(input: TokenStream) -> TokenStream {
1194    define_sql_function_inner(input.into()).into()
1195}
1196
1197fn define_sql_function_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
1198    syn::parse2(input)
1199        .map(|input| sql_function::expand(vec![input], false, false))
1200        .unwrap_or_else(syn::Error::into_compile_error)
1201}
1202
1203/// 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 {
1233    sql_function_proc_inner(input.into()).into()
1234}
1235
1236#[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(vec![i], true, false))
1240        .unwrap_or_else(syn::Error::into_compile_error)
1241}
1242
1243/// 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}
1251
1252fn __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}
1257
1258/// 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}
1266
1267fn __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}
1276
1277/// 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(docsrs, doc = include_str!(concat!(env!("OUT_DIR"), "/table.md")))]
1444#[proc_macro]
1445pub fn table_proc(input: TokenStream) -> TokenStream {
1446    table_proc_inner(input.into()).into()
1447}
1448
1449fn table_proc_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
1450    // include the input in the error output so that rust-analyzer is happy
1451    let tokenstream2 = input.clone();
1452    match syn::parse2(input) {
1453        Ok(input) => table::expand(input),
1454        Err(_) => quote::quote! {
1455            compile_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}
1463
1464/// 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(docsrs, doc = include_str!(concat!(env!("OUT_DIR"), "/multiconnection.md")))]
1644#[proc_macro_derive(MultiConnection)]
1645pub fn derive_multiconnection(input: TokenStream) -> TokenStream {
1646    derive_multiconnection_inner(input.into()).into()
1647}
1648
1649fn 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}
1654
1655/// 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(docsrs, doc = 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 {
1810    auto_type_inner(attr.into(), input.into()).into()
1811}
1812
1813fn 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(
1818        attr,
1819        input,
1820        dsl_auto_type::DeriveSettings::builder()
1821            .default_dsl_path(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}
1828
1829const 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;
1831
1832/// 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(docsrs, doc = 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 {
2322    declare_sql_function_inner(attr.into(), input.into()).into()
2323}
2324
2325fn declare_sql_function_inner(
2326    attr: proc_macro2::TokenStream,
2327    input: proc_macro2::TokenStream,
2328) -> proc_macro2::TokenStream {
2329    let attr = crate::sql_function::DeclareSqlFunctionArgs::parse_from_macro_input(attr);
2330
2331    let result = syn::parse2::<ExternSqlBlock>(input.clone()).map(|res| {
2332        sql_function::expand(
2333            res.function_decls,
2334            false,
2335            attr.as_ref()
2336                .map(|attr| attr.generate_return_type_helpers)
2337                .unwrap_or(true),
2338        )
2339    });
2340
2341    let mut output = match result {
2342        Ok(token_stream) => token_stream,
2343        Err(e) => {
2344            let mut output = input;
2345            output.extend(e.into_compile_error());
2346            output
2347        }
2348    };
2349    if let Err(e) = attr {
2350        output.extend(e.into_compile_error());
2351    }
2352    output
2353}
2354
2355/// 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(docsrs, doc = include_str!(concat!(env!("OUT_DIR"), "/has_query.md")))]
2520#[proc_macro_derive(HasQuery, attributes(diesel))]
2521pub fn derive_has_query(input: TokenStream) -> TokenStream {
2522    derive_has_query_inner(input.into()).into()
2523}
2524
2525fn 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}