Skip to main content

ActiveModelTrait

Trait ActiveModelTrait 

Source
pub trait ActiveModelTrait: Clone + Debug {
    type Entity: EntityTrait;

Show 23 methods // Required methods fn take( &mut self, c: <Self::Entity as EntityTrait>::Column, ) -> ActiveValue<Value>; fn get( &self, c: <Self::Entity as EntityTrait>::Column, ) -> ActiveValue<Value>; fn set_if_not_equals( &mut self, c: <Self::Entity as EntityTrait>::Column, v: Value, ); fn try_set( &mut self, c: <Self::Entity as EntityTrait>::Column, v: Value, ) -> Result<(), DbErr>; fn not_set(&mut self, c: <Self::Entity as EntityTrait>::Column); fn is_not_set(&self, c: <Self::Entity as EntityTrait>::Column) -> bool; fn default() -> Self; fn default_values() -> Self; fn reset(&mut self, c: <Self::Entity as EntityTrait>::Column); // Provided methods fn set(&mut self, c: <Self::Entity as EntityTrait>::Column, v: Value) { ... } fn reset_all(self) -> Self { ... } fn get_primary_key_value(&self) -> Option<ValueTuple> { ... } fn insert<'a, C>( self, db: &'a C, ) -> Result<<Self::Entity as EntityTrait>::Model, DbErr> where <Self::Entity as EntityTrait>::Model: IntoActiveModel<Self>, Self: ActiveModelBehavior, C: ConnectionTrait { ... } fn update<'a, C>( self, db: &'a C, ) -> Result<<Self::Entity as EntityTrait>::Model, DbErr> where <Self::Entity as EntityTrait>::Model: IntoActiveModel<Self>, Self: ActiveModelBehavior, C: ConnectionTrait { ... } fn update_without_returning<'a, C>( self, db: &'a C, ) -> Result<UpdateResult, DbErr> where Self: ActiveModelBehavior, C: ConnectionTrait { ... } fn save<'a, C>(self, db: &'a C) -> Result<Self, DbErr> where <Self::Entity as EntityTrait>::Model: IntoActiveModel<Self>, Self: ActiveModelBehavior, C: ConnectionTrait { ... } fn delete<'a, C>(self, db: &'a C) -> Result<DeleteResult, DbErr> where Self: ActiveModelBehavior, C: ConnectionTrait { ... } fn set_from_json(&mut self, json: Value) -> Result<(), DbErr> where Self: TryIntoModel<<Self::Entity as EntityTrait>::Model>, for<'de> <<Self as ActiveModelTrait>::Entity as EntityTrait>::Model: IntoActiveModel<Self> + Deserialize<'de> + Serialize { ... } fn from_json(json: Value) -> Result<Self, DbErr> where Self: TryIntoModel<<Self::Entity as EntityTrait>::Model>, for<'de> <<Self as ActiveModelTrait>::Entity as EntityTrait>::Model: IntoActiveModel<Self> + Deserialize<'de> + Serialize { ... } fn from_arrow(batch: &RecordBatch) -> Result<Vec<Self>, DbErr> { ... } fn to_arrow(models: &[Self], schema: &Schema) -> Result<RecordBatch, DbErr> { ... } fn is_changed(&self) -> bool { ... } fn find_related<R>(&self, _: R) -> Select<R> where R: EntityTrait, Self::Entity: Related<R> { ... }
}
Expand description

The editable counterpart of a Model, used to build INSERT and UPDATE statements.

Each field of an ActiveModel is wrapped in an ActiveValue, so it can be one of:

  • Set(v) — a new value to write,
  • Unchanged(v) — the value already in the database, will not be sent in UPDATE,
  • NotSet — value is absent; the column is omitted from INSERT (letting the database supply a default) and from UPDATE.

This makes ActiveModel ideal for partial updates: only the columns you touch end up in the generated UPDATE.

Required Associated Types§

Source

type Entity: EntityTrait

The EntityTrait this ActiveModel belongs to.

Required Methods§

Source

fn take( &mut self, c: <Self::Entity as EntityTrait>::Column, ) -> ActiveValue<Value>

Take the ActiveValue of a column, leaving it as NotSet.

Source

fn get(&self, c: <Self::Entity as EntityTrait>::Column) -> ActiveValue<Value>

Read the ActiveValue of a column.

Source

fn set_if_not_equals( &mut self, c: <Self::Entity as EntityTrait>::Column, v: Value, )

Set one column to Set(v) only if v differs from the current value, avoiding spurious UPDATE rewrites. Panics on type mismatch.

Source

fn try_set( &mut self, c: <Self::Entity as EntityTrait>::Column, v: Value, ) -> Result<(), DbErr>

Set one column to Set(v), returning an error on type mismatch.

Source

