all files / axway/lib/ jdbc.js

94.03% Statements 315/335
93.8% Branches 242/258
100% Functions 1/1
96.07% Lines 269/280
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 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487                    20× 20× 20× 20× 20×   20×                   20×         20×       20×         20×     20×           20×   20× 12×     20×   20×   20×   20× 13×   13×       20×   20×       20×   20× 30×       20×   20×   20×   20×   20×   20×   20×   20×             20×   20×     20×   20×                           20×   20×                   20×   20×                   20×   20×                               20×   20×                                 20×   20×       11×       20×       20× 10× 10×         20×   20× 13× 13×   12× 12× 12× 11×   11× 10×       13×   20×   20× 13× 13× 13× 13×         20×   20× 20× 20× 20× 20× 20× 20× 20×         20×   20× 23× 23×     23× 22× 21× 21× 17× 17×             23× 23× 23× 23×   20×   20× 24× 24×     24× 23× 21×       20×   20×                             20×   20×     23× 23× 23× 23× 23× 23× 22× 22× 22×     23×             23× 23×   20×   20× 19× 18×   20×   20×   20×  
'use strict';
 
/*
 * This radically inappropriately named 'jdbc' module is roughly
 * analogous to the AbstractJdbcHelper class (and friends) in the Java
 * executor package. It is responsible for delivering the appropriate
 * mysql (or whatever) queries, and calling context.succeed (or
 * context.fail) with correct data.
 */
 
const _ = require('lodash');
const util = require('./util');
const mysql = require('mysql');
const psql = require('pg');
const named = require('node-postgres-named');
 
exports.send = (context, output) => {
  if (isSchemaRequest(context, output)) {
    requestSchema(context, output);
  } else if (isValidateConnection(context, output)) {
    validateConnection(context, output);
  } else {
    requestJdbc(context, output);
  }
};
 
const isSchemaRequest = (context, output) => {
  // TODO
  return false;
};
 
const requestSchema = (context, output) => {
  // TODO
};
 
const isValidateConnection = (context, output) => {
  // TODO
  return false;
};
 
const validateConnection = (context, output) => {
};
 
const requestJdbc = (context, output) => {
  if (isNamedQuery(context, output)) {
    executeNamedQuery(context, output);
  } else if (isQuery(context, output)) {
    const script = getScript(context, output);
    if (_.isEmpty(script)) {
      return context.fail({error: `No script found for JDBC query`});
    }
 
    // TODO: Set MAX_ROWS
    execute(script, context, output);
  } else if (isGetAll(context, output)) {
    executeGetAll(context, output);
  } else if (isGetById(context, output)) {
    executeGetById(context, output);
  } else if (isDelete(context, output)) {
    executeDelete(context, output);
  } else if (isInsert(context, output)) {
    executeInsert(context, output);
  } else Eif (isUpdate(context, output)) {
    executeUpdate(context, output);
  }
};
exports.requestJdbc = (context, output) => requestJdbc(context, output);
 
const isQuery = (context, output) => {
  return (output.resource.method || '').toUpperCase() === 'POST' &&
      (output.resource.path || '').endsWith('/query');
};
exports.isQuery = (context, output) => isQuery(context, output);
 
const getScript = (context, output) => {
  return (output.query || {}).script || (output.input.body || '').toString();
};
exports.getScript = (context, output) => getScript(context, output);
 
const isNamedQuery = (context, output) => {
  const vpUpper = (output.input.sql || output.resource.vendorPath || '')
      .trim().toUpperCase();
  return vpUpper.startsWith("INSERT") || vpUpper.startsWith("UPDATE") ||
      vpUpper.startsWith("DELETE") || vpUpper.startsWith("SELECT") ||
      (vpUpper.indexOf('(') !== -1 && vpUpper.indexOf(')') !== -1);
};
exports.isNamedQuery = (context, output) => isNamedQuery(context, output);
 
const isGetAll = (context, output) => {
  return (output.resource.method || 'GET').toUpperCase() === 'GET' &&
      !(output.resource.path || '').endsWith('/{objectId}') &&
      !(output.resource.path || '').endsWith('/{id}');
};
exports.isGetAll = (context, output) => isGetAll(context, output);
 
const isGetById = (context, output) => {
  return (output.resource.method || 'GET').toUpperCase() === 'GET' &&
      ((output.resource.path || '').endsWith('/{objectId}') ||
      (output.resource.path || '').endsWith('/{id}'));
};
exports.isGetById = (context, output) => isGetById(context, output);
 
const isDelete = (context, output) => {
  return (output.resource.method || '').toUpperCase() === 'DELETE';
};
exports.isDelete = (context, output) => isDelete(context, output);
 
