Skip to content
On this page

Prefixed UUIDs

You are presented with the ID, 837eb1fb-7b56-434d-a152-4b1847c7b3b4. Is it a tenant, a user, a blog post, what? No way to tell easily. To make things clearer, prefix UUIDs with an identifier:

company_837eb1fb-7b56-434d-a152-4b1847c7b3b4 is clearly a company.
user_837eb1fb-7b56-434d-a152-4b1847c7b3b4 is clearly a user.

This makes it easier to identify what the UUID is for, especially when debugging or looking at logs.

Prisma setup with Postgres

Define models using database @default dbgenerated:

prisma
model User {
  id    String    @id @default(dbgenerated("prefix_uuid('user_'::text)"))
  // ...
}

Run the following command: npx prisma migrate dev --create-only

Add the following to the top of the created migration SQL file:

sql
CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE OR REPLACE FUNCTION prefix_uuid(prefix text) RETURNS text AS $$
BEGIN
    RETURN concat(prefix, gen_random_uuid());
END;
$$ LANGUAGE PLPGSQL VOLATILE;

Run npx prisma migrate dev