How can I drop all the tables in a PostgreSQL database?
如何从命令行删除PostgreSQL中的所有表?
我不想删除数据库本身,只删除所有表和其中的所有数据。
如果您的所有表都在一个模式中,那么这种方法可以工作(下面的代码假设您的模式名称是
1 2 | DROP SCHEMA public CASCADE; CREATE SCHEMA public; |
如果您使用的是PostgreSQL 9.3或更高版本,则可能还需要恢复默认的授权。
1 2 | GRANT ALL ON SCHEMA public TO postgres; GRANT ALL ON SCHEMA public TO public; |
您可以编写一个查询来生成这样的SQL脚本:
1 | SELECT 'drop table"' || tablename || '" cascade;' FROM pg_tables; |
或:
1 | SELECT 'drop table if exists"' || tablename || '" cascade;' FROM pg_tables; |
如果由于前一句中的CASCADE选项而自动删除某些表。
此外,如注释中所述,您可能希望按架构名称筛选要删除的表:
1 2 3 | SELECT 'drop table if exists"' || tablename || '" cascade;' FROM pg_tables WHERE schemaname = 'public'; -- or any other schema |
然后运行它。
光荣的复制+粘贴也会起作用。
截至本函(2014年1月)最普遍接受的回答是:
1 2 | DROP SCHEMA public CASCADE; CREATE SCHEMA public; |
但是,如果您的目的是将公共模式恢复到原始状态,那么这就不会完全完成任务。在PGADMIN III for PostgreSQL 9.3.1下,如果单击以这种方式创建的"公共"模式并在"SQL窗格"中查找,将看到以下内容:
1 2 3 4 5 6 | -- Schema: public -- DROP SCHEMA public; CREATE SCHEMA public AUTHORIZATION postgres; |
然而,相比之下,一个全新的数据库将具有以下功能:
1 2 3 4 5 6 7 8 9 10 11 | -- Schema: public -- DROP SCHEMA public; CREATE SCHEMA public AUTHORIZATION postgres; GRANT ALL ON SCHEMA public TO postgres; GRANT ALL ON SCHEMA public TO public; COMMENT ON SCHEMA public IS 'standard public schema'; |
对于我来说,使用创建数据库表的python web框架(web2py),使用前者会导致问题:
1 | <class 'psycopg2.ProgrammingError'> no schema has been selected TO CREATE IN |
所以在我看来,完全正确的答案是:
1 2 3 4 5 | DROP SCHEMA public CASCADE; CREATE SCHEMA public; GRANT ALL ON SCHEMA public TO postgres; GRANT ALL ON SCHEMA public TO public; COMMENT ON SCHEMA public IS 'standard public schema'; |
(另请注意,要从pgadmin III发出这些命令,我转到plugins->psql console)
你可以放下所有的桌子
1 2 3 4 5 6 7 8 9 10 | 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 $$; |
在我看来,这比
额外的好处是,这不需要外部脚本语言,也不需要将生成的SQL复制回解释器。
如果要删除的所有内容都属于同一用户,则可以使用:
1 | DROP owned BY the_user; |
这将删除用户拥有的所有内容。
其中包括
您必须将
手册中的更多详细信息:http://www.postgresql.org/docs/current/static/sql-drop-owned.html
根据上面的pablo,从一个特定的模式中删除,关于case:
1 2 | SELECT 'drop table"' || tablename || '" cascade;' FROM pg_tables WHERE schemaname = 'public'; |
1 | DROP schema public cascade; |
应该有技巧。
在pablo和lenw之后,这里有一个一行程序可以完成所有的准备和执行:
注意:用您想要的值设置或替换
如果安装了pl/pgsql过程语言,则可以使用以下命令删除所有内容,而无需使用shell/perl外部脚本。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | DROP FUNCTION IF EXISTS remove_all(); CREATE FUNCTION remove_all() RETURNS void AS $$ DECLARE rec RECORD; cmd text; BEGIN cmd := ''; FOR rec IN SELECT 'DROP SEQUENCE ' || quote_ident(n.nspname) || '.' || quote_ident(c.relname) || ' CASCADE;' AS name FROM pg_catalog.pg_class AS c LEFT JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace WHERE relkind = 'S' AND n.nspname NOT IN ('pg_catalog', 'pg_toast') AND pg_catalog.pg_table_is_visible(c.oid) LOOP cmd := cmd || rec.name; END LOOP; FOR rec IN SELECT 'DROP TABLE ' || quote_ident(n.nspname) || '.' || quote_ident(c.relname) || ' CASCADE;' AS name FROM pg_catalog.pg_class AS c LEFT JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace WHERE relkind = 'r' AND n.nspname NOT IN ('pg_catalog', 'pg_toast') AND pg_catalog.pg_table_is_visible(c.oid) LOOP cmd := cmd || rec.name; END LOOP; FOR rec IN SELECT 'DROP FUNCTION ' || quote_ident(ns.nspname) || '.' || quote_ident(proname) || '(' || oidvectortypes(proargtypes) || ');' AS name FROM pg_proc INNER JOIN pg_namespace ns ON (pg_proc.pronamespace = ns.oid) WHERE ns.nspname = 'public' ORDER BY proname LOOP cmd := cmd || rec.name; END LOOP; EXECUTE cmd; RETURN; END; $$ LANGUAGE plpgsql; SELECT remove_all(); |
我建议您将其复制到一个文件中,然后使用"-file"或"-f"选项将该文件作为输入传递给psql,而不是在"psql"提示下键入:
1 | psql -f clean_all_pg.sql |
信用到期:我编写了这个函数,但认为查询(或者至少是第一个查询)是几年前从pgsql邮件列表中的某个人发出的。不记得确切的时间和地点。
为了方便将生成的SQL命令作为单个字符串返回,我稍微修改了pablo的答案:
1 2 | SELECT string_agg('drop table"' || tablename || '" cascade', '; ') FROM pg_tables WHERE schemaname = 'public' |
在pgadmin中使用此脚本:
1 2 3 4 5 6 7 8 | 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; $$ |
以防万一…清理PostgreSQL数据库的简单python脚本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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依赖于它。
您可以使用string_agg函数生成一个逗号分隔的列表,非常适合放置表格。从bash脚本:
1 2 3 4 5 | #!/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" |
如果您无论如何都想对所有表进行nuke操作,那么可以通过将所有表放入一个语句中来省去诸如cascade之类的细节。这也使得执行速度更快。
1 2 | SELECT 'TRUNCATE TABLE ' || string_agg('"' || tablename || '"', ', ') || ';' FROM pg_tables WHERE schemaname = 'public'; |
直接执行:
1 2 3 4 5 6 7 | DO $$ DECLARE tablenames text; BEGIN tablenames := string_agg('"' || tablename || '"', ', ') FROM pg_tables WHERE schemaname = 'public'; EXECUTE 'TRUNCATE TABLE ' || tablenames; END; $$ |
如适用,用
你需要删除表格和序列,这是对我有用的
1 2 | 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 |
在运行命令之前,您可能需要向
用于销毁当前数据库中所有表的Rails的rake任务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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 |
如果要删除数据(而不是删除表):
1 2 3 4 | -- Truncate tables and restart sequnces SELECT 'TRUNCATE TABLE"' || table_schema || '"."' || TABLE_NAME || '" RESTART IDENTITY CASCADE;' FROM information_schema.tables WHERE table_catalog = '<database>' AND table_schema = '<schema>'; |
或者,如果要删除表,可以使用此SQL:
1 2 3 4 5 6 7 8 9 | -- For tables SELECT 'DROP TABLE"' || table_schema || '"."' || TABLE_NAME || '" CASCADE;' FROM information_schema.tables WHERE table_catalog = '<database>' AND table_schema = '<schema>'; -- For sequences SELECT 'DROP SEQUENCE d_a_seq"' || sequence_schema || '"."' || sequence_name || '";' FROM information_schema.sequences WHERE sequence_catalog = '<database>' AND sequence_schema = '<schema>'; |
在Windows批处理文件中:
1 2 3 4 5 | @echo off FOR /f"tokens=2 delims=|" %%G IN ('psql --host localhost --username postgres --command="\dt" YOUR_TABLE_NAME') DO ( psql --host localhost --username postgres --command="DROP table if exists %%G cascade" sfkb echo TABLE %%G dropped ) |
我通过处理视图增强了Jamie的bash方法,因为他只关注默认的表类型"基表"。
下面的bash代码首先删除视图,然后删除所有其他视图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #!/usr/bin/env bash PGDB="yourDB" # BY exporting USER & pass your dont need TO interactively TYPE them ON execution export PGUSER="PGusername" export PGPASSWORD="PGpassword" VIEWS=`psql -d $PGDB -t --command"SELECT string_agg(table_name, ',') FROM information_schema.tables WHERE table_schema='public' AND table_type='VIEW'"` BASETBLS=`psql -d $PGDB -t --command"SELECT string_agg(table_name, ',') FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE'"` echo Dropping views:${VIEWS} psql $PGDB --command"DROP VIEW IF EXISTS ${VIEWS} CASCADE" echo Dropping TABLES:${BASETBLS} psql $PGDB --command"DROP TABLE IF EXISTS ${BASETBLS} CASCADE" |
对于不能只使用
- 表上的触发器
- 表约束(fk、pk、
CHECK 、UNIQUE ) - 印度语
VIEW S(正常或物化)- 桌子
- 序列
- 功能/程序(
pg_proc.proisagg 可能应该得到尊重) - all n_n-default(即不是
public 或db internal)schemata"we"own:当以"not a database superuser"的身份运行时,脚本很有用;超级用户可以删除所有schemata(但真正重要的模式仍然被明确排除在外)
未删除是(有些是故意的;有些只是因为在数据库中没有示例):
public 模式(例如,扩展提供的内容)- 扩展
- 聚合函数
- 排序规则和其他区域设置内容
- 事件触发器
- 文本搜索资料,…(请参阅此处了解我可能错过的其他资料)
- 角色或其他安全设置
- 复合类型
- 烤面包桌
- FDW和外部表
我还有一个版本,它删除了"除了两个表以外的所有内容以及属于它们的内容",以防有人感兴趣;diff很小。必要时联系我。
SQL1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 | -- Copyright ? 2019 -- mirabilos <[email protected]> -- -- Provided that these terms and disclaimer and all copyright notices -- are retained or reproduced in an accompanying document, permission -- is granted to deal in this work without restriction, including un‐ -- limited rights to use, publicly perform, distribute, sell, modify, -- merge, give away, or sublicence. -- -- This work is provided"AS IS" and WITHOUT WARRANTY of any kind, to -- the utmost extent permitted by applicable law, neither express nor -- implied; without malicious intent or gross negligence. In no event -- may a licensor, author or contributor be held liable for indirect, -- direct, other damage, loss, or other issues arising in any way out -- of dealing in the work, even if advised of the possibility of such -- damage or existence of a defect, except proven that it results out -- of said person’s immediate fault when using the work as intended. -- - -- Drop everything from the PostgreSQL database. DO $$ DECLARE r RECORD; BEGIN -- triggers FOR r IN (SELECT pns.nspname, pc.relname, pt.tgname FROM pg_trigger pt, pg_class pc, pg_namespace pns WHERE pns.oid=pc.relnamespace AND pc.oid=pt.tgrelid AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast') AND pt.tgisinternal=FALSE ) LOOP EXECUTE format('DROP TRIGGER %I ON %I.%I;', r.tgname, r.nspname, r.relname); END LOOP; -- constraints #1: foreign key FOR r IN (SELECT pns.nspname, pc.relname, pcon.conname FROM pg_constraint pcon, pg_class pc, pg_namespace pns WHERE pns.oid=pc.relnamespace AND pc.oid=pcon.conrelid AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast') AND pcon.contype='f' ) LOOP EXECUTE format('ALTER TABLE ONLY %I.%I DROP CONSTRAINT %I;', r.nspname, r.relname, r.conname); END LOOP; -- constraints #2: the rest FOR r IN (SELECT pns.nspname, pc.relname, pcon.conname FROM pg_constraint pcon, pg_class pc, pg_namespace pns WHERE pns.oid=pc.relnamespace AND pc.oid=pcon.conrelid AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast') AND pcon.contype<>'f' ) LOOP EXECUTE format('ALTER TABLE ONLY %I.%I DROP CONSTRAINT %I;', r.nspname, r.relname, r.conname); END LOOP; -- indicēs FOR r IN (SELECT pns.nspname, pc.relname FROM pg_class pc, pg_namespace pns WHERE pns.oid=pc.relnamespace AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast') AND pc.relkind='i' ) LOOP EXECUTE format('DROP INDEX %I.%I;', r.nspname, r.relname); END LOOP; -- normal and materialised views FOR r IN (SELECT pns.nspname, pc.relname FROM pg_class pc, pg_namespace pns WHERE pns.oid=pc.relnamespace AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast') AND pc.relkind IN ('v', 'm') ) LOOP EXECUTE format('DROP VIEW %I.%I;', r.nspname, r.relname); END LOOP; -- tables FOR r IN (SELECT pns.nspname, pc.relname FROM pg_class pc, pg_namespace pns WHERE pns.oid=pc.relnamespace AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast') AND pc.relkind='r' ) LOOP EXECUTE format('DROP TABLE %I.%I;', r.nspname, r.relname); END LOOP; -- sequences FOR r IN (SELECT pns.nspname, pc.relname FROM pg_class pc, pg_namespace pns WHERE pns.oid=pc.relnamespace AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast') AND pc.relkind='S' ) LOOP EXECUTE format('DROP SEQUENCE %I.%I;', r.nspname, r.relname); END LOOP; -- functions / procedures FOR r IN (SELECT pns.nspname, pp.proname, pp.oid FROM pg_proc pp, pg_namespace pns WHERE pns.oid=pp.pronamespace AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast') ) LOOP EXECUTE format('DROP FUNCTION %I.%I(%s);', r.nspname, r.proname, pg_get_function_identity_arguments(r.oid)); END LOOP; -- nōn-default schemata we own; assume to be run by a not-superuser FOR r IN (SELECT pns.nspname FROM pg_namespace pns, pg_roles pr WHERE pr.oid=pns.nspowner AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast', 'public') AND pr.rolname=CURRENT_USER ) LOOP EXECUTE format('DROP SCHEMA %I;', r.nspname); END LOOP; -- voilà RAISE NOTICE 'Database cleared!'; END; $$; |
在PostgreSQL 9.6(
既然我喜欢在命令行工作…
List of relations
Schema | Name | Type | Owner
--------+-------------------+-------+----------
public | _d_psidxddlparm | table | djuser
public | _d_psindexdefn | table | djuser
然后使用
drop table if exists _d_psidxddlparm;
drop table if exists _d_psindexdefn;
注:如文所述,这将为
最简单的方法是删除公共模式,正如其他人在前面的答案中所建议的那样。然而,这不是一个好方法。您永远不知道对公共模式做了什么,这些模式后来被遗忘了,并且没有记录在案。你也不知道这是否会对未来产生同样的影响。在V9中,这是可以的,但在V10中,您的所有用户都将失去对模式的访问权,必须再次授予访问权,否则您的应用程序将中断。我没有检查过v11,但重点是,当你从一台机器移动到另一台机器、从一个站点移动到另一个站点或从一个版本移动到另一个版本时,你永远不知道会发生什么。如果您是一个可以访问数据库但不能访问架构的用户,则也不能执行此操作。
如果你需要以编程的方式来做这件事,那么上面的其他答案就包含了这一点,但是上面的答案不考虑的一件事是让Postgres为你做这项工作。如果将pg_dump与-c选项一起使用,如下所示:
1 | sudo su postgres -c"pg_dump -U postgres WhateverDB -c -f"/home/Anyone/DBBackupWhateverDB-ServerUnscheduled.sql"" |
这将创建一个数据库还原脚本,其中包含将删除所有表的SQL语句。
如果问这个问题的唯一目的是在还原之前删除表,那么您的还原将为您完成这项工作。
但是,如果您还需要它,您可以简单地从SQL脚本复制DROP语句。