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