Crate sea_orm

Crate sea_orm 

Source
Expand description
SeaORM

SeaORM is a powerful ORM for building web services in Rust

crate build status GitHub stars
Support us with a ⭐ !

§🐚 SeaORM

中文文档

§Advanced Relations

Model complex relationships 1-1, 1-N, M-N, and even self-referential in a high-level, conceptual way.

§Familiar Concepts

Inspired by popular ORMs in the Ruby, Python, and Node.js ecosystem, SeaORM offers a developer experience that feels instantly recognizable.

§Feature Rich

SeaORM is a batteries-included ORM with filters, pagination, and nested queries to accelerate building REST, GraphQL, and gRPC APIs.

§Production Ready

With 250k+ weekly downloads, SeaORM is production-ready, trusted by startups and enterprises worldwide.

§Getting Started

Discord Join our Discord server to chat with others!

Integration examples:

If you want a simple, clean example that fits in a single file that demonstrates the best of SeaORM, you can try:

Let’s have a quick walk through of the unique features of SeaORM.

§Expressive Entity format

You don’t have to write this by hand! Entity files can be generated from an existing database using sea-orm-cli, following is generated with --entity-format dense (new in 2.0).

mod user {
    use sea_orm::entity::prelude::*;

    #[sea_orm::model]
    #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
    #[sea_orm(table_name = "user")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i32,
        pub name: String,
        #[sea_orm(unique)]
        pub email: String,
        #[sea_orm(has_one)]
        pub profile: HasOne<super::profile::Entity>,
        #[sea_orm(has_many)]
        pub posts: HasMany<super::post::Entity>,
    }
}
mod post {
    use sea_orm::entity::prelude::*;

    #[sea_orm::model]
    #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
    #[sea_orm(table_name = "post")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i32,
        pub user_id: i32,
        pub title: String,
        #[sea_orm(belongs_to, from = "user_id", to = "id")]
        pub author: HasOne<super::user::Entity>,
        #[sea_orm(has_many, via = "post_tag")] // M-N relation with junction
        pub tags: HasMany<super::tag::Entity>,
    }
}

§Smart Entity Loader

The Entity Loader intelligently uses join for 1-1 and data loader for 1-N relations, eliminating the N+1 problem even when performing nested queries.

// join paths:
// user -> profile
// user -> post
//         post -> post_tag -> tag
let smart_user = user::Entity::load()
    .filter_by_id(42) // shorthand for .filter(user::COLUMN.id.eq(42))
    .with(profile::Entity) // 1-1 uses join
    .with((post::Entity, tag::Entity)) // 1-N uses data loader
    .one(db)
    ?
    .unwrap();

// 3 queries are executed under the hood:
// 1. SELECT FROM user JOIN profile WHERE id = $
// 2. SELECT FROM post WHERE user_id IN (..)
// 3. SELECT FROM tag JOIN post_tag WHERE post_id IN (..)

smart_user
    == user::ModelEx {
        id: 42,
        name: "Bob".into(),
        email: "bob@sea-ql.org".into(),
        profile: HasOne::Loaded(
            profile::ModelEx {
                picture: "image.jpg".into(),
            }
            .into(),
        ),
        posts: HasMany::Loaded(vec![post::ModelEx {
            title: "Nice weather".into(),
            tags: HasMany::Loaded(vec![tag::ModelEx {
                tag: "sunny".into(),
            }]),
        }]),
    };

§ActiveModel: nested persistence made simple

Persist an entire object graph: user, profile (1-1), posts (1-N), and tags (M-N) in a single operation using a fluent builder API. SeaORM automatically determines the dependencies and inserts or deletes objects in the correct order.

// this creates the nested object as shown above:
let user = user::ActiveModel::builder()
    .set_name("Bob")
    .set_email("bob@sea-ql.org")
    .set_profile(profile::ActiveModel::builder().set_picture("image.jpg"))
    .add_post(
        post::ActiveModel::builder()
            .set_title("Nice weather")
            .add_tag(tag::ActiveModel::builder().set_tag("sunny")),
    )
    .save(db)
    ?;

§Schema first or Entity first? Your choice

SeaORM provides a powerful migration system that lets you create tables, modify schemas, and seed data with ease.

With SeaORM 2.0, you also get a first-class Entity First Workflow: simply define new entities or add columns to existing ones, and SeaORM will automatically detect the changes and create the new tables, columns, unique keys, and foreign keys.

// SeaORM resolves foreign key dependencies and creates the tables in topological order.
// Requires the `entity-registry` and `schema-sync` feature flags.
db.get_schema_registry("my_crate::entity::*").sync(db);

§Ergonomic Raw SQL

Let SeaORM handle 95% of your transactional queries. For the remaining cases that are too complex to express, SeaORM still offers convenient support for writing raw SQL.

