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
Sillvva8mo ago
Is the idea is to distinguish between ids from different tables?
xxxxx
xxxxxOP8mo ago
yes and for the users of api to understand what the id is pointing to
Sillvva
Sillvva8mo 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
xxxxxOP8mo ago
thank you so much :D
Sillvva
Sillvva8mo 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
xxxxxOP8mo ago
yes there probably wont be any operations made using sql client
iolyd
iolyd8mo 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, '-', '' ))`)
})
Want results from more Discord servers?
Add your server