如何为PostgreSQL模式将所有表转储为CSV?


11

我有一个包含很多架构的数据库,我想将每个表内容都转储为CSV。我知道COPY命令,但不确定如何编写脚本来读取架构中的所有表并对它们执行COPY。

Answers:


18

这是一个可以执行您想要的操作的shell脚本:

SCHEMA="myschema"
DB="mydb"

psql -Atc "select tablename from pg_tables where schemaname='$SCHEMA'" $DB |\
  while read TBL; do
    psql -c "COPY $SCHEMA.$TBL TO STDOUT WITH CSV" $DB > $TBL.csv
  done

确保将DB和SCHEMA变量设置为特定的数据库和模式。

包装的psql命令使用A和t标志从传递给c命令的字符串中制成表列表。


3

如果您需要导出所有模式,请使用以下脚本

PGDATABASE="db"
PGUSER="user"

psql -Atc "select schema_name from information_schema.schemata" |\
    while read SCHEMA; do
    if [[ "$SCHEMA" != "pg_catalog" && "$SCHEMA" != "information_schema" ]]; then
        psql -Atc "select tablename from pg_tables where schemaname='$SCHEMA'" |\
            while read TBL; do
                psql -c "COPY $SCHEMA.$TBL TO STDOUT WITH CSV DELIMITER ';' HEADER ENCODING 'UTF-8'" > $SCHEMA.$TBL.csv
            done
    fi
    done
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.