Skip to content

Instantly share code, notes, and snippets.

@hos
Created February 11, 2023 05:48
Show Gist options
  • Save hos/4e50cd57d22ea20ea4534698ec54347d to your computer and use it in GitHub Desktop.
Save hos/4e50cd57d22ea20ea4534698ec54347d to your computer and use it in GitHub Desktop.
Firestore's newId function implemented in PostgreSQL. Converted using ChatGPT.
create or replace function public.gen_id()
returns text as $$
declare
chars text := 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
max_multiple integer := floor(256 / char_length(chars)) * char_length(chars);
i integer;
auto_id text := '';
target_length integer := 20;
bytes bytea;
begin
while char_length(auto_id) < target_length loop
bytes := gen_random_bytes(40);
for i in 1..40 loop
if char_length(auto_id) < target_length and ascii(substring(encode(bytes, 'escape'), i, 1)) < max_multiple then
auto_id := auto_id || substring(chars, (ascii(substring(encode(bytes, 'escape'), i, 1)) % char_length(chars)) + 1, 1);
end if;
end loop;
end loop;
return auto_id;
end;
$$ language plpgsql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment