All files / src/utils parser.js

85.99% Statements 356/414
77.89% Branches 236/303
97.37% Functions 37/38
86.5% Lines 346/400

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 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 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 7401x 1x 1x   1x 1x   1x   1x     1x   1x 1x 1x   1x   1x 3x 3x 3x         1x   56x   56x 56x 56x             1x   56x 56x   56x     1x                                       1x 40322x 9x     40313x 33x     40280x 40280x   40280x 1x 3x   3x       1x     40279x 40279x 2x     40277x 5x 5x 2x 5x 5x     40272x     1x 22x       22x 1x 1x   21x     1x 42x 42x 42x 42x 42x   42x   42x   41x 17x 17x     24x   24x 15x 3x 12x 1x 1x             11x 3x 3x       24x 2x 1x 1x 1x 1x 1x 1x           1x 1x 1x 1x 1x                           22x 22x       1x 15x 15x   15x 9x 9x       15x 9x 9x       15x 42x   42x 42x   42x                         42x 3x         42x 42x   1x 1x   41x     15x     1x 20015x 20015x 20015x   20015x 5x 1x       20015x 5x 1x       20015x 40184x     40179x 40179x   40179x 45x 45x 16x 29x   29x             40163x 3x         40163x   40163x 40163x 40162x 40146x 40146x   16x     1x 1x   40162x     20015x               1x 117x 117x   117x       117x 117x     117x       117x 117x   117x 112x 112x 112x       112x                 117x 3x 3x 3x         3x 1x 1x 2x 2x 2x 2x 2x         1x         2x       117x 2x   2x 2x 3x 3x 3x   115x 4x 4x 4x 1x 1x       1x 1x     3x       3x         111x 1x 1x     1x       1x   110x   117x     1x 79x 79x   79x 142x     25x                 25x                   25x     117x   117x   117x 117x   117x                             117x 17x 17x 17x 17x   1x 1x       100x     117x 117x 117x 117x 117x             117x 117x         79x     1x 79x 79x 79x 73x   6x   79x 79x     1x 1x 1x 1x 3x 3x   3x   3x           3x         3x       3x   1x     1x 77x     1x 1x     1x 4x 4x 4x   4x 4x     1x   3x       4x 4x 4x     4x 4x 7x         4x 4x 4x 4x     4x     1x 4x 4x 4x 4x   4x   4x   1x 4x   2x       1x 1x         4x 4x 14x 14x                     14x   8x     4x     1x 56x 56x 100x 100x 2x     2x   2x 3x 3x 3x   3x 3x     3x 3x                     56x     1x 56x   56x 136x   136x 3x       3x       56x   56x     1x 56x 56x 100x 100x 23x 23x     56x     1x 56x 56x 6x 6x   41x 13x 5x 5x 8x 2x 6x 5x 5x 5x 1x 4x 3x   1x   5x 1x 1x     6x   56x     1x  
const Promise = require('bluebird');
const _ = require('lodash');
const util = require('util');
 
let dseDriver;
try {
  // eslint-disable-next-line import/no-extraneous-dependencies, import/no-unresolved
  dseDriver = require('dse-driver');
} catch (e) {
  dseDriver = null;
}
 
const cql = Promise.promisifyAll(dseDriver || require('cassandra-driver'));
 
const buildError = require('../orm/apollo_error.js');
const datatypes = require('../validators/datatypes');
const schemer = require('../validators/schema');
 
const parser = {};
 
parser.callback_or_throw = function f(err, callback) {
  Eif (typeof callback === 'function') {
    callback(err);
    return;
  }
  throw (err);
};
 
parser.extract_type = function f(val) {
  // decompose composite types
  const decomposed = val ? val.replace(/[\s]/g, '').split(/[<,>]/g) : [''];
 
  for (let d = 0; d < decomposed.length; d++) {
    Eif (_.has(datatypes, decomposed[d])) {
      return decomposed[d];
    }
  }
 
  return val;
};
 
