[英]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.我正在开发一个项目,在该项目中我需要使用 UUID 作为表名生成一组动态表。 All the online material helps to generate UUID for a column in the table but not to the table.
所有在线材料都有助于为表中的列生成 UUID,但不会为表生成 UUID。
Pls help me regarding the issue.请帮助我解决这个问题。
Thanks.谢谢。
If I understand correctly you need to rename each table name to a UUID.如果我理解正确,您需要将每个表名重命名为 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.我不明白为什么有人会想要这样可怕的表名,这可以使用动态 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. format()
函数的%I
占位符负责正确引用那些可怕的名字。
As a UUID is not a valid SQL identifier you are now forced to use double quotes whenever you access the table, eg:由于 UUID 不是有效的 SQL 标识符,因此您现在必须在访问表时使用双引号,例如:
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:一个稍微好一点的版本是通过将所有
-
替换为_
并使用字符前缀(因为 SQL 标识符不允许以数字开头)来将 UUID 转换为有效标识符,以便整个名称成为有效标识符不需要那些可怕的双引号:
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.以上创建的名称如下:
t_2b526a62_a6bc_4c3a_bd52_f0db050c485c
这是一个有效的标识符,不需要任何特殊处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.