Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Documentation for sea-orm #280

Merged
merged 21 commits into from
Nov 1, 2021
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
21 commits
Select commit Hold shift click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 260,27 @@ jobs:
args: >
--manifest-path sea-orm-cli/Cargo.toml

test-temp:
name: Unit Test (Temp)
runs-on: ubuntu-20.04
strategy:
matrix:
args: ["--workspace", "--doc", "--all-targets"]
fail-fast: false
steps:
- uses: actions/checkout@v2

- uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: stable
override: true

- uses: actions-rs/cargo@v1
with:
command: test
args: ${{ matrix.args }}
Comment on lines 263 to 282
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a kind reminder. Removing it before merge :P


cli:
name: CLI
needs: init
Expand Down
2 changes: 2 additions & 0 deletions sea-orm-macros/src/attributes.rs
Original file line number Diff line number Diff line change
@@ -1,6 1,7 @@
pub mod derive_attr {
use bae::FromAttributes;

/// Attributes for Models and ActiveModels
#[derive(Default, FromAttributes)]
pub struct SeaOrm {
pub column: Option<syn::Ident>,
Expand All @@ -16,6 17,7 @@ pub mod derive_attr {
pub mod field_attr {
use bae::FromAttributes;

/// Operations for Models and ActiveModels
#[derive(Default, FromAttributes)]
pub struct SeaOrm {
pub belongs_to: Option<syn::Lit>,
Expand Down
1 change: 1 addition & 0 deletions sea-orm-macros/src/derives/active_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 4,7 @@ use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote, quote_spanned};
use syn::{punctuated::Punctuated, token::Comma, Data, DataStruct, Field, Fields, Lit, Meta, Type};

/// Method to derive an [ActiveModel](sea_orm::ActiveModel)
pub fn expand_derive_active_model(ident: Ident, data: Data) -> syn::Result<TokenStream> {
let fields = match data {
Data::Struct(DataStruct {
Expand Down
1 change: 1 addition & 0 deletions sea-orm-macros/src/derives/active_model_behavior.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 2,7 @@ use proc_macro2::{Ident, TokenStream};
use quote::quote;
use syn::Data;

/// Method to derive an implementation of [ActiveModelBehavior](sea_orm::ActiveModelBehavior)
pub fn expand_derive_active_model_behavior(_ident: Ident, _data: Data) -> syn::Result<TokenStream> {
Ok(quote!(
#[automatically_derived]
Expand Down
3 changes: 3 additions & 0 deletions sea-orm-macros/src/derives/column.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 3,7 @@ use proc_macro2::{Ident, TokenStream};
use quote::{quote, quote_spanned};
use syn::{punctuated::Punctuated, token::Comma, Data, DataEnum, Fields, Lit, Meta, Variant};

/// Derive a Column name for an enum type
pub fn impl_default_as_str(ident: &Ident, data: &Data) -> syn::Result<TokenStream> {
let variants = match data {
syn::Data::Enum(DataEnum { variants, .. }) => variants,
Expand Down Expand Up @@ -65,6 66,7 @@ pub fn impl_default_as_str(ident: &Ident, data: &Data) -> syn::Result<TokenStrea
))
}

/// Implement a column using for an enum using [DeriveColumn](sea_orm::DeriveColumn)
pub fn impl_col_from_str(ident: &Ident, data: &Data) -> syn::Result<TokenStream> {
let data_enum = match data {
Data::Enum(data_enum) => data_enum,
Expand Down Expand Up @@ -114,6 116,7 @@ pub fn expand_derive_column(ident: &Ident, data: &Data) -> syn::Result<TokenStre
))
}

/// Derive a column with a non_snake_case name
pub fn expand_derive_custom_column(ident: &Ident, data: &Data) -> syn::Result<TokenStream> {
let impl_default_as_str = impl_default_as_str(ident, data)?;
let impl_col_from_str = impl_col_from_str(ident, data)?;
Expand Down
1 change: 1 addition & 0 deletions sea-orm-macros/src/derives/entity_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 7,7 @@ use syn::{
Lit, Meta,
};

/// Method to derive an Model
pub fn expand_derive_entity_model(data: Data, attrs: Vec<Attribute>) -> syn::Result<TokenStream> {
// if #[sea_orm(table_name = "foo", schema_name = "bar")] specified, create Entity struct
let mut table_name = None;
Expand Down
1 change: 1 addition & 0 deletions sea-orm-macros/src/derives/from_query_result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 2,7 @@ use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote, quote_spanned};
use syn::{Data, DataStruct, Field, Fields};

/// Method to derive a [QueryResult](sea_orm::QueryResult)
pub fn expand_derive_from_query_result(ident: Ident, data: Data) -> syn::Result<TokenStream> {
let fields = match data {
Data::Struct(DataStruct {
Expand Down
2 changes: 2 additions & 0 deletions sea-orm-macros/src/derives/into_active_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 2,7 @@ use bae::FromAttributes;
use proc_macro2::{Span, TokenStream};
use quote::{quote, quote_spanned};

/// Attributes to derive an ActiveModel
#[derive(Default, FromAttributes)]
pub struct SeaOrm {
pub active_model: Option<syn::Ident>,
Expand Down Expand Up @@ -89,6 90,7 @@ impl IntoActiveModel {
}
}

/// Method to derive the ActiveModel from the [ActiveModelTrait](sea_orm::ActiveModelTrait)
pub fn expand_into_active_model(input: syn::DeriveInput) -> syn::Result<TokenStream> {
let ident_span = input.ident.span();

Expand Down
1 change: 1 addition & 0 deletions sea-orm-macros/src/derives/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 183,7 @@ impl DeriveModel {
}
}

/// Method to derive an ActiveModel
pub fn expand_derive_model(input: syn::DeriveInput) -> syn::Result<TokenStream> {
let ident_span = input.ident.span();

Expand Down
1 change: 1 addition & 0 deletions sea-orm-macros/src/derives/primary_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 3,7 @@ use proc_macro2::{Ident, TokenStream};
use quote::{quote, quote_spanned};
use syn::{Data, DataEnum, Fields, Variant};

/// Method to derive a Primary Key for a Model using the [PrimaryKeyTrait](sea_orm::PrimaryKeyTrait)
pub fn expand_derive_primary_key(ident: Ident, data: Data) -> syn::Result<TokenStream> {
let variants = match data {
syn::Data::Enum(DataEnum { variants, .. }) => variants,
Expand Down
1 change: 1 addition & 0 deletions sea-orm-macros/src/derives/relation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 166,7 @@ impl DeriveRelation {
}
}

/// Method to derive a Relation
pub fn expand_derive_relation(input: syn::DeriveInput) -> syn::Result<TokenStream> {
let ident_span = input.ident.span();

Expand Down
126 changes: 126 additions & 0 deletions sea-orm-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 7,14 @@ mod attributes;
mod derives;
mod util;

/// Create an Entity
/// ### Usage
/// ```
/// use sea_orm::entity::prelude::*;
///
/// #[derive(Copy, Clone, Default, Debug, DeriveEntity)]
/// pub struct Entity;
/// ```
#[proc_macro_derive(DeriveEntity, attributes(sea_orm))]
pub fn derive_entity(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
Expand All @@ -15,6 23,21 @@ pub fn derive_entity(input: TokenStream) -> TokenStream {
.into()
}

/// This derive macro is the 'almighty' macro which automatically generates
/// Entity, Column, and PrimaryKey from a given Model.
/// ### Usage
/// use sea_orm::entity::prelude::*;
///
/// #[derive(Clone, Debug, PartialEq, DeriveEntityModel, Deserialize, Serialize, FromForm)]
/// #[sea_orm(table_name = "posts")]
/// pub struct Model {
/// #[sea_orm(primary_key)]
/// pub id: i32,
/// pub title: String,
/// #[sea_orm(column_type = "Text")]
/// pub text: String,
/// }
/// ```
#[proc_macro_derive(DeriveEntityModel, attributes(sea_orm))]
pub fn derive_entity_model(input: TokenStream) -> TokenStream {
let input_ts = input.clone();
Expand All @@ -36,6 59,19 @@ pub fn derive_entity_model(input: TokenStream) -> TokenStream {
ts
}

/// The DerivePrimaryKey derive macro will implement [PrimaryKeyToColumn]
/// for PrimaryKey which defines tedious mappings between primary keys and columns.
/// The [EnumIter] is also derived, allowing iteration over all enum variants.
/// ### Usage
/// ```
/// use sea_orm::entity::prelude::*;
///
/// #[derive(Copy, Clone, Debug, EnumIter, DerivePrimaryKey)]
/// pub enum PrimaryKey {
/// CakeId,
/// FillingId,
/// }
/// ```
#[proc_macro_derive(DerivePrimaryKey)]
pub fn derive_primary_key(input: TokenStream) -> TokenStream {
let DeriveInput { ident, data, .. } = parse_macro_input!(input);
Expand All @@ -46,6 82,19 @@ pub fn derive_primary_key(input: TokenStream) -> TokenStream {
}
}

/// The DeriveColumn derive macro will implement [ColumnTrait] for Columns.
/// It defines the identifier of each column by implementing Iden and IdenStatic.
/// The EnumIter is also derived, allowing iteration over all enum variants.
/// ### Usage
/// ```
/// use sea_orm::entity::prelude::*;
///
/// #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
/// pub enum Column {
/// CakeId,
/// FillingId,
/// }
/// ```
#[proc_macro_derive(DeriveColumn, attributes(sea_orm))]
pub fn derive_column(input: TokenStream) -> TokenStream {
let DeriveInput { ident, data, .. } = parse_macro_input!(input);
Expand All @@ -56,6 105,16 @@ pub fn derive_column(input: TokenStream) -> TokenStream {
}
}

/// Derive a column if column names are not in snake-case
/// ### Usage
/// ```
/// #[derive(Copy, Clone, Debug, EnumIter, DeriveCustomColumn)]
/// pub enum Column {
/// Id,
/// Name,
/// VendorId,
/// }
/// ```
#[proc_macro_derive(DeriveCustomColumn)]
pub fn derive_custom_column(input: TokenStream) -> TokenStream {
let DeriveInput { ident, data, .. } = parse_macro_input!(input);
Expand All @@ -66,6 125,18 @@ pub fn derive_custom_column(input: TokenStream) -> TokenStream {
}
}

/// The DeriveModel derive macro will implement ModelTrait for Model,
/// which provides setters and getters for all attributes in the mod
/// It also implements FromQueryResult to convert a query result into the corresponding Model.
/// ### Usage
///
/// ```
/// #[derive(Clone, Debug, PartialEq, DeriveModel, DeriveActiveModel)]
/// pub struct Model {
/// pub id: i32,
/// pub name: String,
/// }
/// ```
#[proc_macro_derive(DeriveModel, attributes(sea_orm))]
pub fn derive_model(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
Expand All @@ -74,6 145,17 @@ pub fn derive_model(input: TokenStream) -> TokenStream {
.into()
}

/// The DeriveActiveModel derive macro will implement ActiveModelTrait for ActiveModel
/// which provides setters and getters for all active values in the active model.
/// ### Usage
///
/// ```
/// #[derive(Clone, Debug, PartialEq, DeriveModel, DeriveActiveModel)]
/// pub struct Model {
/// pub id: i32,
/// pub name: String,
/// }
/// ```
#[proc_macro_derive(DeriveActiveModel, attributes(sea_orm))]
pub fn derive_active_model(input: TokenStream) -> TokenStream {
let DeriveInput { ident, data, .. } = parse_macro_input!(input);
Expand All @@ -84,6 166,7 @@ pub fn derive_active_model(input: TokenStream) -> TokenStream {
}
}

/// Derive into an active model
#[proc_macro_derive(DeriveIntoActiveModel, attributes(sea_orm))]
pub fn derive_into_active_model(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
Expand All @@ -92,6 175,20 @@ pub fn derive_into_active_model(input: TokenStream) -> TokenStream {
.into()
}

/// Models that a user can override
/// ### Usage
///
/// ```
/// use sea_orm::entity::prelude::*;
///
/// #[derive(
/// Clone, Debug, PartialEq, DeriveModel, DeriveActiveModel, DeriveActiveModelBehavior,
/// )]
/// pub struct Model {
/// pub id: i32,
/// pub name: String,
/// }
/// ```
#[proc_macro_derive(DeriveActiveModelBehavior)]
pub fn derive_active_model_behavior(input: TokenStream) -> TokenStream {
let DeriveInput { ident, data, .. } = parse_macro_input!(input);
Expand All @@ -102,6 199,16 @@ pub fn derive_active_model_behavior(input: TokenStream) -> TokenStream {
}
}

/// Convert a query result into the corresponding Model.
/// ### Usage
///
/// ```
/// #[derive(Debug, FromQueryResult)]
/// struct SelectResult {
/// name: String,
/// num_of_fruits: i32,
/// }
/// ```
#[proc_macro_derive(FromQueryResult)]
pub fn derive_from_query_result(input: TokenStream) -> TokenStream {
let DeriveInput { ident, data, .. } = parse_macro_input!(input);
Expand All @@ -112,6 219,25 @@ pub fn derive_from_query_result(input: TokenStream) -> TokenStream {
}
}

/// The DeriveRelation derive macro will implement RelationTrait for Relation.
/// ### Usage
/// ```
/// #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
/// pub enum Relation {
/// #[sea_orm(
/// belongs_to = "super::cake::Entity",
/// from = "Column::CakeId",
/// to = "super::cake::Column::Id"
/// )]
/// Cake,
/// #[sea_orm(
/// belongs_to = "super::cake_expanded::Entity",
/// from = "Column::CakeId",
/// to = "super::cake_expanded::Column::Id"
/// )]
/// CakeExpanded,
/// }
/// ```
#[proc_macro_derive(DeriveRelation, attributes(sea_orm))]
pub fn derive_relation(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
Expand Down
12 changes: 12 additions & 0 deletions src/database/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 4,34 @@ use crate::{
use futures::Stream;
use std::{future::Future, pin::Pin};

/// Creates constraints for any structure that wants to create a database connection
/// and execute SQL statements
#[async_trait::async_trait]
pub trait ConnectionTrait<'a>: Sync {
/// Create a stream for the [QueryResult]
type Stream: Stream<Item = Result<QueryResult, DbErr>>;

/// Fetch the database backend as specified in [DbBackend].
/// This depends on feature flags enabled.
fn get_database_backend(&self) -> DbBackend;

/// Execute a [Statement]
async fn execute(&self, stmt: Statement) -> Result<ExecResult, DbErr>;

/// Execute a [Statement] and return a query
async fn query_one(&self, stmt: Statement) -> Result<Option<QueryResult>, DbErr>;

/// Execute a [Statement] and return a collection Vec<[QueryResult]> on success
async fn query_all(&self, stmt: Statement) -> Result<Vec<QueryResult>, DbErr>;

/// Execute a [Statement] and return a stream of results
fn stream(
&'a self,
stmt: Statement,
) -> Pin<Box<dyn Future<Output = Result<Self::Stream, DbErr>> 'a>>;

/// Execute SQL `BEGIN` transaction.
/// Returns a Transaction that can be committed or rolled back
async fn begin(&self) -> Result<DatabaseTransaction, DbErr>;

/// Execute the function inside a transaction.
Expand All @@ -34,6 45,7 @@ pub trait ConnectionTrait<'a>: Sync {
T: Send,
E: std::error::Error Send;

/// Check if the connection is a test connection for the Mock database
fn is_mock_connection(&self) -> bool {
false
}
Expand Down
Loading