如何从命令行删除PostgreSQL中的所有表?
我不想删除数据库本身,只想删除其中的所有表和所有数据。
如何从命令行删除PostgreSQL中的所有表?
我不想删除数据库本身,只想删除其中的所有表和所有数据。
当前回答
只需执行以下查询:
DO $$ DECLARE
r RECORD;
BEGIN
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 $$;
其他回答
如果要删除的所有内容都属于同一用户,则可以使用:
drop owned by the_user;
这将删除用户拥有的所有内容。
这包括用户拥有(=创建)的物化视图、视图、序列、触发器、模式、函数、类型、聚合、运算符、域等(实际上是:所有)。
您必须用实际的用户名替换_user,目前没有选项删除“当前用户”的所有内容。即将推出的9.5版本将拥有current_user拥有的选项drop。
手册中的更多详细信息:http://www.postgresql.org/docs/current/static/sql-drop-owned.html
drop schema public cascade;
应该会成功。
您可以使用string_agg函数创建逗号分隔的列表,非常适合DROP TABLE。从bash脚本:
#!/bin/bash
TABLES=`psql $PGDB -t --command "SELECT string_agg(table_name, ',') FROM information_schema.tables WHERE table_schema='public'"`
echo Dropping tables:${TABLES}
psql $PGDB --command "DROP TABLE IF EXISTS ${TABLES} CASCADE"
以防万一。。。清理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依赖它。
将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)