TripleSpeeder
TripleSpeeder•16mo ago

Enforce unique?

My data model has a "slug" component so I have readable urls like /blog/my-new-entry/ instead of /blog/3fp6dtpeg3rxcxfbexp2cd3r9jp7kxg. Is there a way to enforce uniqueness of the slugfield on db level? I know i can use query(...).unique() but throwing here is a bit too late 🙂
4 Replies
ballingt
ballingt•16mo ago
You can check for that slug existing at insert time, that's early enough 🙂 Since mutations run as transactions there's no race conditions to worry about here
TripleSpeeder
TripleSpeederOP•16mo ago
Hmm. but i think exactly thats the problem? If uniqueness is not enforced on db level 2 users creating the same slug at the same time will be possible.
handler: async (ctx, { body, title}) => {
const slug = slugify(title);
// 1. check if slug exists and throw an error accordingly

// 2. if slug is not existing, create db entry.
return await ctx.db.insert("post", {
body,
title,
slug,
});
},
handler: async (ctx, { body, title}) => {
const slug = slugify(title);
// 1. check if slug exists and throw an error accordingly

// 2. if slug is not existing, create db entry.
return await ctx.db.insert("post", {
body,
title,
slug,
});
},
If between 1. and 2. another user creates a blog entry with the same title I end up with 2 identical slugs in the db.
lee
lee•16mo ago
Convex mutations are transactions, so race conditions like you describe are not possible. Here's a description of the transaction property https://stack.convex.dev/dont-drop-acid
Don't Drop ACID
When your database supports ACID semantics, you're free to write code the intuitive way and ignore the complexities of concurrency and failure.
TripleSpeeder
TripleSpeederOP•16mo ago
Ah, thank you. Interesting read and together with https://docs.convex.dev/database/advanced/occ clears all my questions!
OCC and Atomicity | Convex Developer Hub
In Queries, we mentioned that determinism