mysql.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. var mysql = require('mysql');
  2. function MysqlConnector(opts) {
  3. this.conn = null;
  4. this.errorHandler = function(err) { console.log(err) };
  5. this.releaseCallback = function(err) { console.log('unassigned MysqlConnector release callback'); };
  6. this.opts = _.extend({}, opts);
  7. }
  8. // creates a new connection and returns it in the callback
  9. MysqlConnector.prototype.connect = function(schema, cb) {
  10. var that = this;
  11. this.conn = mysql.createConnection({
  12. host: this.opts.host,
  13. user: this.opts.user,
  14. password: this.opts.pass,
  15. database: schema || this.opts.defaultDB
  16. });
  17. this.conn.connect(onConnect);
  18. function onConnect(err) {
  19. cb(err, that);
  20. };
  21. }
  22. // run arbitrary sql. no escaping, no magic.
  23. MysqlConnector.prototype.query = function(sql, cb) {
  24. this.conn.query(sql, cb);
  25. }
  26. // sets the schema
  27. MysqlConnector.prototype.setSchema = function(schema, cb) {
  28. this.conn.query("USE " + mysql.escapeId(schema), cb);
  29. }
  30. // called when there is an error on the connection.
  31. // the connection is assumed to be in an invalid state and will be released.
  32. // TODO: add non-fatal error flag
  33. MysqlConnector.prototype.onError = function(handler) {
  34. this.errorHandler = handler;
  35. this.conn.on('error', this.errorHandler);
  36. }
  37. // called when a connection is ended, gracefully or not
  38. MysqlConnector.prototype.onRelease = function(callback) {
  39. this.releaseCallback = callback;
  40. }
  41. // graceful shutdown
  42. MysqlConnector.prototype.release = function() {
  43. this.conn.end(this.releaseCallback);
  44. };
  45. // not so graceful shutdown
  46. MysqlConnector.prototype.terminate = function() {
  47. this.conn.destroy();
  48. this.releaseCallback();
  49. };
  50. MysqlConnector.prototype.escape = mysql.escape;
  51. MysqlConnector.prototype.escapeID = mysql.escapeId;
  52. module.exports = function() {
  53. return new MysqlConnector();
  54. };