pg_hashids: Short UIDs
A guide from Supabase
Apps on Plentiful run on Supabase's open-source database, sign-in, file storage and live updates, so most of this guide applies. The differences: your app reaches its database through its own server — not Supabase's data API (supabase.from(…)) — there are no Edge Functions (your app's server does that work), and scheduled work uses Jobs. Where it says "Supabase dashboard", use your app's Dashboard. Ask the builder when in doubt.
pg_hashids provides a secure way to generate short, unique, non-sequential ids from numbers. The hashes are intended to be small, easy-to-remember identifiers that can be used to obfuscate data (optionally) with a password, alphabet, and salt. For example, you may wish to hide data like user IDs, order numbers, or tracking codes in favor of pg_hashid's unique identifiers.
Enable the extension#
- Go to the Database page in the Dashboard.
- Click on Extensions in the sidebar.
- Search for "pg_hashids" and enable the extension.
Usage#
Suppose we have a table that stores order information, and we want to give customers a unique identifier without exposing the sequential id column. To do this, we can use pg_hashid's id_encode function.
1create table orders (2 id serial primary key,3 description text,4 price_cents bigint5);67insert into orders (description, price_cents)8values ('a book', 9095);910select11 id,12 id_encode(id) as short_id,13 description,14 price_cents15from16 orders;1718 id | short_id | description | price_cents19----+----------+-------------+-------------20 1 | jR | a book | 909521(1 row)To reverse the short_id back into an id, there is an equivalent function named id_decode.
Resources#
- Official pg_hashids documentation