如何在psql中使用外键约束将一个表的结构复制到另一个表?

Pre*_*thi 10 postgresql foreign-keys plpgsql create-table

使用时不会复制外键约束

create table table_name ( like source_table INCLUDING ALL)' 
Run Code Online (Sandbox Code Playgroud)

在Postgres.如何创建包含所有外键的现有表的副本.

kli*_*lin 19

没有选项可以自动创建外键CREATE TABLE ... LIKE ....

对于文档:

像source_table [like_option ...]

始终将非空约束复制到新表.仅当指定了INCLUDING CONSTRAINTS时才会复制CHECK约束[...]

仅当指定了INCLUDING INDEXES子句时,才会在新表上创建原始表的索引,PRIMARY KEY和UNIQUE约束.

在实践中,使用GUI工具很容易.例如,在PgAdmin III中:

  • 复制声明(DDL)source_table到查询工具(ctrl-e),
  • 编辑声明,
  • 执行sql.

在SQL脚本中,您可以使用以下函数.重要的假设:源表外键具有正确的名称,即它们的名称包含源表名称(典型情况是什么).

create or replace function create_table_like(source_table text, new_table text)
returns void language plpgsql
as $$
declare
    rec record;
begin
    execute format(
        'create table %s (like %s including all)',
        new_table, source_table);
    for rec in
        select oid, conname
        from pg_constraint
        where contype = 'f' 
        and conrelid = source_table::regclass
    loop
        execute format(
            'alter table %s add constraint %s %s',
            new_table,
            replace(rec.conname, source_table, new_table),
            pg_get_constraintdef(rec.oid));
    end loop;
end $$;
Run Code Online (Sandbox Code Playgroud)

使用示例:

create table base_table (base_id int primary key);
create table source_table (id int primary key, base_id int references base_table);

select create_table_like('source_table', 'new_table');

\d new_table

   Table "public.new_table"
 Column  |  Type   | Modifiers 
---------+---------+-----------
 id      | integer | not null
 base_id | integer | 
Indexes:
    "new_table_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
    "new_table_base_id_fkey" FOREIGN KEY (base_id) REFERENCES base_table(base_id)
Run Code Online (Sandbox Code Playgroud)