Skip to main content

Model

Trait Model 

Source
pub trait Model:
    Callbacks
    + Sized
    + Send
    + Sync
    + 'static {
    type Columns;
Show 15 associated constants and 81 methods const TABLE: &'static str; const COLUMNS: &'static [&'static str]; const ATTRIBUTES: &'static [&'static str] = Self::COLUMNS; const OWNER: &'static [(&'static str, &'static str)] = _; const PARENTS: &'static [Parent] = _; const ENCRYPTED: &'static [&'static str] = _; const GLOBAL_ROWS: bool = false; const SOFT_DELETE: Option<&'static str> = None; const DETERMINISTIC: &'static [&'static str] = _; const HIDDEN: &'static [&'static str] = _; const PRIMARY_KEY: &'static str = "id"; const INTEGER_KEY: bool = true; const DATABASE: Option<&'static str> = None; const CREATED_AT: Option<&'static str> = None; const UPDATED_AT: Option<&'static str> = None; // Required methods fn columns() -> Self::Columns; fn from_row(row: &Row) -> Result<Self>; fn values(&self) -> Vec<(&'static str, Value)>; fn id_value(&self) -> Value; // Provided methods fn attribute_values(&self) -> Vec<(&'static str, Value)> { ... } fn validate(changeset: Changeset<Self>) -> Changeset<Self> { ... } fn from_params(params: &Params) -> Changeset<Self> { ... } fn params_schema() -> Value { ... } fn path(&self) -> String { ... } fn collection_path() -> String { ... } fn all() -> Query<Self> { ... } fn default_scope(query: Query<Self>) -> Query<Self> { ... } fn for(access: &dyn Access) -> Query<Self> { ... } fn set_owner(&mut self, column: &str, value: &str) { ... } fn unscoped() -> Query<Self> { ... } fn filter(condition: impl FnOnce(&Self::Columns) -> Expr) -> Query<Self> { ... } fn where_sql( sql: &str, values: impl IntoIterator<Item = Value>, ) -> Query<Self> { ... } fn order(order: impl FnOnce(&Self::Columns) -> Order) -> Query<Self> { ... } fn preload<P: Into<Preload<Self>>>( association: impl FnOnce(&Self::Columns) -> P, ) -> Query<Self> { ... } fn find(id: impl ToValue) -> impl Future<Output = Result<Self>> + Send { ... } fn find_by( condition: impl FnOnce(&Self::Columns) -> Expr, ) -> impl Future<Output = Result<Option<Self>>> + Send { ... } fn find_or_initialize_by( condition: impl FnOnce(&Self::Columns) -> Expr, init: impl FnOnce(&mut Self) + Send, ) -> impl Future<Output = Result<Self>> + Send where Self: Default { ... } fn find_or_create_by( condition: impl FnOnce(&Self::Columns) -> Expr, init: impl FnOnce(&mut Self) + Send, ) -> impl Future<Output = Result<Self>> + Send where Self: Default + Clone { ... } fn first() -> impl Future<Output = Result<Option<Self>>> + Send { ... } fn last() -> impl Future<Output = Result<Option<Self>>> + Send { ... } fn take(n: u64) -> impl Future<Output = Result<Vec<Self>>> + Send { ... } fn count() -> impl Future<Output = Result<i64>> + Send { ... } fn ids() -> impl Future<Output = Result<Vec<i64>>> + Send { ... } fn exists() -> impl Future<Output = Result<bool>> + Send { ... } fn join<C: Model>( association: impl FnOnce(&Self::Columns) -> Association<Self, C>, condition: impl FnOnce(&C::Columns) -> Expr, ) -> Query<Self> { ... } fn joins<C: Model>( association: impl FnOnce(&Self::Columns) -> Association<Self, C>, ) -> Query<Self> { ... } fn group<K: FromColumn>( column: impl FnOnce(&Self::Columns) -> Col<Self, K>, ) -> Grouped<Self, K> { ... } fn sum<T: Summable>( column: impl FnOnce(&Self::Columns) -> Col<Self, T>, ) -> impl Future<Output = Result<T::Sum>> + Send { ... } fn average<T: Summable>( column: impl FnOnce(&Self::Columns) -> Col<Self, T>, ) -> impl Future<Output = Result<Option<f64>>> + Send { ... } fn minimum<T: Aggregable>( column: impl FnOnce(&Self::Columns) -> Col<Self, T>, ) -> impl Future<Output = Result<Option<T::Value>>> + Send { ... } fn maximum<T: Aggregable>( column: impl FnOnce(&Self::Columns) -> Col<Self, T>, ) -> impl Future<Output = Result<Option<T::Value>>> + Send { ... } fn create( changes: impl Into<Changeset<Self>>, ) -> impl Future<Output = Result<Save<Self>>> + Send { ... } fn create_with( change: impl FnOnce(&mut Self), ) -> impl Future<Output = Result<Save<Self>>> + Send where Self: Default + Clone { ... } fn changeset() -> Changeset<Self> { ... } fn change(self) -> Changeset<Self> { ... } fn update_changeset( self, changes: impl Into<Changeset<Self>>, ) -> impl Future<Output = Result<Save<Self>>> + Send { ... } fn destroy(self) -> impl Future<Output = Result<()>> + Send { ... } fn delete(self) -> impl Future<Output = Result<()>> + Send { ... } fn is_trashed(&self) -> bool { ... } fn restore(&mut self) -> impl Future<Output = Result<()>> + Send { ... } fn force_delete(self) -> impl Future<Output = Result<()>> + Send { ... } fn where_has<C: Model>( association: impl FnOnce(&Self::Columns) -> Association<Self, C>, inner: impl FnOnce(Query<C>) -> Query<C>, ) -> Query<Self> { ... } fn without<C: Model>( association: impl FnOnce(&Self::Columns) -> Association<Self, C>, ) -> Query<Self> { ... } fn with_trashed() -> Query<Self> { ... } fn only_trashed() -> Query<Self> { ... } fn touch(&self) -> impl Future<Output = Result<()>> + Send { ... } fn record(&self) -> Option<&Record> { ... } fn record_mut(&mut self) -> Option<&mut Record> { ... } fn new() -> Self where Self: Default { ... } fn tap(self, change: impl FnOnce(&mut Self)) -> Self { ... } fn build(params: impl Into<Params>) -> Self where Self: Default { ... } fn build_with(change: impl FnOnce(&mut Self)) -> Self where Self: Default { ... } fn load<P: Into<Preload<Self>>>( &mut self, association: impl FnOnce(&Self::Columns) -> P, ) -> impl Future<Output = Result<()>> + Send { ... } fn build_in<C: Model + Default>( &self, association: impl FnOnce(&Self::Columns) -> Association<Self, C>, change: impl FnOnce(&mut C), ) -> C { ... } fn attach<C: Model>( &self, association: impl FnOnce(&Self::Columns) -> Association<Self, C>, ids: impl IntoIterator<Item = i64>, ) -> impl Future<Output = Result<()>> + Send { ... } fn detach<C: Model>( &self, association: impl FnOnce(&Self::Columns) -> Association<Self, C>, ids: impl IntoIterator<Item = i64>, ) -> impl Future<Output = Result<()>> + Send { ... } fn sync<C: Model>( &self, association: impl FnOnce(&Self::Columns) -> Association<Self, C>, ids: impl IntoIterator<Item = i64>, ) -> impl Future<Output = Result<()>> + Send { ... } fn create_in<C: Model + Default + Clone>( &self, association: impl FnOnce(&Self::Columns) -> Association<Self, C>, change: impl FnOnce(&mut C), ) -> impl Future<Output = Result<Save<C>>> + Send { ... } fn assign(&mut self, params: &Params) { ... } fn is_new(&self) -> bool { ... } fn is_persisted(&self) -> bool { ... } fn changes(&self) -> Vec<(&'static str, Value)> { ... } fn is_changed(&self) -> bool { ... } fn changed(&self, column: &str) -> bool { ... } fn was(&self, column: &str) -> Option<Value> { ... } fn save(&mut self) -> impl Future<Output = Result<bool>> + Send where Self: Clone { ... } fn update( &mut self, params: impl Into<Params>, ) -> impl Future<Output = Result<bool>> + Send where Self: Clone { ... } fn update_with( &mut self, change: impl FnOnce(&mut Self), ) -> impl Future<Output = Result<bool>> + Send where Self: Clone { ... } fn reload(&mut self) -> impl Future<Output = Result<()>> + Send { ... } fn errors(&self) -> &[(&'static str, String)] { ... } fn errors_on(&self, column: &str) -> Vec<&str> { ... } fn errors_json(&self) -> Value { ... } fn messages(&self) -> Vec<String> { ... } fn full_messages(&self) -> Vec<String> { ... } fn field(&self, column: &str) -> Field { ... } fn text(&self, column: &str) -> String { ... }
}

