Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute an insert or update using Diesel

I am trying to execute an insert or update using Diesel with PostgreSQL.

I have tried:

diesel::insert_into($table::table).values(&objects).on_conflict($table::id).do_update().set(&objects).execute(conn).unwrap();

where objects is a std::vec::Vec<Struct> - which results in the compiler error:

^^^ the trait 'diesel::query_builder::AsChangeset' is not implemented for '&std::vec::Vec<Struct>'

There is a on_conflict_do_nothing() in the query builder but I can't seem to find something like on_conflict_do_update() or on_conflict_do_replace().

like image 414
Ronny Avatar asked Dec 04 '17 03:12

Ronny


1 Answers

Diesel 1.3.3's documentation already has examples for using an upsert:

Set specific value on conflict

diesel::insert_into(users)
    .values(&user2)
    .on_conflict(id)
    .do_update()
    .set(name.eq("I DONT KNOW ANYMORE"))
    .execute(&conn);

Set AsChangeset struct on conflict

diesel::insert_into(users)
    .values(&user2)
    .on_conflict(id)
    .do_update()
    .set(&user2)
    .execute(&conn);

Use excluded to get the rejected value

diesel::insert_into(users)
    .values(&vec![user2, user3])
    .on_conflict(id)
    .do_update()
    .set(name.eq(excluded(name)))
    .execute(&conn)

IncompleteDoUpdate::set takes any value that implements AsChangeset, which &Vec<T> does not. Thus it is invalid to pass it as an argument to set.

like image 172
Shepmaster Avatar answered Nov 18 '22 12:11

Shepmaster