PostgreSQL 事务性 DDL 和 to_regclass

PostgreSQL transactional DDL and to_regclass

按照 this question 的建议,我正在使用 to_regclass 函数检查 table 是否存在,如果不存在则创建它。但是,看起来如果 table 是在当前事务中创建的,to_regclass 仍然 returns null.

这种行为是预期的吗?或者这是一个错误?

详情

这里有一个简短的例子来说明哪里出了问题:

begin;
create schema test;
create table test.test ( id serial, category integer );

create or replace function test.test_insert () returns trigger as $$
declare
    child_table_name text;
    table_id     text;
begin
    child_table_name = concat('test.test_', text(new.category));
    table_id = to_regclass(child_table_name::cstring);
    if table_id is null then
        execute format('create table %I ( primary key (id), check ( category = %L ) ) inherits (test.test)', child_table_name, new.category);
    end if;
    execute format ('insert into %I values (.*)', child_table_name) using new;
    return null;
end;
$$ language plpgsql;

create trigger test_insert before insert on test.test for each row execute procedure test.test_insert();

insert into test.test (category) values (1);
insert into test.test (category) values (1);
insert into test.test (category) values (1);
commit;

您使用的 %I 格式说明符不正确。

如果您的类别是 1,那么您最终会调用 to_regclass('test.test_1'),即检查模式 test 中的 table test_1

然而,format('create table %I', 'test.test_1') 会将格式参数视为单个标识符并相应地引用它,计算结果为 'create table "test.test_1"'。这将在您的默认架构中创建一个名为 "test.test_1" 的 table(可能是 public)。

相反,您需要将架构和 table 名称视为单独的标识符。将您的 table 名称定义为:

child_table_name = format('test.%I', 'test_' || new.category);

... 在构建 SQL 字符串时,只需直接替换此值(即使用 %s 而不是 %I)。