如何从命令行删除PostgreSQL中的所有表?
我不想删除数据库本身,只想删除其中的所有表和所有数据。
如何从命令行删除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
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
嗯,因为我喜欢从命令行工作。。。
psql -U <user> -d <mydb> -c '\dt' | cut -d ' ' -f 4 | sed -e "s/^/drop table if exists /" | sed -e "s/$/;/"
-c'\dt'将调用list tables命令。
List of relations
Schema | Name | Type | Owner
--------+-------------------+-------+----------
public | _d_psidxddlparm | table | djuser
public | _d_psindexdefn | table | djuser
现在剪切-d“”-f 4,通过管道将其输出抓取第4个字段(当使用空格作为分隔符时),即表。
然后,sed被用于给一个drop表加前缀,并在后面加后缀;命令分隔符。
|egrep“_d_”-再将其转换为grep,这样您就可以更有选择地删除哪些表。
drop table if exists _d_psidxddlparm;
drop table if exists _d_psindexdefn;
注意:如前所述,这将为\dt命令输出的列标题和末尾的总行生成伪行。我会用grepping来避免,但你可以用head和tail。
为了方便将生成的SQL命令作为一个字符串返回,我稍微修改了Pablo的答案:
select string_agg('drop table "' || tablename || '" cascade', '; ')
from pg_tables where schemaname = 'public'
您可以使用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"