mysql-schema-sync 是一款使用 Go 开发跨平台的 MySQL 表结构自动同步工具。

用于将 线上 数据库结构变化同步到 本地环境!

mysql-schema-sync 支持功能:

只能同步表结构,无法同步表内数据

  1. 同步新表
  2. 同步字段 变动:新增、修改
  3. 同步索引 变动:新增、修改
  4. 支持预览(只对比不同步变动)
  5. 邮件通知变动结果
  6. 支持屏蔽更新表、字段、索引、外键
  7. 支持本地比线上额外多一些表、字段、索引、外键

项目地址:https://github.com/hidu/mysql-schema-sync

安装

需要先安装go环境:https://www.runoob.com/go/go-environment.html

1
2
3
4
5
wget https://dl.google.com/go/go1.14.2.linux-amd64.tar.gz
tar -C /usr/local -xzf go1.14.2.linux-amd64.tar.gz
echo 'export PATH=$PATH:/usr/local/go/bin' >> /root/.bash_profile
source ~/.bash_profile
go version

安装mysql-schema-sync (cd在哪里就安装到哪里)

1
2
cd /home
go get -u github.com/hidu/mysql-schema-sync

默认运行位置为:

1
/home/go/bin/mysql-schema-sync

配置

参考 默认配置文件 config.json 配置同步源、目的地址。 修改邮件接收人 当运行失败或者有表结构变化的时候你可以收到邮件通知。

默认情况不会对多出的表、字段、索引、外键删除。若需要删除字段、索引、外键 可以使用 -drop 参数。

配置示例(config.json):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{
//source:同步源
source:test:test@(127.0.0.1:3306)/test_0,
//dest:待同步的数据库
dest:test:test@(127.0.0.1:3306)/test_1,
//alter_ignore: 同步时忽略的字段和索引
alter_ignore:{
tb1*:{
column:[aaa,a*],
index:[aa],
foreign:[]
}
},
// tables: table to check schema,default is all.eg :[order_*,goods]
tables:[],
//有变动或者失败时,邮件接收人
email:{
send_mail:false,
smtp_host:smtp.163.com:25,
from:[email protected],
password:xxx,
to:[email protected]
}
}

一键写配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
cat > /home/go/bin/config.json<<-EOF
{
//source:同步源
source:test:test@(127.0.0.1:3306)/test_0,
//dest:待同步的数据库
dest:test:test@(127.0.0.1:3306)/test_1,
//alter_ignore: 同步时忽略的字段和索引
alter_ignore:{
tb1*:{
column:[aaa,a*],
index:[aa],
foreign:[]
}
},
// tables: table to check schema,default is all.eg :[order_*,goods]
tables:[],
//有变动或者失败时,邮件接收人
email:{
send_mail:false,
smtp_host:smtp.163.com:25,
from:[email protected],
password:xxx,
to:[email protected]
}
}
EOF

json配置项说明

source: 数据库同步源 dest: 待同步的数据库 tables: 数组,配置需要同步的表,为空则是不限制,eg: [goods,order_] alter_ignore: 忽略修改的配置,表名为tableName,可以配置 column 和 index,支持通配符 email : 同步完成后发送邮件通知信息

运行

直接运行

1
mysql-schema-sync -conf mydb_conf.json -sync

预览并生成变更sql

1
mysql-schema-sync -conf mydb_conf.json 2>/dev/null >db_alter.sql

使用shell调度

1
bash check.sh

每个json文件配置一个目的数据库,check.sh脚本会依次运行每份配置。 log存储在当前的log目录中。

自动定时运行

添加crontab 任务

1
30 * * * * cd /your/path/xxx/ && bash check.sh >/dev/null 2>&1

参数说明

1
mysql-schema-sync [-conf] [-dest] [-source] [-sync] [-drop]

说明:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# mysql-schema-sync -help  
-conf string
配置文件名称
-dest string
待同步的数据库 eg: test@(10.10.0.1:3306)/test_1
该项不为空时,忽略读入 -conf参数项
-drop
是否对本地多出的字段和索引进行删除 默认否
-source string
mysql 同步源,eg test@(127.0.0.1:3306)/test_0
-sync
是否将修改同步到数据库中去,默认否
-tables string
待检查同步的数据库表,为空则是全部
eg : product_base,order_*