Mukund
Mukund2w ago

Autoincrement and unique fields in convex.

This is my drizzle schema:
const admins = createTable("admins", {
id: int("id").autoincrement().primaryKey(),
name: varchar("name", { length: 255 }).notNull().unique(),
username: varchar("username", { length: 12 }).notNull(),
email: varchar("email", { length: 255 }).notNull(),
phone: varchar("phone", { length: 15 }).notNull(),
passwordHash: varchar("password_hash", { length: 255 }).notNull(),

...created_updated_at,
}, (t)=>[
uniqueIndex("username_idx").on(t.username),
index("email_idx").on(t.email),
index("phone_idx").on(t.phone),
],
);
const admins = createTable("admins", {
id: int("id").autoincrement().primaryKey(),
name: varchar("name", { length: 255 }).notNull().unique(),
username: varchar("username", { length: 12 }).notNull(),
email: varchar("email", { length: 255 }).notNull(),
phone: varchar("phone", { length: 15 }).notNull(),
passwordHash: varchar("password_hash", { length: 255 }).notNull(),

...created_updated_at,
}, (t)=>[
uniqueIndex("username_idx").on(t.username),
index("email_idx").on(t.email),
index("phone_idx").on(t.phone),
],
);
I created a convex schema like this:
const admin = defineTable({
name: v.string(),
username: v.number(),
email: v.string(),
phone: v.string(),
passwordHash: v.string(),
});
const admin = defineTable({
name: v.string(),
username: v.number(),
email: v.string(),
phone: v.string(),
passwordHash: v.string(),
});
I want username to be something like this ADMIN00001, ADMIN00002, ADMIN00003, and so on. Currently I have SQL DB and I am using AUTO_INCREMENT field by creating an id field and based on value of id updating the username. How can I do that in convex. Also, I didn't find any way to create unique fields (in my sql schema username is unique) how can I do same here.
2 Replies
Convex Bot
Convex Bot2w ago
Thanks for posting in <#1088161997662724167>. Reminder: If you have a Convex Pro account, use the Convex Dashboard to file support tickets. - Provide context: What are you trying to achieve, what is the end-user interaction, what are you seeing? (full error message, command output, etc.) - Use search.convex.dev to search Docs, Stack, and Discord all at once. - Additionally, you can post your questions in the Convex Community's <#1228095053885476985> channel to receive a response from AI. - Avoid tagging staff unless specifically instructed. Thank you!
ballingt
ballingt7d ago
Convex mutations run as transactions so you can - query for the largest current username - insert a record with a username one larger and that's safe, there's no race condition. If you're inserting high rates of these (say more than a 10,000/hour) then you might consider something fancier to lower contention, but generally you just enforce your constraints with code. The important thing here is to have an index on username getting the largest username is fast.

Did you find this page helpful?