如何从命令行删除PostgreSQL中的所有表?

我不想删除数据库本身,只想删除其中的所有表和所有数据。


当前回答

你需要删除表和序列,这是对我有用的

psql -qAtX -c "select 'DROP TABLE IF EXISTS ' || quote_ident(table_schema) || '.' || quote_ident(table_name) || ' CASCADE;' FROM information_schema.tables where table_type = 'BASE TABLE' and not table_schema ~ '^(information_schema|pg_.*)$'" | psql -qAtX
psql -qAtX -c "select 'DROP SEQUENCE IF EXISTS ' || quote_ident(relname) || ' CASCADE;' from pg_statio_user_sequences;" | psql -qAtX

在运行该命令之前,可能需要sudo/su到postgres用户或(导出连接详细信息PGHOST、PGPORT、PGUSER和PGPASSWORD),然后导出PGDATABASE=yourdatabase

其他回答

您可以使用

DO $$ DECLARE
    r RECORD;
BEGIN
    -- if the schema you operate on is not "current", you will want to
    -- replace current_schema() in query with 'schematodeletetablesfrom'
    -- *and* update the generate 'DROP...' accordingly.
    FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = current_schema()) LOOP
        EXECUTE 'DROP TABLE IF EXISTS ' || quote_ident(r.tablename) || ' CASCADE';
    END LOOP;
END $$;

IMO这比丢弃模式public要好,因为您不需要重新创建模式并恢复所有授权。

额外的好处是,这不需要外部脚本语言,也不需要将生成的SQL复制粘贴回解释器。

将PSQL与\gexec一起使用

这是一个比迄今为止更全面的查询,因为它将处理特殊的表名。

SELECT FORMAT('DROP TABLE %I.%I.%I CASCADE;', table_catalog, table_schema, table_name)
FROM information_schema.tables
WHERE table_type = 'BASE TABLE'
  AND table_schema <> 'information_schema'
  AND table_schema NOT LIKE 'pg_%';

您可以预览要运行的命令,并且可以在psql中运行该查询后键入\gexec来执行该查询的输出。

注意:使用CASCADE将删除依赖于表的所有内容(如VIEW)

Rails的Rake任务用于销毁当前数据库中的所有表

namespace :db do
  # rake db:drop_all_tables
  task drop_all_tables: :environment do
    query = <<-QUERY
      SELECT
        table_name
      FROM
        information_schema.tables
      WHERE
        table_type = 'BASE TABLE'
      AND
        table_schema NOT IN ('pg_catalog', 'information_schema');
    QUERY

    connection = ActiveRecord::Base.connection
    results    = connection.execute query

    tables = results.map do |line|
      table_name = line['table_name']
    end.join ", "

    connection.execute "DROP TABLE IF EXISTS #{ tables } CASCADE;"
  end
end

你需要删除表和序列,这是对我有用的

psql -qAtX -c "select 'DROP TABLE IF EXISTS ' || quote_ident(table_schema) || '.' || quote_ident(table_name) || ' CASCADE;' FROM information_schema.tables where table_type = 'BASE TABLE' and not table_schema ~ '^(information_schema|pg_.*)$'" | psql -qAtX
psql -qAtX -c "select 'DROP SEQUENCE IF EXISTS ' || quote_ident(relname) || ' CASCADE;' from pg_statio_user_sequences;" | psql -qAtX

在运行该命令之前,可能需要sudo/su到postgres用户或(导出连接详细信息PGHOST、PGPORT、PGUSER和PGPASSWORD),然后导出PGDATABASE=yourdatabase

您可以编写一个查询来生成SQL脚本,如下所示:

select 'drop table "' || tablename || '" cascade;' from pg_tables;

Or:

select 'drop table if exists "' || tablename || '" cascade;' from pg_tables;

如果某些表由于前一句中的级联选项而自动删除。

此外,如注释中所述,您可能需要按架构名称筛选要删除的表:

select 'drop table if exists "' || tablename || '" cascade;' 
  from pg_tables
 where schemaname = 'public'; -- or any other schema

然后运行它。

光荣的COPY+PASTE也将发挥作用。