parser.extract_typeDef = function f(val) {
  // decompose composite types
  let decomposed = val ? val.replace(/[\s]/g, '') : '';
  decomposed = decomposed.substr(decomposed.indexOf('<'), decomposed.length - decomposed.indexOf('<'));
 
  return decomposed;
};
 
parser.extract_altered_type = function f(normalizedModelSchema, diff) {
  const fieldName = diff.path[0];
  let type = '';
  if (diff.path.length > 1) {
    if (diff.path[1] === 'type') {
      type = diff.rhs;
      if (normalizedModelSchema.fields[fieldName].typeDef) {
        type += normalizedModelSchema.fields[fieldName].typeDef;
      }
    } else {
      type = normalizedModelSchema.fields[fieldName].type;
      type += diff.rhs;
    }
  } else {
    type = diff.rhs.type;
    if (diff.rhs.typeDef) type += diff.rhs.typeDef;
  }
  return type;
};
 
parser.get_db_value_expression = function f(schema, fieldName, fieldValue) {
  if (fieldValue == null || fieldValue === cql.types.unset) {
    return { query_segment: '?', parameter: fieldValue };
  }
 
  if (_.isPlainObject(fieldValue) && fieldValue.$db_function) {
    return fieldValue.$db_function;
  }
 
  const fieldType = schemer.get_field_type(schema, fieldName);
  const validators = schemer.get_validators(schema, fieldName);
 
  if (_.isArray(fieldValue) && fieldType !== 'list' && fieldType !== 'set' && fieldType !== 'frozen') {
    const val = fieldValue.map((v) => {
      const dbVal = parser.get_db_value_expression(schema, fieldName, v);
 
      Eif (_.isPlainObject(dbVal) && dbVal.query_segment) return dbVal.parameter;
      return dbVal;
    });
 
    return { query_segment: '?', parameter: val };
  }
 
  const validationMessage = schemer.get_validation_message(validators, fieldValue);
  if (typeof validationMessage === 'function') {
    throw (buildError('model.validator.invalidvalue', validationMessage(fieldValue, fieldName, fieldType)));
  }
 
  if (fieldType === 'counter') {
    let counterQuerySegment = util.format('"%s"', fieldName);
    if (fieldValue >= 0) counterQuerySegment += ' + ?';
    else counterQuerySegment += ' - ?';
    fieldValue = Math.abs(fieldValue);
    return { query_segment: counterQuerySegment, parameter: fieldValue };
  }
 
  return { query_segment: '?', parameter: fieldValue };
};
 
parser.unset_not_allowed = function f(operation, schema, fieldName, callback) {
  Iif (schemer.is_primary_key_field(schema, fieldName)) {
    parser.callback_or_throw(buildError(`model.${operation}.unsetkey`, fieldName), callback);
    return true;
  }
  if (schemer.is_required_field(schema, fieldName)) {
    parser.callback_or_throw(buildError(`model.${operation}.unsetrequired`, fieldName), callback);
    return true;
  }
  return false;
};
 
