-
-
Save oojikoo/7fe6dcf601f61ced8c705cc0b6cc7ea5 to your computer and use it in GitHub Desktop.
Nano ID implementation in PostgreSQL - PL/pgSQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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$ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment