导入 MySQL 转储到 Postgres 并转义 \

import MySQL dump into Postgres and escape \

我收到了一个 MYSQL 转储,需要将其推送到 Postgres table。

在这个 poi_dump.sql 转储中,有很多行插入。例子如下:

Insert into table values (1,'hello','\rthis is a beautiful Alan\'s cottage', '\nbyebye')
Insert into table values (1,'hello','\rthis is a big\"Work', '\nbyebye')

我正在使用 PSQL 命令:

psql analytics < poi_dump.sql

但是,postgres 无法识别用于在 ' ' 字段中转义的所有 \。

Errors From Postgres:
Query buffer reset (cleared).
invalid command \nOn
invalid command \n
invalid command \'
invalid command \'
invalid command \'
invalid command \n
invalid command \"Without
invalid command \nPort-a-loo
Query buffer reset (cleared).
invalid command \n

如何让 postgres 接受引号字段中的那些 \r ,\n ?

PostgreSQL 默认不识别字符串中的反斜杠。但是这个行为可以简单地改变:

ides_jmmaj_prac=# select 'hello\nworld';
┌──────────────┐
│   ?column?   │
╞══════════════╡
│ hello\nworld │
└──────────────┘
(1 row)

Time: 0,496 ms
ides_jmmaj_prac=# set standard_conforming_strings TO off;
SET
Time: 0,251 ms
ides_jmmaj_prac=# select 'hello\nworld';
WARNING:  nonstandard use of escape in a string literal
ŘÁDKA 1: select 'hello\nworld';
                ^
DOPORUČENÍ:  Use the escape string syntax for escapes, e.g., E'\r\n'.
┌──────────┐
│ ?column? │
╞══════════╡
│ hello   ↵│
│ world    │
└──────────┘
(1 row)

Time: 0,496 ms

通过以下方式禁用警告:

set escape_string_warning to off;

可能 \r 应该删除。 PostgreSQL 使用 Unix 行尾 - 仅 \n(我没有测试)。

这对我有用

执行 mysqlpdump

然后我运行

cat mysqldumpfile | sed "s/,'/,E'/g" > pgimportfile