Required Associated Constants§

Source

const TABLE: &'static str

Defaults to the snake_case, pluralized struct name.

Source

const COLUMNS: &'static [&'static str]

Provided Associated Constants§

Source

const ATTRIBUTES: &'static [&'static str] = Self::COLUMNS

What a bare JSON body may set, which a controller’s params wrap as Rails’ wrap_parameters does: the columns, and the derive adds attributes that aren’t stored and nested <name>_attributes.

Source

const OWNER: &'static [(&'static str, &'static str)] = _

The columns an Access owns rows by, each with the access’s key it holds: ("org_id", "org_id") for owned_by :org in .glacier, ("account_id", "org_id") for owned_by :org, foreign_key: :account_id. Empty for a model that isn’t scoped.

Source

const PARENTS: &'static [Parent] = _

The model’s belongs_to parents, so saving checks that an owned parent is the same tenant’s (a project of this note’s org).

Source

const ENCRYPTED: &'static [&'static str] = _

The columns stored encrypted (field secret: String, encrypted): written through crate::encryption and read back as plain text.

Source

const GLOBAL_ROWS: bool = false

Rows with no owner (org_id NULL) that every tenant reads, as owned_by :org, global: true declares: shared templates, defaults. They change only unscoped.

Source

const SOFT_DELETE: Option<&'static str> = None

