Crate sea_orm

Source
Expand description

SeaORM

🐚 An async & dynamic ORM for Rust

crate docs build status

§SeaORM

§SeaORM is a relational ORM to help you build web services in Rust with the familiarity of dynamic languages.

GitHub stars If you like what we do, consider starring, sharing and contributing!

Please help us with maintaining SeaORM by completing the SeaQL Community Survey 2024!

Discord Join our Discord server to chat with other members of the SeaQL community!

§Getting Started

Integration examples:

§Features

  1. Async

    Relying on SQLx, SeaORM is a new library with async support from day 1.

  2. Dynamic

    Built upon SeaQuery, SeaORM allows you to build complex dynamic queries.

  3. Testable

    Use mock connections and/or SQLite to write tests for your application logic.

  4. Service Oriented

    Quickly build services that join, filter, sort and paginate data in REST, GraphQL and gRPC APIs.

§A quick taste of SeaORM

§Entity

use sea_orm::entity::prelude::*;

#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "cake")]
pub struct Model {
    #[sea_orm(primary_key)]
    pub id: i32,
    pub name: String,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
    #[sea_orm(has_many = "super::fruit::Entity")]
    Fruit,
}

impl Related<super::fruit::Entity> for Entity {
    fn to() -> RelationDef {
        Relation::Fruit.def()
    }
}

§Select

// find all models
let cakes: Vec<cake::Model> = Cake::find().all(db).await?;

// find and filter
let chocolate: Vec<cake::Model> = Cake::find()
    .filter(cake::Column::Name.contains("chocolate"))
    .all(db)
    .await?;

// find one model
let cheese: Option<cake::Model> = Cake::find_by_id(1).one(db).await?;
let cheese: cake::Model = cheese.unwrap();

// find related models (lazy)
let fruits: Vec<fruit::Model> = cheese.find_related(Fruit).all(db).await?;

// find related models (eager)
let cake_with_fruits: Vec<(cake::Model, Vec<fruit::Model>)> =
    Cake::find().find_with_related(Fruit).all(db).await?;

§Insert

let apple = fruit::ActiveModel {
    name: Set("Apple".to_owned()),
    ..Default::default() // no need to set primary key
};

let pear = fruit::ActiveModel {
    name: Set("Pear".to_owned()),
    ..Default::default()
};

// insert one
let pear = pear.insert(db).await?;

// insert many
Fruit::insert_many([apple, pear]).exec(db).await?;

§Update

use sea_orm::sea_query::{Expr, Value};

let pear: Option<fruit::Model> = Fruit::find_by_id(1).one(db).await?;
let mut pear: fruit::ActiveModel = pear.unwrap().into();

pear.name = Set("Sweet pear".to_owned());

// update one
let pear: fruit::Model = pear.update(db).await?;

// update many: UPDATE "fruit" SET "cake_id" = NULL WHERE "fruit"."name" LIKE '%Apple%'
Fruit::update_many()
    .col_expr(fruit::Column::CakeId, Expr::value(Value::Int(None)))
    .filter(fruit::Column::Name.contains("Apple"))
    .exec(db)
    .await?;

§Save

let banana = fruit::ActiveModel {
    id: NotSet,
    name: Set("Banana".to_owned()),
    ..Default::default()
};

// create, because primary key `id` is `NotSet`
let mut banana = banana.save(db).await?;

banana.name = Set("Banana Mongo".to_owned());

// update, because primary key `id` is `Set`
let banana = banana.save(db).await?;

§Delete

// delete one
let orange: Option<fruit::Model> = Fruit::find_by_id(1).one(db).await?;
let orange: fruit::Model = orange.unwrap();
fruit::Entity::delete(orange.into_active_model())
    .exec(db)
    .await?;

// or simply
let orange: Option<fruit::Model> = Fruit::find_by_id(1).one(db).await?;
let orange: fruit::Model = orange.unwrap();
orange.delete(db).await?;

// delete many: DELETE FROM "fruit" WHERE "fruit"."name" LIKE 'Orange'
fruit::Entity::delete_many()
    .filter(fruit::Column::Name.contains("Orange"))
    .exec(db)
    .await?;

