Last active
September 25, 2015 01:17
-
-
Save spearwolf/838760 to your computer and use it in GitHub Desktop.
nodejs based mysql table tail
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var _ = require('./underscore'), | |
| MysqlClient = require('mysql').Client; | |
| //=========================================================== | |
| // MysqlTail( options ) | |
| // -------------------- | |
| // | |
| // initialize the mysql tail module. | |
| // | |
| // opts.host --> mysql hostname | |
| // opts.user --> .. username | |
| // opts.database --> .. database | |
| // | |
| // opts.delay --> sleep ms between select's | |
| // | |
| // opts.table --> db table | |
| // opts.select := '*' --> what to select (default) | |
| // opts.attrId := 'id' --> id field name (default) | |
| // | |
| //=========================================================== | |
| exports.MysqlTail = function(options_) { | |
| var options = _.extend({ | |
| select: '*', | |
| attrId: 'id' }, options_), | |
| client = new MysqlClient({ | |
| host: options.host, | |
| user: options.user, | |
| database: options.database }), | |
| lastId = null; | |
| function fetchLatestRows(fn) { | |
| var sql = 'SELECT '+options.select+' FROM '+options.table; | |
| if (typeof lastId === 'number' || typeof lastId === 'string') { | |
| sql += lastId < 0 ? ' ORDER BY '+options.attrId+' DESC LIMIT 1' : ' WHERE '+options.attrId+' > '+lastId; | |
| } | |
| client.query(sql, function (err, results, fields) { | |
| if (err) { | |
| throw err; | |
| } | |
| if (lastId < 0 && results.length === 1) { | |
| lastId = results[0].id; | |
| fetchLatestRows(fn); | |
| } else { | |
| for (var i= 0; i < results.length; i++) { | |
| lastId = results[i].id; | |
| fn(results[i]); | |
| } | |
| setTimeout(fetchLatestRows, options.delay, fn); | |
| } | |
| }); | |
| } | |
| return { | |
| //=========================================================== | |
| // opts.lastId := -1 --> show only new inserted rows | |
| // null --> show all rows | |
| // <ID> --> show new rows, begins at <ID+1> | |
| //=========================================================== | |
| tail: function(opts, fn) { | |
| lastId = opts.lastId; | |
| client.connect(); | |
| fetchLatestRows(fn); | |
| } | |
| }; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment