I am providing a key table to my users in various categories so I am thinking how to TRIGGER/RETURNING the function with each SELECT
.
Functions to generate shorthand unique IDs
- The thread answer Generating human-readable/usable, short but unique IDs but no salt so no.
- http://hashids.org/ can be a valid option as proposed by the answer here
- Any default PostgreSQL options?
Example of key table where I need the keys
Module 1
1. <key1>
2. <key2>
3. ...
Module 2
1. <key1>
2. <key2>
Keys are bound to the SERIAL primary keys in the table event_log
.
I am thinking if the database can do the generation task for you i.e. how to bind your primary key to any algorithm that can generate such shorthand forms.
I have currently the data as the following in the table where SERIAL PRIMARY
is not so clear
CREATE TABLE event_log (
data_id SERIAL PRIMARY KEY NOT NULL,
name VARCHAR(10) NOT NULL,
module INTEGER NOT NULL, - - 1 or 2 or 3 as value
time TIMESTAMP NOT NULL
);
Idea: Bind a TRIGGER
and/or RETURNING nice_id
to SELECT * FROM event_log WHERE module=1
queries
OS: Debian Linux 8.7
SQL: PostgreSQL 9.4 and/or R sqldf
Best Answer
Since you mention a salt, I assume you're looking for short strings that are hard to guess or reproduce by an outsider, despite being originated with a database sequence. The permuteseq extension essentially does that.
The function that produces a short string from an integer has to be provided, for instance:
Then you may set the short id slug in a BEFORE INSERT trigger, like this:
Testing it:
In this example, there is both
id
andshort_id
in the table, butid
is technically redundant withshort_id
. You could create a sequence outside of the table without theSERIAL
syntax like this, and not even haveid
in the table:If you can't use
permuteseq
, as an alternative still based on encrypting the ID, you may look at the plpgsql implementation of SKIP32, or XTEA for 64-bit (bigint) which won't require a compilation or being superuser. The drawback is that you cannot fine-tune the size of the output by changing the sequence's range.