fn not_set(&mut self, c: <Self::Entity as EntityTrait>::Column)

Mark a column as NotSet so it is omitted from the next INSERT or UPDATE.

Source

fn is_not_set(&self, c: <Self::Entity as EntityTrait>::Column) -> bool

true if the column is currently in the NotSet state.

Source

fn default() -> Self

A fresh ActiveModel with every column NotSet.

Source

fn default_values() -> Self

A fresh ActiveModel pre-populated with Set(default_value) for each column that has a Default impl; other columns remain NotSet.

Source

fn reset(&mut self, c: <Self::Entity as EntityTrait>::Column)

Promote one column from Unchanged to Set so it will be included in the next UPDATE. Leaves NotSet untouched.

Provided Methods§

Source

fn set(&mut self, c: <Self::Entity as EntityTrait>::Column, v: Value)

Set one column to Set(v). Panics on type mismatch; prefer try_set when the value comes from untrusted input.

Source

fn reset_all(self) -> Self

Apply reset to every column, forcing the next UPDATE to write all non-NotSet columns.

Source

fn get_primary_key_value(&self) -> Option<ValueTuple>

The primary key as a ValueTuple, or None if any primary-key column is still NotSet.

Source

fn insert<'a, C>( self, db: &'a C, ) -> Result<<Self::Entity as EntityTrait>::Model, DbErr>

Perform an INSERT operation on the ActiveModel

§Example (Postgres)
use sea_orm::{entity::*, query::*, tests_cfg::cake};

let apple = cake::ActiveModel {
    name: Set("Apple Pie".to_owned()),
    ..Default::default()
};

assert_eq!(
    apple.insert(&db)?,
    cake::Model {
        id: 15,
        name: "Apple Pie".to_owned(),
    }
);

assert_eq!(
    db.into_transaction_log(),
    [Transaction::from_sql_and_values(
        DbBackend::Postgres,
        r#"INSERT INTO "cake" ("name") VALUES ($1) RETURNING "id", "name""#,
        ["Apple Pie".into()]
    )]
);
§Example (MySQL)
use sea_orm::{entity::*, query::*, tests_cfg::cake};

let apple = cake::ActiveModel {
    name: Set("Apple Pie".to_owned()),
    ..Default::default()
};

assert_eq!(
    apple.insert(&db)?,
    cake::Model {
        id: 15,
        name: "Apple Pie".to_owned(),
    }
);

assert_eq!(
    db.into_transaction_log(),
    [
        Transaction::from_sql_and_values(
            DbBackend::MySql,
            r#"INSERT INTO `cake` (`name`) VALUES (?)"#,
            ["Apple Pie".into()]
        ),
        Transaction::from_sql_and_values(
            DbBackend::MySql,
            r#"SELECT `cake`.`id`, `cake`.`name` FROM `cake` WHERE `cake`.`id` = ? LIMIT ?"#,
            [15.into(), 1u64.into()]
        )
    ]
);
Source

fn update<'a, C>( self, db: &'a C, ) -> Result<<Self::Entity as EntityTrait>::Model, DbErr>

Perform the UPDATE operation on an ActiveModel

§Example (Postgres)
use sea_orm::{entity::*, query::*, tests_cfg::fruit};

let orange = fruit::ActiveModel {
    id: Set(1),
    name: Set("Orange".to_owned()),
    ..Default::default()
};

assert_eq!(
    orange.update(&db)?,
    fruit::Model {
        id: 1,
        name: "Orange".to_owned(),
        cake_id: None,
    }
);

assert_eq!(
    db.into_transaction_log(),
    [Transaction::from_sql_and_values(
        DbBackend::Postgres,
        r#"UPDATE "fruit" SET "name" = $1 WHERE "fruit"."id" = $2 RETURNING "id", "name", "cake_id""#,
        ["Orange".into(), 1i32.into()]
    )]);
§Example (MySQL)
use sea_orm::{entity::*, query::*, tests_cfg::fruit};

let orange = fruit::ActiveModel {
    id: Set(1),
    name: Set("Orange".to_owned()),
    ..Default::default()
};

assert_eq!(
    orange.update(&db)?,
    fruit::Model {
        id: 1,
        name: "Orange".to_owned(),
        cake_id: None,
    }
);

assert_eq!(
    db.into_transaction_log(),
    [
        Transaction::from_sql_and_values(
            DbBackend::MySql,
            r#"UPDATE `fruit` SET `name` = ? WHERE `fruit`.`id` = ?"#,
            ["Orange".into(), 1i32.into()]
        ),
        Transaction::from_sql_and_values(
            DbBackend::MySql,
            r#"SELECT `fruit`.`id`, `fruit`.`name`, `fruit`.`cake_id` FROM `fruit` WHERE `fruit`.`id` = ? LIMIT ?"#,
            [1i32.into(), 1u64.into()]
        )]);
