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

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


当前回答

根据上面的Pablo,从一个特定的模式中删除案例:

select 'drop table "' || tablename || '" cascade;' 
from pg_tables where schemaname = 'public';

其他回答

如果您无论如何都想对所有表进行核处理,可以通过将所有表放在一个语句中来省去诸如CASCADE之类的细节。这也使执行速度更快。

SELECT 'TRUNCATE TABLE ' || string_agg('"' || tablename || '"', ', ') || ';' 
FROM pg_tables WHERE schemaname = 'public';

直接执行:

DO $$
DECLARE tablenames text;
BEGIN    
    tablenames := string_agg('"' || tablename || '"', ', ') 
        FROM pg_tables WHERE schemaname = 'public';
    EXECUTE 'TRUNCATE TABLE ' || tablenames;
END; $$

如果适用,用DROP替换TRUNCATE。

您可以使用

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

为了方便将生成的SQL命令作为一个字符串返回,我稍微修改了Pablo的答案:

select string_agg('drop table "' || tablename || '" cascade', '; ') 
from pg_tables where schemaname = 'public'

将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)

以防万一。。。清理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依赖它。