expression
SeaORM: repository boundaries and ORM trade-offs
A repository function can centralize database access and hide query construction from business logic. SeaORM offers composable entity queries; SQLx offers explicit SQL and optional compile-time query macros; Diesel provides a typed query DSL. SeaORM entity types do not prove that the deployed database schema matches. All three still need integration tests and query-plan review for performance-sensitive queries. Uses a disposable in-memory SQLite database. Expected stdout (not executed): available products: 2 Common mistake: Treating a typed ORM as proof of schema compatibility, correct permissions, or efficient SQL.
Formal Syntax & Structure
rust syntaxrust
async fn in_stock(db: &DatabaseConnection) -> Result<Vec<item::Model>, DbErr>Working Example
Example Snippetrust
use sea_orm::{ActiveModelTrait, ColumnTrait, ConnectOptions, ConnectionTrait, Database, DatabaseConnection, DbBackend, DbErr, EntityTrait, IntoActiveModel, PaginatorTrait, QueryFilter, QueryOrder, Set, Statement};
mod item { use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)] #[sea_orm(table_name = "items")] pub struct Model { #[sea_orm(primary_key)] pub id: i32, pub label: String, pub stock: i32, pub note: Option<String>, } #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] pub enum Relation {} impl ActiveModelBehavior for ActiveModel {}}
async fn sample_db() -> Result<DatabaseConnection, DbErr> { let mut options = ConnectOptions::new("sqlite::memory:"); options.max_connections(1).min_connections(1).sqlx_logging(false); let db = Database::connect(options).await?; db.execute(Statement::from_string(DbBackend::Sqlite, "CREATE TABLE items (id INTEGER PRIMARY KEY AUTOINCREMENT, label TEXT NOT NULL, stock INTEGER NOT NULL CHECK(stock >= 0), note TEXT)".to_owned())).await?; db.execute(Statement::from_string(DbBackend::Sqlite, "INSERT INTO items (label, stock, note) VALUES ('Pen', 4, NULL), ('Pad', 0, 'blue'), ('Clip', 8, NULL)".to_owned())).await?; Ok(db)}
#[tokio::main(flavor = "current_thread")]async fn main() -> Result<(), DbErr> { async fn in_stock(db: &DatabaseConnection) -> Result<Vec<item::Model>, DbErr> { item::Entity::find().filter(item::Column::Stock.gt(0)) .order_by_asc(item::Column::Id).all(db).await } let db = sample_db().await?; let rows = in_stock(&db).await?; println!("available products: {}", rows.len()); Ok(())}