Hi guys! I have some database tables which has a n...
# orm-help
f
Hi guys! I have some database tables which has a non-incremental id field (Int). For every new entry I need to manually increase this value, and I can't change the database model because these are legacy tables with huge amount of data. I did some research but didn't find any relevant examples. I was thinking of doing something like this:
Copy code
const data = await prisma.model.create({
  data: {
    id: (await prisma.model.count()) + 1,
    ...params,
  },
});
Is there other way for doing this?
n
Hello, I believe you can use the preview feature “atomicNumberOperations”, something like { id: {increment: 1 }}
https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#atomic-number-operations here are some more details You need to update the feature flag to gain access to that, you can find more details here: https://github.com/prisma/prisma/releases/tag/2.6.0
f
Thanks for your answer @Nichita Z, but these
atomicOperations
only work for update operations =/ I need to do something like that but for
create
ones
r
@Felipe Belinassi 👋 The way you have suggested above could cause conflicts if more than 1 item is added at the same time. The only way I see this for now is using a raw query with a transaction block.
👋 1
f
@Ryan do this works without raw queries? Because I was planning to create a generic helper for it since I have a lot of tables that will need this Do you think something like this would work and prevent what you said?
Copy code
const insertNextVal = (prisma, model, values) => {
  const createEntry = prisma[model].create({
    id: (await prisma.model.count()) + 1,
    ...values
  })
  return prisma.$transaction([createEntry]);
}
r
No this will not work as you expect it to. The
await
inside will always be run outside the transaction. A raw query is the only way for now.
f
You mean a raw query for the
count
part or for everything (whole query as raw)?
r
The whole query.