Home > front end >  why the return id was usize when inserting record
why the return id was usize when inserting record

Time:05-28

I am using rust rustc 1.59.0 (9d1b2106e 2022-02-23) diesel diesel = { version = "1.4.8", features = ["postgres","64-column-tables","chrono","serde_json"] } to insert a record into PostgreSQL 13 database, what I am trying to do is that fetch the inserted record id after the insert action. This is part of the rust code looks like right now:

let menu_id = diesel::insert_into(crate::model::diesel::dolphin::dolphin_schema::menu_resource::table)
        .values(&new_menu_resource)
        .returning(crate::model::diesel::dolphin::dolphin_schema::menu_resource::id)
        .on_conflict_do_nothing()
        .execute(&connection)
        .unwrap();

this is my menu_resource define in rust:

table! {
    menu_resource (id) {
        id -> Int4,
        name -> Varchar,
        res_type -> Int4,
        created_time -> Int8,
        updated_time -> Int8,
        remark -> Nullable<Varchar>,
        path -> Varchar,
        parent_id -> Int4,
        component -> Nullable<Varchar>,
        sort -> Int4,
        name_zh -> Varchar,
        tree_id_path -> Varchar,
        code -> Varchar,
    }
}

but the recevied menu_id was usize data type. why return the unsize data type not the i32? what I am missing? what should I do to make it return the id with i32? I am follow the docs from here: https://docs.diesel.rs/diesel/fn.insert_into.html that tell that could returnt he value like this:

let inserted_names = diesel::insert_into(users)
    .values(&vec![
        name.eq("Diva Plavalaguna"),
        name.eq("Father Vito Cornelius"),
    ])
    .returning(name)
    .get_results(&connection);
assert_eq!(Ok(vec!["Diva Plavalaguna".to_string(), "Father Vito Cornelius".to_string()]), inserted_names);

CodePudding user response:

The documentation of RunQueryDsl::execute indicates that the return value is the number of rows affected, which is naturally represented by using an unsigned type usize. If you really want i32 instead, cast the return value by yourself.

  • Related