let user = Item { name: "Bob" }; // nested parameter access
let ids = [2, 3, 4]; // expanded by the `..` operator

let user: Option<user::Model> = user::Entity::find()
    .from_raw_sql(raw_sql!(
        Sqlite,
        r#"SELECT "id", "name" FROM "user"
           WHERE "name" LIKE {user.name}
           AND "id" in ({..ids})
        "#
    ))
    .one(db)
    ?;

§Synchronous Support

sea-orm-sync provides the full SeaORM API without requiring an runtime, making it ideal for lightweight CLI programs with SQLite.

See the quickstart example for usage.

§Basics

§Select

SeaORM models 1-N and M-N relationships at the Entity level, letting you traverse many-to-many links through a junction table in a single call.

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

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

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

// find related models (lazy)
let fruit: Option<fruit::Model> = cheese.find_related(Fruit).one(db)?;

// find related models (eager): for 1-1 relations
let cake_with_fruit: Vec<(cake::Model, Option<fruit::Model>)> =
    Cake::find().find_also_related(Fruit).all(db)?;

// find related models (eager): works for both 1-N and M-N relations
let cake_with_fillings: Vec<(cake::Model, Vec<filling::Model>)> = Cake::find()
    .find_with_related(Filling) // for M-N relations, two joins are performed
    .all(db) // rows are automatically consolidated by left entity
    ?;

§Nested Select

Partial models prevent overfetching by letting you querying only the fields you need; it also makes writing deeply nested relational queries simple.

use sea_orm::DerivePartialModel;

#[derive(DerivePartialModel)]
#[sea_orm(entity = "cake::Entity")]
struct CakeWithFruit {
    id: i32,
    name: String,
    #[sea_orm(nested)]
    fruit: Option<fruit::Model>, // this can be a regular or another partial model
}

let cakes: Vec<CakeWithFruit> = Cake::find()
    .left_join(fruit::Entity) // no need to specify join condition
    .into_partial_model() // only the columns in the partial model will be selected
    .all(db)
    ?;

§Insert

SeaORM’s ActiveModel lets you work directly with Rust data structures and persist them through a simple API. It’s easy to insert large batches of rows from different data sources.

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: Active Record style
let apple = apple.insert(db)?;
apple.id == 1;

// insert one: repository style
let result = Fruit::insert(apple).exec(db)?;
result.last_insert_id == 1;

// insert many returning last insert id
let result = Fruit::insert_many([apple, pear]).exec(db)?;
result.last_insert_id == Some(2);

§Insert (advanced)

You can take advantage of database specific features to perform upsert and idempotent insert.

// insert many with returning (if supported by database)
let models: Vec<fruit::Model> = Fruit::insert_many([apple, pear])
    .exec_with_returning(db)
    ?;
models[0]
    == fruit::Model {
        id: 1, // database assigned value
        name: "Apple".to_owned(),
        cake_id: None,
    };

// insert with ON CONFLICT on primary key do nothing, with MySQL specific polyfill
let result = Fruit::insert_many([apple, pear])
    .on_conflict_do_nothing()
    .exec(db)
    ?;

matches!(result, TryInsertResult::Conflicted);

§Update

ActiveModel avoids race conditions by updating only the fields you’ve changed, never overwriting untouched columns. You can also craft complex bulk update queries with a fluent query building API.

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

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

pear.name = Set("Sweet pear".to_owned()); // update value of a single field

// update one: only changed columns will be updated
let pear: fruit::Model = pear.update(db)?;

// update many: UPDATE "fruit" SET "cake_id" = "cake_id" + 2
//               WHERE "fruit"."name" LIKE '%Apple%'
Fruit::update_many()
    .col_expr(fruit::COLUMN.cake_id, fruit::COLUMN.cake_id.add(2))
    .filter(fruit::COLUMN.name.contains("Apple"))
    .exec(db)
    ?;

§Save

You can perform “insert or update” operation with ActiveModel, making it easy to compose transactional operations.

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)?;

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

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

§Delete

The same ActiveModel API consistent with insert and update.

// delete one: Active Record style
let orange: Option<fruit::Model> = Fruit::find_by_id(1).one(db)?;
let orange: fruit::Model = orange.unwrap();
orange.delete(db)?;

// delete one: repository style
let orange = fruit::ActiveModel {
    id: Set(2),
    ..Default::default()
};
fruit::Entity::delete(orange).exec(db)?;

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

§Raw SQL Query

The raw_sql! macro is like the format! macro but without the risk of SQL injection. It supports nested parameter interpolation, array and tuple expansion, and even repeating group, offering great flexibility in crafting complex queries.

