Expand description
§SeaORM
§SeaORM is a relational ORM to help you build web services in Rust with the familiarity of dynamic languages.
If you like what we do, consider starring, sharing and contributing!
Please help us with maintaining SeaORM by completing the SeaQL Community Survey 2024!
Join our Discord server to chat with other members of the SeaQL community!
§Getting Started
Integration examples:
- Actix v4 Example
- Axum Example
- GraphQL Example
- jsonrpsee Example
- Loco TODO Example / Loco REST Starter
- Poem Example
- Rocket Example / Rocket OpenAPI Example
- Salvo Example
- Tonic Example
- Seaography Example
§Features
-
Async
Relying on SQLx, SeaORM is a new library with async support from day 1.
-
Dynamic
Built upon SeaQuery, SeaORM allows you to build complex dynamic queries.
-
Testable
Use mock connections and/or SQLite to write tests for your application logic.
-
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:
- React Admin Example
- Adding GraphQL Support to Loco with Seaography
- GraphQL based Admin Dashboard with Loco and Seaography

§Learn More
§Who’s using SeaORM?
See Built with SeaORM. Feel free to submit yours!
§License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
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!
§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.

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 implQueryTrait
.
Structs§
- Connect
Options - Defines the configuration options of a database
- Cursor
- Cursor pagination
- Database
- Defines a database
- Database
Transaction - Defines a database transaction, whether it is an open transaction and the type of backend to use
- Delete
Result - The result of a DELETE operation
- Deleter
- Handles DELETE operations in a ActiveModel using DeleteStatement
- Exec
Result - Defines the result of executing an operation
- Insert
Result - The result of an INSERT operation on an ActiveModel
- Inserter
- Defines a structure to perform INSERT operations in an ActiveModel
- Items
AndPages Number - Define a structure containing the numbers of items and pages of a Paginator
- Mock
Database mock
- Defines a Mock database suitable for testing
- Mock
Database Connection - Defines a connection for the MockDatabase
- Mock
Database Connector - Defines a database driver for the MockDatabase
- Mock
Exec Result mock
- Defines the results obtained from a MockDatabase
- MockRow
mock
- Defines the structure of a test Row for the MockDatabase which is just a BTreeMap<String, Value>
- Open
Transaction mock
- 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
- Proxy
Database Connection - Defines a connection for the [ProxyDatabase]
- Proxy
Database Connector - Defines a database driver for the [ProxyDatabase]
- Proxy
Exec Result proxy
- Defines the results obtained from a [ProxyDatabase]
- Proxy
Row proxy
- Defines the structure of a Row for the [ProxyDatabase] which is just a BTreeMap<String, Value>
- Query
Result - Defines the result of a query operation on a Model
- Query
Stream - The self-referencing struct.
- Select
Getable Tuple - Get tuple from query result based on column index
- Select
Getable Value - Get tuple from query result based on a list of column identifiers
- Select
Model - Defines a type to get a Model
- Select
TwoModel - Defines a type to get two Models
- Selector
- Defines a type to do
SELECT
operations through a SelectStatement on a Model - Selector
Raw - Performs a raw
SELECT
operation on a model - Sqlx
MySql Connector - Defines the sqlx::mysql connector
- Sqlx
MySql Pool Connection - Defines a sqlx MySQL pool
- Sqlx
Postgres Connector - Defines the sqlx::postgres connector
- Sqlx
Postgres Pool Connection - Defines a sqlx PostgreSQL pool
- Sqlx
Sqlite Connector - Defines the sqlx::sqlite connector
- Sqlx
Sqlite Pool Connection - Defines a sqlx SQLite pool
- Statement
- Defines an SQL statement
- Transaction
mock
- Defines a database transaction as it holds a Vec<Statement>
- Transaction
Stream - The self-referencing struct.
- Update
Result - The result of an update operation on an ActiveModel
- Updater
- Defines an update operation
- Values
Enums§
- Access
Mode - Access mode
- Database
Backend - The type of database backend for real world databases. This is enabled by feature flags as specified in the crate documentation
- Database
Connection - 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 flagmock
is enabled. - Isolation
Level - Isolation level
- Transaction
Error - Defines errors for handling transaction failures
- TryGet
Error - An error from trying to get a row from a Model
- TryInsert
Result - The types of results for an INSERT operation
- Value
- Value variants
Traits§
- ColIdx
- Column Index, used by
TryGetable
. Implemented for&str
andusize
- Connection
Trait - The generic API for a database connection that can perform query or execute statements. It abstracts database connection and transaction
- Cursor
Trait - A trait for any type that can be turn into a cursor
- Iden
- Identifier
- Into
Mock Row mock
- A trait to get a MockRow from a type useful for testing in the MockDatabase
- Mock
Database Trait - A Trait for any type wanting to perform operations on the MockDatabase
- Paginator
Trait - A Trait for any type that can paginate results
- Proxy
Database Trait proxy
- Defines the ProxyDatabaseTrait to save the functions
- Selector
Trait - A Trait for any type that can perform SELECT queries
- Statement
Builder - Any type that can build a Statement
- Stream
Trait - Stream query results
- Transaction
Trait - Spawn database transaction
- TryFrom
U64 - Try to convert a type to a u64
- TryGetable
- An interface to get a value from the query result
- TryGetable
Array - An interface to get an array of values from the query result.
A type can only implement
ActiveEnum
orTryGetableFromJson
, but not both. A blanket impl is provided forTryGetableFromJson
, while the impl forActiveEnum
is provided by theDeriveActiveEnum
macro. So as an end user you won’t normally touch this trait. - TryGetable
From Json - An interface to get a JSON from the query result
- TryGetable
Many - An interface to get a tuple value from the query result
Functions§
- from_
query_ result_ to_ proxy_ row proxy
- Convert QueryResult to ProxyRow
Type Aliases§
- DbBackend
- The same as DatabaseBackend just shorter :)
- DbConn
- The same as a DatabaseConnection
- PinBox
Stream - Pin a Model so that stream operations can be performed on the model
Derive Macros§
- Derive
Active Enum - A derive macro to implement
sea_orm::ActiveEnum
trait for enums. - Derive
Active Model - The DeriveActiveModel derive macro will implement ActiveModelTrait for ActiveModel which provides setters and getters for all active values in the active model.
- Derive
Active Model Behavior - Models that a user can override
- Derive
Column - 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.
- Derive
Custom Column - Derive a column if column names are not in snake-case
- Derive
Display - Derive
Entity - Create an Entity
- Derive
Entity Model - This derive macro is the ‘almighty’ macro which automatically generates Entity, Column, and PrimaryKey from a given Model.
- Derive
Iden - The DeriveIden derive macro will implement
sea_orm::sea_query::Iden
for simplify Iden implementation. - Derive
Into Active Model - Derive into an active model
- Derive
Migration Name - The DeriveMigrationName derive macro will implement
sea_orm_migration::MigrationName
for a migration. - Derive
Model - 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.
- Derive
Partial Model - The DerivePartialModel derive macro will implement
sea_orm::PartialModelTrait
for simplify partial model queries. - Derive
Primary Key - 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.
- Derive
Related Entity - The DeriveRelatedEntity derive macro will implement seaography::RelationBuilder for RelatedEntity enumeration.
- Derive
Relation - The DeriveRelation derive macro will implement RelationTrait for Relation.
- Derive
Value Type - Implements traits for types that wrap a database value type.
- Enum
Iter - Creates a new type that iterates of the variants of an enum.
- From
Json Query Result - From
Query Result - Convert a query result into the corresponding Model.