Skip to content

Instantly share code, notes, and snippets.

@prashant-shahi
Created August 4, 2021 20:40
Show Gist options
  • Save prashant-shahi/3e5609aa63735d84690f7346cde1d064 to your computer and use it in GitHub Desktop.
Save prashant-shahi/3e5609aa63735d84690f7346cde1d064 to your computer and use it in GitHub Desktop.

Revisions

  1. prashant-shahi created this gist Aug 4, 2021.
    24 changes: 24 additions & 0 deletions nanoid.sql
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    CREATE EXTENSION IF NOT EXISTS pgcrypto;

    CREATE OR REPLACE FUNCTION public.nanoid(size integer DEFAULT 21)
    RETURNS text
    LANGUAGE plpgsql
    STABLE
    AS $function$
    DECLARE
    id text := '';
    i int := 0;
    urlAlphabet char(64) := '_-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    bytes bytea := gen_random_bytes(size);
    byte int;
    pos int;
    BEGIN
    WHILE i < size LOOP
    byte := get_byte(bytes, i);
    pos := (byte & 63) + 1;
    id := id || substr(urlAlphabet, pos, 1);
    i = i + 1;
    END LOOP;
    RETURN id;
    END
    $function$