我可以在不检查约束的情况下空表



上下文:我是一个大型项目,其中有大量的PostgreSQL表(46)和外键,也没有文档。我们与Java,Spring,Hibernate和Testng一起工作。

目标:我正在寻找能够清空数据库的脚本(在每个单位测试案例之前将其调用)。不幸的是,我不能花太多时间来找到外国钥匙以便以正确的顺序排空桌子。

问题:有没有办法空的(我不想将其放置),而不检查外国键的约束?

作为@a_horse_with_no_name评论,使用截断...每个表的级联都可以正常工作。该链接还提供了一个自动通过数据库中所有表的函数。

如果您有大桌子,带有很多外键,则可能需要很多时间来浏览所有外国密钥索引。在这种情况下,最好将架构丢弃,丢弃数据库,重新创建数据库并在批处理中重新加载模式。链接中有一个示例,但它没有告诉您如何运行它们。这有点完善:

#!/bin/sh
# Run this as the postgres user because you need create database permissions
# I'm assuming you're using a Unix variant, 
# the postgresql database is at localhost,
# and that psql trusts the Unix account.  
# Otherwise add -h hostname to the command lines 
# and set $PGPASSWORD variable before the first command.
pg_dump –s yourdb > /tmp/clean.sql
psql –c "drop database yourdb;"
psql –c "create database yourdb with owner you;"
psql yourdb < /tmp/clean.sql
rm –f /tmp/clean.sql

相关内容

最新更新