parser.get_inplace_update_expression = function f(schema, fieldName, fieldValue, updateClauses, queryParams) {
  const $add = (_.isPlainObject(fieldValue) && fieldValue.$add) || false;
  const $append = (_.isPlainObject(fieldValue) && fieldValue.$append) || false;
  const $prepend = (_.isPlainObject(fieldValue) && fieldValue.$prepend) || false;
  const $replace = (_.isPlainObject(fieldValue) && fieldValue.$replace) || false;
  const $remove = (_.isPlainObject(fieldValue) && fieldValue.$remove) || false;
 
  fieldValue = $add || $append || $prepend || $replace || $remove || fieldValue;
 
  const dbVal = parser.get_db_value_expression(schema, fieldName, fieldValue);
 
  if (!_.isPlainObject(dbVal) || !dbVal.query_segment) {
    updateClauses.push(util.format('"%s"=%s', fieldName, dbVal));
    return;
  }
 
  const fieldType = schemer.get_field_type(schema, fieldName);
 
  if (['map', 'list', 'set'].includes(fieldType)) {
    if ($add || $append) {
      dbVal.query_segment = util.format('"%s" + %s', fieldName, dbVal.query_segment);
    } else if ($prepend) {
      Eif (fieldType === 'list') {
        dbVal.query_segment = util.format('%s + "%s"', dbVal.query_segment, fieldName);
      } else {
        throw (buildError(
          'model.update.invalidprependop',
          util.format('%s datatypes does not support $prepend, use $add instead', fieldType),
        ));
      }
    } else if ($remove) {
      dbVal.query_segment = util.format('"%s" - %s', fieldName, dbVal.query_segment);
      if (fieldType === 'map') dbVal.parameter = Object.keys(dbVal.parameter);
    }
  }
 
  if ($replace) {
    if (fieldType === 'map') {
      updateClauses.push(util.format('"%s"[?]=%s', fieldName, dbVal.query_segment));
      const replaceKeys = Object.keys(dbVal.parameter);
      const replaceValues = _.values(dbVal.parameter);
      Eif (replaceKeys.length === 1) {
        queryParams.push(replaceKeys[0]);
        queryParams.push(replaceValues[0]);
      } else {
        throw (
          buildError('model.update.invalidreplaceop', '$replace in map does not support more than one item')
        );
      }
    } else Eif (fieldType === 'list') {
      updateClauses.push(util.format('"%s"[?]=%s', fieldName, dbVal.query_segment));
      Eif (dbVal.parameter.length === 2) {
        queryParams.push(dbVal.parameter[0]);
        queryParams.push(dbVal.parameter[1]);
      } else {
        throw (buildError(
          'model.update.invalidreplaceop',
          '$replace in list should have exactly 2 items, first one as the index and the second one as the value',
        ));
      }
    } else {
      throw (buildError(
        'model.update.invalidreplaceop',
        util.format('%s datatypes does not support $replace', fieldType),
      ));
    }
  } else {
    updateClauses.push(util.format('"%s"=%s', fieldName, dbVal.query_segment));
    queryParams.push(dbVal.parameter);
  }
};
 
parser.get_update_value_expression = function f(instance, schema, updateValues, callback) {
  const updateClauses = [];
  const queryParams = [];
 
  if (schema.options && schema.options.timestamps) {
    Eif (!updateValues[schema.options.timestamps.updatedAt]) {
      updateValues[schema.options.timestamps.updatedAt] = { $db_function: 'toTimestamp(now())' };
    }
  }
 
  if (schema.options && schema.options.versions) {
    Eif (!updateValues[schema.options.versions.key]) {
      updateValues[schema.options.versions.key] = { $db_function: 'now()' };
    }
  }
 
  const errorHappened = Object.keys(updateValues).some((fieldName) => {
    Iif (schema.fields[fieldName] === undefined || schema.fields[fieldName].virtual) return false;
 
    const fieldType = schemer.get_field_type(schema, fieldName);
    let fieldValue = updateValues[fieldName];
 
    Iif (fieldValue === undefined) {
      fieldValue = instance._get_default_value(fieldName);
      if (fieldValue === undefined) {
        return parser.unset_not_allowed('update', schema, fieldName, callback);
      } else if (!schema.fields[fieldName].rule || !schema.fields[fieldName].rule.ignore_default) {
        // did set a default value, ignore default is not set
        if (instance.validate(fieldName, fieldValue) !== true) {
          parser.callback_or_throw(buildError('model.update.invaliddefaultvalue', fieldValue, fieldName, fieldType), callback);
          return true;
        }
      }
    }
 
    if (fieldValue === null || fieldValue === cql.types.unset) {
      Iif (parser.unset_not_allowed('update', schema, fieldName, callback)) {
        return true;
      }
    }
 
    try {
      parser.get_inplace_update_expression(schema, fieldName, fieldValue, updateClauses, queryParams);
    } catch (e) {
      parser.callback_or_throw(e, callback);
      return true;
    }
    return false;
  });
 
  return { updateClauses, queryParams, errorHappened };
};
 