const isInsert = (context, output) => {
  return (output.resource.method || '').toUpperCase() === 'POST';
};
exports.isInsert = (context, output) => isInsert(context, output);
 
const isUpdate = (context, output) => {
  return (output.resource.method || '').toUpperCase() === 'PATCH';
};
exports.isUpdate = (context, output) => isUpdate(context, output);
 
const executeNamedQuery = (context, output) => {
  const scriptNamedValues = findNamedValues(context, output);
  const script = scriptNamedValues[0];
  const namedValues = scriptNamedValues[1];
 
  if (script.toUpperCase().indexOf('RETURNING') !== -1) {
    // we are hosed: mysql doesn't support "returning"
    output.fail("Returning unsupported in mysql");
  } else {
    withConnection(context, output, (conn, cb) => {
      console.log("in with conn", script, namedValues);
      conn.query(script, namedValues, cb);
    }, standardResponse(context, output));
  }
};
exports.executeNamedQuery = (context, output) => executeNamedQuery(context, output);
 
const execute = (script, context, output) => {
  withConnection(context, output, (conn, cb) => { conn.query(script, cb); },
      standardResponse(context, output));
};
exports.execute = (script, context, output) => execute(script, context, output);
 
const executeGetAll = (context, output) => {
  const orderBy = (output.query || {}).orderBy || '';
 
  let whereClause = (output.query || {}).where || '';
  if (!_.isEmpty(whereClause)) { whereClause = " where " + whereClause; }
 
  let tname = (output.input.mappedPaths || {}).objectName;
  if (_.isEmpty(tname)) {
    return context.fail({error: "No `objectName` value found."});
  }
 
  const fields = findFields(context, output, tname);
 
  let page = parseInt((output.input.query || {}).page);
  if (isNaN(page)) { page = 1; }
  let pageSize = parseInt((output.input.query || {}).pageSize);
  if (isNaN(pageSize)) { pageSize = 50; }
  const offset = pageOffset(page, pageSize);
 
  let script;
  if (!_.isEmpty(orderBy)) {
    script = `select ${fields} from ${tname}${whereClause} ` +
        `order by ${orderBy} limit ${pageSize} offset ${offset}`;
  } else {
    script = `select ${fields} from ${tname}${whereClause} ` +
        `limit ${pageSize} offset ${offset}`;
  }
 
  withConnection(context, output, (conn, cb) => {
    conn.query(script, cb);
  }, standardResponse(context, output));
};
exports.executeGetAll = (context, output) => executeGetAll(context, output);
 
const executeGetById = (context, output) => {
  let tname = (output.input.mappedPaths || {}).objectName;
  if (_.isEmpty(tname)) {
    return context.fail({error: "No `objectName` value found."});
  }
 
  let objectId = (output.query || {}).objectId;
  if (_.isEmpty(objectId)) {
    return context.fail({error: `No ID found in query for ${tname}.`});
  }
 
  const pk = findPk(context, output, tname);
  if (_.isEmpty(pk)) {
    return context.fail({error: `No PK found in query for ${tname}.`});
  }
 
  const fields = findFields(context, output, tname);
  const script = `select ${fields} from ${tname} where ${pk} = :val limit 1`;
 
  withConnection(context, output, (conn, cb) => {
    conn.query(script, {val: objectId}, cb);
  }, standardResponse(context, output));
};
exports.executeGetById = (context, output) => executeGetById(context, output);
 
const executeDelete = (context, output) => {
  let tname = (output.input.mappedPaths || {}).objectName;
  if (_.isEmpty(tname)) {
    return context.fail({error: "No `objectName` value found."});
  }
 
  let objectId = (output.query || {}).objectId;
  if (_.isEmpty(objectId) && !_.isNumber(objectId)) {
    return context.fail({error: `No ID found in query for ${tname}.`});
  }
 
  const pk = findPk(context, output, tname);
  if (_.isEmpty(pk)) {
    return context.fail({error: `No PK found in query for ${tname}.`});
  }
 
  const script = `delete from ${tname} where ${pk} = :val`;
 
  withConnection(context, output, (conn, cb) => {
    conn.query(script, {val: objectId}, cb);
  }, standardResponse(context, output));
};
exports.executeDelete = (context, output) => executeDelete(context, output);
 
