Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Update ActiveModel by JSON #492

Merged
merged 3 commits into from
Mar 13, 2022
Merged

Update ActiveModel by JSON #492

merged 3 commits into from
Mar 13, 2022

Conversation

billy1624
Copy link
Member

@billy1624 billy1624 commented Jan 27, 2022

PR Info

Added

  • Set the corresponding attributes in the ActiveModel from a JSON value with ActiveModel::set_from_json method
  • New error variant DbErr::Json, representing error of converting JSON value into Model

@billy1624 billy1624 self-assigned this Jan 27, 2022
@billy1624 billy1624 marked this pull request as ready for review January 27, 2022 10:48
@billy1624 billy1624 requested a review from tyt2y3 January 27, 2022 10:48
@billy1624 billy1624 linked an issue Jan 28, 2022 that may be closed by this pull request
billy1624 added a commit to SeaQL/seaql.github.io that referenced this pull request Jan 31, 2022
@billy1624
Copy link
Member Author

billy1624 commented Feb 4, 2022

But instead of setting columns one by one, why don't we convert a custom deserializable Model into ActiveModel?
https://www.sea-ql.org/SeaORM/docs/advanced-query/custom-active-model

@tyt2y3 tyt2y3 force-pushed the master branch 2 times, most recently from 7ce941b to 33a87d7 Compare February 6, 2022 06:39
billy1624 added a commit to SeaQL/seaql.github.io that referenced this pull request Feb 7, 2022
@qyihua
Copy link

qyihua commented Feb 16, 2022

But instead of setting columns one by one, why don't we convert a custom deserializable Model into ActiveModel? https://www.sea-ql.org/SeaORM/docs/advanced-query/custom-active-model

Hi @billy1624 Thanks for your suggestion. And Sorry for the delay
The Custom Active Model is very helpful for most case of mine.
But in some use case, the keys in json is dynamic at runtime, Custom Active Model can not satisfy.
Do you have any thought of this?

@billy1624
Copy link
Member Author

Hey @qyihua, if you wanna do it dynamically. I guess you need to do it via SeaQuery.

let mut stmt = Query::insert();

stmt.into_table(entity::Entity)
    .columns(cols); // List of columns

for node_json in node_json_batch.into_iter() { // Iterate array of JSON object
    let mut vals = vec![];
    for attribute in attributes.iter() { // Iterate attributes in JSON object
        let val = node_json.get(attribute).unwrap();
        vals.push(val);
    }
    stmt.values_panic(vals);
}

let builder = db.get_database_backend();
let mut stmt = builder.build(&stmt);
db.execute(stmt).await?;

@qyihua
Copy link

qyihua commented Feb 16, 2022

@billy1624 Thank you

stmt.into_table(entity::Entity)
    .columns(cols); // List of columns

But sea_query need provide special columns in rust code.
So I write a helper trait for my use case:

pub trait SetFromJson
where
    Self: ActiveModelTrait,
{
    fn set_from_json(&mut self, json: &mut JsonValue) -> Result<(), ConvertError>;
}

impl<T> SetFromJson for T
where
    T: ActiveModelTrait,
{
    fn set_from_json(&mut self, json: &mut JsonValue) -> Result<(), ConvertError> {
        for col in <<Self::Entity as EntityTrait>::Column>::iter() {
            if let Some(json_val) = json.get_mut(col.as_str()) {
                self.set_col_from_json(col, json_val.take())
                    .map_err(|err| {
                        ConvertError::Other(format!(
                            "col: `{}`, err: {}",
                            col.as_str(),
                            err.to_string()
                        ))
                    })?;
            }
        }
        Ok(())
    }
}

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
Archived in project
Development

Successfully merging this pull request may close these issues.

Updating mutiple fields in a Model by passing a reference how to update dynamicly from json value
3 participants