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
-
Set up your PostgreSQL database to handle UUIDs by enabling the
uuid-ossp
extension:CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
-
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 );
- 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:
-
INSERT INTO your_table (id, name) VALUES ({{crypto.randomUUID()}}, 'value1');