const executeInsert = (context, output) => {
  let tname = (output.input.mappedPaths || {}).objectName;
  if (_.isEmpty(tname)) {
    return context.fail({error: "No `objectName` value found."});
  }
 
  const body = output.body || {};
 
  const ks = Object.keys(body);
  const kstr = ks.join(',');
  const vstr = ks.map(k => `:${k}`).join(',');
 
  let script = `insert into ${tname} (${kstr}) values (${vstr})`;
  // const pk = findPk(context, output, tname);
  // TODO: append " returning ${pk}" for DBs that support it
 
  withConnection(context, output, (conn, cb) => {
    conn.query(script, body, cb);
  }, (err, result) => {
    Iif (_.isEmpty(result.id)) {
      if (!util.notNull(output.query)) { output.query = {}; }
      output.query.objectId = result.id;
      executeGetById(context, output);
    } else {
      standardResponse(context, output)(err, result);
    }
  });
};
exports.executeInsert = (context, output) => executeInsert(context, output);
 
const executeUpdate = (context, output) => {
  let tname = (output.input.mappedPaths || {}).objectName;
  if (_.isEmpty(tname)) {
    return context.fail({error: "No `objectName` value found."});
  }
 
  let objectId = (output.query || {}).objectId;
  if (_.isEmpty(objectId)) {
    return context.fail({error: `No ID found in query for ${tname}.`});
  }
 
  const pk = findPk(context, output, tname);
  if (_.isEmpty(pk)) {
    return context.fail({error: `No PK found in query for ${tname}.`});
  }
 
  const body = output.body || {};
 
  const ks = Object.keys(body);
  const kvstr = ks.map(k => `${k} = :${k}`).join(', ');
 
  let script = `update ${tname} set ${kvstr} where ${pk} = :pkval00`;
  let args = _.clone(body); args.pkval00 = objectId;
 
  withConnection(context, output, (conn, cb) => {
    conn.query(script, args, cb);
  }, (err, result) => {
    Iif (util.notNull(err)) { return context.fail({error: err}); }
    Eif (util.notNull(result.count) && result.count > 0) {
      executeGetById(context, output);
    } else {
      context.fail({error:
          `Unable to update: no row in ${tname} where ${pk} = ${objectId}`});
    }
  });
};
exports.executeUpdate = (context, output) => executeUpdate(context, output);
 
const findNamedValues = (context, output) => {
  let namedValues = {};
  let script = (output.input.sql || output.resource.vendorPath || '');
  script = fillInQuery(script, output);
 
  ((output.query || {}).namedParameters || '').split(/,/).forEach(np => {
    namedValues[np.trim()] = null;
  });
 
  Object.keys(output.query || {}).forEach(qk => {
    if (qk === 'namedParameters') { return; }
    script = script.replace(new RegExp(`{${qk}}`, 'g'), `:${qk}`);
    namedValues[qk] = output.query[qk];
  });
 
  return [script, namedValues];
};
exports.findNamedValues = (context, output) => findNamedValues(context, output);
 
// Replace curly parameters in the SQL query with their path parameters,
// handling the "orderBy" and "where" parameters specially.
const fillInQuery = (script, output) => {
  const paths = output.paths || {};
  return util.constructPath(script, v => {
    if (v === 'orderBy' && !_.isEmpty(paths.orderBy)) {
      return `order by ${paths.orderBy}`;
    } else if (v === 'where' && !_.isEmpty(paths.where)) {
      return `where ${paths.where}`;
    } else {
      return paths[v];
    }
  });
};
exports.fillInQuery = (script, output) => fillInQuery(script, output);
 
const findFields = (context, output, tname) => {
  let fields = (output.query || {}).fields || '*';
  if (fields === '*' &&
      !/^true$/i.test(output.findConfig('db.selectall.fields') || 'false')) {
    let table = _.find(JSON.parse(output.findConfig('db.schema')),
        t => t.name === tname);
    if (util.notNull(table)) {
      fields = table.columns.filter(c => util.notNull(c.name) &&
          c.dataType !== 'object').map(c => {
        if (c.name.indexOf(' ') !== -1) { return `"${c.name}"`; }
        else { return c.name; }
      }).join(',');
    }
  }
  return fields;
};
exports.findFields = (context, output, tname) => findFields(context, output, tname);
 
const findPk = (context, output, tname) => {
  let pks = null;
  let table = _.find(JSON.parse(output.findConfig('db.schema')),
      t => t.name === tname);
  if (util.notNull(table)) {
    pks = table.columns.filter(c => util.notNull(c.name) &&
        c.primaryKey).map(c => {
      Iif (c.name.indexOf(' ') !== -1) { return `"${c.name}"`; }
      else { return c.name; }
    });
    return pks[0];
  }
  return null;
};
exports.findPk = (context, output, tname) => findPk(context, output, tname);
 
const withConnection = (context, output, fn, cb) => {
  createConnection(context, output, (err, conn) => {
    Iif (util.notNull(err)) { return cb(err); }
    fn(conn, (err, result) => {
      Iif (util.notNull(err)) { conn.end(); return cb(err); }
      conn.end(err => {
        Iif (util.notNull(err)) { return cb(err); }
        return cb(null, standardizeMySqlResult(context, output, result));
      });
    });
  });
};
exports.withConnection = (context, output, fn, cb) => withConnection(context, output, fn, cb);
 
const standardizeMySqlResult = (context, output, result) => {
  const inheads = (output.input.headers || {});
  const driver = inheads['jdbc.driverClassName'] ||
      output.findConfig('jdbc.driver.classname');
 
  if (driver === 'org.postgresql.Driver') {
    if (util.notNull(result.rows)) {
      result = result.rows;
      if (result.length > 0) {
        const keys = _.keys(result[0]);
        if (keys.length === 1) {
          result.id = result[0][keys[0]];
        }
      }
    } else {
      result.count = result.rowCount;
    }
  }
 
  if (isGetById(context, output) && result.length >= 1) result = result[0];
  if (util.notNull(result.insertId)) result.id = result.insertId;
  if (util.notNull(result.affectedRows)) result.count = result.affectedRows;
  return result;
};
exports.standardizeMySqlResult = (context, output, result) => standardizeMySqlResult(context, output, result);
 
const createConnection = (context, output, cb) => {
  const inheads = (output.input.headers || {});
  const driver = inheads['jdbc.driverClassName'] ||
      output.findConfig('jdbc.driver.classname');
 
  if (driver === 'com.mysql.jdbc.Driver') {
    cb(null, createMysqlConnection(context, output));
  } else if (driver === 'org.postgresql.Driver') {
    createPsqlConnection(context, output, cb);
  } else {
    cb(`Unrecognized driver: ${driver}`);
  }
};
exports.createConnection = (context, output, cb) => createConnection(context, output, cb);
 
const createMysqlConnection = (context, output) => {
  const inheads = (output.input.headers || {});
  const hostport = inheads['jdbc.host'] || output.findConfig('db.host');
  const colon = hostport.indexOf(':');
  let host = hostport;
  let port = 3306;
  if (colon !== -1) {
    host = hostport.substr(0, colon);
    port = parseInt(hostport.substr(colon + 1));
    if (isNaN(port)) { port = 3306; }
  }
  let conn = mysql.createConnection({
    host: host,
    port: port,
    user: inheads['jdbc.username'] || output.findConfig('username'),
    password: inheads['jdbc.password'] || output.findConfig('password'),
    database: inheads['jdbc.database'] || output.findConfig('db.name')
  });
 
  // Here's how mysql can handle named parameters:
  conn.config.queryFormat = (query, values) => {
    if (!values) { return query; }
    return query.replace(/\:(\w+)/g, function (txt, key) {
      if (values.hasOwnProperty(key) && util.notNull(values[key])) {
        return mysql.escape(values[key]);
      }
      return '';
    }.bind(this));
  };
 
  return conn;
};
exports.createMysqlConnection = (context, output) => createMysqlConnection(context, output);
 
const createPsqlConnection = (context, output, cb) => {
  // psql coincidently (or not so coincidently) has the same basic
  // config structure as mysql
  const inheads = (output.input.headers || {});
  const hostport = inheads['jdbc.host'] || output.findConfig('db.host');
  const colon = hostport.indexOf(':');
  let host = hostport;
  let port = 5432;
  if (colon !== -1) {
    host = hostport.substr(0, colon);
    port = parseInt(hostport.substr(colon + 1));
    Eif (isNaN(port)) { port = 5432; }
  }
 
  let client = new psql.Client({
    host: host,
    port: port,
    user: inheads['jdbc.username'] || output.findConfig('username'),
    password: inheads['jdbc.password'] || output.findConfig('password'),
    database: inheads['jdbc.database'] || output.findConfig('db.name')
  });
  named.patch(client);
  client.connect(err => cb(err, client));
};
exports.createPsqlConnection = (context, output, cb) => createPsqlConnection(context, output, cb);
 
const standardResponse = (context, output) => (err, result) => {
  if (util.notNull(err)) { return context.fail({error: err}); }
  else { context.succeed({headers: {}, body: result}); }
};
exports.standardResponse = (context, output) => standardResponse(context, output);
 
const pageOffset = (page, pageSize) => {
  if (page < 1 || pageSize < 1) { return 0; }
  return (page - 1) * pageSize;
};
exports.pageOffset = (page, pageSize) => pageOffset(page, pageSize);