Category: How do I do X?
Resource links
Updated

This solution is summarized from an archived support forum post. This information may have changed. If you notice an error, please let us know in Discord.

How to Generate the Uuidv4 Value?

Issue

I need to insert a new record into a PostgreSQL table and specify the value for the ID field using UUIDv4. I am wondering if there is an existing function to generate UUID, or if I need to implement one myself using Math.random. I also noticed that the browser has a built-in crypto function for UUID generation, but it is not yet supported in Appsmith.

Resolution

When you want to insert a new record into a PostgreSQL database and need to assign an ID using UUIDv4, the best approach is to use:

  • PostgreSQL's built-in functionality
  • JavaScript’s crypto functions

Using PostgreSQL to Generate UUIDs

  1. Set up your PostgreSQL database to handle UUIDs by enabling the uuid-ossp extension:

    CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
  2. Create a table where the id column automatically generates a UUID for each new record. A sample create table script is as follows:

    CREATE TABLE your_table (
        id UUID DEFAULT uuid_generate_v4() PRIMARY KEY,
        name TEXT
    );
    
  3. When you insert a new record into the above table, you don’t need to supply a value for the id column—PostgreSQL will automatically generate the UUID for you.

Using JavaScript’s crypto Functions

Use crypto's randomUUID function to generate a UUID and include it in your insert query. For example:

  1. INSERT INTO your_table (id, name)
    VALUES ({{crypto.randomUUID()}}, 'value1');