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

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


当前回答

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

其他回答

您可以使用

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复制粘贴回解释器。

如果您的所有表都在一个模式中,那么这种方法可以工作(下面的代码假设您的模式的名称是公共的)

DROP SCHEMA public CASCADE;
CREATE SCHEMA public;

如果您使用PostgreSQL 9.3或更高版本,您可能还需要恢复默认授权。

GRANT ALL ON SCHEMA public TO postgres;
GRANT ALL ON SCHEMA public TO public;

如果要删除的所有内容都属于同一用户,则可以使用:

drop owned by the_user;

这将删除用户拥有的所有内容。

这包括用户拥有(=创建)的物化视图、视图、序列、触发器、模式、函数、类型、聚合、运算符、域等(实际上是:所有)。

您必须用实际的用户名替换_user,目前没有选项删除“当前用户”的所有内容。即将推出的9.5版本将拥有current_user拥有的选项drop。

手册中的更多详细信息:http://www.postgresql.org/docs/current/static/sql-drop-owned.html

以防万一。。。清理Postgresql数据库的简单Python脚本

import psycopg2
import sys

# Drop all tables from a given database

try:
    conn = psycopg2.connect("dbname='akcja_miasto' user='postgres' password='postgres'")
    conn.set_isolation_level(0)
except:
    print "Unable to connect to the database."

cur = conn.cursor()

try:
    cur.execute("SELECT table_schema,table_name FROM information_schema.tables WHERE table_schema = 'public' ORDER BY table_schema,table_name")
    rows = cur.fetchall()
    for row in rows:
        print "dropping table: ", row[1]   
        cur.execute("drop table " + row[1] + " cascade") 
    cur.close()
    conn.close()        
except:
    print "Error: ", sys.exc_info()[1]

确保复制后缩进正确,因为Python依赖它。

在pgAdmin中使用此脚本:

DO $$
DECLARE 
    brow record;
BEGIN
    FOR brow IN (select 'drop table "' || tablename || '" cascade;' as table_name from pg_tables where schemaname = 'public') LOOP
        EXECUTE brow.table_name;
    END LOOP;
END; $$