├── README.md ├── nanoid.sql └── LICENSE /README.md: -------------------------------------------------------------------------------- 1 | # nanoid-postgres 2 | Nanoid implementation in PostgreSQL PL/pgSQL 3 | 4 | ## Requirements 5 | * Postgres with pgcrypto 6 | 7 | ## Usage 8 | Run the SQL file, or include the function in your database migrations 9 | 10 | Use as the default value for your id columns! 11 | ```sql 12 | CREATE TABLE users ( 13 | "id" char(21) NOT NULL DEFAULT nanoid(), 14 | ... 15 | ) 16 | ``` 17 | 18 | ## Todo 19 | * Function that takes a custom alphabet -------------------------------------------------------------------------------- /nanoid.sql: -------------------------------------------------------------------------------- 1 | CREATE EXTENSION IF NOT EXISTS pgcrypto; 2 | 3 | CREATE OR REPLACE FUNCTION nanoid(size int DEFAULT 21) 4 | RETURNS text AS $$ 5 | DECLARE 6 | id text := ''; 7 | i int := 0; 8 | urlAlphabet char(64) := 'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW'; 9 | bytes bytea := gen_random_bytes(size); 10 | byte int; 11 | pos int; 12 | BEGIN 13 | WHILE i < size LOOP 14 | byte := get_byte(bytes, i); 15 | pos := (byte & 63) + 1; -- + 1 because substr starts at 1 for some reason 16 | id := id || substr(urlAlphabet, pos, 1); 17 | i = i + 1; 18 | END LOOP; 19 | RETURN id; 20 | END 21 | $$ LANGUAGE PLPGSQL VOLATILE; -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Jake Lee Kennedy 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | --------------------------------------------------------------------------------