parser.get_save_value_expression = function fn(instance, schema, callback) {
  const identifiers = [];
  const values = [];
  const queryParams = [];
 
  if (schema.options && schema.options.timestamps) {
    if (instance[schema.options.timestamps.updatedAt]) {
      instance[schema.options.timestamps.updatedAt] = { $db_function: 'toTimestamp(now())' };
    }
  }
 
  if (schema.options && schema.options.versions) {
    if (instance[schema.options.versions.key]) {
      instance[schema.options.versions.key] = { $db_function: 'now()' };
    }
  }
 
  const errorHappened = Object.keys(schema.fields).some((fieldName) => {
    if (schema.fields[fieldName].virtual) return false;
 
    // check field value
    const fieldType = schemer.get_field_type(schema, fieldName);
    let fieldValue = instance[fieldName];
 
    if (fieldValue === undefined) {
      fieldValue = instance._get_default_value(fieldName);
      if (fieldValue === undefined) {
        return parser.unset_not_allowed('save', schema, fieldName, callback);
      } else Eif (!schema.fields[fieldName].rule || !schema.fields[fieldName].rule.ignore_default) {
        // did set a default value, ignore default is not set
        Iif (instance.validate(fieldName, fieldValue) !== true) {
          parser.callback_or_throw(buildError('model.save.invaliddefaultvalue', fieldValue, fieldName, fieldType), callback);
          return true;
        }
      }
    }
 
    if (fieldValue === null || fieldValue === cql.types.unset) {
      Iif (parser.unset_not_allowed('save', schema, fieldName, callback)) {
        return true;
      }
    }
 
    identifiers.push(util.format('"%s"', fieldName));
 
    try {
      const dbVal = parser.get_db_value_expression(schema, fieldName, fieldValue);
      if (_.isPlainObject(dbVal) && dbVal.query_segment) {
        values.push(dbVal.query_segment);
        queryParams.push(dbVal.parameter);
      } else {
        values.push(dbVal);
      }
    } catch (e) {
      parser.callback_or_throw(e, callback);
      return true;
    }
    return false;
  });
 
  return {
    identifiers,
    values,
    queryParams,
    errorHappened,
  };
};
 