§🧭 Seaography: instant GraphQL API

Seaography is a GraphQL framework built on top of SeaORM. Seaography allows you to build GraphQL resolvers quickly. With just a few commands, you can launch a GraphQL server from SeaORM entities!

Look at the Seaography Example to learn more.

§🖥️ Admin Dashboard

Making use of Seaography, it will be a breeze to create admin dashboard with your favourite frontend framework. Check out our examples and tutorials:

  1. React Admin Example
  2. Adding GraphQL Support to Loco with Seaography
  3. GraphQL based Admin Dashboard with Loco and Seaography

§Learn More

  1. Design
  2. Architecture
  3. Engineering
  4. Change Log

§Who’s using SeaORM?

See Built with SeaORM. Feel free to submit yours!

§License

Licensed under either of

at your option.

§Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

We invite you to participate, contribute and together help build Rust’s future.

A big shout out to our contributors!

Contributors

§Sponsorship

SeaQL.org is an independent open-source organization run by passionate developers. If you enjoy using our libraries, please star and share our repositories. If you feel generous, a small donation via GitHub Sponsor will be greatly appreciated, and goes a long way towards sustaining the organization.

§Silver Sponsors

We’re immensely grateful to our sponsors: Digital Ocean, for sponsoring our servers. And JetBrains, for sponsoring our IDE.

§Mascot

A friend of Ferris, Terres the hermit crab is the official mascot of SeaORM. His hobby is collecting shells.

Terres

Re-exports§

pub use sea_query;
pub use strum;
pub use sqlx;
pub use entity::*;
pub use error::*;
pub use query::*;
pub use schema::*;

Modules§

entity
Module for the Entity type and operations
error
Error types for all database operations
metric
Holds types and methods to perform metric collection
query
Holds types and methods to perform queries
schema
Holds types that defines the schemas of an Entity

Macros§

debug_print
Non-debug version
debug_query
Helper to get a raw SQL string from an object that impl QueryTrait.
debug_query_stmt
Helper to get a Statement from an object that impl QueryTrait.

Structs§

ConnectOptions
Defines the configuration options of a database
Cursor
Cursor pagination
Database
Defines a database
DatabaseTransaction
Defines a database transaction, whether it is an open transaction and the type of backend to use
DeleteResult
The result of a DELETE operation
Deleter
Handles DELETE operations in a ActiveModel using DeleteStatement
ExecResult
Defines the result of executing an operation
InsertResult
The result of an INSERT operation on an ActiveModel
Inserter
Defines a structure to perform INSERT operations in an ActiveModel
ItemsAndPagesNumber
Define a structure containing the numbers of items and pages of a Paginator
MockDatabasemock
Defines a Mock database suitable for testing
MockDatabaseConnection
Defines a connection for the MockDatabase
MockDatabaseConnector
Defines a database driver for the MockDatabase
MockExecResultmock
Defines the results obtained from a MockDatabase
MockRowmock
Defines the structure of a test Row for the MockDatabase which is just a BTreeMap<String, Value>
OpenTransactionmock
Defines a transaction that is has not been committed
Paginator
Defined a structure to handle pagination of a result from a query operation on a Model
ProxyDatabaseConnection
Defines a connection for the [ProxyDatabase]
ProxyDatabaseConnector
Defines a database driver for the [ProxyDatabase]
ProxyExecResultproxy
Defines the results obtained from a [ProxyDatabase]
ProxyRowproxy
Defines the structure of a Row for the [ProxyDatabase] which is just a BTreeMap<String, Value>
QueryResult
Defines the result of a query operation on a Model
QueryStream
The self-referencing struct.
SelectGetableTuple
Get tuple from query result based on column index
SelectGetableValue
Get tuple from query result based on a list of column identifiers
SelectModel
Defines a type to get a Model
SelectTwoModel
Defines a type to get two Models
Selector
Defines a type to do SELECT operations through a SelectStatement on a Model
SelectorRaw
Performs a raw SELECT operation on a model
SqlxMySqlConnector
Defines the sqlx::mysql connector
SqlxMySqlPoolConnection
Defines a sqlx MySQL pool
SqlxPostgresConnector
Defines the sqlx::postgres connector
SqlxPostgresPoolConnection
Defines a sqlx PostgreSQL pool
SqlxSqliteConnector
Defines the sqlx::sqlite connector
SqlxSqlitePoolConnection
Defines a sqlx SQLite pool
Statement
Defines an SQL statement
Transactionmock
Defines a database transaction as it holds a Vec<Statement>
TransactionStream
The self-referencing struct.
UpdateResult
The result of an update operation on an ActiveModel
Updater
Defines an update operation
Values

