简体   繁体   English

Postgres:删除所有表格或级联删除?

[英]Postgres: delete all tables or cascade a delete?

Is it possible either to delete all rows from all tables with a single command in postgres (without destroying the database), or to cascade a delete in postgres? 是否可以使用postgres中的单个命令删除所有表中的所有行(不破坏数据库),或者在postgres中级联删除?

If not, then how can I reset my test database? 如果没有,那么如何重置我的测试数据库?

is it possible either to delete all rows from all tables with a single command in postgres 是否可以使用postgres中的单个命令删除所有表中的所有行

You are right, the answer is NO 你是对的,答案是肯定的

You can define cascading foreign keys that will delete all referencing rows if the "parent" is deleted. 您可以定义级联外键,如果删除“父级”,将删除所有引用行。 But that is an attribute of the foreign key, nothing you can specify with the DELETE statement 但这是外键的属性,您无法使用DELETE语句指定任何内容

if not - wow. 如果不是 - 哇。

What's that supposed to mean? 那是什么意思?

On second thought: what are you trying to achieve? 第二个想法:你想要实现什么?

I have the suspicion that you are trying to "reset" eg a test database. 我怀疑你正试图“重置”例如测试数据库。 In that case the PostgreSQL approach would be: 在这种情况下,PostgreSQL方法将是:

  • Create a database that contains everything (tables, views, indexes etc) you need in a new database (call it eg my_template) 创建一个包含新数据库中所需的所有内容(表,视图,索引等)的数据库(称为my_template)
  • To reset your current test-DB, do a DROP DATABASE testdb and then re-create the test database using CREATE DATABASE testdb TEMPLATE my_template 要重置当前的test-DB,请执行DROP DATABASE testdb ,然后使用CREATE DATABASE testdb TEMPLATE my_template重新创建测试数据库CREATE DATABASE testdb TEMPLATE my_template

The newly created testdb will have all tables defined in my_template. 新创建的testdb将在my_template中定义所有表。 That is probably a lot faster than deleting all rows. 这也许不是删除所有行快了很多

You could write a stored procedure that selects all tables in all schemas and then does a DELETE CASCADE or TRUNCATE on these tables. 您可以编写一个存储过程来选择所有模式中的所有表,然后对这些表执行DELETE CASCADE或TRUNCATE。 It's just a few lines of pl/pgsql-code, not a big deal. 它只是几行pl / pgsql代码,没什么大不了的。

Edit: This will do the trick, but be carefull! 编辑:这将成功,但要小心! :

CREATE OR REPLACE FUNCTION truncate_all() RETURNS void LANGUAGE plpgsql AS
$$
DECLARE
    row record;
    query   text;
BEGIN
    query := 'SELECT table_schema, table_name FROM information_schema.tables WHERE table_schema NOT IN(''pg_catalog'', ''information_schema'') AND table_type = ''BASE TABLE''';

    FOR row IN EXECUTE query LOOP
        EXECUTE 'TRUNCATE ' || quote_ident(row.table_schema) || '.' || quote_ident(row.table_name) || ' CASCADE;';
    END LOOP;

    RETURN;
END;
$$;

-- execute:
SELECT truncate_all();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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