soft_deletes: the column (deleted_at) a deleted record’s time goes in, rather than the row going. Queries leave such records out unless with_trashed(); restore() brings one back and force_delete() deletes it.

Source

const DETERMINISTIC: &'static [&'static str] = _

The encrypted columns encrypted the same way every time (encrypted(deterministic)), so queries can find their values.

Source

const HIDDEN: &'static [&'static str] = _

The columns never written to JSON (serialize::attributes, the model’s Serialize and its schema): hidden fields, encrypted ones and *_digest columns such as password_digest.

Source

const PRIMARY_KEY: &'static str = "id"

Source

const INTEGER_KEY: bool = true

Whether the primary key is a number, so find("12") (a param, as text) parses it, and text that isn’t a number finds nothing.

Source

const DATABASE: Option<&'static str> = None

The named database the model lives in (database = "analytics"), registered with App::named_database; None for the app’s own.

Source

const CREATED_AT: Option<&'static str> = None

The column set when a record is inserted (inserted_at, or Rails’ created_at), if the model has one.

Source

const UPDATED_AT: Option<&'static str> = None

The column set on every write, if the model has one.

Required Associated Types§

Source

type Columns

The generated struct of typed columns (PostColumns).

Required Methods§

Source

fn columns() -> Self::Columns

Source

fn from_row(row: &Row) -> Result<Self>

Source

