Skip to content

Instantly share code, notes, and snippets.

@albttx
Created April 29, 2021 09:39
Show Gist options
  • Select an option

  • Save albttx/6ae869076f109c232d688b6e114f8743 to your computer and use it in GitHub Desktop.

Select an option

Save albttx/6ae869076f109c232d688b6e114f8743 to your computer and use it in GitHub Desktop.

Revisions

  1. albttx revised this gist Apr 29, 2021. No changes.
  2. albttx created this gist Apr 29, 2021.
    32 changes: 32 additions & 0 deletions script.sql
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@

    -- Using script https://github.com/array-analytics/plpg_hashids

    DROP TABLE fruits;

    CREATE TABLE fruits (
    id SERIAL UNIQUE NOT NULL,
    hash_id VARCHAR(16) PRIMARY KEY
    DEFAULT hashids.encode(currval(pg_get_serial_sequence('fruits', 'id')), 'SALT', 16),
    fruit_name VARCHAR
    );

    INSERT INTO fruits (fruit_name) VALUES ('apple'), ('banana'), ('orange');
    -- psql:/scripts/hashid.sql:18: NOTICE: {1}[1]: 1 for 1
    -- psql:/scripts/hashid.sql:18: NOTICE: {2}[1]: 2 for 1
    -- psql:/scripts/hashid.sql:18: NOTICE: {3}[1]: 3 for 1
    -- INSERT 0 3

    SELECT * FROM fruits;
    -- INSERT 0 3
    -- id | hash_id | fruit_name
    -- ----+------------------+------------
    -- 1 | AaW52xD2Q3zLPqbo | apple
    -- 2 | jGQ7MkDaMDXAK0Jx | banana
    -- 3 | yBZMgjvnmp9zmJO8 | orange


    SELECT currval(pg_get_serial_sequence('fruits', 'id'));
    -- currval
    -- ---------
    -- 3
    -- (1 row)