All files / app/lib/mysql script.js

100% Statements 65/65
83.33% Branches 15/18
100% Functions 5/5
100% Lines 65/65

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 6621x 21x 21x 2x 2x 2x 1x 1x 1x 1x 1x 1x 2x 2x 2x 21x 21x 21x 21x 1x 1x 1x 1x 1x 1x 1x 1x 1x 21x 21x 21x 21x 21x 1x 1x 1x 21x 21x 21x 3x 3x 3x 2x 2x 3x 3x 9x 9x 9x 9x 9x 3x 3x 3x 3x 3x 3x 21x 21x 21x 1x 1x 21x 21x 21x  
const Mysql = require('./mysql');
const util = require('util');
 
function Script(pool,schema,table,options) {
  if (!(this instanceof Script))
    return new Script(pool,schema,table,options);
 
  Mysql.call(this,pool,options);
 
  this.schema = schema;
  this.table = table;
  this.columns = this.getColumns();
  this.prefix = this.options.prefix || 'REPLACE INTO ';
  this.maxBuffer = this.options.maxBuffer || 1024 * 1024;
}
 
util.inherits(Script,Mysql);
 
Script.prototype.getColumns = function() {
  const sql = 'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE '+
            `TABLE_SCHEMA="${this.schema}" AND TABLE_NAME="${this.table}";`;
 
  return this.query(sql)
    .then(d => {
      if (!d.length)
        throw 'TABLE_NOT_FOUND';
      return d.map(d => d.COLUMN_NAME);
    });
};
 
Script.prototype.buffer = undefined;
 
Script.prototype._push = function() {
  if (this.buffer)
    this.push(this.buffer);
  this.buffer = undefined;
};
 
Script.prototype._fn = function(d) {
  return this.columns.then(columns => {
    if (!this.buffer)
      this.buffer = `${this.prefix} \`${this.schema}\`.\`${this.table}\` (\`${columns.join('`,`')}\`) VALUES `;
    else
      this.buffer += ', ';
 
    this.buffer += '('+columns.map(key => {
      const value = d[key];
      if (typeof value === 'undefined')
        return 'DEFAULT';
      else
        return this.pool.escape(value);
    })
    .join(',')+')';
 
    if (this.buffer.length >= this.maxBuffer)
      this._push();
  });
};
 
Script.prototype._flush = function(cb) {
  this._push();
  setImmediate(() => Mysql.prototype._flush(cb));
};
 
module.exports = Script;