parser.extract_query_relations = function f(fieldName, relationKey, relationValue, schema, validOperators) {
  const queryRelations = [];
  const queryParams = [];
 
  Iif (!_.has(validOperators, relationKey.toLowerCase())) {
    throw (buildError('model.find.invalidop', relationKey));
  }
 
  relationKey = relationKey.toLowerCase();
  Iif (relationKey === '$in' && !_.isArray(relationValue)) {
    throw (buildError('model.find.invalidinop'));
  }
  Iif (relationKey === '$token' && !(relationValue instanceof Object)) {
    throw (buildError('model.find.invalidtoken'));
  }
 
  let operator = validOperators[relationKey];
  let whereTemplate = '"%s" %s %s';
 
  const buildQueryRelations = (fieldNameLocal, relationValueLocal) => {
    const dbVal = parser.get_db_value_expression(schema, fieldNameLocal, relationValueLocal);
    Eif (_.isPlainObject(dbVal) && dbVal.query_segment) {
      queryRelations.push(util.format(
        whereTemplate,
        fieldNameLocal, operator, dbVal.query_segment,
      ));
      queryParams.push(dbVal.parameter);
    } else {
      queryRelations.push(util.format(
        whereTemplate,
        fieldNameLocal, operator, dbVal,
      ));
    }
  };
 
  const buildTokenQueryRelations = (tokenRelationKey, tokenRelationValue) => {
    tokenRelationKey = tokenRelationKey.toLowerCase();
    Eif (_.has(validOperators, tokenRelationKey) && tokenRelationKey !== '$token' && tokenRelationKey !== '$in') {
      operator = validOperators[tokenRelationKey];
    } else {
      throw (buildError('model.find.invalidtokenop', tokenRelationKey));
    }
 
    if (_.isArray(tokenRelationValue)) {
      const tokenKeys = fieldName.split(',');
      for (let tokenIndex = 0; tokenIndex < tokenRelationValue.length; tokenIndex++) {
        tokenKeys[tokenIndex] = tokenKeys[tokenIndex].trim();
        const dbVal = parser.get_db_value_expression(schema, tokenKeys[tokenIndex], tokenRelationValue[tokenIndex]);
        Eif (_.isPlainObject(dbVal) && dbVal.query_segment) {
          tokenRelationValue[tokenIndex] = dbVal.query_segment;
          queryParams.push(dbVal.parameter);
        } else {
          tokenRelationValue[tokenIndex] = dbVal;
        }
      }
      queryRelations.push(util.format(
        whereTemplate,
        tokenKeys.join('","'), operator, tokenRelationValue.toString(),
      ));
    } else {
      buildQueryRelations(fieldName, tokenRelationValue);
    }
  };
 
  if (relationKey === '$token') {
    whereTemplate = 'token("%s") %s token(%s)';
 
    const tokenRelationKeys = Object.keys(relationValue);
    for (let tokenRK = 0; tokenRK < tokenRelationKeys.length; tokenRK++) {
      const tokenRelationKey = tokenRelationKeys[tokenRK];
      const tokenRelationValue = relationValue[tokenRelationKey];
      buildTokenQueryRelations(tokenRelationKey, tokenRelationValue);
    }
  } else if (relationKey === '$contains') {
    const fieldType1 = schemer.get_field_type(schema, fieldName);
    Eif (['map', 'list', 'set', 'frozen'].includes(fieldType1)) {
      if (fieldType1 === 'map' && _.isPlainObject(relationValue)) {
        Object.keys(relationValue).forEach((key) => {
          queryRelations.push(util.format(
            '"%s"[%s] %s %s',
            fieldName, '?', '=', '?',
          ));
          queryParams.push(key);
          queryParams.push(relationValue[key]);
        });
      } else {
        queryRelations.push(util.format(
          whereTemplate,
          fieldName, operator, '?',
        ));
        queryParams.push(relationValue);
      }
    } else {
      throw (buildError('model.find.invalidcontainsop'));
    }
  } else if (relationKey === '$contains_key') {
    const fieldType2 = schemer.get_field_type(schema, fieldName);
    Iif (fieldType2 !== 'map') {
      throw (buildError('model.find.invalidcontainskeyop'));
    }
    queryRelations.push(util.format(
      whereTemplate,
      fieldName, operator, '?',
    ));
    queryParams.push(relationValue);
  } else {
    buildQueryRelations(fieldName, relationValue);
  }
  return { queryRelations, queryParams };
};
 