fn values(&self) -> Vec<(&'static str, Value)>

Every column with its current value.

Source

fn id_value(&self) -> Value

Provided Methods§

Source

fn attribute_values(&self) -> Vec<(&'static str, Value)>

The virtual fields (#[glacier(attribute)]) with their values.

Source

fn validate(changeset: Changeset<Self>) -> Changeset<Self>

The model’s own validations, run on every insert and update. #[validate(…)] field attributes generate this.

Source

fn from_params(params: &Params) -> Changeset<Self>

A changeset casting the permitted fields from request params: every column except the primary key, timestamps and fields marked #[glacier(protected)]. Generated by the derive.

Source

fn params_schema() -> Value

The JSON Schema of the params from_params takes, for OpenAPI’s request bodies. Generated by the derive.

Source

fn path(&self) -> String

This record’s URL: /posts/7 by default (the table name and the primary key). Override it when the routes differ.

Source

fn collection_path() -> String

The URL of the collection, /posts by default.

Source

fn all() -> Query<Self>

All records, as a query to refine or .await.

Source

fn default_scope(query: Query<Self>) -> Query<Self>

Refines every query of the model, as Rails’ default_scope: default_scope order(:position) in a .glacier model.

Source

fn for(access: &dyn Access) -> Query<Self>

The records access may see, Post.for(access) in .glacier: those whose owner columns hold its values (the org’s id). An access that owns none of them sees nothing. Records built from the query (.build(params)) get those values too.

Source

fn set_owner(&mut self, column: &str, value: &str)

Sets an owner column (org_id) from its value as text. Generated by the derive for OWNER’s columns, which params never set.

Source

fn unscoped() -> Query<Self>

All records, without the default scope.

Source

fn filter(condition: impl FnOnce(&Self::Columns) -> Expr) -> Query<Self>

Source

fn where_sql(sql: &str, values: impl IntoIterator<Item = Value>) -> Query<Self>

The records matching a condition in SQL, ? for each of values, as Rails’ where("…", …): see Query::where_sql.

Source

fn order(order: impl FnOnce(&Self::Columns) -> Order) -> Query<Self>

Source

fn preload<P: Into<Preload<Self>>>( association: impl FnOnce(&Self::Columns) -> P, ) -> Query<Self>

All records with an association loaded: Country::preload(|c| c.installations), Country.preload(:installations) in .glacier.

Source

fn find(id: impl ToValue) -> impl Future<Output = Result<Self>> + Send

The record with this primary key, or 404 Not Found. The record with this primary key, or a 404 Not Found. A key given as text, such as params[:id], is parsed for a numeric key, as Rails’ find is: text that isn’t a number finds nothing.

Source

fn find_by( condition: impl FnOnce(&Self::Columns) -> Expr, ) -> impl Future<Output = Result<Option<Self>>> + Send

The first record matching condition, if any.

Source

fn find_or_initialize_by( condition: impl FnOnce(&Self::Columns) -> Expr, init: impl FnOnce(&mut Self) + Send, ) -> impl Future<Output = Result<Self>> + Send
where Self: Default,

The first record matching condition, or a new unsaved one set up by init, as Rails’ find_or_initialize_by: Tag.find_or_initialize_by(name: "rust") in .glacier.

Source

fn find_or_create_by( condition: impl FnOnce(&Self::Columns) -> Expr, init: impl FnOnce(&mut Self) + Send, ) -> impl Future<Output = Result<Self>> + Send
where Self: Default + Clone,

The first record matching condition, or one set up by init and saved, as Rails’ find_or_create_by. A record that fails validation comes back unsaved, with its errors.

Source

fn first() -> impl Future<Output = Result<Option<Self>>> + Send

The first record by primary key, if any.

Source

fn last() -> impl Future<Output = Result<Option<Self>>> + Send

The last record by primary key, if any.

Source

fn take(n: u64) -> impl Future<Output = Result<Vec<Self>>> + Send

The first n records by primary key.

Source

fn count() -> impl Future<Output = Result<i64>> + Send

Source

fn ids() -> impl Future<Output = Result<Vec<i64>>> + Send

Every record’s primary key: Book.ids()!, as Rails’ Book.ids.

Source

fn exists() -> impl Future<Output = Result<bool>> + Send

Whether there are any records at all: User.exists()!, as Rails’ User.exists? (User.exists(email: e)! for some).

Source

fn join<C: Model>( association: impl FnOnce(&Self::Columns) -> Association<Self, C>, condition: impl FnOnce(&C::Columns) -> Expr, ) -> Query<Self>

Records with a related record meeting a condition: Post::join(|p| p.author, |a| a.name.eq("Ada")).

Source

fn joins<C: Model>( association: impl FnOnce(&Self::Columns) -> Association<Self, C>, ) -> Query<Self>

Records with at least one related record: Post::joins(|p| p.comments).

Source

fn group<K: FromColumn>( column: impl FnOnce(&Self::Columns) -> Col<Self, K>, ) -> Grouped<Self, K>

Every record grouped by a column, to count or total each group: Post::group(|p| p.status).count(), Post.group(:status).count().

Source

fn sum<T: Summable>( column: impl FnOnce(&Self::Columns) -> Col<Self, T>, ) -> impl Future<Output = Result<T::Sum>> + Send

The sum of a numeric column over every record: Post.sum(:views).

Source

fn average<T: Summable>( column: impl FnOnce(&Self::Columns) -> Col<Self, T>, ) -> impl Future<Output = Result<Option<f64>>> + Send

The mean of a numeric column over every record.

Source

fn minimum<T: Aggregable>( column: impl FnOnce(&Self::Columns) -> Col<Self, T>, ) -> impl Future<Output = Result<Option<T::Value>>> + Send

The smallest value of a column.

Source

fn maximum<T: Aggregable>( column: impl FnOnce(&Self::Columns) -> Col<Self, T>, ) -> impl Future<Output = Result<Option<T::Value>>> + Send

The largest value of a column.

Source

fn create( changes: impl Into<Changeset<Self>>, ) -> impl Future<Output = Result<Save<Self>>> + Send

Inserts a record from params, a changeset, or anything convertible into one:

ⓘ
match Post::create(ctx.params()).await? {
    Saved(post) => redirect!(post, notice: "Post created."),
    Invalid(changeset) => render!(changeset; template = new, status = 422),
}

The model’s callbacks run, as Rails’ create runs them; changeset.insert() is the write without them.

Source

fn create_with( change: impl FnOnce(&mut Self), ) -> impl Future<Output = Result<Save<Self>>> + Send
where Self: Default + Clone,

Inserts a new record its fields set by change, running the callbacks and validations as save does: .glacier’s Post.create(title: "Hi")!. Returns Saved(post) or Invalid with its errors.

Source

fn changeset() -> Changeset<Self>

A changeset for a new record: Post::changeset().set(|p| p.title, t).

Source

fn change(self) -> Changeset<Self>

An empty changeset for this record, to build an update by hand.

Source

fn update_changeset( self, changes: impl Into<Changeset<Self>>, ) -> impl Future<Output = Result<Save<Self>>> + Send

Applies params, a changeset or anything convertible into one to this record, Ecto-style, returning Saved(record) or Invalid(changeset). update is the Active Record-style version.

The model’s callbacks run, as update runs them; changeset.update() is the write without them.

Source

fn destroy(self) -> impl Future<Output = Result<()>> + Send

Deletes the record, running before_destroy, then removing its dependent children, then after_destroy.

Source

fn delete(self) -> impl Future<Output = Result<()>> + Send

Deletes the record without callbacks.

Source

fn is_trashed(&self) -> bool

Whether it’s been soft-deleted (soft_deletes): deleted_at set.

Source

fn restore(&mut self) -> impl Future<Output = Result<()>> + Send

Brings a soft-deleted record back: deleted_at cleared, in the database and on the record.

Source

fn force_delete(self) -> impl Future<Output = Result<()>> + Send

Deletes the row for good, even with soft_deletes; no callbacks.

Source

fn where_has<C: Model>( association: impl FnOnce(&Self::Columns) -> Association<Self, C>, inner: impl FnOnce(Query<C>) -> Query<C>, ) -> Query<Self>

The records with an associated record matching inner: Author.where_has(:books, published: true).

Source

fn without<C: Model>( association: impl FnOnce(&Self::Columns) -> Association<Self, C>, ) -> Query<Self>

The records with no associated record: Author.without(:books).

Source

fn with_trashed() -> Query<Self>

Every record, soft-deleted ones too.

Source

fn only_trashed() -> Query<Self>

Only the soft-deleted records.

Source

fn touch(&self) -> impl Future<Output = Result<()>> + Send

Sets the record’s updated_at to now in the database, without callbacks or validation, as Rails’ touch. The record in hand keeps its old updated_at. Nothing happens without that column.

Source

fn record(&self) -> Option<&Record>

The record’s state, when the model has one (#[glacier::model]).

Source

fn record_mut(&mut self) -> Option<&mut Record>

Source

fn new() -> Self
where Self: Default,

A new, unsaved record with default values: Post::new().

Source

fn tap(self, change: impl FnOnce(&mut Self)) -> Self

Changes fields in a closure and returns the record: Post::new().tap(|p| p.title = "Hi".into()).

Source

fn build(params: impl Into<Params>) -> Self
where Self: Default,

A new record from form params: Post::build(ctx.params()).

Source

fn build_with(change: impl FnOnce(&mut Self)) -> Self
where Self: Default,

A new record, with change setting its fields: Note.build(title: "…") in .glacier.

Source

fn load<P: Into<Preload<Self>>>( &mut self, association: impl FnOnce(&Self::Columns) -> P, ) -> impl Future<Output = Result<()>> + Send

Loads an association of this record now, as preload does for a query’s: post.load(:comments)!, then post.comments.

Source

fn build_in<C: Model + Default>( &self, association: impl FnOnce(&Self::Columns) -> Association<Self, C>, change: impl FnOnce(&mut C), ) -> C

A new record of a has_many association, its foreign key this record’s, change setting its fields: post.build(:comments, body: "…") in .glacier, as Rails’ post.comments.build.

Source

fn attach<C: Model>( &self, association: impl FnOnce(&Self::Columns) -> Association<Self, C>, ids: impl IntoIterator<Item = i64>, ) -> impl Future<Output = Result<()>> + Send

Links this record to more records of a has_many … through: (by id), as Laravel’s attach: book.attach(:tags, [tag.id])!. Links that exist already are left alone.

Source

fn detach<C: Model>( &self, association: impl FnOnce(&Self::Columns) -> Association<Self, C>, ids: impl IntoIterator<Item = i64>, ) -> impl Future<Output = Result<()>> + Send

Unlinks records of a has_many … through: (by id): detach.

Source

fn sync<C: Model>( &self, association: impl FnOnce(&Self::Columns) -> Association<Self, C>, ids: impl IntoIterator<Item = i64>, ) -> impl Future<Output = Result<()>> + Send

Links this record to exactly these records of a has_many … through: (by id), as Laravel’s sync.

Source

fn create_in<C: Model + Default + Clone>( &self, association: impl FnOnce(&Self::Columns) -> Association<Self, C>, change: impl FnOnce(&mut C), ) -> impl Future<Output = Result<Save<C>>> + Send

build_in, then saved: post.create(:comments, body: "…")!.

Source

fn assign(&mut self, params: &Params)

Sets the permitted fields from params, keeping input that doesn’t cast (and why) for the form. Generated by the derive.

Source

fn is_new(&self) -> bool

Whether the record hasn’t been saved yet.

Source

fn is_persisted(&self) -> bool

Source

fn changes(&self) -> Vec<(&'static str, Value)>

The columns that differ from what was loaded (every column for a new record), as save would write them.

Source

fn is_changed(&self) -> bool

Source

fn changed(&self, column: &str) -> bool

Whether column differs from what was loaded.

Source

fn was(&self, column: &str) -> Option<Value>

The column’s value as loaded, before any change.

Source

fn save(&mut self) -> impl Future<Output = Result<bool>> + Send
where Self: Clone,

Validates and saves the record (insert or update), in place: true when saved; false with errors when invalid.

Source

fn update( &mut self, params: impl Into<Params>, ) -> impl Future<Output = Result<bool>> + Send
where Self: Clone,

Sets fields from params and saves, in place: true when saved, false with errors when invalid.

ⓘ
if post.update(ctx.params()).await? { … } else { … }
Source

fn update_with( &mut self, change: impl FnOnce(&mut Self), ) -> impl Future<Output = Result<bool>> + Send
where Self: Clone,

Changes fields in a closure, then saves: post.update_with(|p| p.title = "New".into()).await?.

Source

fn reload(&mut self) -> impl Future<Output = Result<()>> + Send

Loads the record again from the database, dropping unsaved changes.

Source

fn errors(&self) -> &[(&'static str, String)]

The errors from the last save: (column, message).

Source

fn errors_on(&self, column: &str) -> Vec<&str>

Error messages for one column, to show next to its form field.

Source

fn errors_json(&self) -> Value

The errors as Rails renders them in JSON: {"title": ["can't be blank"]}.

Source

fn messages(&self) -> Vec<String>

Messages with their column, lower case: ["title can't be blank"], for matching in tests and building nested records’ errors.

Source

fn full_messages(&self) -> Vec<String>

Messages with their column, as Rails shows them: ["Title can't be blank"].

Source

fn field(&self, column: &str) -> Field

One field for a form, its value and errors, for the <.input> component: <.input field={post.field("title")} />.

Source

fn text(&self, column: &str) -> String

The column’s value as text for a form field, or the input that couldn’t be cast: value="{{ post.text("price") }}".

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§