0.5.1 • Published 4 years ago

zongji v0.5.1

Weekly downloads
1,004
License
MIT
Repository
github
Last release
4 years ago

ZongJi Build Status

A MySQL binlog listener running on Node.js.

ZongJi (踪迹) is pronounced as zōng jì in Chinese.

This package is a pure JS implementation based on mysql. It has been tested to work in MySQL 5.5, 5.6, and 5.7.

Latest Release

The latest release is v0.5.0, only supports Node.js from v8.

v0.4.7 is the last release which supports Node.js v4.x.

Quick Start

let zongji = new ZongJi({ /* ... MySQL Connection Settings ... */ });

// Each change to the replication log results in an event
zongji.on('binlog', function(evt) {
  evt.dump();
});

// Binlog must be started, optionally pass in filters
zongji.start({
  includeEvents: ['tablemap', 'writerows', 'updaterows', 'deleterows']
});

For a complete implementation see example.js...

Installation

  • Requires Node.js v8+

    $ npm install zongji
  • Enable MySQL binlog in my.cnf, restart MySQL server after making the changes.

    From MySQL 5.6, binlog checksum is enabled by default. Zongji can work with it, but it doesn't really verify it.

    # Must be unique integer from 1-2^32
    server-id        = 1
    # Row format required for ZongJi
    binlog_format    = row
    # Directory must exist. This path works for Linux. Other OS may require
    #   different path.
    log_bin          = /var/log/mysql/mysql-bin.log
    
    binlog_do_db     = employees   # Optional, limit which databases to log
    expire_logs_days = 10          # Optional, purge old logs
    max_binlog_size  = 100M        # Optional, limit log size
  • Create an account with replication privileges, e.g. given privileges to account zongji (or any account that you use to read binary logs)

    GRANT REPLICATION SLAVE, REPLICATION CLIENT, SELECT ON *.* TO 'zongji'@'localhost'

ZongJi Class

The ZongJi constructor accepts one argument of either:

  • An object containing MySQL connection details in the same format as used by package mysql
  • Or, a mysql Connection or Pool object that will be used for querying column information.

If a Connection or Pool object is passed to the constructor, it will not be destroyed/ended by Zongji's stop() method.

If there is a dateStrings mysql configuration option in the connection details or connection, ZongJi will follow it.

Each instance includes the following methods:

Method NameArgumentsDescription
startoptionsStart receiving replication events, see options listed below
stopNoneDisconnect from MySQL server, stop receiving events
oneventName, handlerAdd a listener to the binlog or error event. Each handler function accepts one argument.

Some events can be emitted in different phases:

Event NameDescription
readyThis event is occurred right after ZongJi successfully established a connection, setup slave status, and set binlog position.
binlogOnce a binlog is received and passes the filter, it will bubble up with this event.
errorEvery error will be caught by this event.
stoppedEmitted when ZongJi connection is stopped (ZongJi#stop is called).

Options available:

Option NameTypeDescription
serverIdintegerUnique number (1 - 232) to identify this replication slave instance. Must be specified if running more than one instance of ZongJi. Must be used in start() method for effect.Default: 1
startAtEndbooleanPass true to only emit binlog events that occur after ZongJi's instantiation. Must be used in start() method for effect.Default: false
filenamestringBegin reading events from this binlog file. If specified together with position, will take precedence over startAtEnd.
positionintegerBegin reading events from this position. Must be included with filename.
includeEvents[string]Array of event names to includeExample: ['writerows', 'updaterows', 'deleterows']
excludeEvents[string]Array of event names to excludeExample: ['rotate', 'tablemap']
includeSchemaobjectObject describing which databases and tables to include (Only for row events). Use database names as the key and pass an array of table names or true (for the entire database).Example: { 'my_database': ['allow_table', 'another_table'], 'another_db': true }
excludeSchemaobjectObject describing which databases and tables to exclude (Same format as includeSchema)Example: { 'other_db': ['disallowed_table'], 'ex_db': true }
  • By default, all events and schema are emitted.
  • excludeSchema and excludeEvents take precedence over includeSchema and includeEvents, respectively.

Supported Binlog Events:

Event nameDescription
unknownCatch any other events
queryInsert/Update/Delete Query
intvarAutoincrement and LAST_INSERT_ID
rotateNew Binlog file Not required to be included to rotate to new files, but it is required to be included in order to keep the filename and position properties updated with current values for graceful restarting on errors.
formatFormat Description
xidTransaction ID
tablemapBefore any row event (must be included for any other row events)
writerowsRows inserted, row data array available as rows property on event object
updaterowsRows changed, row data array available as rows property on event object
deleterowsRows deleted, row data array available as rows property on event object

Event Methods

Neither method requires any arguments.

NameDescription
dumpLog a description of the event to the console
getEventNameReturn the name of the event

Important Notes

  • :star2: All types allowed by mysql are supported by this package.
  • :speak_no_evil: 64-bit integer is supported via package big-integer(see #108). If an integer is within the safe range of JS number (-2^53, 2^53), a Number object will returned, otherwise, will return as String.
  • :point_right: TRUNCATE statement does not cause corresponding DeleteRows event. Use unqualified DELETE FROM for same effect.
  • When using fractional seconds with DATETIME and TIMESTAMP data types in MySQL > 5.6.4, only millisecond precision is available due to the limit of Javascript's Date object.

Run Tests

  • install Docker
  • run docker-compose up and then ./docker-test.sh

Reference

I learnt many things from following resources while making ZongJi.

License

MIT