如何从命令行删除PostgreSQL中的所有表?
我不想删除数据库本身,只想删除其中的所有表和所有数据。
如何从命令行删除PostgreSQL中的所有表?
我不想删除数据库本身,只想删除其中的所有表和所有数据。
当前回答
继Pablo和LenW之后,这里有一个单行程序,它既准备又执行:
psql-U$PGUSER$PGDB-t-c“从pg_tables中选择'drop table\”'||tablename||'\“cascade;',其中schemaname='public'”|psql-U$PGUSER$PGDB
注意:设置$PGUSER和$PGDB或将其替换为所需的值
其他回答
嗯,因为我喜欢从命令行工作。。。
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。
如果要删除的所有内容都属于同一用户,则可以使用:
drop owned by the_user;
这将删除用户拥有的所有内容。
这包括用户拥有(=创建)的物化视图、视图、序列、触发器、模式、函数、类型、聚合、运算符、域等(实际上是:所有)。
您必须用实际的用户名替换_user,目前没有选项删除“当前用户”的所有内容。即将推出的9.5版本将拥有current_user拥有的选项drop。
手册中的更多详细信息:http://www.postgresql.org/docs/current/static/sql-drop-owned.html
我通过关注视图增强了jamie的bash方法,因为他只关注默认的表类型“base table”。
以下bash代码首先删除视图,然后删除所有其余视图
#!/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"
以防万一。。。清理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依赖它。
在Windows批处理文件中:
@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
)