sea_orm_macros/lib.rs
1extern crate proc_macro;
2
3use proc_macro::TokenStream;
4
5use syn::{parse_macro_input, DeriveInput, Error};
6
7#[cfg(feature = "derive")]
8mod derives;
9
10#[cfg(feature = "strum")]
11mod strum;
12
13/// Create an Entity
14///
15/// ### Usage
16///
17/// ```
18/// use sea_orm::entity::prelude::*;
19///
20/// #[derive(Copy, Clone, Default, Debug, DeriveEntity)]
21/// pub struct Entity;
22///
23/// # impl EntityName for Entity {
24/// # fn table_name(&self) -> &str {
25/// # "cake"
26/// # }
27/// # }
28/// #
29/// # #[derive(Clone, Debug, PartialEq, DeriveModel, DeriveActiveModel)]
30/// # pub struct Model {
31/// # pub id: i32,
32/// # pub name: String,
33/// # }
34/// #
35/// # #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
36/// # pub enum Column {
37/// # Id,
38/// # Name,
39/// # }
40/// #
41/// # #[derive(Copy, Clone, Debug, EnumIter, DerivePrimaryKey)]
42/// # pub enum PrimaryKey {
43/// # Id,
44/// # }
45/// #
46/// # impl PrimaryKeyTrait for PrimaryKey {
47/// # type ValueType = i32;
48/// #
49/// # fn auto_increment() -> bool {
50/// # true
51/// # }
52/// # }
53/// #
54/// # #[derive(Copy, Clone, Debug, EnumIter)]
55/// # pub enum Relation {}
56/// #
57/// # impl ColumnTrait for Column {
58/// # type EntityName = Entity;
59/// #
60/// # fn def(&self) -> ColumnDef {
61/// # match self {
62/// # Self::Id => ColumnType::Integer.def(),
63/// # Self::Name => ColumnType::String(StringLen::None).def(),
64/// # }
65/// # }
66/// # }
67/// #
68/// # impl RelationTrait for Relation {
69/// # fn def(&self) -> RelationDef {
70/// # panic!("No Relation");
71/// # }
72/// # }
73/// #
74/// # impl ActiveModelBehavior for ActiveModel {}
75/// ```
76#[cfg(feature = "derive")]
77#[proc_macro_derive(DeriveEntity, attributes(sea_orm))]
78pub fn derive_entity(input: TokenStream) -> TokenStream {
79 let input = parse_macro_input!(input as DeriveInput);
80 derives::expand_derive_entity(input)
81 .unwrap_or_else(Error::into_compile_error)
82 .into()
83}
84
85/// This derive macro is the 'almighty' macro which automatically generates
86/// Entity, Column, and PrimaryKey from a given Model.
87///
88/// ### Usage
89///
90/// ```
91/// use sea_orm::entity::prelude::*;
92/// use serde::{Deserialize, Serialize};
93///
94/// #[derive(Clone, Debug, PartialEq, DeriveEntityModel, Deserialize, Serialize)]
95/// #[sea_orm(table_name = "posts")]
96/// pub struct Model {
97/// #[sea_orm(primary_key)]
98/// pub id: i32,
99/// pub title: String,
100/// #[sea_orm(column_type = "Text")]
101/// pub text: String,
102/// }
103///
104/// # #[derive(Copy, Clone, Debug, EnumIter)]
105/// # pub enum Relation {}
106/// #
107/// # impl RelationTrait for Relation {
108/// # fn def(&self) -> RelationDef {
109/// # panic!("No Relation");
110/// # }
111/// # }
112/// #
113/// # impl ActiveModelBehavior for ActiveModel {}
114/// ```
115///
116/// Entity should always have a primary key.
117/// Or, it will result in a compile error.
118/// See <https://github.com/SeaQL/sea-orm/issues/485> for details.
119///
120/// ```compile_fail
121/// use sea_orm::entity::prelude::*;
122///
123/// #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
124/// #[sea_orm(table_name = "posts")]
125/// pub struct Model {
126/// pub title: String,
127/// #[sea_orm(column_type = "Text")]
128/// pub text: String,
129/// }
130///
131/// # #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
132/// # pub enum Relation {}
133/// #
134/// # impl ActiveModelBehavior for ActiveModel {}
135/// ```
136#[cfg(feature = "derive")]
137#[proc_macro_derive(DeriveEntityModel, attributes(sea_orm))]
138pub fn derive_entity_model(input: TokenStream) -> TokenStream {
139 let input_ts = input.clone();
140 let DeriveInput {
141 ident, data, attrs, ..
142 } = parse_macro_input!(input as DeriveInput);
143
144 if ident != "Model" {
145 panic!("Struct name must be Model");
146 }
147
148 let mut ts: TokenStream = derives::expand_derive_entity_model(data, attrs)
149 .unwrap_or_else(Error::into_compile_error)
150 .into();
151 ts.extend([
152 derive_model(input_ts.clone()),
153 derive_active_model(input_ts),
154 ]);
155 ts
156}
157
158/// The DerivePrimaryKey derive macro will implement [PrimaryKeyToColumn]
159/// for PrimaryKey which defines tedious mappings between primary keys and columns.
160/// The [EnumIter] is also derived, allowing iteration over all enum variants.
161///
162/// ### Usage
163///
164/// ```
165/// use sea_orm::entity::prelude::*;
166///
167/// #[derive(Copy, Clone, Debug, EnumIter, DerivePrimaryKey)]
168/// pub enum PrimaryKey {
169/// CakeId,
170/// FillingId,
171/// }
172///
173/// # #[derive(Copy, Clone, Default, Debug, DeriveEntity)]
174/// # pub struct Entity;
175/// #
176/// # impl EntityName for Entity {
177/// # fn table_name(&self) -> &str {
178/// # "cake"
179/// # }
180/// # }
181/// #
182/// # #[derive(Clone, Debug, PartialEq, DeriveModel, DeriveActiveModel)]
183/// # pub struct Model {
184/// # pub cake_id: i32,
185/// # pub filling_id: i32,
186/// # }
187/// #
188/// # #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
189/// # pub enum Column {
190/// # CakeId,
191/// # FillingId,
192/// # }
193/// #
194/// # #[derive(Copy, Clone, Debug, EnumIter)]
195/// # pub enum Relation {}
196/// #
197/// # impl ColumnTrait for Column {
198/// # type EntityName = Entity;
199/// #
200/// # fn def(&self) -> ColumnDef {
201/// # match self {
202/// # Self::CakeId => ColumnType::Integer.def(),
203/// # Self::FillingId => ColumnType::Integer.def(),
204/// # }
205/// # }
206/// # }
207/// #
208/// # impl PrimaryKeyTrait for PrimaryKey {
209/// # type ValueType = (i32, i32);
210/// #
211/// # fn auto_increment() -> bool {
212/// # false
213/// # }
214/// # }
215/// #
216/// # impl RelationTrait for Relation {
217/// # fn def(&self) -> RelationDef {
218/// # panic!("No Relation");
219/// # }
220/// # }
221/// #
222/// # impl ActiveModelBehavior for ActiveModel {}
223/// ```
224#[cfg(feature = "derive")]
225#[proc_macro_derive(DerivePrimaryKey, attributes(sea_orm))]
226pub fn derive_primary_key(input: TokenStream) -> TokenStream {
227 let DeriveInput { ident, data, .. } = parse_macro_input!(input);
228
229 match derives::expand_derive_primary_key(ident, data) {
230 Ok(ts) => ts.into(),
231 Err(e) => e.to_compile_error().into(),
232 }
233}
234
235/// The DeriveColumn derive macro will implement [ColumnTrait] for Columns.
236/// It defines the identifier of each column by implementing Iden and IdenStatic.
237/// The EnumIter is also derived, allowing iteration over all enum variants.
238///
239/// ### Usage
240///
241/// ```
242/// use sea_orm::entity::prelude::*;
243///
244/// #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
245/// pub enum Column {
246/// CakeId,
247/// FillingId,
248/// }
249/// ```
250#[cfg(feature = "derive")]
251#[proc_macro_derive(DeriveColumn, attributes(sea_orm))]
252pub fn derive_column(input: TokenStream) -> TokenStream {
253 let DeriveInput { ident, data, .. } = parse_macro_input!(input);
254
255 match derives::expand_derive_column(&ident, &data) {
256 Ok(ts) => ts.into(),
257 Err(e) => e.to_compile_error().into(),
258 }
259}
260
261/// Derive a column if column names are not in snake-case
262///
263/// ### Usage
264///
265/// ```
266/// use sea_orm::entity::prelude::*;
267///
268/// #[derive(Copy, Clone, Debug, EnumIter, DeriveCustomColumn)]
269/// pub enum Column {
270/// Id,
271/// Name,
272/// VendorId,
273/// }
274///
275/// impl IdenStatic for Column {
276/// fn as_str(&self) -> &str {
277/// match self {
278/// Self::Id => "id",
279/// _ => self.default_as_str(),
280/// }
281/// }
282/// }
283/// ```
284#[cfg(feature = "derive")]
285#[proc_macro_derive(DeriveCustomColumn)]
286pub fn derive_custom_column(input: TokenStream) -> TokenStream {
287 let DeriveInput { ident, data, .. } = parse_macro_input!(input);
288
289 match derives::expand_derive_custom_column(&ident, &data) {
290 Ok(ts) => ts.into(),
291 Err(e) => e.to_compile_error().into(),
292 }
293}
294
295/// The DeriveModel derive macro will implement ModelTrait for Model,
296/// which provides setters and getters for all attributes in the mod
297/// It also implements FromQueryResult to convert a query result into the corresponding Model.
298///
299/// ### Usage
300///
301/// ```
302/// use sea_orm::entity::prelude::*;
303///
304/// #[derive(Clone, Debug, PartialEq, DeriveModel, DeriveActiveModel)]
305/// pub struct Model {
306/// pub id: i32,
307/// pub name: String,
308/// }
309///
310/// # #[derive(Copy, Clone, Default, Debug, DeriveEntity)]
311/// # pub struct Entity;
312/// #
313/// # impl EntityName for Entity {
314/// # fn table_name(&self) -> &str {
315/// # "cake"
316/// # }
317/// # }
318/// #
319/// # #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
320/// # pub enum Column {
321/// # Id,
322/// # Name,
323/// # }
324/// #
325/// # #[derive(Copy, Clone, Debug, EnumIter, DerivePrimaryKey)]
326/// # pub enum PrimaryKey {
327/// # Id,
328/// # }
329/// #
330/// # impl PrimaryKeyTrait for PrimaryKey {
331/// # type ValueType = i32;
332/// #
333/// # fn auto_increment() -> bool {
334/// # true
335/// # }
336/// # }
337/// #
338/// # #[derive(Copy, Clone, Debug, EnumIter)]
339/// # pub enum Relation {}
340/// #
341/// # impl ColumnTrait for Column {
342/// # type EntityName = Entity;
343/// #
344/// # fn def(&self) -> ColumnDef {
345/// # match self {
346/// # Self::Id => ColumnType::Integer.def(),
347/// # Self::Name => ColumnType::String(StringLen::None).def(),
348/// # }
349/// # }
350/// # }
351/// #
352/// # impl RelationTrait for Relation {
353/// # fn def(&self) -> RelationDef {
354/// # panic!("No Relation");
355/// # }
356/// # }
357/// #
358/// # impl ActiveModelBehavior for ActiveModel {}
359/// ```
360#[cfg(feature = "derive")]
361#[proc_macro_derive(DeriveModel, attributes(sea_orm))]
362pub fn derive_model(input: TokenStream) -> TokenStream {
363 let input = parse_macro_input!(input as DeriveInput);
364 derives::expand_derive_model(input)
365 .unwrap_or_else(Error::into_compile_error)
366 .into()
367}
368
369/// The DeriveActiveModel derive macro will implement ActiveModelTrait for ActiveModel
370/// which provides setters and getters for all active values in the active model.
371///
372/// ### Usage
373///
374/// ```
375/// use sea_orm::entity::prelude::*;
376///
377/// #[derive(Clone, Debug, PartialEq, DeriveModel, DeriveActiveModel)]
378/// pub struct Model {
379/// pub id: i32,
380/// pub name: String,
381/// }
382///
383/// # #[derive(Copy, Clone, Default, Debug, DeriveEntity)]
384/// # pub struct Entity;
385/// #
386/// # impl EntityName for Entity {
387/// # fn table_name(&self) -> &str {
388/// # "cake"
389/// # }
390/// # }
391/// #
392/// # #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
393/// # pub enum Column {
394/// # Id,
395/// # Name,
396/// # }
397/// #
398/// # #[derive(Copy, Clone, Debug, EnumIter, DerivePrimaryKey)]
399/// # pub enum PrimaryKey {
400/// # Id,
401/// # }
402/// #
403/// # impl PrimaryKeyTrait for PrimaryKey {
404/// # type ValueType = i32;
405/// #
406/// # fn auto_increment() -> bool {
407/// # true
408/// # }
409/// # }
410/// #
411/// # #[derive(Copy, Clone, Debug, EnumIter)]
412/// # pub enum Relation {}
413/// #
414/// # impl ColumnTrait for Column {
415/// # type EntityName = Entity;
416/// #
417/// # fn def(&self) -> ColumnDef {
418/// # match self {
419/// # Self::Id => ColumnType::Integer.def(),
420/// # Self::Name => ColumnType::String(StringLen::None).def(),
421/// # }
422/// # }
423/// # }
424/// #
425/// # impl RelationTrait for Relation {
426/// # fn def(&self) -> RelationDef {
427/// # panic!("No Relation");
428/// # }
429/// # }
430/// #
431/// # impl ActiveModelBehavior for ActiveModel {}
432/// ```
433#[cfg(feature = "derive")]
434#[proc_macro_derive(DeriveActiveModel, attributes(sea_orm))]
435pub fn derive_active_model(input: TokenStream) -> TokenStream {
436 let DeriveInput { ident, data, .. } = parse_macro_input!(input);
437
438 match derives::expand_derive_active_model(ident, data) {
439 Ok(ts) => ts.into(),
440 Err(e) => e.to_compile_error().into(),
441 }
442}
443
444/// Derive into an active model
445#[cfg(feature = "derive")]
446#[proc_macro_derive(DeriveIntoActiveModel, attributes(sea_orm))]
447pub fn derive_into_active_model(input: TokenStream) -> TokenStream {
448 let input = parse_macro_input!(input as DeriveInput);
449 derives::expand_into_active_model(input)
450 .unwrap_or_else(Error::into_compile_error)
451 .into()
452}
453
454/// Models that a user can override
455///
456/// ### Usage
457///
458/// ```
459/// use sea_orm::entity::prelude::*;
460///
461/// #[derive(
462/// Clone, Debug, PartialEq, DeriveModel, DeriveActiveModel, DeriveActiveModelBehavior,
463/// )]
464/// pub struct Model {
465/// pub id: i32,
466/// pub name: String,
467/// }
468///
469/// # #[derive(Copy, Clone, Default, Debug, DeriveEntity)]
470/// # pub struct Entity;
471/// #
472/// # impl EntityName for Entity {
473/// # fn table_name(&self) -> &str {
474/// # "cake"
475/// # }
476/// # }
477/// #
478/// # #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
479/// # pub enum Column {
480/// # Id,
481/// # Name,
482/// # }
483/// #
484/// # #[derive(Copy, Clone, Debug, EnumIter, DerivePrimaryKey)]
485/// # pub enum PrimaryKey {
486/// # Id,
487/// # }
488/// #
489/// # impl PrimaryKeyTrait for PrimaryKey {
490/// # type ValueType = i32;
491/// #
492/// # fn auto_increment() -> bool {
493/// # true
494/// # }
495/// # }
496/// #
497/// # #[derive(Copy, Clone, Debug, EnumIter)]
498/// # pub enum Relation {}
499/// #
500/// # impl ColumnTrait for Column {
501/// # type EntityName = Entity;
502/// #
503/// # fn def(&self) -> ColumnDef {
504/// # match self {
505/// # Self::Id => ColumnType::Integer.def(),
506/// # Self::Name => ColumnType::String(StringLen::None).def(),
507/// # }
508/// # }
509/// # }
510/// #
511/// # impl RelationTrait for Relation {
512/// # fn def(&self) -> RelationDef {
513/// # panic!("No Relation");
514/// # }
515/// # }
516/// ```
517#[cfg(feature = "derive")]
518#[proc_macro_derive(DeriveActiveModelBehavior)]
519pub fn derive_active_model_behavior(input: TokenStream) -> TokenStream {
520 let DeriveInput { ident, data, .. } = parse_macro_input!(input);
521
522 match derives::expand_derive_active_model_behavior(ident, data) {
523 Ok(ts) => ts.into(),
524 Err(e) => e.to_compile_error().into(),
525 }
526}
527
528/// A derive macro to implement `sea_orm::ActiveEnum` trait for enums.
529///
530/// # Limitations
531///
532/// This derive macros can only be used on enums.
533///
534/// # Macro Attributes
535///
536/// All macro attributes listed below have to be annotated in the form of `#[sea_orm(attr = value)]`.
537///
538/// - For enum
539/// - `rs_type`: Define `ActiveEnum::Value`
540/// - Possible values: `String`, `i8`, `i16`, `i32`, `i64`, `u8`, `u16`, `u32`, `u64`
541/// - Note that value has to be passed as string, i.e. `rs_type = "i8"`
542/// - `db_type`: Define `ColumnType` returned by `ActiveEnum::db_type()`
543/// - Possible values: all available enum variants of `ColumnType`, e.g. `String(StringLen::None)`, `String(StringLen::N(1))`, `Integer`
544/// - Note that value has to be passed as string, i.e. `db_type = "Integer"`
545/// - `enum_name`: Define `String` returned by `ActiveEnum::name()`
546/// - This attribute is optional with default value being the name of enum in camel-case
547/// - Note that value has to be passed as string, i.e. `enum_name = "MyEnum"`
548///
549/// - For enum variant
550/// - `string_value` or `num_value`:
551/// - For `string_value`, value should be passed as string, i.e. `string_value = "A"`
552/// - Due to the way internal Enums are automatically derived, the following restrictions apply:
553/// - members cannot share identical `string_value`, case-insensitive.
554/// - in principle, any future Titlecased Rust keywords are not valid `string_value`.
555/// - For `num_value`, value should be passed as integer, i.e. `num_value = 1` or `num_value = 1i32`
556/// - Note that only one of it can be specified, and all variants of an enum have to annotate with the same `*_value` macro attribute
557///
558/// # Usage
559///
560/// ```
561/// use sea_orm::{entity::prelude::*, DeriveActiveEnum};
562///
563/// #[derive(EnumIter, DeriveActiveEnum)]
564/// #[sea_orm(rs_type = "i32", db_type = "Integer")]
565/// pub enum Color {
566/// Black = 0,
567/// White = 1,
568/// }
569/// ```
570#[cfg(feature = "derive")]
571#[proc_macro_derive(DeriveActiveEnum, attributes(sea_orm))]
572pub fn derive_active_enum(input: TokenStream) -> TokenStream {
573 let input = parse_macro_input!(input as DeriveInput);
574 match derives::expand_derive_active_enum(input) {
575 Ok(ts) => ts.into(),
576 Err(e) => e.to_compile_error().into(),
577 }
578}
579
580/// Convert a query result into the corresponding Model.
581///
582/// ### Attributes
583/// - `skip`: Will not try to pull this field from the query result. And set it to the default value of the type.
584///
585/// ### Usage
586///
587/// ```
588/// use sea_orm::{entity::prelude::*, FromQueryResult};
589///
590/// #[derive(Debug, FromQueryResult)]
591/// struct SelectResult {
592/// name: String,
593/// num_of_fruits: i32,
594/// #[sea_orm(skip)]
595/// skip_me: i32,
596/// }
597/// ```
598#[cfg(feature = "derive")]
599#[proc_macro_derive(FromQueryResult, attributes(sea_orm))]
600pub fn derive_from_query_result(input: TokenStream) -> TokenStream {
601 let DeriveInput {
602 ident,
603 data,
604 generics,
605 ..
606 } = parse_macro_input!(input);
607
608 match derives::expand_derive_from_query_result(ident, data, generics) {
609 Ok(ts) => ts.into(),
610 Err(e) => e.to_compile_error().into(),
611 }
612}
613
614/// The DeriveRelation derive macro will implement RelationTrait for Relation.
615///
616/// ### Usage
617///
618/// ```
619/// # use sea_orm::tests_cfg::fruit::Entity;
620/// use sea_orm::entity::prelude::*;
621///
622/// #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
623/// pub enum Relation {
624/// #[sea_orm(
625/// belongs_to = "sea_orm::tests_cfg::cake::Entity",
626/// from = "sea_orm::tests_cfg::fruit::Column::CakeId",
627/// to = "sea_orm::tests_cfg::cake::Column::Id"
628/// )]
629/// Cake,
630/// #[sea_orm(
631/// belongs_to = "sea_orm::tests_cfg::cake_expanded::Entity",
632/// from = "sea_orm::tests_cfg::fruit::Column::CakeId",
633/// to = "sea_orm::tests_cfg::cake_expanded::Column::Id"
634/// )]
635/// CakeExpanded,
636/// }
637/// ```
638#[cfg(feature = "derive")]
639#[proc_macro_derive(DeriveRelation, attributes(sea_orm))]
640pub fn derive_relation(input: TokenStream) -> TokenStream {
641 let input = parse_macro_input!(input as DeriveInput);
642 derives::expand_derive_relation(input)
643 .unwrap_or_else(Error::into_compile_error)
644 .into()
645}
646
647/// The DeriveRelatedEntity derive macro will implement seaography::RelationBuilder for RelatedEntity enumeration.
648///
649/// ### Usage
650///
651/// ```ignore
652/// use sea_orm::entity::prelude::*;
653///
654/// // ...
655/// // Model, Relation enum, etc.
656/// // ...
657///
658/// #[derive(Copy, Clone, Debug, EnumIter, DeriveRelatedEntity)]
659/// pub enum RelatedEntity {
660/// #[sea_orm(entity = "super::address::Entity")]
661/// Address,
662/// #[sea_orm(entity = "super::payment::Entity")]
663/// Payment,
664/// #[sea_orm(entity = "super::rental::Entity")]
665/// Rental,
666/// #[sea_orm(entity = "Entity", def = "Relation::SelfRef.def()")]
667/// SelfRef,
668/// #[sea_orm(entity = "super::store::Entity")]
669/// Store,
670/// #[sea_orm(entity = "Entity", def = "Relation::SelfRef.def().rev()")]
671/// SelfRefRev,
672/// }
673/// ```
674#[cfg(feature = "derive")]
675#[proc_macro_derive(DeriveRelatedEntity, attributes(sea_orm))]
676pub fn derive_related_entity(input: TokenStream) -> TokenStream {
677 let input = parse_macro_input!(input as DeriveInput);
678 derives::expand_derive_related_entity(input)
679 .unwrap_or_else(Error::into_compile_error)
680 .into()
681}
682
683/// The DeriveMigrationName derive macro will implement `sea_orm_migration::MigrationName` for a migration.
684///
685/// ### Usage
686///
687/// ```ignore
688/// #[derive(DeriveMigrationName)]
689/// pub struct Migration;
690/// ```
691///
692/// The derive macro above will provide following implementation,
693/// given the file name is `m20220120_000001_create_post_table.rs`.
694///
695/// ```ignore
696/// impl MigrationName for Migration {
697/// fn name(&self) -> &str {
698/// "m20220120_000001_create_post_table"
699/// }
700/// }
701/// ```
702#[cfg(feature = "derive")]
703#[proc_macro_derive(DeriveMigrationName)]
704pub fn derive_migration_name(input: TokenStream) -> TokenStream {
705 let input = parse_macro_input!(input as DeriveInput);
706 derives::expand_derive_migration_name(input)
707 .unwrap_or_else(Error::into_compile_error)
708 .into()
709}
710
711#[cfg(feature = "derive")]
712#[proc_macro_derive(FromJsonQueryResult)]
713pub fn derive_from_json_query_result(input: TokenStream) -> TokenStream {
714 let DeriveInput { ident, .. } = parse_macro_input!(input);
715
716 match derives::expand_derive_from_json_query_result(ident) {
717 Ok(ts) => ts.into(),
718 Err(e) => e.to_compile_error().into(),
719 }
720}
721
722/// The DerivePartialModel derive macro will implement `sea_orm::PartialModelTrait` for simplify partial model queries.
723///
724/// ## Usage
725///
726/// ```rust
727/// use sea_orm::{entity::prelude::*, sea_query::Expr, DerivePartialModel, FromQueryResult};
728/// use serde::{Deserialize, Serialize};
729///
730/// #[derive(Clone, Debug, PartialEq, DeriveEntityModel, Deserialize, Serialize)]
731/// #[sea_orm(table_name = "posts")]
732/// pub struct Model {
733/// #[sea_orm(primary_key)]
734/// pub id: i32,
735/// pub title: String,
736/// #[sea_orm(column_type = "Text")]
737/// pub text: String,
738/// }
739/// # #[derive(Copy, Clone, Debug, EnumIter)]
740/// # pub enum Relation {}
741/// #
742/// # impl RelationTrait for Relation {
743/// # fn def(&self) -> RelationDef {
744/// # panic!("No Relation");
745/// # }
746/// # }
747/// #
748/// # impl ActiveModelBehavior for ActiveModel {}
749///
750/// #[derive(Debug, FromQueryResult, DerivePartialModel)]
751/// #[sea_orm(entity = "Entity")]
752/// struct SelectResult {
753/// title: String,
754/// #[sea_orm(from_col = "text")]
755/// content: String,
756/// #[sea_orm(from_expr = "Expr::val(1).add(1)")]
757/// sum: i32,
758/// }
759/// ```
760///
761/// If all fields in the partial model is `from_expr`, the `entity` can be ignore.
762/// ```
763/// use sea_orm::{entity::prelude::*, sea_query::Expr, DerivePartialModel, FromQueryResult};
764///
765/// #[derive(Debug, FromQueryResult, DerivePartialModel)]
766/// struct SelectResult {
767/// #[sea_orm(from_expr = "Expr::val(1).add(1)")]
768/// sum: i32,
769/// }
770/// ```
771///
772/// A field cannot have attributes `from_col` and `from_expr` at the same time.
773/// Or, it will result in a compile error.
774///
775/// ```compile_fail
776/// use sea_orm::{entity::prelude::*, FromQueryResult, DerivePartialModel, sea_query::Expr};
777///
778/// #[derive(Debug, FromQueryResult, DerivePartialModel)]
779/// #[sea_orm(entity = "Entity")]
780/// struct SelectResult {
781/// #[sea_orm(from_expr = "Expr::val(1).add(1)", from_col = "foo")]
782/// sum: i32
783/// }
784/// ```
785#[cfg(feature = "derive")]
786#[proc_macro_derive(DerivePartialModel, attributes(sea_orm))]
787pub fn derive_partial_model(input: TokenStream) -> TokenStream {
788 let derive_input = parse_macro_input!(input);
789
790 match derives::expand_derive_partial_model(derive_input) {
791 Ok(token_stream) => token_stream.into(),
792 Err(e) => e.to_compile_error().into(),
793 }
794}
795
796#[doc(hidden)]
797#[cfg(feature = "derive")]
798#[proc_macro_attribute]
799pub fn test(_: TokenStream, input: TokenStream) -> TokenStream {
800 let input = parse_macro_input!(input as syn::ItemFn);
801
802 let ret = &input.sig.output;
803 let name = &input.sig.ident;
804 let body = &input.block;
805 let attrs = &input.attrs;
806
807 quote::quote! (
808 #[test]
809 #[cfg(any(
810 feature = "sqlx-mysql",
811 feature = "sqlx-sqlite",
812 feature = "sqlx-postgres",
813 ))]
814 #(#attrs)*
815 fn #name() #ret {
816 let _ = ::tracing_subscriber::fmt()
817 .with_max_level(::tracing::Level::DEBUG)
818 .with_test_writer()
819 .try_init();
820 crate::block_on!(async { #body })
821 }
822 )
823 .into()
824}
825
826/// Creates a new type that iterates of the variants of an enum.
827///
828/// Iterate over the variants of an Enum. Any additional data on your variants will be set to `Default::default()`.
829/// The macro implements `strum::IntoEnumIterator` on your enum and creates a new type called `YourEnumIter` that is the iterator object.
830/// You cannot derive `EnumIter` on any type with a lifetime bound (`<'a>`) because the iterator would surely
831/// create [unbounded lifetimes](https://doc.rust-lang.org/nightly/nomicon/unbounded-lifetimes.html).
832#[cfg(feature = "strum")]
833#[proc_macro_derive(EnumIter, attributes(strum))]
834pub fn enum_iter(input: TokenStream) -> TokenStream {
835 let ast = parse_macro_input!(input as DeriveInput);
836
837 strum::enum_iter::enum_iter_inner(&ast)
838 .unwrap_or_else(Error::into_compile_error)
839 .into()
840}
841
842/// Implements traits for types that wrap a database value type.
843///
844/// This procedure macro implements `From<T> for Value`, `sea_orm::TryGetTable`, and
845/// `sea_query::ValueType` for the wrapper type `T`.
846///
847/// ## Usage
848///
849/// ```rust
850/// use sea_orm::DeriveValueType;
851///
852/// #[derive(DeriveValueType)]
853/// struct MyString(String);
854/// ```
855#[cfg(feature = "derive")]
856#[proc_macro_derive(DeriveValueType, attributes(sea_orm))]
857pub fn derive_value_type(input: TokenStream) -> TokenStream {
858 let derive_input = parse_macro_input!(input as DeriveInput);
859 match derives::expand_derive_value_type(derive_input) {
860 Ok(token_stream) => token_stream.into(),
861 Err(e) => e.to_compile_error().into(),
862 }
863}
864
865#[cfg(feature = "derive")]
866#[proc_macro_derive(DeriveDisplay, attributes(sea_orm))]
867pub fn derive_active_enum_display(input: TokenStream) -> TokenStream {
868 let input = parse_macro_input!(input as DeriveInput);
869 match derives::expand_derive_active_enum_display(input) {
870 Ok(ts) => ts.into(),
871 Err(e) => e.to_compile_error().into(),
872 }
873}
874
875/// The DeriveIden derive macro will implement `sea_orm::sea_query::Iden` for simplify Iden implementation.
876///
877/// ## Usage
878///
879/// ```rust
880/// use sea_orm::{DeriveIden, Iden};
881///
882/// #[derive(DeriveIden)]
883/// pub enum MyClass {
884/// Table, // this is a special case, which maps to the enum's name
885/// Id,
886/// #[sea_orm(iden = "turtle")]
887/// Title,
888/// Text,
889/// }
890///
891/// #[derive(DeriveIden)]
892/// struct MyOther;
893///
894/// assert_eq!(MyClass::Table.to_string(), "my_class");
895/// assert_eq!(MyClass::Id.to_string(), "id");
896/// assert_eq!(MyClass::Title.to_string(), "turtle"); // renamed!
897/// assert_eq!(MyClass::Text.to_string(), "text");
898/// assert_eq!(MyOther.to_string(), "my_other");
899/// ```
900#[cfg(feature = "derive")]
901#[proc_macro_derive(DeriveIden, attributes(sea_orm))]
902pub fn derive_iden(input: TokenStream) -> TokenStream {
903 let derive_input = parse_macro_input!(input as DeriveInput);
904
905 match derives::expand_derive_iden(derive_input) {
906 Ok(token_stream) => token_stream.into(),
907 Err(e) => e.to_compile_error().into(),
908 }
909}