mysql-replication

Pure Python Implementation of MySQL replication protocol build on top of PyMYSQL. This allow you to receive event like insert, update, delete with their datas and raw SQL queries.

Use cases

  • MySQL to NoSQL database replication
  • MySQL to search engine replication
  • Invalidate cache when something change in database
  • Audit
  • Real time analytics

Documentation

A work in progress documentation is available here: https://python-mysql-replication.readthedocs.org/en/latest/

Installation

pip install mysql-replication

Mailling List

You can get support and discuss about new features on: https://groups.google.com/d/forum/python-mysql-replication

Project status

The current project is a proof of concept of what you can do with the MySQL replication log.

The project is test with:

  • MySQL 5.5 and 5.6
  • Python 2.7
  • Python 3.2

It's not tested in real production situation.

Limitations

GEOMETRY field is not decoded you will get the raw data.

Only binlog_row_image=full is supported (it's the default value).

Project using this library

MySQL server settings

In your MySQL server configuration file you need to enable replication:

[mysqld]
server-id        = 1
log_bin          = /var/log/mysql/mysql-bin.log
expire_logs_days = 10
max_binlog_size  = 100M
binlog-format    = row #Very important if you want to receive write, update and delete row events

Examples

All examples are available in the examples directory

This example will dump all replication events to the console:

from pymysqlreplication import BinLogStreamReader

mysql_settings = {'host': '127.0.0.1', 'port': 3306, 'user': 'root', 'passwd': ''}

stream = BinLogStreamReader(connection_settings = mysql_settings)

for binlogevent in stream:
    binlogevent.dump()

stream.close()

For this SQL sessions:

CREATE DATABASE test;
use test;
CREATE TABLE test4 (id int NOT NULL AUTO_INCREMENT, data VARCHAR(255), data2 VARCHAR(255), PRIMARY KEY(id));
INSERT INTO test4 (data,data2) VALUES ("Hello", "World");
UPDATE test4 SET data = "World", data2="Hello" WHERE id = 1;
DELETE FROM test4 WHERE id = 1;

Output will be:

=== RotateEvent ===
Date: 1970-01-01T01:00:00
Event size: 24
Read bytes: 0

=== FormatDescriptionEvent ===
Date: 2012-10-07T15:03:06
Event size: 84
Read bytes: 0

=== QueryEvent ===
Date: 2012-10-07T15:03:16
Event size: 64
Read bytes: 64
Schema: test
Execution time: 0
Query: CREATE DATABASE test

=== QueryEvent ===
Date: 2012-10-07T15:03:16
Event size: 151
Read bytes: 151
Schema: test
Execution time: 0
Query: CREATE TABLE test4 (id int NOT NULL AUTO_INCREMENT, data VARCHAR(255), data2 VARCHAR(255), PRIMARY KEY(id))

=== QueryEvent ===
Date: 2012-10-07T15:03:16
Event size: 49
Read bytes: 49
Schema: test
Execution time: 0
Query: BEGIN

=== TableMapEvent ===
Date: 2012-10-07T15:03:16
Event size: 31
Read bytes: 30
Table id: 781
Schema: test
Table: test4
Columns: 3

=== WriteRowsEvent ===
Date: 2012-10-07T15:03:16
Event size: 27
Read bytes: 10
Table: test.test4
Affected columns: 3
Changed rows: 1
Values:
--
* data : Hello
* id : 1
* data2 : World

=== XidEvent ===
Date: 2012-10-07T15:03:16
Event size: 8
Read bytes: 8
Transaction ID: 14097

=== QueryEvent ===
Date: 2012-10-07T15:03:17
Event size: 49
Read bytes: 49
Schema: test
Execution time: 0
Query: BEGIN

=== TableMapEvent ===
Date: 2012-10-07T15:03:17
Event size: 31
Read bytes: 30
Table id: 781
Schema: test
Table: test4
Columns: 3

=== UpdateRowsEvent ===
Date: 2012-10-07T15:03:17
Event size: 45
Read bytes: 11
Table: test.test4
Affected columns: 3
Changed rows: 1
Affected columns: 3
Values:
--
* data : Hello => World
* id : 1 => 1
* data2 : World => Hello

=== XidEvent ===
Date: 2012-10-07T15:03:17
Event size: 8
Read bytes: 8
Transaction ID: 14098

=== QueryEvent ===
Date: 2012-10-07T15:03:17
Event size: 49
Read bytes: 49
Schema: test
Execution time: 1
Query: BEGIN

=== TableMapEvent ===
Date: 2012-10-07T15:03:17
Event size: 31
Read bytes: 30
Table id: 781
Schema: test
Table: test4
Columns: 3

=== DeleteRowsEvent ===
Date: 2012-10-07T15:03:17
Event size: 27
Read bytes: 10
Table: test.test4
Affected columns: 3
Changed rows: 1
Values:
--
* data : World
* id : 1
* data2 : Hello

=== XidEvent ===
Date: 2012-10-07T15:03:17
Event size: 8
Read bytes: 8
Transaction ID: 14099

Tests

Be carefull tests will reset the binary log of your MySQL server.

Make sure you have the following configuration set in your mysql config file (usually my.cnf on development env):

log-bin=mysql-bin
server-id=1
binlog_do_db=pymysqlreplication_test
binlog-format    = row #Very important if you want to receive write, update and delete row events

To run tests:

python setup.py test

Similar projects

Special thanks

Contributors

Licence

Copyright 2012 Julien Duponchelle

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个使用 mysql-replication 包监控 MySQL 表变动的 Python 代码示例: ```python from mysql_replication import BinLogStreamReader from mysql.connector import connect # 连接 MySQL 数据库 conn = connect(host='localhost', user='root', password='password', database='test') # 创建 BinLogStreamReader 对象 stream = BinLogStreamReader( connection_settings={ "host": "localhost", "port": 3306, "user": "root", "password": "password" }, server_id=100, blocking=True, only_events=["tablemap", "writerows", "updaterows", "deleterows"], only_schemas=["test"], only_tables=["task_name"] ) # 监听 MySQL 表变动 for binlogevent in stream: for row in binlogevent.rows: event = {"schema": binlogevent.schema, "table": binlogevent.table} if binlogevent.event_type == "tablemap": event["column_schemas"] = binlogevent.column_schemas elif binlogevent.event_type == "writerows": event["action"] = "insert" event["rows"] = row["values"] elif binlogevent.event_type == "updaterows": event["action"] = "update" event["rows"] = row["after_values"] event["old_rows"] = row["before_values"] elif binlogevent.event_type == "deleterows": event["action"] = "delete" event["rows"] = row["values"] # 打印表变动信息 print(event) # 关闭 BinLogStreamReader 对象 stream.close() # 关闭数据库连接 conn.close() ``` 在上述代码中,我们首先使用 mysql.connector 包连接到 MySQL 数据库。然后,我们创建一个 BinLogStreamReader 对象,该对象可以监听 MySQL 数据库的二进制日志(binlog),并实时获取表变动信息。在创建 BinLogStreamReader 对象时,我们指定了需要监听的表名为 task_name,只监听 tablemap、writerows、updaterows 和 deleterows 事件,只监听 test 数据库。接着,我们使用 for 循环遍历 BinLogStreamReader 对象,处理每个表变动事件,并打印表变动信息。最后,我们在循环结束后关闭 BinLogStreamReader 对象和数据库连接。 需要注意的是,上述代码仅演示了如何使用 mysql-replication 包监控 MySQL 表变动,实际使用时还需要根据自己的需求进行修改。例如,我们可以将表变动信息保存到文件、发送邮件或调用其他 API 进行处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值