parser._parse_query_object = function f(schema, queryObject) {
  let queryRelations = [];
  let queryParams = [];
 
  Object.keys(queryObject).forEach((fieldName) => {
    if (fieldName.startsWith('$')) {
      // search queries based on lucene index or solr
      // escape all single quotes for queries in cassandra
      Iif (fieldName === '$expr') {
        if (typeof queryObject[fieldName].index === 'string' && typeof queryObject[fieldName].query === 'string') {
          queryRelations.push(util.format(
            "expr(%s,'%s')",
            queryObject[fieldName].index, queryObject[fieldName].query.replace(/'/g, "''"),
          ));
        } else {
          throw (buildError('model.find.invalidexpr'));
        }
      } else Iif (fieldName === '$solr_query') {
        if (typeof queryObject[fieldName] === 'string') {
          queryRelations.push(util.format(
            "solr_query='%s'",
            queryObject[fieldName].replace(/'/g, "''"),
          ));
        } else {
          throw (buildError('model.find.invalidsolrquery'));
        }
      }
      return;
    }
 
    let whereObject = queryObject[fieldName];
    // Array of operators
    Eif (!_.isArray(whereObject)) whereObject = [whereObject];
 
    for (let fk = 0; fk < whereObject.length; fk++) {
      let fieldRelation = whereObject[fk];
 
      const cqlOperators = {
        $eq: '=',
        $ne: '!=',
        $isnt: 'IS NOT',
        $gt: '>',
        $lt: '<',
        $gte: '>=',
        $lte: '<=',
        $in: 'IN',
        $like: 'LIKE',
        $token: 'token',
        $contains: 'CONTAINS',
        $contains_key: 'CONTAINS KEY',
      };
 
      if (_.isPlainObject(fieldRelation)) {
        const validKeys = Object.keys(cqlOperators);
        const fieldRelationKeys = Object.keys(fieldRelation);
        for (let i = 0; i < fieldRelationKeys.length; i++) {
          if (!validKeys.includes(fieldRelationKeys[i])) {
            // field relation key invalid, apply default $eq operator
            fieldRelation = { $eq: fieldRelation };
            break;
          }
        }
      } else {
        fieldRelation = { $eq: fieldRelation };
      }
 
      const relationKeys = Object.keys(fieldRelation);
      for (let rk = 0; rk < relationKeys.length; rk++) {
        const relationKey = relationKeys[rk];
        const relationValue = fieldRelation[relationKey];
        const extractedRelations = parser.extract_query_relations(
          fieldName,
          relationKey,
          relationValue,
          schema,
          cqlOperators,
        );
        queryRelations = queryRelations.concat(extractedRelations.queryRelations);
        queryParams = queryParams.concat(extractedRelations.queryParams);
      }
    }
  });
 
  return { queryRelations, queryParams };
};
 
parser.get_filter_clause = function f(schema, queryObject, clause) {
  const parsedObject = parser._parse_query_object(schema, queryObject);
  const filterClause = {};
  if (parsedObject.queryRelations.length > 0) {
    filterClause.query = util.format('%s %s', clause, parsedObject.queryRelations.join(' AND '));
  } else {
    filterClause.query = '';
  }
  filterClause.params = parsedObject.queryParams;
  return filterClause;
};
 
parser.get_filter_clause_ddl = function f(schema, queryObject, clause) {
  const filterClause = parser.get_filter_clause(schema, queryObject, clause);
  let filterQuery = filterClause.query;
  filterClause.params.forEach((param) => {
    let queryParam;
    Iif (typeof param === 'string') {
      queryParam = util.format("'%s'", param);
    } else Iif (param instanceof Date) {
      queryParam = util.format("'%s'", param.toISOString());
    } else Iif (param instanceof cql.types.Long
      || param instanceof cql.types.Integer
      || param instanceof cql.types.BigDecimal
      || param instanceof cql.types.TimeUuid
      || param instanceof cql.types.Uuid) {
      queryParam = param.toString();
    } else Iif (param instanceof cql.types.LocalDate
      || param instanceof cql.types.LocalTime
      || param instanceof cql.types.InetAddress) {
      queryParam = util.format("'%s'", param.toString());
    } else {
      queryParam = param;
    }
    // TODO: unhandled if queryParam is a string containing ? character
    // though this is unlikely to have in materialized view filters, but...
    filterQuery = filterQuery.replace('?', queryParam);
  });
  return filterQuery;
};
 
parser.get_where_clause = function f(schema, queryObject) {
  return parser.get_filter_clause(schema, queryObject, 'WHERE');
};
 
parser.get_if_clause = function f(schema, queryObject) {
  return parser.get_filter_clause(schema, queryObject, 'IF');
};
 
parser.get_primary_key_clauses = function f(schema) {
  const partitionKey = schema.key[0];
  let clusteringKey = schema.key.slice(1, schema.key.length);
  const clusteringOrder = [];
 
  for (let field = 0; field < clusteringKey.length; field++) {
    if (schema.clustering_order
        && schema.clustering_order[clusteringKey[field]]
        && schema.clustering_order[clusteringKey[field]].toLowerCase() === 'desc') {
      clusteringOrder.push(util.format('"%s" DESC', clusteringKey[field]));
    } else {
      clusteringOrder.push(util.format('"%s" ASC', clusteringKey[field]));
    }
  }
 
  let clusteringOrderClause = '';
  Eif (clusteringOrder.length > 0) {
    clusteringOrderClause = util.format(' WITH CLUSTERING ORDER BY (%s)', clusteringOrder.toString());
  }
 
  let partitionKeyClause = '';
  Eif (_.isArray(partitionKey)) {
    partitionKeyClause = partitionKey.map((v) => util.format('"%s"', v)).join(',');
  } else {
    partitionKeyClause = util.format('"%s"', partitionKey);
  }
 
  let clusteringKeyClause = '';
  Eif (clusteringKey.length) {
    clusteringKey = clusteringKey.map((v) => util.format('"%s"', v)).join(',');
    clusteringKeyClause = util.format(',%s', clusteringKey);
  }
 
  return { partitionKeyClause, clusteringKeyClause, clusteringOrderClause };
};
 
parser.get_mview_where_clause = function f(schema, viewSchema) {
  const clauses = parser.get_primary_key_clauses(viewSchema);
  let whereClause = clauses.partitionKeyClause.split(',').join(' IS NOT NULL AND ');
  Eif (clauses.clusteringKeyClause) whereClause += clauses.clusteringKeyClause.split(',').join(' IS NOT NULL AND ');
  whereClause += ' IS NOT NULL';
 
  const filters = _.cloneDeep(viewSchema.filters);
 
  if (_.isPlainObject(filters)) {
    // delete primary key fields defined as isn't null in filters
    Object.keys(filters).forEach((filterKey) => {
      if (filters[filterKey].$isnt === null
          && (viewSchema.key.includes(filterKey) || viewSchema.key[0].includes(filterKey))) {
        delete filters[filterKey].$isnt;
      }
    });
 
    const filterClause = parser.get_filter_clause_ddl(schema, filters, 'AND');
    whereClause += util.format(' %s', filterClause).replace(/IS NOT null/g, 'IS NOT NULL');
  }
 
  // remove unnecessarily quoted field names in generated where clause
  // so that it matches the where_clause from database schema
  const quotedFieldNames = whereClause.match(/"(.*?)"/g);
  quotedFieldNames.forEach((fieldName) => {
    const unquotedFieldName = fieldName.replace(/"/g, '');
    const reservedKeywords = [
      'ADD', 'AGGREGATE', 'ALLOW', 'ALTER', 'AND', 'ANY', 'APPLY',
      'ASC', 'AUTHORIZE', 'BATCH', 'BEGIN', 'BY', 'COLUMNFAMILY',
      'CREATE', 'DELETE', 'DESC', 'DROP', 'EACH_QUORUM', 'ENTRIES',
      'FROM', 'FULL', 'GRANT', 'IF', 'IN', 'INDEX', 'INET', 'INFINITY',
      'INSERT', 'INTO', 'KEYSPACE', 'KEYSPACES', 'LIMIT', 'LOCAL_ONE',
      'LOCAL_QUORUM', 'MATERIALIZED', 'MODIFY', 'NAN', 'NORECURSIVE',
      'NOT', 'OF', 'ON', 'ONE', 'ORDER', 'PARTITION', 'PASSWORD', 'PER',
      'PRIMARY', 'QUORUM', 'RENAME', 'REVOKE', 'SCHEMA', 'SELECT', 'SET',
      'TABLE', 'TIME', 'THREE', 'TO', 'TOKEN', 'TRUNCATE', 'TWO', 'UNLOGGED',
      'UPDATE', 'USE', 'USING', 'VIEW', 'WHERE', 'WITH'];
    if (unquotedFieldName === unquotedFieldName.toLowerCase()
      && !reservedKeywords.includes(unquotedFieldName.toUpperCase())) {
      whereClause = whereClause.replace(fieldName, unquotedFieldName);
    }
  });
  return whereClause;
};
 
parser.get_orderby_clause = function f(queryObject) {
  const orderKeys = [];
  Object.keys(queryObject).forEach((k) => {
    const queryItem = queryObject[k];
    if (k.toLowerCase() === '$orderby') {
      Iif (!(queryItem instanceof Object)) {
        throw (buildError('model.find.invalidorder'));
      }
      const orderItemKeys = Object.keys(queryItem);
 
      for (let i = 0; i < orderItemKeys.length; i++) {
        const cqlOrderDirection = { $asc: 'ASC', $desc: 'DESC' };
        Eif (orderItemKeys[i].toLowerCase() in cqlOrderDirection) {
          let orderFields = queryItem[orderItemKeys[i]];
 
          Eif (!_.isArray(orderFields)) {
            orderFields = [orderFields];
          }
 
          for (let j = 0; j < orderFields.length; j++) {
            orderKeys.push(util.format(
              '"%s" %s',
              orderFields[j], cqlOrderDirection[orderItemKeys[i]],
            ));
          }
        } else {
          throw (buildError('model.find.invalidordertype', orderItemKeys[i]));
        }
      }
    }
  });
  return orderKeys.length ? util.format('ORDER BY %s', orderKeys.join(', ')) : ' ';
};
 
parser.get_groupby_clause = function f(queryObject) {
  let groupbyKeys = [];
 
  Object.keys(queryObject).forEach((k) => {
    const queryItem = queryObject[k];
 
    if (k.toLowerCase() === '$groupby') {
      Iif (!(queryItem instanceof Array)) {
        throw (buildError('model.find.invalidgroup'));
      }
 
      groupbyKeys = groupbyKeys.concat(queryItem);
    }
  });
 
  groupbyKeys = groupbyKeys.map((key) => `"${key}"`);
 
  return groupbyKeys.length ? util.format('GROUP BY %s', groupbyKeys.join(', ')) : ' ';
};
 
parser.get_limit_clause = function f(queryObject) {
  let limit = null;
  Object.keys(queryObject).forEach((k) => {
    const queryItem = queryObject[k];
    if (k.toLowerCase() === '$limit') {
      Iif (typeof queryItem !== 'number') throw (buildError('model.find.limittype'));
      limit = queryItem;
    }
  });
  return limit ? util.format('LIMIT %s', limit) : ' ';
};
 
parser.get_select_clause = function f(options) {
  let selectClause = '*';
  if (options.select && _.isArray(options.select) && options.select.length > 0) {
    const selectArray = [];
    for (let i = 0; i < options.select.length; i++) {
      // separate the aggregate function and the column name if select is an aggregate function
      const selection = options.select[i].split(/[(, )]/g).filter((e) => (e));
      if (selection.length === 1) {
        Iif (selection[0] === '*') selectArray.push('*');
        else selectArray.push(util.format('"%s"', selection[0]));
      } else if (selection.length === 2) {
        selectArray.push(util.format('%s("%s")', selection[0], selection[1]));
      } else if (selection.length >= 3 && selection[selection.length - 2].toLowerCase() === 'as') {
        const selectionEndChunk = selection.splice(selection.length - 2);
        let selectionChunk = '';
        if (selection.length === 1) {
          selectionChunk = util.format('"%s"', selection[0]);
        } else if (selection.length === 2) {
          selectionChunk = util.format('%s("%s")', selection[0], selection[1]);
        } else {
          selectionChunk = util.format('%s(%s)', selection[0], `"${selection.splice(1).join('","')}"`);
        }
        selectArray.push(util.format('%s AS "%s"', selectionChunk, selectionEndChunk[1]));
      } else Eif (selection.length >= 3) {
        selectArray.push(util.format('%s(%s)', selection[0], `"${selection.splice(1).join('","')}"`));
      }
    }
    selectClause = selectArray.join(',');
  }
  return selectClause;
};
 
module.exports = parser;