Repository navigation
How does upsert work in PostgreSQL connector?
#15506
|
I am wondering how the I understand that every SQL query is a mini transaction, so I expected that the second would be ignored if I upsert two rows with the same values. I expected that Is there something I am missing, or is that the expected behavior? Is there a way to change this behavior and prevent race conditions? |
Replies: 6 comments 2 replies
|
Hey @maticzav 👋, How are you creating two entries with equal values simultaneously? Do you have any code you can share? |
|
Thank you for being so patient with my reproduction. I reduced our code to showcase the error. You can try it out yourself though it may work. If you increase concurrency, it will fail inconsistently (e.g., it fails 9/10 times), and if you change concurrency to 1, it always works. I am running a Postgres instance in Docker on an M1 Mac. import { PrismaClient } from '@prisma/client'
import cuid from 'cuid'
import plimit from 'p-limit'
// import { getUniqueID } from '../src/lib/identifiers'
const MODELS = {
WORD: 'wrd',
}
function getUniqueID(model: keyof typeof MODELS): string {
const id = cuid()
return `${MODELS[model]}-${id}`
}
// import sskj from './data/sskj.json'
const sskj = {
words: [
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'a' },
{ word: 'abak' },
{ word: 'abalienacija' },
{ word: 'abalienacijski' },
{ word: 'abbe' },
{ word: 'abc' },
{ word: 'abderit' },
{ word: 'abderitski' },
{ word: 'abderitstvo' },
{ word: 'abdicirati' },
],
}
const prisma = new PrismaClient()
async function main() {
// Seed Slovene Words
console.log(`Seeding Slovene Words...`)
const progress: { current: number } = { current: 0 }
// NOTE: This number tells the number of concurrently processed promises. Try changing to 1 or 64 to see the error.
const limit = plimit(64)
const words: { word: string }[] = sskj['words']
const tasks = words.map((w) =>
limit(async () => {
const word = w.word.toLowerCase()
const id = getUniqueID('WORD')
await prisma.word.upsert({
where: { word_lang: { word, lang: 'SLOVENIAN' } },
create: { id, word, lang: 'SLOVENIAN' },
update: {},
})
progress.current += 1
console.log(`[${progress.current}/${words.length}] Created word: "${word}" (${id})!`)
}),
)
await Promise.all(tasks)
console.log(`Seeding complete!`)
}
// Run
main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})And you can see the applicable schema for this part below. Note that I commented out appearances, but if the model Word {
id String @id
// Word should be lowercase.
word String
lang Language
explanation String?
// appearances ChallengeWord[]
@@unique([word, lang])
}
enum Language {
ENGLISH
FRENCH
GERMAN
ITALIAN
SPANISH
SLOVENIAN
DANISH
}I hope this suffices for reproduction on your end. I can also check the implementation if you could point me to the part of the engine that is responsible for checking uniqueness constraints. |
|
@maticzav because of the number of nested queries we can support in an upsert, Prisma does a few checks when an upsert happens. We have improved our docs around upserts. Take a look here https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#unique-key-constraint-errors-on-upserts This should explain what is happening. In your case, there is a race condition. Two Prisma operations first do a |
|
@garrensmith thank you for confirming my understanding. Is there a way to get the actual SQL This is kind-of a big deal for us because the client often request the same mutation multiple times and we are seeing numerous upsert failures in our logs. |
|
Hi there, To keep our discussions organized and focused on the most relevant topics, we’re reviewing and tidying up our backlog. As part of this process, we’re closing discussions that have already been marked as answered but remain open. If this discussion still requires further input or clarification, feel free to reopen it or start a new one with updated details. Your contributions are invaluable to the community, and we’re here to help! For more details about our priorities and vision for the future of Prisma ORM, check out our latest blog post: https://www.prisma.io/blog/prisma-orm-manifesto. Thank you for your understanding and ongoing support of the Prisma community! |

@maticzav because of the number of nested queries we can support in an upsert, Prisma does a few checks when an upsert happens. We have improved our docs around upserts. Take a look here https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#unique-key-constraint-errors-on-upserts This should explain what is happening.
In your case, there is a race condition. Two Prisma operations first do a
SELECTto see if a row withaandSLOVENIANexists. Both operations do not see a row that exists. So both operations try to add the row. The first operation inserts the new row. The second operation tries to insert and fails on because the row now exists. In those cases, you catch …