pub trait Model:
FromRow
+ ModelHooks
+ Clone
+ Send
+ Sync
+ 'static {
const TABLE: &'static str;
const COLUMNS: &'static [ColumnDef];
const PRIMARY_KEY: &'static str;
const UPDATED_AT: Option<&'static str> = None;
const DELETED_AT: Option<&'static str> = None;
const CHECKS: &'static [&'static str] = _;
const VERSION: Option<&'static str> = None;
Show 24 methods
// Required methods
fn insert_values(&self) -> Vec<(&'static str, Value)>;
fn primary_key_value(&self) -> Value;
// Provided methods
fn column_values(&self) -> Vec<(&'static str, Value)> { ... }
fn version_value(&self) -> Option<Value> { ... }
fn bump_version(&mut self) { ... }
fn apply_client_defaults(&mut self) { ... }
fn indexes() -> Vec<IndexDef>
where Self: Sized { ... }
fn index_statements(dialect: &dyn Dialect) -> Result<Vec<String>>
where Self: Sized { ... }
fn table_schema() -> TableSchema
where Self: Sized { ... }
fn query() -> QuerySet<Self>
where Self: Sized { ... }
fn find<E: Executor + Send>(
executor: E,
pk: impl BindValue + Send,
) -> impl Future<Output = Result<Self>> + Send
where Self: Sized { ... }
fn get_or_none<E: Executor + Send>(
executor: E,
pk: impl BindValue + Send,
) -> impl Future<Output = Result<Option<Self>>> + Send
where Self: Sized { ... }
fn create<E: Executor + Send + Sync>(
executor: E,
value: &Self,
) -> impl Future<Output = Result<Self>> + Send
where Self: Sized { ... }
fn bulk_create<E: Executor + Send>(
executor: E,
values: &[Self],
) -> impl Future<Output = Result<u64>> + Send
where Self: Sized { ... }
fn upsert<E: Executor + Send + Sync>(
executor: E,
value: &Self,
) -> impl Future<Output = Result<Self>> + Send
where Self: Sized { ... }
fn upsert_on<E: Executor + Send + Sync>(
executor: E,
value: &Self,
conflict_target: &'static [&'static str],
) -> impl Future<Output = Result<Self>> + Send
where Self: Sized { ... }
fn get_or_create<E, F>(
executor: E,
filter: F,
value: &Self,
) -> impl Future<Output = Result<(Self, bool)>> + Send
where E: Executor + Send + Sync,
F: FnOnce(QuerySet<Self>) -> QuerySet<Self> + Send,
Self: Sized { ... }
fn update_or_create<E, F>(
executor: E,
filter: F,
value: &Self,
) -> impl Future<Output = Result<(Self, bool)>> + Send
where E: Executor + Send + Sync,
F: FnOnce(QuerySet<Self>) -> QuerySet<Self> + Send,
Self: Sized { ... }
fn first_or_create<E, F>(
executor: E,
filter: F,
value: &Self,
) -> impl Future<Output = Result<Self>> + Send
where E: Executor + Send + Sync,
F: FnOnce(QuerySet<Self>) -> QuerySet<Self> + Send,
Self: Sized { ... }
fn save<E: Executor + Send + Sync>(
&mut self,
executor: E,
) -> impl Future<Output = Result<u64>> + Send
where Self: Sized { ... }
fn delete<E: Executor + Send + Sync>(
&self,
executor: E,
) -> impl Future<Output = Result<u64>> + Send
where Self: Sized { ... }
fn force_delete<E: Executor + Send + Sync>(
&self,
executor: E,
) -> impl Future<Output = Result<u64>> + Send
where Self: Sized { ... }
fn restore<E: Executor + Send + Sync>(
&self,
executor: E,
) -> impl Future<Output = Result<u64>> + Send
where Self: Sized { ... }
fn primary_key_filter(&self) -> Expr
where Self: Sized { ... }
}Expand description
A struct that maps to a database table.
§Examples
use tork_orm_core::{ColumnDef, Model};
fn primary_key<M: Model>() -> &'static str {
M::PRIMARY_KEY
}Required Associated Constants§
Sourceconst PRIMARY_KEY: &'static str
const PRIMARY_KEY: &'static str
The name of the primary key column.
Provided Associated Constants§
Sourceconst UPDATED_AT: Option<&'static str> = None
const UPDATED_AT: Option<&'static str> = None
The column auto-set to the current time on every save, if
the model declares a #[field(updated_at)] column. None otherwise.
Sourceconst DELETED_AT: Option<&'static str> = None
const DELETED_AT: Option<&'static str> = None
The soft-delete timestamp column, if the model declares a
#[field(deleted_at)] column. None otherwise.
When set, delete and QuerySet::delete stamp this column
instead of removing the row, and Model::query excludes rows where it is
non-null by default.
Sourceconst CHECKS: &'static [&'static str] = _
const CHECKS: &'static [&'static str] = _
Table-level CHECK (...) constraint expressions declared with
#[table(check = "...")]. Empty by default.
Sourceconst VERSION: Option<&'static str> = None
const VERSION: Option<&'static str> = None
The optimistic-lock version column, if the model declares a
#[field(version)] column. None otherwise.
When set, save only updates the row when its version still
matches, bumps the version, and returns an [ErrorKind::Conflict] error if
the row was changed concurrently.
Required Methods§
Sourcefn insert_values(&self) -> Vec<(&'static str, Value)>
fn insert_values(&self) -> Vec<(&'static str, Value)>
Returns the column-name and value pairs to write on insert.
Auto-assigned columns (such as an auto-increment primary key) are omitted so the database fills them in.
Sourcefn primary_key_value(&self) -> Value
fn primary_key_value(&self) -> Value
Returns the value of the primary key column for this instance.
Provided Methods§
Sourcefn column_values(&self) -> Vec<(&'static str, Value)>
fn column_values(&self) -> Vec<(&'static str, Value)>
Returns every column’s current value, including auto-assigned and
DB-defaulted columns (unlike insert_values).
Used to read a relation join key by column name, which may be an auto column
on a loaded model. #[derive(Model)] overrides this with the full column
set; the default covers the insert columns plus the primary key, which is
enough for hand-written impls whose join key is the primary key or a plain
(non-auto) column.
Sourcefn version_value(&self) -> Option<Value>
fn version_value(&self) -> Option<Value>
Returns this instance’s current optimistic-lock version, or None when the
model has no #[field(version)] column. Generated by #[derive(Model)].
Sourcefn bump_version(&mut self)
fn bump_version(&mut self)
Increments this instance’s in-memory version after a successful locked
save, so a subsequent save uses the new value. A no-op when
the model has no version column. Generated by #[derive(Model)].
Sourcefn apply_client_defaults(&mut self)
fn apply_client_defaults(&mut self)
Applies the model’s client-side field defaults (#[field(default_with = …)])
to any field still at its empty value.
Generated by #[derive(Model)]; a no-op when no field declares one. Called
by create/upsert just before before_create,
so a value you set explicitly is preserved and only an unset field is filled.
Sourcefn indexes() -> Vec<IndexDef>where
Self: Sized,
fn indexes() -> Vec<IndexDef>where
Self: Sized,
Returns the indexes declared on this model.
The default is empty; #[derive(Model)] overrides it from the field-level
index/unique attributes and the table-level #[table(indexes = [...])]
list. This is a method rather than an associated constant because a partial
index’s predicate is a runtime Expr.
Sourcefn index_statements(dialect: &dyn Dialect) -> Result<Vec<String>>where
Self: Sized,
fn index_statements(dialect: &dyn Dialect) -> Result<Vec<String>>where
Self: Sized,
Renders every index on this model to its CREATE INDEX statement.
This is the reflection helper a future schema-diffing tool builds on; it is
also handy in tests. Each index is rendered for dialect, so an unsupported
feature (such as an index method on a backend that lacks one) surfaces as an
error here.
Sourcefn table_schema() -> TableSchemawhere
Self: Sized,
fn table_schema() -> TableSchemawhere
Self: Sized,
Returns this model’s full intended schema (columns and indexes).
The reflection migrate generate diffs against the live database.
Sourcefn find<E: Executor + Send>(
executor: E,
pk: impl BindValue + Send,
) -> impl Future<Output = Result<Self>> + Sendwhere
Self: Sized,
fn find<E: Executor + Send>(
executor: E,
pk: impl BindValue + Send,
) -> impl Future<Output = Result<Self>> + Sendwhere
Self: Sized,
Finds a single row by its primary key.
Returns the row if found, or
ErrorKind::NotFound when no row has that
key.
§Examples
let user = User::find(&db, 42).await?;Sourcefn get_or_none<E: Executor + Send>(
executor: E,
pk: impl BindValue + Send,
) -> impl Future<Output = Result<Option<Self>>> + Sendwhere
Self: Sized,
fn get_or_none<E: Executor + Send>(
executor: E,
pk: impl BindValue + Send,
) -> impl Future<Output = Result<Option<Self>>> + Sendwhere
Self: Sized,
Finds a single row by its primary key, returning None when it does not
exist.
Errors with ErrorKind::MultipleFound if
more than one row matches (which should never happen for a proper primary
key, but the check is there for safety).
§Examples
if let Some(user) = User::get_or_none(&db, 42).await? {
println!("found user {:?}", user.primary_key_value());
}Sourcefn create<E: Executor + Send + Sync>(
executor: E,
value: &Self,
) -> impl Future<Output = Result<Self>> + Sendwhere
Self: Sized,
fn create<E: Executor + Send + Sync>(
executor: E,
value: &Self,
) -> impl Future<Output = Result<Self>> + Sendwhere
Self: Sized,
Inserts value and returns the stored row, including any
database-assigned columns (such as an auto-increment primary key).
Sourcefn bulk_create<E: Executor + Send>(
executor: E,
values: &[Self],
) -> impl Future<Output = Result<u64>> + Sendwhere
Self: Sized,
fn bulk_create<E: Executor + Send>(
executor: E,
values: &[Self],
) -> impl Future<Output = Result<u64>> + Sendwhere
Self: Sized,
Inserts many values in one statement, returning the number inserted.
An empty slice inserts nothing and returns zero.
Sourcefn upsert<E: Executor + Send + Sync>(
executor: E,
value: &Self,
) -> impl Future<Output = Result<Self>> + Sendwhere
Self: Sized,
fn upsert<E: Executor + Send + Sync>(
executor: E,
value: &Self,
) -> impl Future<Output = Result<Self>> + Sendwhere
Self: Sized,
Inserts value, or updates the existing row when it conflicts on the
primary key.
A convenience over upsert_on using the primary key as
the conflict target. For an auto-increment primary key (which never collides
on insert) target a unique business key with upsert_on instead.
§Examples
let updated = User::upsert(&db, &User { /* ... */ }).await?;Sourcefn upsert_on<E: Executor + Send + Sync>(
executor: E,
value: &Self,
conflict_target: &'static [&'static str],
) -> impl Future<Output = Result<Self>> + Sendwhere
Self: Sized,
fn upsert_on<E: Executor + Send + Sync>(
executor: E,
value: &Self,
conflict_target: &'static [&'static str],
) -> impl Future<Output = Result<Self>> + Sendwhere
Self: Sized,
Inserts value, or updates the existing row when it conflicts on the
conflict_target columns (a unique or primary key).
Renders portable INSERT ... ON CONFLICT (target) DO UPDATE SET ..., setting
every non-target column to its inserted value. Returns the stored row.
§Examples
// Insert, or update the existing row with the same email.
let saved = User::upsert_on(&db, &User { /* ... */ }, &["email"]).await?;Sourcefn get_or_create<E, F>(
executor: E,
filter: F,
value: &Self,
) -> impl Future<Output = Result<(Self, bool)>> + Send
fn get_or_create<E, F>( executor: E, filter: F, value: &Self, ) -> impl Future<Output = Result<(Self, bool)>> + Send
Tries to find a row matching filter, creating it with value if none
exists.
Returns (row, true) if a new row was created, or (row, false) if an
existing row was found. The lookup uses
one_or_none so it errors when the filter
matches more than one row.
§Examples
let (user, created) = User::get_or_create(
&db,
|q| q.filter(User::query().into_statement().filters.is_empty().then_some(tork_orm_core::Expr::CountStar).unwrap_or(tork_orm_core::Expr::CountStar)),
&User { /* ... */ },
).await?;Sourcefn update_or_create<E, F>(
executor: E,
filter: F,
value: &Self,
) -> impl Future<Output = Result<(Self, bool)>> + Send
fn update_or_create<E, F>( executor: E, filter: F, value: &Self, ) -> impl Future<Output = Result<(Self, bool)>> + Send
Tries to find a row matching filter, updating it with value’s fields
if found, or creating it if not.
Returns (row, true) if a new row was created, or (row, false) if an
existing row was found and updated.
§Examples
let (user, created) = User::update_or_create(
&db,
|q| q.filter(User::query().into_statement().filters.is_empty().then_some(tork_orm_core::Expr::CountStar).unwrap_or(tork_orm_core::Expr::CountStar)),
&User { /* ... */ },
).await?;Sourcefn first_or_create<E, F>(
executor: E,
filter: F,
value: &Self,
) -> impl Future<Output = Result<Self>> + Send
fn first_or_create<E, F>( executor: E, filter: F, value: &Self, ) -> impl Future<Output = Result<Self>> + Send
Tries to find the first row matching filter, creating it with value
if none exists.
Like get_or_create but uses
first for the lookup, so the filter matching
multiple rows silently returns the first one.
§Examples
let user = User::first_or_create(
&db,
|q| q.filter(User::query().into_statement().filters.is_empty().then_some(tork_orm_core::Expr::CountStar).unwrap_or(tork_orm_core::Expr::CountStar)),
&User { /* ... */ },
).await?;Sourcefn save<E: Executor + Send + Sync>(
&mut self,
executor: E,
) -> impl Future<Output = Result<u64>> + Sendwhere
Self: Sized,
fn save<E: Executor + Send + Sync>(
&mut self,
executor: E,
) -> impl Future<Output = Result<u64>> + Sendwhere
Self: Sized,
Writes this instance’s current field values to the row with its primary key, returning the number of rows changed (zero if no such row exists).
Takes &mut self so the before_save hook can mutate the instance (e.g.
bump updated_at) and the caller sees the change.
Sourcefn delete<E: Executor + Send + Sync>(
&self,
executor: E,
) -> impl Future<Output = Result<u64>> + Sendwhere
Self: Sized,
fn delete<E: Executor + Send + Sync>(
&self,
executor: E,
) -> impl Future<Output = Result<u64>> + Sendwhere
Self: Sized,
Deletes the row identified by this instance’s primary key, returning the number of rows removed (zero if no row with that key exists).
Sourcefn force_delete<E: Executor + Send + Sync>(
&self,
executor: E,
) -> impl Future<Output = Result<u64>> + Sendwhere
Self: Sized,
fn force_delete<E: Executor + Send + Sync>(
&self,
executor: E,
) -> impl Future<Output = Result<u64>> + Sendwhere
Self: Sized,
Permanently removes this row, bypassing soft-delete. Identical to
delete for models without a soft-delete column.
Sourcefn restore<E: Executor + Send + Sync>(
&self,
executor: E,
) -> impl Future<Output = Result<u64>> + Sendwhere
Self: Sized,
fn restore<E: Executor + Send + Sync>(
&self,
executor: E,
) -> impl Future<Output = Result<u64>> + Sendwhere
Self: Sized,
Clears this row’s soft-delete mark (deleted_at = NULL), returning the
number of rows restored. A no-op (returns Ok(0)) for models without a
soft-delete column.
Sourcefn primary_key_filter(&self) -> Exprwhere
Self: Sized,
fn primary_key_filter(&self) -> Exprwhere
Self: Sized,
Builds the primary_key = <value> predicate for this instance.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".