All files / app/lib/postgres script.js

95.17% Statements 138/145
75.55% Branches 34/45
100% Functions 9/9
95.17% Lines 138/145

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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 14621x 21x 21x 21x 21x 21x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 21x 21x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 21x 21x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x         1x 1x 21x 21x 5x 4x 4x 5x 5x 21x 21x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 2x 2x 6x 6x 18x 18x 18x 18x 18x 18x 18x 12x 12x 6x 6x 6x 6x 3x 3x 9x 9x 9x 9x 9x 9x 9x 9x 9x 6x 6x 9x 9x 9x 3x 3x 3x 3x 3x 3x 6x 6x 6x 6x 21x 21x 2x 2x 2x 21x 21x 21x 27x 27x 27x 27x 27x 27x 18x 27x 348x 348x   348x     348x 348x 348x 348x 18x 18x 18x 18x 27x 18x 18x 27x 21x 21x  
const Postgres = require('./postgres');
 
const quoteString = (str) => `"${str}"`;
 
class Script extends Postgres {
  constructor(pool, schema, table, options) {
    super(pool, options);
 
    this.schema = schema;
    this.table = table;
    this.columns = this.getColumns();
    this.upsert = options.upsert;
    if (this.upsert) this.pkeys = this.getPrimaryKeys();
    this.prefix = this.options.prefix || 'INSERT INTO';
    this.maxBuffer = options.maxBuffer || 1024 * 1024;
  }
 
  getColumns() {
    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 => {
        d = d.rows;
        if (!d.length)
          throw 'TABLE_NOT_FOUND';
        return d.map(d => d.column_name);
      });
  }
 
  getPrimaryKeys() {
    const sql = 'SELECT a.attname' +
      ' FROM   pg_index i' +
      ' JOIN   pg_attribute a ON a.attrelid = i.indrelid' +
      ' AND a.attnum = ANY(i.indkey)' +
      ` WHERE  i.indrelid = '${this.schema}.${this.table}'::regclass` +
      ' AND    i.indisprimary;';
 
    return this.query(sql)
      .then(d => d.rows.map(d => d.attname))
      .catch(e => {
        if (e.message && e.message.includes('op ANY/ALL'))
          return [];
        else
          throw e;
      });
  }
 
  _push() {
    if (this.buffer) {
      this.push(this.buffer);
    }
    this.buffer = undefined;
  }
 
  _fn(record) {
    return Promise.all([this.columns, this.pkeys]).then(data => {
      const columns = data[0];
      const pkeys = data[1] || [];
      const d = (Array.isArray(record)) ? record[0] : record;
 
      if (typeof d === 'undefined')
        return;
 
      if (!this.buffer)
        this.buffer = `${this.prefix} ${this.schema}.${this.table} ( ${columns.map(quoteString).join(',')} ) VALUES `;
      else
        this.buffer += ', ';
 
      this.buffer += '(' + columns.map(key => {
        const value = d[key];
        if (typeof value === 'undefined')
          return 'DEFAULT';
        else if (value === null)
          return 'null';
        else if (typeof value === 'object')
          return escapeLiteral(JSON.stringify(value));
        else
          return escapeLiteral(value);
      })
        .join(',') + ')';
 
      if (this.upsert) {
        let tmp_arr = [];
        for (let i = 0, l = columns.length; i < l; i++) {
          const value = d[columns[i]];
          if (typeof value === 'undefined')
            continue;
 
          let sql = `"${columns[i]}" =`;
          if (value === null)
            sql += 'null';
          else if (typeof value === 'object')
            sql += escapeLiteral(JSON.stringify(value));
          else
            sql += escapeLiteral(value);
 
          tmp_arr.push(sql);
        }
        if (tmp_arr.length && pkeys.length) {
          this.buffer += ` ON CONFLICT (${pkeys.map(quoteString).join(', ')}) DO UPDATE SET ${tmp_arr.join(', ')}`;
        }
 
        this._push();
      }
      if (this.buffer && this.buffer.length > this.maxBuffer) this._push();
 
    });
  }
 
  _flush(cb) {
    this._push();
    setImmediate(() => Postgres.prototype._flush(cb));
  }
}
 
// https://github.com/brianc/node-postgres/blob/83a946f61cb9e74c7f499e44d03a268c399bd623/lib/client.js
function escapeLiteral(str) {
  let hasBackslash = false;
  let escaped = '\'';
 
  if (typeof str !== 'string')
    return str;
 
  for (let i = 0; i < str.length; i++) {
    const c = str[i];
    if (c === '\'') {
      escaped += c + c;
    } else if (c === '\\') {
      escaped += c + c;
      hasBackslash = true;
    } else {
      escaped += c;
    }
  }
 
  escaped += '\'';
 
  if (hasBackslash === true)
    escaped = ' E' + escaped;
 
  return escaped;
}
 
module.exports = (...params) => new Script(...params);