Created
February 11, 2023 05:48
-
-
Save hos/4e50cd57d22ea20ea4534698ec54347d to your computer and use it in GitHub Desktop.
Firestore's newId function implemented in PostgreSQL. Converted using ChatGPT.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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