#[derive(FromQueryResult)]
struct CakeWithBakery {
    name: String,
    #[sea_orm(nested)]
    bakery: Option<Bakery>,
}

#[derive(FromQueryResult)]
struct Bakery {
    #[sea_orm(alias = "bakery_name")]
    name: String,
}

let cake_ids = [2, 3, 4]; // expanded by the `..` operator

// can use many APIs with raw SQL, including nested select
let cake: Option<CakeWithBakery> = CakeWithBakery::find_by_statement(raw_sql!(
    Sqlite,
    r#"SELECT "cake"."name", "bakery"."name" AS "bakery_name"
       FROM "cake"
       LEFT JOIN "bakery" ON "cake"."bakery_id" = "bakery"."id"
       WHERE "cake"."id" IN ({..cake_ids})"#
))
.one(db)
?;

§🧭 Seaography: instant GraphQL API

Seaography is a GraphQL framework built for SeaORM. Seaography allows you to build GraphQL resolvers quickly. With just a few commands, you can launch a fullly-featured GraphQL server from SeaORM entities, complete with filter, pagination, relational queries and mutations!

Look at the Seaography Example to learn more.

§🖥️ SeaORM Pro: Professional Admin Panel

SeaORM Pro is an admin panel solution allowing you to quickly and easily launch an admin panel for your application - frontend development skills not required, but certainly nice to have!

SeaORM Pro has been updated to support the latest features in SeaORM 2.0.

Features:

  • Full CRUD
  • Built on React + GraphQL
  • Built-in GraphQL resolver
  • Customize the UI with TOML config
  • Role Based Access Control (new in 2.0)

Read the Getting Started guide to learn more.

§SQL Server Support

SQL Server for SeaORM offers the same SeaORM API for MSSQL. We ported all test cases and examples, complemented by MSSQL specific documentation. If you are building enterprise software, you can request commercial access. It is currently based on SeaORM 1.0, but we will offer free upgrade to existing users when SeaORM 2.0 is finalized.

§Releases

SeaORM 2.0 has reached its release candidate phase. We’d love for you to try it out and help shape the final release by sharing your feedback.

SeaORM 2.0 is shaping up to be our most significant release yet - with a few breaking changes, plenty of enhancements, and a clear focus on developer experience.

If you make extensive use of SeaQuery, we recommend checking out our blog post on SeaQuery 1.0 release:

§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

§Who’s using SeaORM?

Here is a short list of awesome open source software built with SeaORM. Feel free to submit yours!

ProjectGitHubTagline
ZedGitHub starsA high-performance, multiplayer code editor
OpenObserveGitHub starsOpen-source observability platform
RisingWaveGitHub starsStream processing and management platform
LLDAPGitHub starsA light LDAP server for user management
WarpgateGitHub starsSmart SSH bastion that works with any SSH client
SvixGitHub starsThe enterprise ready webhooks service
RyotGitHub starsThe only self hosted tracker you will ever need
LapdevGitHub starsSelf-hosted remote development enviroment
System InitiativeGitHub starsDevOps Automation Platform
OctoBaseGitHub starsA light-weight, scalable, offline collaborative data backend

§Sponsorship

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

§Gold Sponsors

QDX pioneers quantum dynamics-powered drug discovery, leveraging AI and supercomputing to accelerate molecular modeling. We’re immensely grateful to QDX for sponsoring the development of SeaORM, the SQL toolkit that powers their data intensive applications.

§Silver Sponsors

We’re grateful to our silver 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

§🦀 Rustacean Sticker Pack

The Rustacean Sticker Pack is the perfect way to express your passion for Rust. Our stickers are made with a premium water-resistant vinyl with a unique matte finish.

Sticker Pack Contents:

  • Logo of SeaQL projects: SeaQL, SeaORM, SeaQuery, Seaography
  • Mascots: Ferris the Crab x 3, Terres the Hermit Crab
  • The Rustacean wordmark

Support SeaQL and get a Sticker Pack! All proceeds contributes directly to the ongoing development of SeaQL projects.

Rustacean Sticker Pack by SeaQL

Re-exports§

pub use crate::error::TryGetError;
pub use sea_query;
pub use strum;
pub use entity::*;
pub use error::*;
pub use query::*;
pub use schema::*;

Modules§

dynamic
The API of this module is not yet stable, and may have breaking changes between minor versions.
entity
Module for the Entity type and operations
error
Error types for all database operations
metric
Types and methods to perform metric collection
query
Types and methods to perform queries
rbacrbac
schema
Types that defines the schemas of an Entity
value
Helpers for working with Value

Macros§

debug_printNon-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.
raw_sqlmacros

Structs§

ConnectOptions
Defines the configuration options of a database
Cursor
Cursor pagination
Database
Defines a database
DatabaseConnection
Handle a database connection depending on the backend enabled by the feature flags. This creates a connection pool internally (for SQLx connections), and so is cheap to clone.
DatabaseTransaction
Defines a database transaction, whether it is an open transaction and the type of backend to use. Under the hood, a Transaction is just a wrapper for a connection where START TRANSACTION has been executed.
DeleteResult
The result of a DELETE operation
Deleter
Handles DELETE operations in a ActiveModel using DeleteStatement
ExecResult
Defines the result of executing an operation
InsertManyResult
The result of an INSERT many operation for a set of ActiveModels
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
MockDatabaseConnectionmock
Defines a connection for the MockDatabase
MockDatabaseConnectormock
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
PaginatorStreamsync
Stream items by page
ProxyDatabaseConnectionproxy
Defines a connection for the [ProxyDatabase]
ProxyDatabaseConnectorproxy
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>
QueryAccessAuditrbac
QueryResult
Defines the result of a query operation on a Model
QueryStream
The self-referencing struct.
RestrictedConnectionrbac
Wrapper of DatabaseConnection that performs authorization on all executed queries for the current user. Note that raw SQL Statement is not allowed currently.
RestrictedTransactionrbac
Wrapper of DatabaseTransaction that performs authorization on all executed queries for the current user. Note that raw SQL Statement is not allowed currently.
SelectFiveModel
Helper class to handle query result for 5 Models
SelectFourModel
Helper class to handle query result for 4 Models
SelectGetableTuple
Get tuple from query result based on column index
SelectGetableValue
Get tuple from query result based on a list of column identifiers
SelectModel
Helper class to handle query result for 1 Model
SelectSixModel
Helper class to handle query result for 6 Models
SelectThreeModel
Helper class to handle query result for 3 Models
SelectTwoModel
Helper class to handle query result for 2 Models
Selector
Defines a type to do SELECT operations through a SelectStatement on a Model
SelectorRaw
Performs a raw SELECT operation on a model
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
AuditErrorrbac
DatabaseBackend
The type of database backend for real world databases. This is enabled by feature flags as specified in the crate documentation
DatabaseConnectionType
The underlying database connection type.
DatabaseExecutor
A wrapper that holds either a reference to a DatabaseConnection or DatabaseTransaction.
IsolationLevel
Isolation level
TransactionError
Defines errors for handling transaction failures
TryInsertResult
The types of results for an INSERT operation
Value
Value variants

Traits§

AuditTraitrbac
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
IntoDatabaseExecutor
A trait for converting into DatabaseExecutor
IntoMockRowmock
A trait to get a MockRow from a type useful for testing in the MockDatabase
MockDatabaseTraitmock
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
TransactionSession
Represents an open transaction
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.
TryGetableFromJsonwith-json
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
A shorthand for DatabaseBackend.
DbConn
The same as a DatabaseConnection

Attribute Macros§

compact_modelmacros
modelmacros

Derive Macros§

DeriveActiveEnummacros
A derive macro to implement sea_orm::ActiveEnum trait for enums.
DeriveActiveModelmacros
The DeriveActiveModel derive macro will implement ActiveModelTrait for ActiveModel which provides setters and getters for all active values in the active model.
DeriveActiveModelBehaviormacros
Models that a user can override
DeriveActiveModelExmacros
Derive a complex active model with relational fields
DeriveColumnmacros
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.
DeriveDisplaymacros
DeriveEntitymacros
Create an Entity
DeriveEntityModelmacros
This derive macro is the ‘almighty’ macro which automatically generates Entity, Column, and PrimaryKey from a given Model.
DeriveIdenmacros
The DeriveIden derive macro will implement sea_orm::Iden for simplify Iden implementation.
DeriveIntoActiveModelmacros
Derive into an active model
DeriveMigrationNamemacros
The DeriveMigrationName derive macro will implement sea_orm_migration::MigrationName for a migration.
DeriveModelmacros
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.
DeriveModelExmacros
Derive a complex model with relational fields
DerivePartialModelmacros
The DerivePartialModel derive macro will implement [sea_orm::PartialModelTrait] for simplify partial model queries. Since 2.0, this macro cannot be used with the FromQueryResult macro.
DerivePrimaryKeymacros
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.
DeriveRelatedEntitymacros
The DeriveRelatedEntity derive macro will implement seaography::RelationBuilder for RelatedEntity enumeration.
DeriveRelationmacros
The DeriveRelation derive macro will implement RelationTrait for Relation.
DeriveValueTypemacros
Implements traits for types that wrap a database value type.
EnumIter
Creates a new type that iterates of the variants of an enum.
FromJsonQueryResultmacros
FromQueryResultmacros
Convert a query result into the corresponding Model.
Iden