Search code examples
rustrust-diesel

How to insert into table with max(ordering) + 1 in ordering column?


I have a chapters table with a ordering column(integer) in Postgres. How to insert/create a new row with ordering set to MAX(ordering) + 1 in diesel? I've tried using raw sql as following:

INSERT INTO chapters
(id, name, user_id, book_id, ordering, date_created, date_modified)
SELECT ?, ?, ?, ?, IFNULL(MAX(ordering), 0) + 1, ?, ?
FROM chapters
WHERE book_id = ?;

and insert into by:

 let id = Uuid::new_v4().to_string_id();
    let now = Utc::now().naive_utc();
    diesel::sql_query(INSERT_CHAPTER)
        .bind::<Text, _>(&id)
        .bind::<Text, _>(name)
        .bind::<Text, _>(uid)
        .bind::<Text, _>(bid)
        .bind::<Timestamp, _>(&now)
        .bind::<Timestamp, _>(&now)
        .bind::<Text, _>(bid)
        .execute(conn)?;

It works on Sqlite3 backend, but fails on Pg backend with following error message:

"syntax error at or near \",\""

Solution

  • Use $N as placeholders for Postgres and ? for sqlite3.