pub trait Model {
// Required methods
fn from_row(row: &Row<'_>) -> Result<Self>
where Self: Sized;
fn insert<C>(&self, conn: C) -> Result<()>
where Self: Sized,
C: Deref<Target = Connection>;
fn insert_or<C>(&self, conn: C, strategy: OnConflict) -> Result<()>
where Self: Sized,
C: Deref<Target = Connection>;
fn as_params(&self) -> Result<Parameters<'_>>;
fn metadata(&self) -> ModelMeta;
}Expand description
An interface for types that model database tables.
Ordinarily you would use the associated derive macro to implement this trait, but it’s perfectly acceptable to implement it by hand.
Required Methods§
sourcefn from_row(row: &Row<'_>) -> Result<Self>where
Self: Sized,
fn from_row(row: &Row<'_>) -> Result<Self>where
Self: Sized,
Attempt to extract an instance of Self from the provided Row.
Best used with the query_and_then method on Statement:
#[derive(Model)]
#[table("people")]
pub struct Person {
pub name: String,
pub age: u16,
}
stmt.query_and_then([], Person::from_row)?
.map(|_| ...)sourcefn insert<C>(&self, conn: C) -> Result<()>
fn insert<C>(&self, conn: C) -> Result<()>
Attempt to insert self into the database behind the provided connection.
This method is a convenience shorthand for Model::insert_or with the Abort conflict resolution strategy.
Performance
This method uses prepare_cached to create the insertion SQL statement,
so any calls after the first with the same connection and self type should be significantly faster.
sourcefn insert_or<C>(&self, conn: C, strategy: OnConflict) -> Result<()>
fn insert_or<C>(&self, conn: C, strategy: OnConflict) -> Result<()>
Attempt to insert self into the database behind the provided connection, using the provided conflict resolution strategy.
Performance
This method uses prepare_cached to create the insertion SQL statement,
so any calls after the first with the same connection and self type should be significantly faster.
sourcefn as_params(&self) -> Result<Parameters<'_>>
fn as_params(&self) -> Result<Parameters<'_>>
Generate a slice of named Parameters from an instance of self.
This method is object-safe, making it callable on a dyn Model.
Performance
This method allocates at least once, in order to Box the returned slice.
If the implementing type has any fields annotated with #[bind]/#[extr], an additional boxing will be incurred for each annotated field.
sourcefn metadata(&self) -> ModelMeta
fn metadata(&self) -> ModelMeta
Retrieve ModelMeta (model metadata) associated with the implementing type.
This method is object-safe, making it callable on a dyn Model.
If (for whatever reason) you find yourself needing to dynamically reflect on Model properties, then this is for you.
Performance
ModelMeta is composed entirely of &'static/known-at-comptime data, making it little more than a bundle of trivially-copyable usizes.
The only overhead on this call is therefore dynamic dispatch and several shallow copies.