【问题标题】:How do I copy only 2 tables in Postgres and ignore foreign keys and constraints?如何在 Postgres 中仅复制 2 个表并忽略外键和约束?
【发布时间】:2015-12-22 20:29:03
【问题描述】:

我需要将 2 个表从生产复制到开发。它们是相同的,只是生产表中​​有更多数据。我尝试pg_dump 从生产转储并复制到开发,但它抱怨外键约束。如何暂时关闭约束?我不想复制整个数据库,因为它的数据太多,我想保留我的测试数据和用户。

ALTER TABLE
DROP INDEX
ERROR:  cannot drop constraint foods_pkey on table foods because other objects depend on it
DETAIL:  constraint fk_rails_7e399284de on table histories depends on index foods_pkey
        constraint fk_rails_8d89280489 on table food_nutrients depends on index foods_pkey

这是两张表:

                                        Table "public.foods"
      Column      |            Type             |                     Modifiers
------------------+-----------------------------+----------------------------------------------------
 id               | integer                     | not null default nextval('foods_id_seq'::regclass)
 ...
Indexes:
    "foods_pkey" PRIMARY KEY, btree (id)
    "index_foods_on_food_category_id" btree (food_category_id)
Foreign-key constraints:
    "fk_rails_a28abb337f" FOREIGN KEY (food_category_id) REFERENCES food_categories(id)
Referenced by:
    TABLE "histories" CONSTRAINT "fk_rails_7e399284de" FOREIGN KEY (food_id) REFERENCES foods(id)
    TABLE "food_nutrients" CONSTRAINT "fk_rails_8d89280489" FOREIGN KEY (food_id) REFERENCES foods(id)

                                     Table "public.food_categories"
   Column   |            Type             |                          Modifiers
------------+-----------------------------+--------------------------------------------------------------
 id         | integer                     | not null default nextval('food_categories_id_seq'::regclass)
 ...
Indexes:
    "food_categories_pkey" PRIMARY KEY, btree (id)
Referenced by:
    TABLE "foods" CONSTRAINT "fk_rails_a28abb337f" FOREIGN KEY (food_category_id) REFERENCES food_categories(id)

我也试过--disable-triggers,但没有帮助。

【问题讨论】:

  • 您只想从foodfood_categories 获取数据?,您如何需要它,例如在开发数据库中创建新表并将数据从生产数据库复制到它或什么?
  • 你见过这个 - stackoverflow.com/questions/3195125/… 吗?
  • @wingᴇdpᴀnᴛʜᴇʀ 通过使用pg_dump | psql
  • 如果是常规操作(从 prod 复制到 dev),您可以将您的约束(FK)声明为 DEFERRABLE,并且可以在 copy 事务结束时进行检查。请看这个优秀的answer
  • @Houari 但是我不必使用 DEFERRABLE 创建约束吗?如果约束和索引已经存在怎么办?如何删除它和表格以便重新创建它?

标签: postgresql


【解决方案1】:

您可以先复制“food_categories”表。之后,您可以复制“食物”表。

【讨论】:

  • 但我什至不能先删除索引或表。我尝试复制哪个顺序并不重要,因为我必须先删除它们,而且它不会让我这样做,正如您在问题中的错误中看到的那样。
  • @Chloe 您必须先删除“历史”表和“食物营养素”。因为它们依赖于“食物”表。你也可以试试“DROP TABLE name CASCADE”
  • 就是这样。我不想删除我的本地测试数据。我只想添加数据并暂时关闭约束以在这些表中添加这些缺失的行。
  • @Chloe 您可以使用“pgAdmin”备份这些表,然后将它们导入回来。
猜你喜欢
  • 2023-03-27
  • 1970-01-01
  • 2021-04-02
  • 1970-01-01
  • 2019-02-20
  • 2011-05-15
  • 2022-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多