Enums§

AccessMode
Access mode
DatabaseBackend
The type of database backend for real world databases. This is enabled by feature flags as specified in the crate documentation
DatabaseConnection
Handle a database connection depending on the backend enabled by the feature flags. This creates a database pool. This will be Clone unless the feature flag mock is enabled.
IsolationLevel
Isolation level
TransactionError
Defines errors for handling transaction failures
TryGetError
An error from trying to get a row from a Model
TryInsertResult
The types of results for an INSERT operation
Value
Value variants

Traits§

ColIdx
Column Index, used by TryGetable. Implemented for &str and usize
ConnectionTrait
The generic API for a database connection that can perform query or execute statements. It abstracts database connection and transaction
CursorTrait
A trait for any type that can be turn into a cursor
Iden
Identifier
IntoMockRowmock
A trait to get a MockRow from a type useful for testing in the MockDatabase
MockDatabaseTrait
A Trait for any type wanting to perform operations on the MockDatabase
PaginatorTrait
A Trait for any type that can paginate results
ProxyDatabaseTraitproxy
Defines the ProxyDatabaseTrait to save the functions
SelectorTrait
A Trait for any type that can perform SELECT queries
StatementBuilder
Any type that can build a Statement
StreamTrait
Stream query results
TransactionTrait
Spawn database transaction
TryFromU64
Try to convert a type to a u64
TryGetable
An interface to get a value from the query result
TryGetableArray
An interface to get an array of values from the query result. A type can only implement ActiveEnum or TryGetableFromJson, but not both. A blanket impl is provided for TryGetableFromJson, while the impl for ActiveEnum is provided by the DeriveActiveEnum macro. So as an end user you won’t normally touch this trait.
TryGetableFromJson
An interface to get a JSON from the query result
TryGetableMany
An interface to get a tuple value from the query result

Functions§

from_query_result_to_proxy_rowproxy
Convert QueryResult to ProxyRow

Type Aliases§

DbBackend
The same as DatabaseBackend just shorter :)
DbConn
The same as a DatabaseConnection
PinBoxStream
Pin a Model so that stream operations can be performed on the model

Derive Macros§

DeriveActiveEnum
A derive macro to implement sea_orm::ActiveEnum trait for enums.
DeriveActiveModel
The DeriveActiveModel derive macro will implement ActiveModelTrait for ActiveModel which provides setters and getters for all active values in the active model.
DeriveActiveModelBehavior
Models that a user can override
DeriveColumn
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.
DeriveCustomColumn
Derive a column if column names are not in snake-case
DeriveDisplay
DeriveEntity
Create an Entity
DeriveEntityModel
This derive macro is the ‘almighty’ macro which automatically generates Entity, Column, and PrimaryKey from a given Model.
DeriveIden
The DeriveIden derive macro will implement sea_orm::sea_query::Iden for simplify Iden implementation.
DeriveIntoActiveModel
Derive into an active model
DeriveMigrationName
The DeriveMigrationName derive macro will implement sea_orm_migration::MigrationName for a migration.
DeriveModel
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.
DerivePartialModel
The DerivePartialModel derive macro will implement sea_orm::PartialModelTrait for simplify partial model queries.
DerivePrimaryKey
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.
DeriveRelatedEntity
The DeriveRelatedEntity derive macro will implement seaography::RelationBuilder for RelatedEntity enumeration.
DeriveRelation
The DeriveRelation derive macro will implement RelationTrait for Relation.
DeriveValueType
Implements traits for types that wrap a database value type.
EnumIter
Creates a new type that iterates of the variants of an enum.
FromJsonQueryResult
FromQueryResult
Convert a query result into the corresponding Model.