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 syn::{parse_macro_input, parse_quote};
27
28mod attrs;
29mod deprecated;
30mod field;
31mod model;
32mod parsers;
33mod util;
34
35mod as_changeset;
36mod as_expression;
37mod associations;
38mod diesel_for_each_tuple;
39mod diesel_numeric_ops;
40mod diesel_public_if;
41mod from_sql_row;
42mod identifiable;
43mod insertable;
44mod multiconnection;
45mod query_id;
46mod queryable;
47mod queryable_by_name;
48mod selectable;
49mod sql_function;
50mod sql_type;
51mod table;
52mod valid_grouping;
53
54/// Implements `AsChangeset`
55///
56/// To implement `AsChangeset` this derive needs to know the corresponding table
57/// type. By default, it uses the `snake_case` type name with an added `s` from
58/// the current scope.
59/// It is possible to change this default by using `#[diesel(table_name = something)]`.
60///
61/// If a field name of your struct differs
62/// from the name of the corresponding column, you can annotate the field with
63/// `#[diesel(column_name = some_column_name)]`.
64///
65/// To provide custom serialization behavior for a field, you can use
66/// `#[diesel(serialize_as = SomeType)]`. If this attribute is present, Diesel
67/// will call `.into` on the corresponding field and serialize the instance of `SomeType`,
68/// rather than the actual field on your struct. This can be used to add custom behavior for a
69/// single field, or use types that are otherwise unsupported by Diesel.
70/// Normally, Diesel produces two implementations of the `AsChangeset` trait for your
71/// struct using this derive: one for an owned version and one for a borrowed version.
72/// Using `#[diesel(serialize_as)]` implies a conversion using `.into` which consumes the underlying value.
73/// Hence, once you use `#[diesel(serialize_as)]`, Diesel can no longer insert borrowed
74/// versions of your struct.
75///
76/// By default, any `Option` fields on the struct are skipped if their value is
77/// `None`. If you would like to assign `NULL` to the field instead, you can
78/// annotate your struct with `#[diesel(treat_none_as_null = true)]`.
79///
80/// # Attributes
81///
82/// ## Optional container attributes
83///
84/// * `#[diesel(treat_none_as_null = true)]`, specifies that
85///    the derive should treat `None` values as `NULL`. By default
86///    `Option::<T>::None` is just skipped. To insert a `NULL` using default
87///    behavior use `Option::<Option<T>>::Some(None)`
88/// * `#[diesel(table_name = path::to::table)]`, specifies a path to the table for which the
89///    current type is a changeset. The path is relative to the current module.
90///    If this attribute is not used, the type name converted to
91///    `snake_case` with an added `s` is used as table name.
92/// * `#[diesel(primary_key(id1, id2))]` to specify the struct field that
93///    that corresponds to the primary key. If not used, `id` will be
94///    assumed as primary key field
95///
96/// ## Optional field attributes
97///
98/// * `#[diesel(column_name = some_column_name)]`, overrides the column name
99///    of the current field to `some_column_name`. By default, the field
100///    name is used as column name.
101/// * `#[diesel(serialize_as = SomeType)]`, instead of serializing the actual
102///    field type, Diesel will convert the field into `SomeType` using `.into` and
103///    serialize that instead. By default, this derive will serialize directly using
104///    the actual field type.
105/// * `#[diesel(treat_none_as_null = true/false)]`, overrides the container-level
106///   `treat_none_as_null` attribute for the current field.
107#[cfg_attr(
108    all(not(feature = "without-deprecated"), feature = "with-deprecated"),
109    proc_macro_derive(
110        AsChangeset,
111        attributes(diesel, table_name, column_name, primary_key, changeset_options)
112    )
113)]
114#[cfg_attr(
115    any(feature = "without-deprecated", not(feature = "with-deprecated")),
116    proc_macro_derive(AsChangeset, attributes(diesel))
117)]
118pub fn derive_as_changeset(input: TokenStream) -> TokenStream {
119    as_changeset::derive(parse_macro_input!(input))
120        .unwrap_or_else(syn::Error::into_compile_error)
121        .into()
122}
123
124/// Implements all required variants of `AsExpression`
125///
126/// This derive will generate the following impls:
127///
128/// - `impl AsExpression<SqlType> for YourType`
129/// - `impl AsExpression<Nullable<SqlType>> for YourType`
130/// - `impl AsExpression<SqlType> for &'a YourType`
131/// - `impl AsExpression<Nullable<SqlType>> for &'a YourType`
132/// - `impl AsExpression<SqlType> for &'a &'b YourType`
133/// - `impl AsExpression<Nullable<SqlType>> for &'a &'b YourType`
134///
135/// If your type is unsized,
136/// you can specify this by adding the annotation `#[diesel(not_sized)]`
137/// as attribute on the type. This will skip the impls for non-reference types.
138///
139/// Using this derive requires implementing the `ToSql` trait for your type.
140///
141/// # Attributes:
142///
143/// ## Required container attributes
144///
145/// * `#[diesel(sql_type = SqlType)]`, to specify the sql type of the
146///    generated implementations. If the attribute exists multiple times
147///    impls for each sql type is generated.
148///
149/// ## Optional container attributes
150///
151/// * `#[diesel(not_sized)]`, to skip generating impls that require
152///    that the type is `Sized`
153#[cfg_attr(
154    all(not(feature = "without-deprecated"), feature = "with-deprecated"),
155    proc_macro_derive(AsExpression, attributes(diesel, sql_type))
156)]
157#[cfg_attr(
158    any(feature = "without-deprecated", not(feature = "with-deprecated")),
159    proc_macro_derive(AsExpression, attributes(diesel))
160)]
161pub fn derive_as_expression(input: TokenStream) -> TokenStream {
162    as_expression::derive(parse_macro_input!(input))
163        .unwrap_or_else(syn::Error::into_compile_error)
164        .into()
165}
166
167/// Implement required traits for the associations API
168///
169/// This derive implements support for Diesel's associations api. Check the
170/// module level documentation of the `diesel::associations` module for details.
171///
172/// This derive generates the following impls:
173/// * `impl BelongsTo<Parent> for YourType`
174/// * `impl BelongsTo<&'a Parent> for YourType`
175///
176/// # Attributes
177///
178/// # Required container attributes
179///
180/// * `#[diesel(belongs_to(User))]`, to specify a child-to-parent relationship
181///    between the current type and the specified parent type (`User`).
182///    If this attribute is given multiple times, multiple relationships
183///    are generated. `#[diesel(belongs_to(User, foreign_key = mykey))]` variant
184///    allows us to specify the name of the foreign key. If the foreign key
185///    is not specified explicitly, the remote lower case type name with
186///    appended `_id` is used as a foreign key name. (`user_id` in this example
187///    case)
188///
189/// # Optional container attributes
190///
191/// * `#[diesel(table_name = path::to::table)]` specifies a path to the table this
192///    type belongs to. The path is relative to the current module.
193///    If this attribute is not used, the type name converted to
194///    `snake_case` with an added `s` is used as table name.
195///
196/// # Optional field attributes
197///
198/// * `#[diesel(column_name = some_column_name)]`, overrides the column the current
199///    field maps to `some_column_name`. By default, the field name is used
200///    as a column name.
201#[cfg_attr(
202    all(not(feature = "without-deprecated"), feature = "with-deprecated"),
203    proc_macro_derive(Associations, attributes(diesel, belongs_to, column_name, table_name))
204)]
205#[cfg_attr(
206    any(feature = "without-deprecated", not(feature = "with-deprecated")),
207    proc_macro_derive(Associations, attributes(diesel, belongs_to, column_name, table_name))
208)]
209pub fn derive_associations(input: TokenStream) -> TokenStream {
210    associations::derive(parse_macro_input!(input))
211        .unwrap_or_else(syn::Error::into_compile_error)
212        .into()
213}
214
215/// Implement numeric operators for the current query node
216#[proc_macro_derive(DieselNumericOps)]
217pub fn derive_diesel_numeric_ops(input: TokenStream) -> TokenStream {
218    diesel_numeric_ops::derive(parse_macro_input!(input)).into()
219}
220
221/// Implements `Queryable` for types that correspond to a single SQL type. The type must implement `FromSql`.
222///
223/// This derive is mostly useful to implement support deserializing
224/// into rust types not supported by Diesel itself.
225///
226/// There are no options or special considerations needed for this derive.
227#[proc_macro_derive(FromSqlRow, attributes(diesel))]
228pub fn derive_from_sql_row(input: TokenStream) -> TokenStream {
229    from_sql_row::derive(parse_macro_input!(input))
230        .unwrap_or_else(syn::Error::into_compile_error)
231        .into()
232}
233
234/// Implements `Identifiable` for references of the current type
235///
236/// By default, the primary key field is assumed to be a single field called `id`.
237/// If it isn't, you can put `#[diesel(primary_key(your_id))]` on your struct.
238/// If you have a composite primary key, the syntax is `#[diesel(primary_key(id1, id2))]`.
239///
240/// By default, `#[derive(Identifiable)]` will assume that your table is
241/// in scope and its name is the plural form of your struct name.
242/// Diesel uses basic pluralization rules.
243/// It only adds an `s` to the end, and converts `CamelCase` to `snake_case`.
244/// If your table name doesn't follow this convention or is not in scope,
245/// you can specify a path to the table with `#[diesel(table_name = path::to::table)]`.
246/// Our rules for inferring table names are considered public API.
247/// It will never change without a major version bump.
248///
249/// This derive generates the following impls:
250/// * `impl Identifiable for &'a YourType`
251/// * `impl Identifiable for &'_ &'a YourType`
252///
253/// # Attributes
254///
255/// ## Optional container attributes
256///
257/// * `#[diesel(table_name = path::to::table)]` specifies a path to the table this
258///    type belongs to. The path is relative to the current module.
259///    If this attribute is not used, the type name converted to
260///    `snake_case` with an added `s` is used as table name
261/// * `#[diesel(primary_key(id1, id2))]` to specify the struct field that
262///    that corresponds to the primary key. If not used, `id` will be
263///    assumed as primary key field
264///
265/// # Optional field attributes
266///
267/// * `#[diesel(column_name = some_column_name)]`, overrides the column the current
268///    field maps to `some_column_name`. By default, the field name is used
269///    as a column name.
270#[cfg_attr(
271    all(not(feature = "without-deprecated"), feature = "with-deprecated"),
272    proc_macro_derive(Identifiable, attributes(diesel, table_name, column_name, primary_key))
273)]
274#[cfg_attr(
275    any(feature = "without-deprecated", not(feature = "with-deprecated")),
276    proc_macro_derive(Identifiable, attributes(diesel))
277)]
278pub fn derive_identifiable(input: TokenStream) -> TokenStream {
279    identifiable::derive(parse_macro_input!(input))
280        .unwrap_or_else(syn::Error::into_compile_error)
281        .into()
282}
283
284/// Implements `Insertable`
285///
286/// To implement `Insertable` this derive needs to know the corresponding table
287/// type. By default, it uses the `snake_case` type name with an added `s`
288/// from the current scope.
289/// It is possible to change this default by using `#[diesel(table_name = something)]`.
290/// If `table_name` attribute is given multiple times, impls for each table are generated.
291///
292/// If a field name of your
293/// struct differs from the name of the corresponding column,
294/// you can annotate the field with `#[diesel(column_name = some_column_name)]`.
295///
296/// Your struct can also contain fields which implement `Insertable`. This is
297/// useful when you want to have one field map to more than one column (for
298/// example, an enum that maps to a label and a value column). Add
299/// `#[diesel(embed)]` to any such fields.
300///
301/// To provide custom serialization behavior for a field, you can use
302/// `#[diesel(serialize_as = SomeType)]`. If this attribute is present, Diesel
303/// will call `.into` on the corresponding field and serialize the instance of `SomeType`,
304/// rather than the actual field on your struct. This can be used to add custom behavior for a
305/// single field, or use types that are otherwise unsupported by Diesel.
306/// Using `#[diesel(serialize_as)]` is **incompatible** with `#[diesel(embed)]`.
307/// Normally, Diesel produces two implementations of the `Insertable` trait for your
308/// struct using this derive: one for an owned version and one for a borrowed version.
309/// Using `#[diesel(serialize_as)]` implies a conversion using `.into` which consumes the underlying value.
310/// Hence, once you use `#[diesel(serialize_as)]`, Diesel can no longer insert borrowed
311/// versions of your struct.
312///
313/// # Attributes
314///
315/// ## Optional container attributes
316///
317/// * `#[diesel(table_name = path::to::table)]`, specifies a path to the table this type
318///    is insertable into. The path is relative to the current module.
319///    If this attribute is not used, the type name converted to
320///    `snake_case` with an added `s` is used as table name
321/// * `#[diesel(treat_none_as_default_value = false)]`, specifies that `None` values
322///    should be converted to `NULL` values on the SQL side instead of being treated as `DEFAULT`
323///    value primitive. *Note*: This option may control if your query is stored in the
324///    prepared statement cache or not*
325///
326/// ## Optional field attributes
327///
328/// * `#[diesel(column_name = some_column_name)]`, overrides the column the current
329///    field maps to `some_column_name`. By default, the field name is used
330///    as column name
331/// * `#[diesel(embed)]`, specifies that the current field maps not only
332///    to a single database field, but is a struct that implements `Insertable`
333/// * `#[diesel(serialize_as = SomeType)]`, instead of serializing the actual
334///    field type, Diesel will convert the field into `SomeType` using `.into` and
335///    serialize that instead. By default, this derive will serialize directly using
336///    the actual field type.
337/// * `#[diesel(treat_none_as_default_value = true/false)]`, overrides the container-level
338///   `treat_none_as_default_value` attribute for the current field.
339/// * `#[diesel(skip_insertion)]`, skips insertion of this field. Useful for working with
340///    generated columns.
341///
342/// # Examples
343///
344/// If we want to customize the serialization during insert, we can use `#[diesel(serialize_as)]`.
345///
346/// ```rust
347/// # extern crate diesel;
348/// # extern crate dotenvy;
349/// # include!("../../diesel/src/doctest_setup.rs");
350/// # use diesel::{prelude::*, serialize::{ToSql, Output, self}, deserialize::{FromSqlRow}, expression::AsExpression, sql_types, backend::Backend};
351/// # use schema::users;
352/// # use std::io::Write;
353/// #
354/// #[derive(Debug, FromSqlRow, AsExpression)]
355/// #[diesel(sql_type = sql_types::Text)]
356/// struct UppercaseString(pub String);
357///
358/// impl Into<UppercaseString> for String {
359///     fn into(self) -> UppercaseString {
360///         UppercaseString(self.to_uppercase())
361///     }
362/// }
363///
364/// impl<DB> ToSql<sql_types::Text, DB> for UppercaseString
365///     where
366///         DB: Backend,
367///         String: ToSql<sql_types::Text, DB>,
368/// {
369///     fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> serialize::Result {
370///         self.0.to_sql(out)
371///     }
372/// }
373///
374/// #[derive(Insertable, PartialEq, Debug)]
375/// #[diesel(table_name = users)]
376/// struct InsertableUser {
377///     id: i32,
378///     #[diesel(serialize_as = UppercaseString)]
379///     name: String,
380/// }
381///
382/// # fn main() {
383/// #     run_test();
384/// # }
385/// #
386/// # fn run_test() -> QueryResult<()> {
387/// #     use schema::users::dsl::*;
388/// #     let connection = &mut connection_no_data();
389/// #     diesel::sql_query("CREATE TABLE users (id INTEGER PRIMARY KEY, name VARCHAR(255) NOT NULL)")
390/// #         .execute(connection)
391/// #         .unwrap();
392/// let user = InsertableUser {
393///     id: 1,
394///     name: "thomas".to_string(),
395/// };
396///
397/// diesel::insert_into(users)
398///     .values(user)
399///     .execute(connection)
400///     .unwrap();
401///
402/// assert_eq!(
403///     Ok("THOMAS".to_string()),
404///     users.select(name).first(connection)
405/// );
406/// # Ok(())
407/// # }
408/// ```
409#[cfg_attr(
410    all(not(feature = "without-deprecated"), feature = "with-deprecated"),
411    proc_macro_derive(Insertable, attributes(diesel, table_name, column_name))
412)]
413#[cfg_attr(
414    any(feature = "without-deprecated", not(feature = "with-deprecated")),
415    proc_macro_derive(Insertable, attributes(diesel))
416)]
417pub fn derive_insertable(input: TokenStream) -> TokenStream {
418    insertable::derive(parse_macro_input!(input))
419        .unwrap_or_else(syn::Error::into_compile_error)
420        .into()
421}
422
423/// Implements `QueryId`
424///
425/// For example, given this struct:
426///
427/// ```rust
428/// # extern crate diesel;
429/// #[derive(diesel::query_builder::QueryId)]
430/// pub struct And<Left, Right> {
431///     left: Left,
432///     right: Right,
433/// }
434/// ```
435///
436/// the following implementation will be generated
437///
438/// ```rust
439/// # extern crate diesel;
440/// # struct And<Left, Right>(Left, Right);
441/// # use diesel::query_builder::QueryId;
442/// impl<Left, Right> QueryId for And<Left, Right>
443/// where
444///     Left: QueryId,
445///     Right: QueryId,
446/// {
447///     type QueryId = And<Left::QueryId, Right::QueryId>;
448///
449///     const HAS_STATIC_QUERY_ID: bool = Left::HAS_STATIC_QUERY_ID && Right::HAS_STATIC_QUERY_ID;
450/// }
451/// ```
452///
453/// If the SQL generated by a struct is not uniquely identifiable by its type,
454/// meaning that `HAS_STATIC_QUERY_ID` should always be false,
455/// you shouldn't derive this trait.
456/// In that case, you should implement it manually instead.
457#[proc_macro_derive(QueryId)]
458pub fn derive_query_id(input: TokenStream) -> TokenStream {
459    query_id::derive(parse_macro_input!(input)).into()
460}
461
462/// Implements `Queryable` to load the result of statically typed queries
463///
464/// This trait can only be derived for structs, not enums.
465///
466/// **Note**: When this trait is derived, it will assume that __all fields on
467/// your struct__ matches __all fields in the query__, including the order and
468/// count. This means that field order is significant if you're using
469/// `#[derive(Queryable)]`. __Field name has no effect__. If you see errors while
470/// loading data into a struct that derives `Queryable`: Consider using
471/// [`#[derive(Selectable)]`] + `#[diesel(check_for_backend(YourBackendType))]`
472/// to check for mismatching fields at compile-time.
473///
474/// To provide custom deserialization behavior for a field, you can use
475/// `#[diesel(deserialize_as = SomeType)]`. If this attribute is present, Diesel
476/// will deserialize the corresponding field into `SomeType`, rather than the
477/// actual field type on your struct and then call
478/// [`.try_into`](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into)
479/// to convert it to the actual field type. This can be used to add custom behavior for a
480/// single field, or use types that are otherwise unsupported by Diesel.
481/// (Note: all types that have `Into<T>` automatically implement `TryInto<T>`,
482/// for cases where your conversion is not fallible.)
483///
484/// # Attributes
485///
486/// ## Optional field attributes
487///
488/// * `#[diesel(deserialize_as = Type)]`, instead of deserializing directly
489///    into the field type, the implementation will deserialize into `Type`.
490///    Then `Type` is converted via
491///    [`.try_into`](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into)
492///    into the field type. By default, this derive will deserialize directly into the field type
493///
494/// # Examples
495///
496/// If we just want to map a query to our struct, we can use `derive`.
497///
498/// ```rust
499/// # extern crate diesel;
500/// # extern crate dotenvy;
501/// # include!("../../diesel/src/doctest_setup.rs");
502/// #
503/// #[derive(Queryable, PartialEq, Debug)]
504/// struct User {
505///     id: i32,
506///     name: String,
507/// }
508///
509/// # fn main() {
510/// #     run_test();
511/// # }
512/// #
513/// # fn run_test() -> QueryResult<()> {
514/// #     use schema::users::dsl::*;
515/// #     let connection = &mut establish_connection();
516/// let first_user = users.first(connection)?;
517/// let expected = User { id: 1, name: "Sean".into() };
518/// assert_eq!(expected, first_user);
519/// #     Ok(())
520/// # }
521/// ```
522///
523/// If we want to do additional work during deserialization, we can use
524/// `deserialize_as` to use a different implementation.
525///
526/// ```rust
527/// # extern crate diesel;
528/// # extern crate dotenvy;
529/// # include!("../../diesel/src/doctest_setup.rs");
530/// #
531/// # use schema::users;
532/// # use diesel::backend::{self, Backend};
533/// # use diesel::deserialize::{self, Queryable, FromSql};
534/// # use diesel::sql_types::Text;
535/// #
536/// struct LowercaseString(String);
537///
538/// impl Into<String> for LowercaseString {
539///     fn into(self) -> String {
540///         self.0
541///     }
542/// }
543///
544/// impl<DB> Queryable<Text, DB> for LowercaseString
545/// where
546///     DB: Backend,
547///     String: FromSql<Text, DB>
548/// {
549///
550///     type Row = String;
551///
552///     fn build(s: String) -> deserialize::Result<Self> {
553///         Ok(LowercaseString(s.to_lowercase()))
554///     }
555/// }
556///
557/// #[derive(Queryable, PartialEq, Debug)]
558/// struct User {
559///     id: i32,
560///     #[diesel(deserialize_as = LowercaseString)]
561///     name: String,
562/// }
563///
564/// # fn main() {
565/// #     run_test();
566/// # }
567/// #
568/// # fn run_test() -> QueryResult<()> {
569/// #     use schema::users::dsl::*;
570/// #     let connection = &mut establish_connection();
571/// let first_user = users.first(connection)?;
572/// let expected = User { id: 1, name: "sean".into() };
573/// assert_eq!(expected, first_user);
574/// #     Ok(())
575/// # }
576/// ```
577///
578/// Alternatively, we can implement the trait for our struct manually.
579///
580/// ```rust
581/// # extern crate diesel;
582/// # extern crate dotenvy;
583/// # include!("../../diesel/src/doctest_setup.rs");
584/// #
585/// use schema::users;
586/// use diesel::deserialize::{self, Queryable, FromSqlRow};
587/// use diesel::row::Row;
588///
589/// # /*
590/// type DB = diesel::sqlite::Sqlite;
591/// # */
592///
593/// #[derive(PartialEq, Debug)]
594/// struct User {
595///     id: i32,
596///     name: String,
597/// }
598///
599/// impl Queryable<users::SqlType, DB> for User
600/// where
601///    (i32, String): FromSqlRow<users::SqlType, DB>,
602/// {
603///     type Row = (i32, String);
604///
605///     fn build((id, name): Self::Row) -> deserialize::Result<Self> {
606///         Ok(User { id, name: name.to_lowercase() })
607///     }
608/// }
609///
610/// # fn main() {
611/// #     run_test();
612/// # }
613/// #
614/// # fn run_test() -> QueryResult<()> {
615/// #     use schema::users::dsl::*;
616/// #     let connection = &mut establish_connection();
617/// let first_user = users.first(connection)?;
618/// let expected = User { id: 1, name: "sean".into() };
619/// assert_eq!(expected, first_user);
620/// #     Ok(())
621/// # }
622/// ```
623#[cfg_attr(
624    all(not(feature = "without-deprecated"), feature = "with-deprecated"),
625    proc_macro_derive(Queryable, attributes(diesel, column_name))
626)]
627#[cfg_attr(
628    any(feature = "without-deprecated", not(feature = "with-deprecated")),
629    proc_macro_derive(Queryable, attributes(diesel))
630)]
631pub fn derive_queryable(input: TokenStream) -> TokenStream {
632    queryable::derive(parse_macro_input!(input))
633        .unwrap_or_else(syn::Error::into_compile_error)
634        .into()
635}
636
637/// Implements `QueryableByName` for untyped sql queries, such as that one generated
638/// by `sql_query`
639///
640/// To derive this trait, Diesel needs to know the SQL type of each field.
641/// It can get the data from the corresponding table type.
642/// It uses the `snake_case` type name with an added `s`.
643/// It is possible to change this default by using `#[diesel(table_name = something)]`.
644/// If you define use the table type, the SQL type will be
645/// `diesel::dsl::SqlTypeOf<table_name::column_name>`. In cases which there are no table type,
646/// you can do the same by annotating each field with `#[diesel(sql_type = SomeType)]`.
647///
648/// If the name of a field on your struct is different from the column in your
649/// `table!` declaration, or if you're deriving this trait on a tuple struct,
650/// you can annotate the field with `#[diesel(column_name = some_column)]`. For tuple
651/// structs, all fields must have this annotation.
652///
653/// If a field is another struct which implements `QueryableByName`,
654/// instead of a column, you can annotate that with `#[diesel(embed)]`.
655/// Then all fields contained by that inner struct are loaded into the embedded struct.
656///
657/// To provide custom deserialization behavior for a field, you can use
658/// `#[diesel(deserialize_as = SomeType)]`. If this attribute is present, Diesel
659/// will deserialize the corresponding field into `SomeType`, rather than the
660/// actual field type on your struct and then call `.into` to convert it to the
661/// actual field type. This can be used to add custom behavior for a
662/// single field, or use types that are otherwise unsupported by Diesel.
663///
664/// # Attributes
665///
666/// ## Optional container attributes
667///
668/// * `#[diesel(table_name = path::to::table)]`, to specify that this type contains
669///    columns for the specified table. The path is relative to the current module.
670///    If no field attributes are specified the derive will use the sql type of
671///    the corresponding column.
672/// * `#[diesel(check_for_backend(diesel::pg::Pg, diesel::mysql::Mysql))]`, instructs
673///    the derive to generate additional code to identify potential type mismatches.
674///    It accepts a list of backend types to check the types against. Using this option
675///    will result in much better error messages in cases where some types in your `QueryableByName`
676///    struct don't match. You need to specify the concrete database backend
677///    this specific struct is indented to be used with, as otherwise rustc can't correctly
678///    identify the required deserialization implementation.
679///
680/// ## Optional field attributes
681///
682/// * `#[diesel(column_name = some_column)]`, overrides the column name for
683///    a given field. If not set, the name of the field is used as a column
684///    name. This attribute is required on tuple structs, if
685///    `#[diesel(table_name = some_table)]` is used, otherwise it's optional.
686/// * `#[diesel(sql_type = SomeType)]`, assumes `SomeType` as sql type of the
687///    corresponding field. These attributes have precedence over all other
688///    variants to specify the sql type.
689/// * `#[diesel(deserialize_as = Type)]`, instead of deserializing directly
690///    into the field type, the implementation will deserialize into `Type`.
691///    Then `Type` is converted via `.into()` into the field type. By default,
692///    this derive will deserialize directly into the field type
693/// * `#[diesel(embed)]`, specifies that the current field maps not only
694///    a single database column, but it is a type that implements
695///    `QueryableByName` on its own
696///
697/// # Examples
698///
699/// If we just want to map a query to our struct, we can use `derive`.
700///
701/// ```rust
702/// # extern crate diesel;
703/// # extern crate dotenvy;
704/// # include!("../../diesel/src/doctest_setup.rs");
705/// # use schema::users;
706/// # use diesel::sql_query;
707/// #
708/// #[derive(QueryableByName, PartialEq, Debug)]
709/// struct User {
710///     id: i32,
711///     name: String,
712/// }
713///
714/// # fn main() {
715/// #     run_test();
716/// # }
717/// #
718/// # fn run_test() -> QueryResult<()> {
719/// #     let connection = &mut establish_connection();
720/// let first_user = sql_query("SELECT * FROM users ORDER BY id LIMIT 1")
721///     .get_result(connection)?;
722/// let expected = User { id: 1, name: "Sean".into() };
723/// assert_eq!(expected, first_user);
724/// #     Ok(())
725/// # }
726/// ```
727///
728/// If we want to do additional work during deserialization, we can use
729/// `deserialize_as` to use a different implementation.
730///
731/// ```rust
732/// # extern crate diesel;
733/// # extern crate dotenvy;
734/// # include!("../../diesel/src/doctest_setup.rs");
735/// # use diesel::sql_query;
736/// # use schema::users;
737/// # use diesel::backend::{self, Backend};
738/// # use diesel::deserialize::{self, FromSql};
739/// #
740/// struct LowercaseString(String);
741///
742/// impl Into<String> for LowercaseString {
743///     fn into(self) -> String {
744///         self.0
745///     }
746/// }
747///
748/// impl<DB, ST> FromSql<ST, DB> for LowercaseString
749/// where
750///     DB: Backend,
751///     String: FromSql<ST, DB>,
752/// {
753///     fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
754///         String::from_sql(bytes)
755///             .map(|s| LowercaseString(s.to_lowercase()))
756///     }
757/// }
758///
759/// #[derive(QueryableByName, PartialEq, Debug)]
760/// struct User {
761///     id: i32,
762///     #[diesel(deserialize_as = LowercaseString)]
763///     name: String,
764/// }
765///
766/// # fn main() {
767/// #     run_test();
768/// # }
769/// #
770/// # fn run_test() -> QueryResult<()> {
771/// #     let connection = &mut establish_connection();
772/// let first_user = sql_query("SELECT * FROM users ORDER BY id LIMIT 1")
773///     .get_result(connection)?;
774/// let expected = User { id: 1, name: "sean".into() };
775/// assert_eq!(expected, first_user);
776/// #     Ok(())
777/// # }
778/// ```
779///
780/// The custom derive generates impls similar to the following one
781///
782/// ```rust
783/// # extern crate diesel;
784/// # extern crate dotenvy;
785/// # include!("../../diesel/src/doctest_setup.rs");
786/// # use schema::users;
787/// # use diesel::sql_query;
788/// # use diesel::deserialize::{self, QueryableByName, FromSql};
789/// # use diesel::row::NamedRow;
790/// # use diesel::backend::Backend;
791/// #
792/// #[derive(PartialEq, Debug)]
793/// struct User {
794///     id: i32,
795///     name: String,
796/// }
797///
798/// impl<DB> QueryableByName<DB> for User
799/// where
800///     DB: Backend,
801///     i32: FromSql<diesel::dsl::SqlTypeOf<users::id>, DB>,
802///     String: FromSql<diesel::dsl::SqlTypeOf<users::name>, DB>,
803/// {
804///     fn build<'a>(row: &impl NamedRow<'a, DB>) -> deserialize::Result<Self> {
805///         let id = NamedRow::get::<diesel::dsl::SqlTypeOf<users::id>, _>(row, "id")?;
806///         let name = NamedRow::get::<diesel::dsl::SqlTypeOf<users::name>, _>(row, "name")?;
807///
808///         Ok(Self { id, name })
809///     }
810/// }
811///
812/// # fn main() {
813/// #     run_test();
814/// # }
815/// #
816/// # fn run_test() -> QueryResult<()> {
817/// #     let connection = &mut establish_connection();
818/// let first_user = sql_query("SELECT * FROM users ORDER BY id LIMIT 1")
819///     .get_result(connection)?;
820/// let expected = User { id: 1, name: "Sean".into() };
821/// assert_eq!(expected, first_user);
822/// #     Ok(())
823/// # }
824/// ```
825#[cfg_attr(
826    all(not(feature = "without-deprecated"), feature = "with-deprecated"),
827    proc_macro_derive(QueryableByName, attributes(diesel, table_name, column_name, sql_type))
828)]
829#[cfg_attr(
830    any(feature = "without-deprecated", not(feature = "with-deprecated")),
831    proc_macro_derive(QueryableByName, attributes(diesel))
832)]
833pub fn derive_queryable_by_name(input: TokenStream) -> TokenStream {
834    queryable_by_name::derive(parse_macro_input!(input))
835        .unwrap_or_else(syn::Error::into_compile_error)
836        .into()
837}
838
839/// Implements `Selectable`
840///
841/// To implement `Selectable` this derive needs to know the corresponding table
842/// type. By default, it uses the `snake_case` type name with an added `s`.
843/// It is possible to change this default by using `#[diesel(table_name = something)]`.
844///
845/// If the name of a field on your struct is different from the column in your
846/// `table!` declaration, or if you're deriving this trait on a tuple struct,
847/// you can annotate the field with `#[diesel(column_name = some_column)]`. For tuple
848/// structs, all fields must have this annotation.
849///
850/// If a field is another struct which implements `Selectable`,
851/// instead of a column, you can annotate that with `#[diesel(embed)]`.
852/// Then all fields contained by that inner struct are selected as separate tuple.
853/// Fields from an inner struct can come from a different table, as long as the
854/// select clause is valid in the current query.
855///
856/// The derive enables using the `SelectableHelper::as_select` method to construct
857/// select clauses, in order to use LoadDsl, you might also check the
858/// `Queryable` trait and derive.
859///
860/// # Attributes
861///
862/// ## Type attributes
863///
864/// * `#[diesel(table_name = path::to::table)]`, specifies a path to the table for which the
865///    current type is selectable. The path is relative to the current module.
866///    If this attribute is not used, the type name converted to
867///    `snake_case` with an added `s` is used as table name.
868///
869/// ## Optional Type attributes
870///
871/// * `#[diesel(check_for_backend(diesel::pg::Pg, diesel::mysql::Mysql))]`, instructs
872///    the derive to generate additional code to identify potential type mismatches.
873///    It accepts a list of backend types to check the types against. Using this option
874///    will result in much better error messages in cases where some types in your `Queryable`
875///    struct don't match. You need to specify the concrete database backend
876///    this specific struct is indented to be used with, as otherwise rustc can't correctly
877///    identify the required deserialization implementation.
878///
879/// ## Field attributes
880///
881/// * `#[diesel(column_name = some_column)]`, overrides the column name for
882///    a given field. If not set, the name of the field is used as column
883///    name.
884/// * `#[diesel(embed)]`, specifies that the current field maps not only
885///    a single database column, but is a type that implements
886///    `Selectable` on its own
887/// * `#[diesel(select_expression = some_custom_select_expression)]`, overrides
888///   the entire select expression for the given field. It may be used to select with
889///   custom tuples, or specify `select_expression = my_table::some_field.is_not_null()`,
890///   or separate tables...
891///   It may be used in conjunction with `select_expression_type` (described below)
892/// * `#[diesel(select_expression_type = the_custom_select_expression_type]`, should be used
893///   in conjunction with `select_expression` (described above) if the type is too complex
894///   for diesel to infer it automatically. This will be required if select_expression is a custom
895///   function call that doesn't have the corresponding associated type defined at the same path.
896///   Example use (this would actually be inferred):
897///   `#[diesel(select_expression_type = dsl::IsNotNull<my_table::some_field>)]`
898#[proc_macro_derive(Selectable, attributes(diesel))]
899pub fn derive_selectable(input: TokenStream) -> TokenStream {
900    selectable::derive(parse_macro_input!(input))
901        .unwrap_or_else(syn::Error::into_compile_error)
902        .into()
903}
904
905/// Implement necessary traits for adding a new sql type
906///
907/// This trait implements all necessary traits to define a
908/// new sql type. This is useful for adding support for unsupported
909/// or custom types on the sql side. The sql type will be usable for
910/// all backends you specified via the attributes listed below.
911///
912/// This derive will implement `NotNull`, `HasSqlType` and `SingleValue`.
913/// When using this derive macro,
914/// you need to specify how the type is represented on various backends.
915/// You don't need to specify every backend,
916/// only the ones supported by your type.
917///
918/// For PostgreSQL, add `#[diesel(postgres_type(name = "pg_type_name", schema = "pg_schema_name"))]`
919/// or `#[diesel(postgres_type(oid = "some_oid", array_oid = "some_oid"))]` for
920/// builtin types.
921/// For MySQL, specify which variant of `MysqlType` should be used
922/// by adding `#[diesel(mysql_type(name = "Variant"))]`.
923/// For SQLite, specify which variant of `SqliteType` should be used
924/// by adding `#[diesel(sqlite_type(name = "Variant"))]`.
925///
926/// # Attributes
927///
928/// ## Type attributes
929///
930/// * `#[diesel(postgres_type(name = "TypeName", schema = "public"))]` specifies support for
931///    a postgresql type with the name `TypeName` in the schema `public`. Prefer this variant
932///    for types with no stable OID (== everything but the builtin types). It is possible to leaf
933///    of the `schema` part. In that case, Diesel defaults to the default postgres search path.
934/// * `#[diesel(postgres_type(oid = 42, array_oid = 142))]`, specifies support for a
935///    postgresql type with the given `oid` and `array_oid`. This variant
936///    should only be used with types that have a stable OID.
937/// * `#[diesel(sqlite_type(name = "TypeName"))]`, specifies support for a sqlite type
938///    with the given name. `TypeName` needs to be one of the possible values
939///    in `SqliteType`
940/// * `#[diesel(mysql_type(name = "TypeName"))]`, specifies support for a mysql type
941///    with the given name. `TypeName` needs to be one of the possible values
942///    in `MysqlType`
943#[cfg_attr(
944    all(not(feature = "without-deprecated"), feature = "with-deprecated"),
945    proc_macro_derive(SqlType, attributes(diesel, postgres, sqlite_type, mysql_type))
946)]
947#[cfg_attr(
948    any(feature = "without-deprecated", not(feature = "with-deprecated")),
949    proc_macro_derive(SqlType, attributes(diesel))
950)]
951pub fn derive_sql_type(input: TokenStream) -> TokenStream {
952    sql_type::derive(parse_macro_input!(input))
953        .unwrap_or_else(syn::Error::into_compile_error)
954        .into()
955}
956
957/// Implements `ValidGrouping`
958///
959/// This trait can be automatically derived for structs with no type parameters
960/// which are never aggregate, as well as for structs which are `NonAggregate`
961/// when all type parameters are `NonAggregate`. For example:
962///
963/// ```ignore
964/// #[derive(ValidGrouping)]
965/// struct LiteralOne;
966///
967/// #[derive(ValidGrouping)]
968/// struct Plus<Lhs, Rhs>(Lhs, Rhs);
969///
970/// // The following impl will be generated:
971///
972/// impl<GroupByClause> ValidGrouping<GroupByClause> for LiteralOne {
973///     type IsAggregate = is_aggregate::Never;
974/// }
975///
976/// impl<Lhs, Rhs, GroupByClause> ValidGrouping<GroupByClause> for Plus<Lhs, Rhs>
977/// where
978///     Lhs: ValidGrouping<GroupByClause>,
979///     Rhs: ValidGrouping<GroupByClause>,
980///     Lhs::IsAggregate: MixedAggregates<Rhs::IsAggregate>,
981/// {
982///     type IsAggregate = <Lhs::IsAggregate as MixedAggregates<Rhs::IsAggregate>>::Output;
983/// }
984/// ```
985///
986/// For types which are always considered aggregate (such as an aggregate
987/// function), annotate your struct with `#[diesel(aggregate)]` to set `IsAggregate`
988/// explicitly to `is_aggregate::Yes`.
989///
990/// # Attributes
991///
992/// ## Optional container attributes
993///
994/// * `#[diesel(aggregate)]` for cases where the type represents an aggregating
995///    SQL expression
996#[proc_macro_derive(ValidGrouping, attributes(diesel))]
997pub fn derive_valid_grouping(input: TokenStream) -> TokenStream {
998    valid_grouping::derive(parse_macro_input!(input))
999        .unwrap_or_else(syn::Error::into_compile_error)
1000        .into()
1001}
1002
1003/// Declare a sql function for use in your code.
1004///
1005/// Diesel only provides support for a very small number of SQL functions.
1006/// This macro enables you to add additional functions from the SQL standard,
1007/// as well as any custom functions your application might have.
1008///
1009/// The syntax for this macro is very similar to that of a normal Rust function,
1010/// except the argument and return types will be the SQL types being used.
1011/// Typically, these types will come from [`diesel::sql_types`](../diesel/sql_types/index.html)
1012///
1013/// This macro will generate two items. A function with the name that you've
1014/// given, and a module with a helper type representing the return type of your
1015/// function. For example, this invocation:
1016///
1017/// ```ignore
1018/// define_sql_function!(fn lower(x: Text) -> Text);
1019/// ```
1020///
1021/// will generate this code:
1022///
1023/// ```ignore
1024/// pub fn lower<X>(x: X) -> lower<X> {
1025///     ...
1026/// }
1027///
1028/// pub type lower<X> = ...;
1029/// ```
1030///
1031/// Most attributes given to this macro will be put on the generated function
1032/// (including doc comments).
1033///
1034/// # Adding Doc Comments
1035///
1036/// ```no_run
1037/// # extern crate diesel;
1038/// # use diesel::*;
1039/// #
1040/// # table! { crates { id -> Integer, name -> VarChar, } }
1041/// #
1042/// use diesel::sql_types::Text;
1043///
1044/// define_sql_function! {
1045///     /// Represents the `canon_crate_name` SQL function, created in
1046///     /// migration ....
1047///     fn canon_crate_name(a: Text) -> Text;
1048/// }
1049///
1050/// # fn main() {
1051/// # use self::crates::dsl::*;
1052/// let target_name = "diesel";
1053/// crates.filter(canon_crate_name(name).eq(canon_crate_name(target_name)));
1054/// // This will generate the following SQL
1055/// // SELECT * FROM crates WHERE canon_crate_name(crates.name) = canon_crate_name($1)
1056/// # }
1057/// ```
1058///
1059/// # Special Attributes
1060///
1061/// There are a handful of special attributes that Diesel will recognize. They
1062/// are:
1063///
1064/// - `#[aggregate]`
1065///   - Indicates that this is an aggregate function, and that `NonAggregate`
1066///     shouldn't be implemented.
1067/// - `#[sql_name = "name"]`
1068///   - The SQL to be generated is different from the Rust name of the function.
1069///     This can be used to represent functions which can take many argument
1070///     types, or to capitalize function names.
1071///
1072/// Functions can also be generic. Take the definition of `sum`, for example:
1073///
1074/// ```no_run
1075/// # extern crate diesel;
1076/// # use diesel::*;
1077/// #
1078/// # table! { crates { id -> Integer, name -> VarChar, } }
1079/// #
1080/// use diesel::sql_types::Foldable;
1081///
1082/// define_sql_function! {
1083///     #[aggregate]
1084///     #[sql_name = "SUM"]
1085///     fn sum<ST: Foldable>(expr: ST) -> ST::Sum;
1086/// }
1087///
1088/// # fn main() {
1089/// # use self::crates::dsl::*;
1090/// crates.select(sum(id));
1091/// # }
1092/// ```
1093///
1094/// # SQL Functions without Arguments
1095///
1096/// A common example is ordering a query using the `RANDOM()` sql function,
1097/// which can be implemented using `define_sql_function!` like this:
1098///
1099/// ```rust
1100/// # extern crate diesel;
1101/// # use diesel::*;
1102/// #
1103/// # table! { crates { id -> Integer, name -> VarChar, } }
1104/// #
1105/// define_sql_function!(fn random() -> Text);
1106///
1107/// # fn main() {
1108/// # use self::crates::dsl::*;
1109/// crates.order(random());
1110/// # }
1111/// ```
1112///
1113/// # Use with SQLite
1114///
1115/// On most backends, the implementation of the function is defined in a
1116/// migration using `CREATE FUNCTION`. On SQLite, the function is implemented in
1117/// Rust instead. You must call `register_impl` or
1118/// `register_nondeterministic_impl` (in the generated function's `_internals`
1119/// module) with every connection before you can use the function.
1120///
1121/// These functions will only be generated if the `sqlite` feature is enabled,
1122/// and the function is not generic.
1123/// SQLite doesn't support generic functions and variadic functions.
1124///
1125/// ```rust
1126/// # extern crate diesel;
1127/// # use diesel::*;
1128/// #
1129/// # #[cfg(feature = "sqlite")]
1130/// # fn main() {
1131/// #     run_test().unwrap();
1132/// # }
1133/// #
1134/// # #[cfg(not(feature = "sqlite"))]
1135/// # fn main() {
1136/// # }
1137/// #
1138/// use diesel::sql_types::{Integer, Double};
1139/// define_sql_function!(fn add_mul(x: Integer, y: Integer, z: Double) -> Double);
1140///
1141/// # #[cfg(feature = "sqlite")]
1142/// # fn run_test() -> Result<(), Box<dyn std::error::Error>> {
1143/// let connection = &mut SqliteConnection::establish(":memory:")?;
1144///
1145/// add_mul_utils::register_impl(connection, |x: i32, y: i32, z: f64| {
1146///     (x + y) as f64 * z
1147/// })?;
1148///
1149/// let result = select(add_mul(1, 2, 1.5))
1150///     .get_result::<f64>(connection)?;
1151/// assert_eq!(4.5, result);
1152/// #     Ok(())
1153/// # }
1154/// ```
1155///
1156/// ## Panics
1157///
1158/// If an implementation of the custom function panics and unwinding is enabled, the panic is
1159/// caught and the function returns to libsqlite with an error. It can't propagate the panics due
1160/// to the FFI boundary.
1161///
1162/// This is the same for [custom aggregate functions](#custom-aggregate-functions).
1163///
1164/// ## Custom Aggregate Functions
1165///
1166/// Custom aggregate functions can be created in SQLite by adding an `#[aggregate]`
1167/// attribute inside `define_sql_function`. `register_impl` (in the generated function's `_utils`
1168/// module) needs to be called with a type implementing the
1169/// [SqliteAggregateFunction](../diesel/sqlite/trait.SqliteAggregateFunction.html)
1170/// trait as a type parameter as shown in the examples below.
1171///
1172/// ```rust
1173/// # extern crate diesel;
1174/// # use diesel::*;
1175/// #
1176/// # #[cfg(feature = "sqlite")]
1177/// # fn main() {
1178/// #   run().unwrap();
1179/// # }
1180/// #
1181/// # #[cfg(not(feature = "sqlite"))]
1182/// # fn main() {
1183/// # }
1184/// use diesel::sql_types::Integer;
1185/// # #[cfg(feature = "sqlite")]
1186/// use diesel::sqlite::SqliteAggregateFunction;
1187///
1188/// define_sql_function! {
1189///     #[aggregate]
1190///     fn my_sum(x: Integer) -> Integer;
1191/// }
1192///
1193/// #[derive(Default)]
1194/// struct MySum { sum: i32 }
1195///
1196/// # #[cfg(feature = "sqlite")]
1197/// impl SqliteAggregateFunction<i32> for MySum {
1198///     type Output = i32;
1199///
1200///     fn step(&mut self, expr: i32) {
1201///         self.sum += expr;
1202///     }
1203///
1204///     fn finalize(aggregator: Option<Self>) -> Self::Output {
1205///         aggregator.map(|a| a.sum).unwrap_or_default()
1206///     }
1207/// }
1208/// # table! {
1209/// #     players {
1210/// #         id -> Integer,
1211/// #         score -> Integer,
1212/// #     }
1213/// # }
1214///
1215/// # #[cfg(feature = "sqlite")]
1216/// fn run() -> Result<(), Box<dyn (::std::error::Error)>> {
1217/// #    use self::players::dsl::*;
1218///     let connection = &mut SqliteConnection::establish(":memory:")?;
1219/// #    diesel::sql_query("create table players (id integer primary key autoincrement, score integer)")
1220/// #        .execute(connection)
1221/// #        .unwrap();
1222/// #    diesel::sql_query("insert into players (score) values (10), (20), (30)")
1223/// #        .execute(connection)
1224/// #        .unwrap();
1225///
1226///     my_sum_utils::register_impl::<MySum, _>(connection)?;
1227///
1228///     let total_score = players.select(my_sum(score))
1229///         .get_result::<i32>(connection)?;
1230///
1231///     println!("The total score of all the players is: {}", total_score);
1232///
1233/// #    assert_eq!(60, total_score);
1234///     Ok(())
1235/// }
1236/// ```
1237///
1238/// With multiple function arguments, the arguments are passed as a tuple to `SqliteAggregateFunction`
1239///
1240/// ```rust
1241/// # extern crate diesel;
1242/// # use diesel::*;
1243/// #
1244/// # #[cfg(feature = "sqlite")]
1245/// # fn main() {
1246/// #   run().unwrap();
1247/// # }
1248/// #
1249/// # #[cfg(not(feature = "sqlite"))]
1250/// # fn main() {
1251/// # }
1252/// use diesel::sql_types::{Float, Nullable};
1253/// # #[cfg(feature = "sqlite")]
1254/// use diesel::sqlite::SqliteAggregateFunction;
1255///
1256/// define_sql_function! {
1257///     #[aggregate]
1258///     fn range_max(x0: Float, x1: Float) -> Nullable<Float>;
1259/// }
1260///
1261/// #[derive(Default)]
1262/// struct RangeMax<T> { max_value: Option<T> }
1263///
1264/// # #[cfg(feature = "sqlite")]
1265/// impl<T: Default + PartialOrd + Copy + Clone> SqliteAggregateFunction<(T, T)> for RangeMax<T> {
1266///     type Output = Option<T>;
1267///
1268///     fn step(&mut self, (x0, x1): (T, T)) {
1269/// #        let max = if x0 >= x1 {
1270/// #            x0
1271/// #        } else {
1272/// #            x1
1273/// #        };
1274/// #
1275/// #        self.max_value = match self.max_value {
1276/// #            Some(current_max_value) if max > current_max_value => Some(max),
1277/// #            None => Some(max),
1278/// #            _ => self.max_value,
1279/// #        };
1280///         // Compare self.max_value to x0 and x1
1281///     }
1282///
1283///     fn finalize(aggregator: Option<Self>) -> Self::Output {
1284///         aggregator?.max_value
1285///     }
1286/// }
1287/// # table! {
1288/// #     student_avgs {
1289/// #         id -> Integer,
1290/// #         s1_avg -> Float,
1291/// #         s2_avg -> Float,
1292/// #     }
1293/// # }
1294///
1295/// # #[cfg(feature = "sqlite")]
1296/// fn run() -> Result<(), Box<dyn (::std::error::Error)>> {
1297/// #    use self::student_avgs::dsl::*;
1298///     let connection = &mut SqliteConnection::establish(":memory:")?;
1299/// #    diesel::sql_query("create table student_avgs (id integer primary key autoincrement, s1_avg float, s2_avg float)")
1300/// #       .execute(connection)
1301/// #       .unwrap();
1302/// #    diesel::sql_query("insert into student_avgs (s1_avg, s2_avg) values (85.5, 90), (79.8, 80.1)")
1303/// #        .execute(connection)
1304/// #        .unwrap();
1305///
1306///     range_max_utils::register_impl::<RangeMax<f32>, _, _>(connection)?;
1307///
1308///     let result = student_avgs.select(range_max(s1_avg, s2_avg))
1309///         .get_result::<Option<f32>>(connection)?;
1310///
1311///     if let Some(max_semester_avg) = result {
1312///         println!("The largest semester average is: {}", max_semester_avg);
1313///     }
1314///
1315/// #    assert_eq!(Some(90f32), result);
1316///     Ok(())
1317/// }
1318/// ```
1319#[proc_macro]
1320pub fn define_sql_function(input: TokenStream) -> TokenStream {
1321    sql_function::expand(parse_macro_input!(input), false).into()
1322}
1323
1324/// A legacy version of [`define_sql_function!`].
1325///
1326/// The difference is that it makes the helper type available in a module named the exact same as
1327/// the function:
1328///
1329/// ```ignore
1330/// sql_function!(fn lower(x: Text) -> Text);
1331/// ```
1332///
1333/// will generate this code:
1334///
1335/// ```ignore
1336/// pub fn lower<X>(x: X) -> lower::HelperType<X> {
1337///     ...
1338/// }
1339///
1340/// pub(crate) mod lower {
1341///     pub type HelperType<X> = ...;
1342/// }
1343/// ```
1344///
1345/// This turned out to be an issue for the support of the `auto_type` feature, which is why
1346/// [`define_sql_function!`] was introduced (and why this is deprecated).
1347///
1348/// SQL functions declared with this version of the macro will not be usable with `#[auto_type]`
1349/// or `Selectable` `select_expression` type inference.
1350#[deprecated(since = "2.2.0", note = "Use [`define_sql_function`] instead")]
1351#[proc_macro]
1352#[cfg(all(feature = "with-deprecated", not(feature = "without-deprecated")))]
1353pub fn sql_function_proc(input: TokenStream) -> TokenStream {
1354    sql_function::expand(parse_macro_input!(input), true).into()
1355}
1356
1357/// This is an internal diesel macro that
1358/// helps to implement all traits for tuples of
1359/// various sizes
1360#[doc(hidden)]
1361#[proc_macro]
1362pub fn __diesel_for_each_tuple(input: TokenStream) -> TokenStream {
1363    diesel_for_each_tuple::expand(parse_macro_input!(input)).into()
1364}
1365
1366/// This is an internal diesel macro that
1367/// helps to restrict the visibility of an item based
1368/// on a feature flag
1369#[doc(hidden)]
1370#[proc_macro_attribute]
1371pub fn __diesel_public_if(attrs: TokenStream, input: TokenStream) -> TokenStream {
1372    diesel_public_if::expand(parse_macro_input!(attrs), parse_macro_input!(input)).into()
1373}
1374
1375/// Specifies that a table exists, and what columns it has. This will create a
1376/// new public module, with the same name, as the name of the table. In this
1377/// module, you will find a unit struct named `table`, and a unit struct with the
1378/// name of each column.
1379///
1380/// By default, this allows a maximum of 32 columns per table.
1381/// You can increase this limit to 64 by enabling the `64-column-tables` feature.
1382/// You can increase it to 128 by enabling the `128-column-tables` feature.
1383/// You can decrease it to 16 columns,
1384/// which improves compilation time,
1385/// by disabling the default features of Diesel.
1386/// Note that enabling 64 column tables or larger will substantially increase
1387/// the compile time of Diesel.
1388///
1389/// Example usage
1390/// -------------
1391///
1392/// ```rust
1393/// # extern crate diesel;
1394///
1395/// diesel::table! {
1396///     users {
1397///         id -> Integer,
1398///         name -> VarChar,
1399///         favorite_color -> Nullable<VarChar>,
1400///     }
1401/// }
1402/// ```
1403///
1404/// You may also specify a primary key if it is called something other than `id`.
1405/// Tables with no primary key aren't supported.
1406///
1407/// ```rust
1408/// # extern crate diesel;
1409///
1410/// diesel::table! {
1411///     users (non_standard_primary_key) {
1412///         non_standard_primary_key -> Integer,
1413///         name -> VarChar,
1414///         favorite_color -> Nullable<VarChar>,
1415///     }
1416/// }
1417/// ```
1418///
1419/// For tables with composite primary keys, list all the columns in the primary key.
1420///
1421/// ```rust
1422/// # extern crate diesel;
1423///
1424/// diesel::table! {
1425///     followings (user_id, post_id) {
1426///         user_id -> Integer,
1427///         post_id -> Integer,
1428///         favorited -> Bool,
1429///     }
1430/// }
1431/// # fn main() {
1432/// #     use diesel::prelude::Table;
1433/// #     use self::followings::dsl::*;
1434/// #     // Poor man's assert_eq! -- since this is type level this would fail
1435/// #     // to compile if the wrong primary key were generated
1436/// #     let (user_id {}, post_id {}) = followings.primary_key();
1437/// # }
1438/// ```
1439///
1440/// If you are using types that aren't from Diesel's core types, you can specify
1441/// which types to import.
1442///
1443/// ```
1444/// # extern crate diesel;
1445/// # mod diesel_full_text_search {
1446/// #     #[derive(diesel::sql_types::SqlType)]
1447/// #     pub struct TsVector;
1448/// # }
1449///
1450/// diesel::table! {
1451///     use diesel::sql_types::*;
1452/// #    use crate::diesel_full_text_search::*;
1453/// # /*
1454///     use diesel_full_text_search::*;
1455/// # */
1456///
1457///     posts {
1458///         id -> Integer,
1459///         title -> Text,
1460///         keywords -> TsVector,
1461///     }
1462/// }
1463/// # fn main() {}
1464/// ```
1465///
1466/// If you want to add documentation to the generated code, you can use the
1467/// following syntax:
1468///
1469/// ```
1470/// # extern crate diesel;
1471///
1472/// diesel::table! {
1473///     /// The table containing all blog posts
1474///     posts {
1475///         /// The post's unique id
1476///         id -> Integer,
1477///         /// The post's title
1478///         title -> Text,
1479///     }
1480/// }
1481/// ```
1482///
1483/// If you have a column with the same name as a Rust reserved keyword, you can use
1484/// the `sql_name` attribute like this:
1485///
1486/// ```
1487/// # extern crate diesel;
1488///
1489/// diesel::table! {
1490///     posts {
1491///         id -> Integer,
1492///         /// This column is named `mytype` but references the table `type` column.
1493///         #[sql_name = "type"]
1494///         mytype -> Text,
1495///     }
1496/// }
1497/// ```
1498///
1499/// This module will also contain several helper types:
1500///
1501/// dsl
1502/// ---
1503///
1504/// This simply re-exports the table, renamed to the same name as the module,
1505/// and each of the columns. This is useful to glob import when you're dealing
1506/// primarily with one table, to allow writing `users.filter(name.eq("Sean"))`
1507/// instead of `users::table.filter(users::name.eq("Sean"))`.
1508///
1509/// `all_columns`
1510/// -----------
1511///
1512/// A constant will be assigned called `all_columns`. This is what will be
1513/// selected if you don't otherwise specify a select clause. It's type will be
1514/// `table::AllColumns`. You can also get this value from the
1515/// `Table::all_columns` function.
1516///
1517/// star
1518/// ----
1519///
1520/// This will be the qualified "star" expression for this table (e.g.
1521/// `users.*`). Internally, we read columns by index, not by name, so this
1522/// column is not safe to read data out of, and it has had its SQL type set to
1523/// `()` to prevent accidentally using it as such. It is sometimes useful for
1524/// counting statements, however. It can also be accessed through the `Table.star()`
1525/// method.
1526///
1527/// `SqlType`
1528/// -------
1529///
1530/// A type alias called `SqlType` will be created. It will be the SQL type of
1531/// `all_columns`. The SQL type is needed for things like returning boxed
1532/// queries.
1533///
1534/// `BoxedQuery`
1535/// ----------
1536///
1537/// ```ignore
1538/// pub type BoxedQuery<'a, DB, ST = SqlType> = BoxedSelectStatement<'a, ST, table, DB>;
1539/// ```
1540#[proc_macro]
1541pub fn table_proc(input: TokenStream) -> TokenStream {
1542    match syn::parse(input) {
1543        Ok(input) => table::expand(input).into(),
1544        Err(_) => quote::quote! {
1545            compile_error!(
1546                "Invalid `table!` syntax. Please see the `table!` macro docs for more info.\n\
1547                 Docs available at: `https://docs.diesel.rs/master/diesel/macro.table.html`\n"
1548            );
1549        }
1550        .into(),
1551    }
1552}
1553
1554/// This derives implements `diesel::Connection` and related traits for an enum of
1555/// connections to different databases.
1556///
1557/// By applying this derive to such an enum, you can use the enum as a connection type in
1558/// any location all the inner connections are valid. This derive supports enum
1559/// variants containing a single tuple field. Each tuple field type must implement
1560/// `diesel::Connection` and a number of related traits. Connection types form Diesel itself
1561/// as well as third party connection types are supported by this derive.
1562///
1563/// The implementation of `diesel::Connection::establish` tries to establish
1564/// a new connection with the given connection string in the order the connections
1565/// are specified in the enum. If one connection fails, it tries the next one and so on.
1566/// That means that as soon as more than one connection type accepts a certain connection
1567/// string the first matching type in your enum will always establish the connection. This
1568/// is especially important if one of the connection types is `diesel::SqliteConnection`
1569/// as this connection type accepts arbitrary paths. It should normally place as last entry
1570/// in your enum. If you want control of which connection type is created, just construct the
1571/// corresponding enum manually by first establishing the connection via the inner type and then
1572/// wrap the result into the enum.
1573///
1574/// # Example
1575/// ```
1576/// # extern crate diesel;
1577/// # use diesel::result::QueryResult;
1578/// use diesel::prelude::*;
1579///
1580/// #[derive(diesel::MultiConnection)]
1581/// pub enum AnyConnection {
1582/// #   #[cfg(feature = "postgres")]
1583///     Postgresql(diesel::PgConnection),
1584/// #   #[cfg(feature = "mysql")]
1585///     Mysql(diesel::MysqlConnection),
1586/// #   #[cfg(feature = "sqlite")]
1587///     Sqlite(diesel::SqliteConnection),
1588/// }
1589///
1590/// diesel::table! {
1591///     users {
1592///         id -> Integer,
1593///         name -> Text,
1594///     }
1595/// }
1596///
1597/// fn use_multi(conn: &mut AnyConnection) -> QueryResult<()> {
1598///    // Use the connection enum as any other connection type
1599///    // for inserting/updating/loading/…
1600///    diesel::insert_into(users::table)
1601///        .values(users::name.eq("Sean"))
1602///        .execute(conn)?;
1603///
1604///    let users = users::table.load::<(i32, String)>(conn)?;
1605///
1606///    // Match on the connection type to access
1607///    // the inner connection. This allows us then to use
1608///    // backend specific methods.
1609/// #    #[cfg(feature = "postgres")]
1610///    if let AnyConnection::Postgresql(ref mut conn) = conn {
1611///        // perform a postgresql specific query here
1612///        let users = users::table.load::<(i32, String)>(conn)?;
1613///    }
1614///
1615///    Ok(())
1616/// }
1617///
1618/// # fn main() {}
1619/// ```
1620///
1621/// # Limitations
1622///
1623/// The derived connection implementation can only cover the common subset of
1624/// all inner connection types. So, if one backend doesn't support certain SQL features,
1625/// like for example, returning clauses, the whole connection implementation doesn't
1626/// support this feature. In addition, only a limited set of SQL types is supported:
1627///
1628/// * `diesel::sql_types::SmallInt`
1629/// * `diesel::sql_types::Integer`
1630/// * `diesel::sql_types::BigInt`
1631/// * `diesel::sql_types::Double`
1632/// * `diesel::sql_types::Float`
1633/// * `diesel::sql_types::Text`
1634/// * `diesel::sql_types::Date`
1635/// * `diesel::sql_types::Time`
1636/// * `diesel::sql_types::Timestamp`
1637///
1638/// Support for additional types can be added by providing manual implementations of
1639/// `HasSqlType`, `FromSql` and `ToSql` for the corresponding type, all databases included
1640/// in your enum, and the backend generated by this derive called `MultiBackend`.
1641/// For example to support a custom enum `MyEnum` with the custom SQL type `MyInteger`:
1642/// ```
1643/// extern crate diesel;
1644/// use diesel::backend::Backend;
1645/// use diesel::deserialize::{self, FromSql, FromSqlRow};
1646/// use diesel::serialize::{self, IsNull, ToSql};
1647/// use diesel::AsExpression;
1648/// use diesel::sql_types::{HasSqlType, SqlType};
1649/// use diesel::prelude::*;
1650///
1651/// #[derive(diesel::MultiConnection)]
1652/// pub enum AnyConnection {
1653/// #   #[cfg(feature = "postgres")]
1654///     Postgresql(diesel::PgConnection),
1655/// #   #[cfg(feature = "mysql")]
1656///     Mysql(diesel::MysqlConnection),
1657/// #   #[cfg(feature = "sqlite")]
1658///     Sqlite(diesel::SqliteConnection),
1659/// }
1660///
1661/// // defining an custom SQL type is optional
1662/// // you can also use types from `diesel::sql_types`
1663/// #[derive(Copy, Clone, Debug, SqlType)]
1664/// #[diesel(postgres_type(name = "Int4"))]
1665/// #[diesel(mysql_type(name = "Long"))]
1666/// #[diesel(sqlite_type(name = "Integer"))]
1667/// struct MyInteger;
1668///
1669///
1670/// // our custom enum
1671/// #[repr(i32)]
1672/// #[derive(Debug, Clone, Copy, AsExpression, FromSqlRow)]
1673/// #[diesel(sql_type = MyInteger)]
1674/// pub enum MyEnum {
1675///     A = 1,
1676///     B = 2,
1677/// }
1678///
1679/// // The `MultiBackend` type is generated by `#[derive(diesel::MultiConnection)]`
1680/// // This part is only required if you define a custom sql type
1681/// impl HasSqlType<MyInteger> for MultiBackend {
1682///    fn metadata(lookup: &mut Self::MetadataLookup) -> Self::TypeMetadata {
1683///        // The `lookup_sql_type` function is exposed by the `MultiBackend` type
1684///        MultiBackend::lookup_sql_type::<MyInteger>(lookup)
1685///    }
1686/// }
1687///
1688/// impl FromSql<MyInteger, MultiBackend> for MyEnum {
1689///    fn from_sql(bytes: <MultiBackend as Backend>::RawValue<'_>) -> deserialize::Result<Self> {
1690///        // The `from_sql` function is exposed by the `RawValue` type of the
1691///        // `MultiBackend` type
1692///        // This requires a `FromSql` impl for each backend
1693///        bytes.from_sql::<MyEnum, MyInteger>()
1694///    }
1695/// }
1696///
1697/// impl ToSql<MyInteger, MultiBackend> for MyEnum {
1698///    fn to_sql<'b>(&'b self, out: &mut serialize::Output<'b, '_, MultiBackend>) -> serialize::Result {
1699///        /// `set_value` expects a tuple consisting of the target SQL type
1700///        /// and self for `MultiBackend`
1701///        /// This requires a `ToSql` impl for each backend
1702///        out.set_value((MyInteger, self));
1703///        Ok(IsNull::No)
1704///    }
1705/// }
1706/// # #[cfg(feature = "postgres")]
1707/// # impl ToSql<MyInteger, diesel::pg::Pg> for MyEnum {
1708/// #    fn to_sql<'b>(&'b self, out: &mut serialize::Output<'b, '_, diesel::pg::Pg>) -> serialize::Result { todo!() }
1709/// # }
1710/// # #[cfg(feature = "mysql")]
1711/// # impl ToSql<MyInteger, diesel::mysql::Mysql> for MyEnum {
1712/// #    fn to_sql<'b>(&'b self, out: &mut serialize::Output<'b, '_, diesel::mysql::Mysql>) -> serialize::Result { todo!() }
1713/// # }
1714/// # #[cfg(feature = "sqlite")]
1715/// # impl ToSql<MyInteger, diesel::sqlite::Sqlite> for MyEnum {
1716/// #    fn to_sql<'b>(&'b self, out: &mut serialize::Output<'b, '_, diesel::sqlite::Sqlite>) -> serialize::Result { todo!() }
1717/// # }
1718/// # #[cfg(feature = "postgres")]
1719/// # impl FromSql<MyInteger, diesel::pg::Pg> for MyEnum {
1720/// #    fn from_sql(bytes: <diesel::pg::Pg as Backend>::RawValue<'_>) -> deserialize::Result<Self> { todo!() }
1721/// # }
1722/// # #[cfg(feature = "mysql")]
1723/// # impl FromSql<MyInteger, diesel::mysql::Mysql> for MyEnum {
1724/// #    fn from_sql(bytes: <diesel::mysql::Mysql as Backend>::RawValue<'_>) -> deserialize::Result<Self> { todo!() }
1725/// # }
1726/// # #[cfg(feature = "sqlite")]
1727/// # impl FromSql<MyInteger, diesel::sqlite::Sqlite> for MyEnum {
1728/// #    fn from_sql(bytes: <diesel::sqlite::Sqlite as Backend>::RawValue<'_>) -> deserialize::Result<Self> { todo!() }
1729/// # }
1730/// # fn main() {}
1731/// ```
1732#[proc_macro_derive(MultiConnection)]
1733pub fn derive_multiconnection(input: TokenStream) -> TokenStream {
1734    multiconnection::derive(syn::parse_macro_input!(input)).into()
1735}
1736
1737/// Automatically annotates return type of a query fragment function
1738///
1739/// This may be useful when factoring out common query fragments into functions.
1740/// If not using this, it would typically involve explicitly writing the full
1741/// type of the query fragment function, which depending on the length of said
1742/// query fragment can be quite difficult (especially to maintain) and verbose.
1743///
1744/// # Example
1745///
1746/// ```rust
1747/// # extern crate diesel;
1748/// # include!("../../diesel/src/doctest_setup.rs");
1749/// # use schema::{users, posts};
1750/// use diesel::dsl;
1751///
1752/// # fn main() {
1753/// #     run_test().unwrap();
1754/// # }
1755/// #
1756/// # fn run_test() -> QueryResult<()> {
1757/// #     let conn = &mut establish_connection();
1758/// #
1759/// #[dsl::auto_type]
1760/// fn user_has_post() -> _ {
1761///     dsl::exists(posts::table.filter(posts::user_id.eq(users::id)))
1762/// }
1763///
1764/// let users_with_posts: Vec<String> = users::table
1765///     .filter(user_has_post())
1766///     .select(users::name)
1767///     .load(conn)?;
1768///
1769/// assert_eq!(
1770///     &["Sean", "Tess"] as &[_],
1771///     users_with_posts
1772///         .iter()
1773///         .map(|s| s.as_str())
1774///         .collect::<Vec<_>>()
1775/// );
1776/// #     Ok(())
1777/// # }
1778/// ```
1779/// # Limitations
1780///
1781/// While this attribute tries to support as much of diesels built-in DSL as possible it's
1782/// unfortunately not possible to support everything. Notable unsupported types are:
1783///
1784/// * Update statements
1785/// * Insert from select statements
1786/// * Query constructed by `diesel::sql_query`
1787/// * Expressions using `diesel::dsl::sql`
1788///
1789/// For these cases a manual type annotation is required. See the "Annotating Types" section below
1790/// for details.
1791///
1792///
1793/// # Advanced usage
1794///
1795/// By default, the macro will:
1796///  - Generate a type alias for the return type of the function, named the
1797///    exact same way as the function itself.
1798///  - Assume that functions, unless otherwise annotated, have a type alias for
1799///    their return type available at the same path as the function itself
1800///    (including case). (e.g. for the `dsl::not(x)` call, it expects that there
1801///    is a `dsl::not<X>` type alias available)
1802///  - Assume that methods, unless otherwise annotated, have a type alias
1803///    available as `diesel::dsl::PascalCaseOfMethodName` (e.g. for the
1804///    `x.and(y)` call, it expects that there is a `diesel::dsl::And<X, Y>` type
1805///    alias available)
1806///
1807/// The defaults can be changed by passing the following attributes to the
1808/// macro:
1809/// - `#[auto_type(no_type_alias)]` to disable the generation of the type alias.
1810/// - `#[auto_type(dsl_path = "path::to::dsl")]` to change the path where the
1811///     macro will look for type aliases for methods. This is required if you mix your own
1812///   custom query dsl extensions with diesel types. In that case, you may use this argument to
1813///   reference a module defined like so:
1814///   ```ignore
1815///   mod dsl {
1816///       /// export all of diesel dsl
1817///       pub use diesel::dsl::*;
1818///    
1819///       /// Export your extension types here
1820///       pub use crate::your_extension::dsl::YourType;
1821///    }
1822///    ```
1823/// - `#[auto_type(method_type_case = "snake_case")]` to change the case of the
1824///   method type alias.
1825/// - `#[auto_type(function_type_case = "snake_case")]` to change the case of
1826///   the function type alias (if you don't want the exact same path but want to
1827///   change the case of the last element of the path).
1828///
1829/// The `dsl_path` attribute in particular may be used to declare an
1830/// intermediate module where you would define the few additional needed type
1831/// aliases that can't be inferred automatically.
1832///
1833/// ## Annotating types
1834///
1835/// Sometimes the macro can't infer the type of a particular sub-expression. In
1836/// that case, you can annotate the type of the sub-expression:
1837///
1838/// ```rust
1839/// # extern crate diesel;
1840/// # include!("../../diesel/src/doctest_setup.rs");
1841/// # use schema::{users, posts};
1842/// use diesel::dsl;
1843///
1844/// # fn main() {
1845/// #     run_test().unwrap();
1846/// # }
1847/// #
1848/// # fn run_test() -> QueryResult<()> {
1849/// #     let conn = &mut establish_connection();
1850/// #
1851/// // This will generate a `user_has_post_with_id_greater_than` type alias
1852/// #[dsl::auto_type]
1853/// fn user_has_post_with_id_greater_than(id_greater_than: i32) -> _ {
1854///     dsl::exists(
1855///         posts::table
1856///             .filter(posts::user_id.eq(users::id))
1857///             .filter(posts::id.gt(id_greater_than)),
1858///     )
1859/// }
1860///
1861/// #[dsl::auto_type]
1862/// fn users_with_posts_with_id_greater_than(id_greater_than: i32) -> _ {
1863///     // If we didn't specify the type for this query fragment, the macro would infer it as
1864///     // `user_has_post_with_id_greater_than<i32>`, which would be incorrect because there is
1865///     // no generic parameter.
1866///     let filter: user_has_post_with_id_greater_than =
1867///         user_has_post_with_id_greater_than(id_greater_than);
1868///     // The macro inferring that it has to pass generic parameters is still the convention
1869///     // because it's the most general case, as well as the common case within Diesel itself,
1870///     // and because annotating this way is reasonably simple, while the other way around
1871///     // would be hard.
1872///
1873///     users::table.filter(filter).select(users::name)
1874/// }
1875///
1876/// let users_with_posts: Vec<String> = users_with_posts_with_id_greater_than(2).load(conn)?;
1877///
1878/// assert_eq!(
1879///     &["Tess"] as &[_],
1880///     users_with_posts
1881///         .iter()
1882///         .map(|s| s.as_str())
1883///         .collect::<Vec<_>>()
1884/// );
1885/// #     Ok(())
1886/// # }
1887/// ```
1888#[proc_macro_attribute]
1889pub fn auto_type(
1890    attr: proc_macro::TokenStream,
1891    input: proc_macro::TokenStream,
1892) -> proc_macro::TokenStream {
1893    dsl_auto_type::auto_type_proc_macro_attribute(
1894        proc_macro2::TokenStream::from(attr),
1895        proc_macro2::TokenStream::from(input),
1896        dsl_auto_type::DeriveSettings::builder()
1897            .default_dsl_path(parse_quote!(diesel::dsl))
1898            .default_generate_type_alias(true)
1899            .default_method_type_case(AUTO_TYPE_DEFAULT_METHOD_TYPE_CASE)
1900            .default_function_type_case(AUTO_TYPE_DEFAULT_FUNCTION_TYPE_CASE)
1901            .build(),
1902    )
1903    .into()
1904}
1905
1906const AUTO_TYPE_DEFAULT_METHOD_TYPE_CASE: dsl_auto_type::Case = dsl_auto_type::Case::UpperCamel;
1907const AUTO_TYPE_DEFAULT_FUNCTION_TYPE_CASE: dsl_auto_type::Case = dsl_auto_type::Case::DoNotChange;