add a prefix to UUID?

I am wondering if there is a functionality where I can add a custom prefix the uuid's. These uuids would be used as a pirmary key in my case. The end result would be something like this: product_9B4F49D6F35C49FEA0dCC579A8ED4755
7 Replies
Sillvva
Sillvva9mo ago
Is the idea is to distinguish between ids from different tables?
xxxxx
xxxxxOP9mo ago
yes and for the users of api to understand what the id is pointing to
Sillvva
Sillvva9mo ago
You can use crypo.randomUUID() to generate a UUID in side drizzle's .defaultFn() method like this:
id: text('id').primaryKey().$defaultFn(() => `product_${crypto.randomUUID()}`)
id: text('id').primaryKey().$defaultFn(() => `product_${crypto.randomUUID()}`)
xxxxx
xxxxxOP9mo ago
thank you so much :D
Sillvva
Sillvva9mo ago
This is an application-level default, not a db-level default. If you tried to insert in an SQL client, the default would not be applied.
xxxxx
xxxxxOP9mo ago
yes there probably wont be any operations made using sql client
iolyd
iolyd9mo ago
For a schema level implementation, you could probably get it working with something along the lines of
const products = pgTable('products', {
id: text('id').primaryKey().default(sql`CONCAT('product_', REPLACE(uuid_generate_v4()::text, '-', '' ))`)
})
const products = pgTable('products', {
id: text('id').primaryKey().default(sql`CONCAT('product_', REPLACE(uuid_generate_v4()::text, '-', '' ))`)
})

Did you find this page helpful?