Skip to content

Instantly share code, notes, and snippets.

@ycku
Created November 4, 2021 04:55
Show Gist options
  • Save ycku/4746bc598205604169e3ae859540eaad to your computer and use it in GitHub Desktop.
Save ycku/4746bc598205604169e3ae859540eaad to your computer and use it in GitHub Desktop.
Generate Taiwan ID in PostgreSQL
create or replace function fake_twid()
returns text
language plpgsql
as
$$
declare
ret text;
check_num int;
check_index int[];
digit int;
i int;
begin
check_index = '{10,11,12,13,14,15,16,17,34,18,19,20,21,22,35,23,24,25,26,27,28,29,32,30,31,33}';
ret = chr(ascii('A')+floor(random()*26)::int+1);
check_num = (check_index[ascii(ret)-ascii('A')+1]/10)::int+(check_index[ascii(ret)-ascii('A')+1]%10)*9;
digit = floor(random()*2+1)::int;
check_num = check_num + digit*8;
ret = ret||digit;
for i in 1..7 loop
digit = floor(random()*10)::int;
check_num = check_num+digit*(8-i);
ret = ret||digit;
end loop;
check_num = check_num%10;
if check_num>0 then
check_num = 10-check_num;
end if;
ret = ret||check_num;
return ret;
end;
$$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment