无法将 PostgreSQL10 转储导入 9.6 数据库

Can't import PostgreSQL10 dump into 9.6 database

我需要以某种方式将 v10 转储文件转换为兼容 9.6 的文件

Google 的 Cloud SQL 运行 PostgreSQL 版本 9.6,而我的数据库自创建以来一直 运行 版本 10。

问题:尝试将数据库导入云 SQL 时,我收到 an unknown error has occurred. 死亡消息。

我已经尝试在导入到 Cloud 时注释掉我的 postgis/其他扩展 SQL 但是,无济于事。

我试过使用 psql my_96_db < my_10.sql 并得到大量这样的错误:

...
CREATE TABLE
ERROR:  syntax error at or near "AS"
LINE 2:     AS integer
            ^
ERROR:  relation "authentication_phonecontact_id_seq" does not exist
CREATE TABLE
...

我尝试在我的 v10 pg_dump -Fc 命令中使用 postgres 9.6 的 pg_restore,但它无法成功导入到 9.6 数据库中。输出中的许多失败之一的示例是

pg_restore: [archiver (db)] could not execute query: ERROR:  relation "public.authentication_referral_id_seq" does not exist
LINE 1: SELECT pg_catalog.setval('public.authentication_referral_id_...
                                 ^
    Command was: SELECT pg_catalog.setval('public.authentication_referral_id_seq', 1, false);

根据您显示的错误消息判断,您必须编辑 SQL 转储并从所有 CREATE SEQUENCE 语句中删除所有出现的 AS integer

AS <em>data_type</em> CREATE SEQUENCE 的子句是 PostgreSQL v10 中新增的,和旧的服务器版本将无法理解。

根据@"Laurenz Albe"的建议,这里有一个python3片段可用于为9.x降级10.xpg_dump脚本:

#!/usr/bin/env python3
import sys

#
#  Downgrades pg_dump 10 script to 9.x
#  removing 'AS integer' from 'CREATE SEQUENCE' statement
#
#  Usage:
#       $ python3 pgdump_10_to_9.py < test10.sql > test9.sql
#  or:
#       $ cat test10.sql | ./pgdump_10_to_9.py > test9.sql
#
#  To obtain a compressed 9.x sql script from a compressed 10 sql script:
#
#       $ gunzip -c test10.sql.gz | ./pgdump_10_to_9.py | gzip > test9.sql.gz
#

inside_create_sequence = False
for row in sys.stdin.readlines():

    if inside_create_sequence and row.strip().lower() == 'as integer':
        pass
    else:
        print(row, end='', flush=True)

    inside_create_sequence = row.strip().startswith('CREATE SEQUENCE ')