I saw a bunch of different solutions on StackOverflow that span many years and many versions of Postgres, but with some of the newer features like gen_random_bytesI want to ask again if there is a simpler solution in newer versions.
The specified identifiers containing a-zA-Z0-9, and vary in size depending on where they are used, for example ...
bTFTxFDPPq
tcgHAdW3BD
IIo11r9J0D
FUW5I8iCiS
uXolWvg49Co5EfCo
LOscuAZu37yV84Sa
YyrbwLTRDb01TmyE
HoQk3a6atGWRMCSA
HwHSZgGRStDMwnNXHk3FmLDEbWAHE1Q9
qgpDcrNSMg87ngwcXTaZ9iImoUmXhSAv
RVZjqdKvtoafLi1O5HlvlpJoKzGeKJYS
3Rls4DjWxJaLfIJyXIEpcjWuh51aHHtK
(Similar to the identifiers that Stripe uses .)
How can you generate them randomly and safely (how much less collisions and less predictability) with a simple way to specify different lengths for different use cases, in Postgres 9.6 +?
, , :
generate_uid(size integer) returns text
size .
, , gen_random_bytes() random() , , .
!
gen_random_uuid() UUID, . -, , , Stripe ( ), : "id": "ch_19iRv22eZvKYlo2CAxkjuHxZ", , - .
, encode(gen_random_bytes(), 'hex') , , , , .
, , . Node.js :
var crypto = require('crypto');
var set = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
function generate(length) {
var bytes = crypto.randomBytes(length);
var chars = [];
for (var i = 0; i < bytes.length; i++) {
chars.push(set[bytes[i] % set.length]);
}
return chars.join('');
}