pgloader的安装与使用

pgloader是由postgresql的作者用lisp语言编写的一个用于将数据从其它数据库迁移到postgresql数据库中的命令行工具,亦可编写简单的脚本,保存为xxx.load文件。

在centos下安装pgloader

1.安装依赖

sudo yum -y install yum-utils rpmdevtools @"Development Tools" sqlite-devel zlib-devel  
sudo yum -y install epel-release sbcl  
sudo yum -y install freetds freetds-devel

2.下载源码

tar -xv pgloader-bundle-3.5.1.tgz
cd pgloader-bundle-3.5.1.tgz
make pgloader

3.编译成功后bin文件夹下会出现pgloader可执行文件,将路径添加到环境变量。

vim ~/.bash_profile
source ~/.bash_profile

pgloader的使用 from mysql to postgresql

load database
    from mysql://username:password@localhost/test
    into postgresql://username:password@110.110.110.110/datahub
with include drop, create tables,  create indexes,  reset sequences, disable triggers, foreign keys, workers=8, concurrency=1
   set work_mem to '16MB', maintenance_work_mem to '512MB'

   INCLUDING ONLY TABLE NAMES MATCHING 'base_job_type'

   CAST type timestamp when default "0000-00-00 00:00:00" with extra on update current timestamp to timestamptz drop default drop not nul drop extra using zero-dates-to-null,
        type smallint when unsigned to integer drop typemod

# FROM: 源数据库信息
# INTO: 目标数据库信息
# 迁移默认选项:no truncate, create schema, create tables, include drop, create indexes,reset sequences,foreign keys,downcase identifiers, uniquify index names

# include drop: 丢弃目标库的表并重新创建
# include no drop: 不做任何drop操作
# truncate: 在迁移数据之前清空表
# no truncate: 不做truncate操作
# disable triggers: 这个选项允许,迁移数据到已经存在的表并忽略外键约束和用户定义的触发器,迁移后可能会出现无效的外键约束
# create tables: 根据元数据自动创建表结构
# create no tables: 不创建表结构,当迁移数据时必须保证表存在
# create indexes: 创建索引
# create no indexes: 不创建索引
# drop indexes: 在迁移数据之前drop indexes,当数据迁移完成之后重新创建索引
# uniquify index names: 因为mysql的索引是表唯一,postgresql的索引是schema唯一,所以当从mysql到postgresql时索引名称可能会出现冲突,pgloader会通过特定规则对索引进行重新命名
# preserve index names: 保留索引名称,尽管如此 mysql primary key也会被重新命名,以保持唯一性
# drop schema: 迁移数据行 drop schema,然后重建
# foreign keys: 创建外键
# no foreign keys: 不创建外键
# reset sequences: 当数据迁移完成后,sequences会设置为当前列的最大值
# reset no sequences: 不设置sequences
# downcase identifiers: 将表名,索引名,列名改为小写
# quote identifiers: 保留大小写
# schema only: 只迁移表结构
# data only: 只复制数据

pgloader转换规则中的坑

假设mysql中有一个字段的类型为datetime,默认值为”0000-00-00 00:00:00” 如果转换规则写为type datetime to timestamptz此时pgloader并不会匹配上,因为pgloader必须全部匹配时,才会执行类型转换。可写为cast type datetime when default "0000-00-00 00:00:00" to timestamptz才能匹配,如果还有其它的限制也必须加上,如with extra on update current timestamp。这种情况和代码异常处理是不一样的。


Ref: 1.https://pgloader.readthedocs.io/en/latest/ref/mysql.html