Source

fn update_without_returning<'a, C>( self, db: &'a C, ) -> Result<UpdateResult, DbErr>

Update an ActiveModel without a RETURNING clause, yielding an UpdateResult instead of the updated model. Useful on backends without RETURNING support, or when the updated model is not needed.

Unlike ActiveModelTrait::update, this runs ActiveModelBehavior::before_save but does not run ActiveModelBehavior::after_save (there is no returned model to pass to it). Returns DbErr::RecordNotUpdated if no row matches.

Source

fn save<'a, C>(self, db: &'a C) -> Result<Self, DbErr>

Insert the model if primary key is NotSet, update otherwise. Only works if the entity has auto increment primary key.

Source

fn delete<'a, C>(self, db: &'a C) -> Result<DeleteResult, DbErr>

Delete an active model by its primary key

§Example
use sea_orm::{entity::*, query::*, tests_cfg::fruit};

let orange = fruit::ActiveModel {
    id: Set(3),
    ..Default::default()
};

let delete_result = orange.delete(&db)?;

assert_eq!(delete_result.rows_affected, 1);

assert_eq!(
    db.into_transaction_log(),
    [Transaction::from_sql_and_values(
        DbBackend::Postgres,
        r#"DELETE FROM "fruit" WHERE "fruit"."id" = $1"#,
        [3i32.into()]
    )]
);
Source

fn set_from_json(&mut self, json: Value) -> Result<(), DbErr>
where Self: TryIntoModel<<Self::Entity as EntityTrait>::Model>, for<'de> <<Self as ActiveModelTrait>::Entity as EntityTrait>::Model: IntoActiveModel<Self> + Deserialize<'de> + Serialize,

Available on crate feature with-json only.

Set the corresponding attributes in the ActiveModel from a JSON value

Note that this method will not alter the primary key values in ActiveModel.

Source

fn from_json(json: Value) -> Result<Self, DbErr>
where Self: TryIntoModel<<Self::Entity as EntityTrait>::Model>, for<'de> <<Self as ActiveModelTrait>::Entity as EntityTrait>::Model: IntoActiveModel<Self> + Deserialize<'de> + Serialize,

Available on crate feature with-json only.

Create ActiveModel from a JSON value

Source

fn from_arrow(batch: &RecordBatch) -> Result<Vec<Self>, DbErr>

Available on crate feature with-arrow only.

Create a Vec of ActiveModels from an Arrow RecordBatch.

Each row in the RecordBatch becomes one ActiveModel. Columns are matched by name (using ColumnTrait::as_str). Columns present in the RecordBatch are marked as Set; columns absent from the RecordBatch are marked as NotSet.

Supported column types: integers (i8–i64, u8–u64), floats (f32, f64), String/Text, Boolean, and date/time types (with with-chrono or with-time). Null values in nullable columns are handled.

When both with-chrono and with-time features are enabled, chrono values are attempted first. If the model uses time-crate types, the conversion automatically falls back to the time-crate representation.

Source

fn to_arrow(models: &[Self], schema: &Schema) -> Result<RecordBatch, DbErr>

Available on crate feature with-arrow only.

Convert a slice of ActiveModels into an Arrow RecordBatch.

The schema determines the output columns: each schema field is matched to an entity column by name (using ColumnTrait::as_str). Columns marked Set or Unchanged contribute their value; NotSet columns become null in the output.

Typical usage together with ArrowSchema:

let schema = MyEntity::arrow_schema();
let batch = MyActiveModel::to_arrow(&models, &schema)?;
Source

fn is_changed(&self) -> bool

Return true if any attribute of ActiveModel is Set

Find related Models belonging to self

Dyn Compatibility§

This trait is not dyn compatible.

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

Implementors§

Source§

impl ActiveModelTrait for sea_orm::rbac::entity::permission::ActiveModel

Available on crate feature rbac only.
Source§

impl ActiveModelTrait for sea_orm::rbac::entity::resource::ActiveModel

Available on crate feature rbac only.
Source§

impl ActiveModelTrait for sea_orm::rbac::entity::role::ActiveModel

Available on crate feature rbac only.
Source§

impl ActiveModelTrait for sea_orm::rbac::entity::role_hierarchy::ActiveModel

Available on crate feature rbac only.
Source§

impl ActiveModelTrait for sea_orm::rbac::entity::role_permission::ActiveModel

Available on crate feature rbac only.
Source§

impl ActiveModelTrait for sea_orm::rbac::entity::user_override::ActiveModel

Available on crate feature rbac only.
Source§

impl ActiveModelTrait for sea_orm::rbac::entity::user_role::ActiveModel

Available on crate feature rbac only.