I am trying to make an insert using Diesel sql_query and return the id of the inserted record, but I am getting an error
here my code
let demo_id: Vec<i32> = sql_query("insert into demo (demoname, description, demovalue) values (?, ?, 2) returning demoid")
.bind::<Text, _>("Demo1")
.bind::<Text, _>("Demo2")
.get_results(&conn).unwrap();
Getting error
the trait `QueryableByName<Pg>` is not implemented for `i32`
Thanks in advance
As it says in the documentation for sql_query
:
Unlike most queries in Diesel, sql_query will deserialize its data by name, not by index. That means that you cannot deserialize into a tuple, and structs which you deserialize from this function will need to have #[derive(QueryableByName)]
So, you would have to create a struct for the data to be deserialized into:
#[derive(QueryableByName)]
struct InsertedRowId {
#[sql_type = "Integer"]
demoid: i32
}
// Then:
let demo_id: Vec<InsertedRowId> = sql_query("insert into demo (demoname, description, demovalue) values ($1, $2, 2) returning demoid")
.bind::<Text, _>("Demo1")
.bind::<Text, _>("Demo2")
.get_results(&conn).unwrap();
Note that it is important for the name of the returned column in the query to have the same name as the corresponding struct field.
See also the documentation for QueryableByName
.
Finally - note that for postgresql, placeholders in queries are specified using the syntax $1
, $2
, etc