I have an REST-ish endpoint that creates a day
object and sets its order
property to whatever the maximum order is +1
. I'm having an issue where calling that endpoint in rapid succession results in some of the days
having the same order
. How do I solve this?
SQL Query is like so.
insert into "days" ("order", "program_id") values (
(select max(days.order)+1
from "days"
where "days"."program_id" = '5'), '5')
returning *
And it results in something like
{"program_id":5,"id":147,"order":38}
{"program_id":5,"id":150,"order":38}
{"program_id":5,"id":148,"order":38}
{"program_id":5,"id":149,"order":38}
{"program_id":5,"id":151,"order":39}
{"program_id":5,"id":152,"order":40}
{"program_id":5,"id":153,"order":41}
If it helps, I'm on Node (Express) and using Knex and Objection to build my queries for a Postgres database. The JavaScript code is as follows.
json.order = knex.select(knex.raw('max(days.order)+1'))
.from('days')
.where('days.program_id', json.program_id);
return await Days
.query(trx)
.returning('*')
.insert(json);
I'm also using max+1
as I want the order values to increment on a per program
basis. So days
of a program
will have unique orders
, but it is possible to have days
of different programs
with the same order
.
Thanks!