简体   繁体   中英

Generate uuid for all the tables in a database

I'm working on a project in which I need to generate a set of dynamic tables using UUID as table name. All the online material helps to generate UUID for a column in the table but not to the table.

Pls help me regarding the issue.

Thanks.

If I understand correctly you need to rename each table name to a UUID. To do that, run:

ALTER TABLE table_name RENAME TO uuid_generate_v1();

It beats me why anyone would want such horrible table names, this can be done using dynamic SQL.

do
$$
declare
  l_count integer;
begin
  for l_count in 1..5 loop
    execute format('create table %I (id integer primary key)', uuid_generate_v4());
  end loop;
end;
$$
;    

The %I placeholder for the format() function takes care of properly quoting those horrible names.

As a UUID is not a valid SQL identifier you are now forced to use double quotes whenever you access the table, eg:

select * 
from "2dc9502b-1e49-4c6f-9675-71a900dabc91";

A slightly nicer version of this would be to turn the UUID into a valid identifier by replacing all - with a _ and use character prefix (because a SQL identifier is not allowed to start with a number) so that the whole name becomes a valid identifier that does not need those gruesome double quotes:

do
$$
declare
  l_count integer;
begin
  for l_count in 1..5 loop
    execute format('create table %I (id integer primary key)', 't_'||replace(uuid_generate_v4()::text, '-', '_'));
  end loop;
end;
$$
; 

The above creates names like: t_2b526a62_a6bc_4c3a_bd52_f0db050c485c which is a valid identifier and doesn't need any special handling.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM