Skip to content

Instantly share code, notes, and snippets.

@simonthompson99
Last active January 13, 2021 12:43
Show Gist options
  • Save simonthompson99/3218136afda7a628248eec8ed2f31e14 to your computer and use it in GitHub Desktop.
Save simonthompson99/3218136afda7a628248eec8ed2f31e14 to your computer and use it in GitHub Desktop.
[Pseudo random integer generator] Create pseudo random integer from sequence ([from Postgres wiki](https://wiki.postgresql.org/wiki/Pseudo_encrypt)) #sql #database
create sequence testes.test_id_seq
;
create or replace function pseudo_encrypt(value int) returns int as $$
declare
l1 int;
l2 int;
r1 int;
r2 int;
i int:=0;
begin
l1:= (value >> 16) & 65535;
r1:= value & 65535;
while i < 3 loop
l2 := r1;
r2 := l1 # ((((1366 * r1 + 150889) % 714025) / 714025.0) * 32767)::int;
l1 := l2;
r1 := r2;
i := i + 1;
end loop;
return ((r1 << 16) + l1);
end;
$$ language plpgsql strict immutable;
create table testes.id_test (
test_uid uuid not null default uuid_generate_v4(),
id varchar not null default concat('sp', lpad(pseudo_encrypt(nextval('testes.test_id_seq')::int)::text, 10, '0'))
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment