All files / src/orm base_model.js

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 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 11541x 1x 1x   1x 1x   1x   1x     1x   1x 1x 1x 1x   1x 1x 1x 1x   1x 63x 63x 63x 63x 63x   63x 40977x 23291x   40977x     63x 40365x     63x 63x   63x 1058x 1058x   1058x 1058x         1058x 1058x   1058x 25x     1058x 28x     1058x           1058x 1058x 1x       63x 1058x 1058x   1058x 960x       63x 25x 25x 25x       1x         1x 9x 9x   9x       9x   9x 9x 9x 9x     1x 9x 9x 9x 9x   9x     9x 1x       9x     9x 9x         9x                                                                           9x                   9x 9x   9x 9x 9x         9x   9x 9x                                                 1x 9x   9x 1x 1x 1x   1x 1x 1x       1x   1x   8x     1x 9x   9x 1x 1x   1x 1x 1x       1x   1x   8x     1x 102x 10x 10x     102x       102x   102x 102x     102x 102x                       1x 64x 64x 64x 64x 64x   64x             64x 64x 64x 64x 64x   64x   64x     1x 3x     1x 1x     1x 106x     1x                   9x 9x 9x         9x 9x         9x 9x         9x 9x           2x 2x 2x       2x       1x 2x     2x     1x 27x     27x     1x 103x     1x 1337x     1x 2x     2x 2x 2x                       2x 2x           2x     2x       2x         2x   2x 2x   2x   2x 2x 2x 2x 2x   2x   2x       2x       1x 2x     2x 2x 2x                       1x 2x 1x 1x 1x 1x     2x     2x       2x         2x   2x 2x   2x   2x   2x 4x 4x 6x 6x 2x 2x 2x 2x 2x       4x   2x       2x       1x 27x 27x 27x       27x       1x 21x 21x       21x       1x 4x 4x 4x 4x       4x 12x   4x 4x       4x     1x 3x 3x 3x         3x       3x     1x 1x 1x 1x         1x 1x   1x 1x       1x     1x 4x 4x 4x           4x       4x     1x 2x 1x 1x   2x 2x 2x             2x 1x   2x 2x           2x     1x 4x 4x 4x         4x       4x     1x 1x 1x 1x         1x 1x   1x 1x       1x     1x 2x 2x 2x           2x       2x     1x 6x 6x 6x 6x         6x 6x       6x     1x 1x 1x   1x       1x 1x       1x       64x 64x 24x 24x   64x       64x         64x       64x   64x   64x 64x 64x 64x 64x           64x 4x     60x   60x 60x       60x 44x 44x 44x 44x 44x 44x   44x   16x 23x 23x   16x       60x     1x 20x 16x 16x   20x       20x   20x 20x       20x 19x 19x   1x       54x 18x 12x 12x     18x   18x       18x   18x         18x             18x   17x 17x 17x 3x 3x   17x   17x 17x 17x 17x 17x           17x   17x 1x 1x 1x 1x   16x 1x     17x   17x 1x       1x     1x     1x     16x   16x 16x 16x       16x       16x               16x     1x 7x 1x 1x     7x   7x       7x   7x         7x   7x 7x 7x 7x 7x 7x           7x   7x 3x       3x     3x     3x     4x   4x 4x 4x       4x       4x               4x     1x 10x 10x   10x 10x     1x       1x 1x     1x       1x 69x 69x   69x 34x 4x   30x   35x     1x 33x 33x 33x     100095x 20019x 13x 13x     20019x 20019x   20019x       20019x   20019x                   20019x   20019x   20016x             20016x   20016x 20016x 1x 1x     20016x   20016x 20004x       20004x     20004x     20004x     12x   12x 12x 12x       12x 11x   12x       12x               12x     1x 5x 3x 3x     5x 5x   5x 10x 10x 4x 4x     6x       5x     8x 8x 8x   8x 24x     8x     1x 15x 10x   5x     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('./apollo_error.js');
const schemer = require('../validators/schema');
const normalizer = require('../utils/normalizer');
const parser = require('../utils/parser');
 
const TableBuilder = require('../builders/table');
const ElassandraBuilder = require('../builders/elassandra');
const JanusGraphBuilder = require('../builders/janusgraph');
const Driver = require('../helpers/driver');
 
const BaseModel = function f(instanceValues) {
  instanceValues = instanceValues || {};
  const fieldValues = {};
  const fields = this.constructor._properties.schema.fields;
  const methods = this.constructor._properties.schema.methods || {};
  const model = this;
 
  const defaultSetter = function f1(propName, newValue) {
    if (this[propName] !== newValue) {
      model._modified[propName] = true;
    }
    this[propName] = newValue;
  };
 
  const defaultGetter = function f1(propName) {
    return this[propName];
  };
 
  this._modified = {};
  this._validators = {};
 
  for (let fieldsKeys = Object.keys(fields), i = 0, len = fieldsKeys.length; i < len; i++) {
    const propertyName = fieldsKeys[i];
    const field = fields[fieldsKeys[i]];
 
    try {
      this._validators[propertyName] = schemer.get_validators(this.constructor._properties.schema, propertyName);
    } catch (e) {
      throw (buildError('model.validator.invalidschema', e.message));
    }
 
    let setter = defaultSetter.bind(fieldValues, propertyName);
    let getter = defaultGetter.bind(fieldValues, propertyName);
 
    if (field.virtual && typeof field.virtual.set === 'function') {
      setter = field.virtual.set.bind(fieldValues);
    }
 
    if (field.virtual && typeof field.virtual.get === 'function') {
      getter = field.virtual.get.bind(fieldValues);
    }
 
    const descriptor = {
      enumerable: true,
      set: setter,
      get: getter,
    };
 
    Object.defineProperty(this, propertyName, descriptor);
    if (field.virtual && typeof instanceValues[propertyName] !== 'undefined') {
      this[propertyName] = instanceValues[propertyName];
    }
  }
 
  for (let fieldsKeys = Object.keys(fields), i = 0, len = fieldsKeys.length; i < len; i++) {
    const propertyName = fieldsKeys[i];
    const field = fields[fieldsKeys[i]];
 
    if (!field.virtual && typeof instanceValues[propertyName] !== 'undefined') {
      this[propertyName] = instanceValues[propertyName];
    }
  }
 
  for (let methodNames = Object.keys(methods), i = 0, len = methodNames.length; i < len; i++) {
    const methodName = methodNames[i];
    const method = methods[methodName];
    this[methodName] = method;
  }
};
 
BaseModel._properties = {
  name: null,
  schema: null,
};
 
BaseModel._set_properties = function f(properties) {
  const schema = properties.schema;
  const tableName = schema.table_name || properties.name;
 
  Iif (!schemer.validate_table_name(tableName)) {
    throw (buildError('model.tablecreation.invalidname', tableName));
  }
 
  const qualifiedTableName = util.format('"%s"."%s"', properties.keyspace, tableName);
 
  this._properties = properties;
  this._properties.table_name = tableName;
  this._properties.qualified_table_name = qualifiedTableName;
  this._driver = new Driver(this._properties);
};
 
BaseModel._sync_model_definition = function f(callback) {
  const properties = this._properties;
  const tableName = properties.table_name;
  const modelSchema = properties.schema;
  let migration = properties.migration;
 
  const tableBuilder = new TableBuilder(this._driver, this._properties);
 
  // backwards compatible change, dropTableOnSchemaChange will work like migration: 'drop'
  if (!migration) {
    Eif (properties.dropTableOnSchemaChange) migration = 'drop';
    else migration = 'safe';
  }
  // always safe migrate if NODE_ENV==='production'
  Iif (process.env.NODE_ENV === 'production') migration = 'safe';
 
  // check for existence of table on DB and if it matches this model's schema
  tableBuilder.get_table_schema((err, dbSchema) => {
    Iif (err) {
      callback(err);
      return;
    }
 
    const afterDBCreate = (err1) => {
      if (err1) {
        callback(err1);
        return;
      }
 
      const indexingTasks = [];
 
      // cassandra index create if defined
      if (_.isArray(modelSchema.indexes)) {
        tableBuilder.createIndexesAsync = Promise.promisify(tableBuilder.create_indexes);
        indexingTasks.push(tableBuilder.createIndexesAsync(modelSchema.indexes));
      }
      // cassandra custom index create if defined
      if (_.isArray(modelSchema.custom_indexes)) {
        tableBuilder.createCustomIndexesAsync = Promise.promisify(tableBuilder.create_custom_indexes);
        indexingTasks.push(tableBuilder.createCustomIndexesAsync(modelSchema.custom_indexes));
      }
      if (modelSchema.custom_index) {
        tableBuilder.createCustomIndexAsync = Promise.promisify(tableBuilder.create_custom_indexes);
        indexingTasks.push(tableBuilder.createCustomIndexAsync([modelSchema.custom_index]));
      }
      // materialized view create if defined
      if (modelSchema.materialized_views) {
        tableBuilder.createViewsAsync = Promise.promisify(tableBuilder.create_mviews);
        indexingTasks.push(tableBuilder.createViewsAsync(modelSchema.materialized_views));
      }
 
      Promise.all(indexingTasks)
        .then(() => {
          // db schema was updated, so callback with true
          callback(null, true);
        })
        .catch((err2) => {
          callback(err2);
        });
    };
 
    Iif (!dbSchema) {
      if (properties.createTable === false) {
        callback(buildError('model.tablecreation.schemanotfound', tableName));
        return;
      }
      // if not existing, it's created
      tableBuilder.create_table(modelSchema, afterDBCreate);
      return;
    }
 
    let normalizedModelSchema;
    let normalizedDBSchema;
 
    try {
      normalizedModelSchema = normalizer.normalize_model_schema(modelSchema);
      normalizedDBSchema = normalizer.normalize_model_schema(dbSchema);
    } catch (e) {
      throw (buildError('model.validator.invalidschema', e.message));
    }
 
    Eif (_.isEqual(normalizedModelSchema, normalizedDBSchema)) {
      // no change in db was made, so callback with false
      callback(null, false);
      return;
    }
 
    if (migration === 'alter') {
      // check if table can be altered to match schema
      if (_.isEqual(normalizedModelSchema.key, normalizedDBSchema.key) &&
          _.isEqual(normalizedModelSchema.clustering_order, normalizedDBSchema.clustering_order)) {
        tableBuilder.init_alter_operations(modelSchema, dbSchema, normalizedModelSchema, normalizedDBSchema, (err1) => {
          if (err1 && err1.message === 'alter_impossible') {
            tableBuilder.drop_recreate_table(modelSchema, normalizedDBSchema.materialized_views, afterDBCreate);
            return;
          }
          callback(err1);
        });
      } else {
        tableBuilder.drop_recreate_table(modelSchema, normalizedDBSchema.materialized_views, afterDBCreate);
      }
    } else if (migration === 'drop') {
      tableBuilder.drop_recreate_table(modelSchema, normalizedDBSchema.materialized_views, afterDBCreate);
    } else {
      callback(buildError('model.tablecreation.schemamismatch', tableName, 'migration suspended, please apply the change manually'));
    }
  });
};
 
BaseModel._sync_es_index = function f(callback) {
  const properties = this._properties;
 
  if (properties.esclient && properties.schema.es_index_mapping) {
    const keyspaceName = properties.keyspace;
    const mappingName = properties.table_name;
    const indexName = `${keyspaceName}_${mappingName}`;
 
    const elassandraBuilder = new ElassandraBuilder(properties.esclient);
    elassandraBuilder.assert_index(keyspaceName, indexName, (err) => {
      Iif (err) {
        callback(err);
        return;
      }
      elassandraBuilder.put_mapping(indexName, mappingName, properties.schema.es_index_mapping, callback);
    });
    return;
  }
  callback();
};
 
BaseModel._sync_graph = function f(callback) {
  const properties = this._properties;
 
  if (properties.gremlin_client && properties.schema.graph_mapping) {
    const graphName = `${properties.keyspace}_graph`;
    const mappingName = properties.table_name;
 
    const graphBuilder = new JanusGraphBuilder(properties.gremlin_client);
    graphBuilder.assert_graph(graphName, (err) => {
      Iif (err) {
        callback(err);
        return;
      }
      graphBuilder.put_mapping(graphName, mappingName, properties.schema.graph_mapping, callback);
    });
    return;
  }
  callback();
};
 
BaseModel._execute_table_query = function f(query, params, options, callback) {
  if (arguments.length === 3) {
    callback = options;
    options = {};
  }
 
  const defaults = {
    prepare: true,
  };
 
  options = _.defaultsDeep({}, options, defaults);
 
  const doExecuteQuery = function f1(doquery, docallback) {
    this.execute_query(doquery, params, options, docallback);
  }.bind(this, query);
 
  Eif (this.is_table_ready()) {
    doExecuteQuery(callback);
  } else {
    this.init((err) => {
      if (err) {
        callback(err);
        return;
      }
      doExecuteQuery(callback);
    });
  }
};
 
BaseModel.get_find_query = function f(queryObject, options) {
  const orderbyClause = parser.get_orderby_clause(queryObject);
  const limitClause = parser.get_limit_clause(queryObject);
  const whereClause = parser.get_where_clause(this._properties.schema, queryObject);
  const selectClause = parser.get_select_clause(options);
  const groupbyClause = parser.get_groupby_clause(options);
 
  let query = util.format(
    'SELECT %s%s FROM "%s"',
    (options.distinct ? 'DISTINCT ' : ''),
    selectClause,
    options.materialized_view ? options.materialized_view : this._properties.table_name,
  );
 
  if (whereClause.query) query += util.format(' %s', whereClause.query);
  if (orderbyClause) query += util.format(' %s', orderbyClause);
  if (groupbyClause) query += util.format(' %s', groupbyClause);
  if (limitClause) query += util.format(' %s', limitClause);
  Iif (options.allow_filtering) query += ' ALLOW FILTERING';
 
  query += ';';
 
  return { query, params: whereClause.params };
};
 
BaseModel.get_table_name = function f() {
  return this._properties.table_name;
};
 
BaseModel.get_keyspace_name = function f() {
  return this._properties.keyspace;
};
 
BaseModel.is_table_ready = function f() {
  return this._ready === true;
};
 
BaseModel.init = function f(options, callback) {
  if (!callback) {
    callback = options;
    options = undefined;
  }
 
  this._ready = true;
  callback();
};
 
BaseModel.syncDB = function f(callback) {
  this._sync_model_definition((err, result) => {
    Iif (err) {
      callback(err);
      return;
    }
 
    this._sync_es_index((err1) => {
      Iif (err1) {
        callback(err1);
        return;
      }
 
      this._sync_graph((err2) => {
        Iif (err2) {
          callback(err2);
          return;
        }
 
        this._ready = true;
        callback(null, result);
      });
    });
  });
};
 
BaseModel.get_cql_client = function f(callback) {
  this._driver.ensure_init((err) => {
    Iif (err) {
      callback(err);
      return;
    }
    callback(null, this._properties.cql);
  });
};
 
BaseModel.get_es_client = function f() {
  Iif (!this._properties.esclient) {
    throw (new Error('To use elassandra features, set `manageESIndex` to true in ormOptions'));
  }
  return this._properties.esclient;
};
 
BaseModel.get_gremlin_client = function f() {
  Iif (!this._properties.gremlin_client) {
    throw (new Error('To use janus graph features, set `manageGraphs` to true in ormOptions'));
  }
  return this._properties.gremlin_client;
};
 
BaseModel.execute_query = function f(...args) {
  this._driver.execute_query(...args);
};
 
BaseModel.execute_batch = function f(...args) {
  this._driver.execute_batch(...args);
};
 
BaseModel.execute_eachRow = function f(...args) {
  this._driver.execute_eachRow(...args);
};
 
BaseModel._execute_table_eachRow = function f(query, params, options, onReadable, callback) {
  Eif (this.is_table_ready()) {
    this.execute_eachRow(query, params, options, onReadable, callback);
  } else {
    this.init((err) => {
      if (err) {
        callback(err);
        return;
      }
      this.execute_eachRow(query, params, options, onReadable, callback);
    });
  }
};
 
BaseModel.eachRow = function f(queryObject, options, onReadable, callback) {
  Iif (arguments.length === 3) {
    const cb = onReadable;
    onReadable = options;
    callback = cb;
    options = {};
  }
  Iif (typeof onReadable !== 'function') {
    throw (buildError('model.find.eachrowerror', 'no valid onReadable function was provided'));
  }
  Iif (typeof callback !== 'function') {
    throw (buildError('model.find.cberror'));
  }
 
  const defaults = {
    raw: false,
    prepare: true,
  };
 
  options = _.defaultsDeep({}, options, defaults);
 
  options.return_query = true;
  const selectQuery = this.find(queryObject, options);
 
  const queryOptions = normalizer.normalize_query_option(options);
 
  this._execute_table_eachRow(selectQuery.query, selectQuery.params, queryOptions, (n, row) => {
    Eif (!options.raw) {
      const ModelConstructor = this._properties.get_constructor();
      row = new ModelConstructor(row);
      row._modified = {};
    }
    onReadable(n, row);
  }, (err, result) => {
    Iif (err) {
      callback(buildError('model.find.dberror', err));
      return;
    }
    callback(err, result);
  });
};
 
BaseModel.execute_stream = function f(...args) {
  this._driver.execute_stream(...args);
};
 
BaseModel._execute_table_stream = function f(query, params, options, onReadable, callback) {
  Eif (this.is_table_ready()) {
    this.execute_stream(query, params, options, onReadable, callback);
  } else {
    this.init((err) => {
      if (err) {
        callback(err);
        return;
      }
      this.execute_stream(query, params, options, onReadable, callback);
    });
  }
};
 
BaseModel.stream = function f(queryObject, options, onReadable, callback) {
  if (arguments.length === 3) {
    const cb = onReadable;
    onReadable = options;
    callback = cb;
    options = {};
  }
 
  Iif (typeof onReadable !== 'function') {
    throw (buildError('model.find.streamerror', 'no valid onReadable function was provided'));
  }
  Iif (typeof callback !== 'function') {
    throw (buildError('model.find.cberror'));
  }
 
  const defaults = {
    raw: false,
    prepare: true,
  };
 
  options = _.defaultsDeep({}, options, defaults);
 
  options.return_query = true;
  const selectQuery = this.find(queryObject, options);
 
  const queryOptions = normalizer.normalize_query_option(options);
 
  const self = this;
 
  this._execute_table_stream(selectQuery.query, selectQuery.params, queryOptions, function f1() {
    const reader = this;
    reader.readRow = () => {
      const row = reader.read();
      if (!row) return row;
      Eif (!options.raw) {
        const ModelConstructor = self._properties.get_constructor();
        const o = new ModelConstructor(row);
        o._modified = {};
        return o;
      }
      return row;
    };
    onReadable(reader);
  }, (err) => {
    Iif (err) {
      callback(buildError('model.find.dberror', err));
      return;
    }
    callback();
  });
};
 
BaseModel._execute_gremlin_query = function f(script, bindings, callback) {
  const gremlinClient = this.get_gremlin_client();
  gremlinClient.execute(script, bindings, (err, results) => {
    Iif (err) {
      callback(err);
      return;
    }
    callback(null, results);
  });
};
 
BaseModel._execute_gremlin_script = function f(script, bindings, callback) {
  this._execute_gremlin_query(script, bindings, (err, results) => {
    Iif (err) {
      callback(err);
      return;
    }
    callback(null, results[0]);
  });
};
 
BaseModel.createVertex = function f(vertexProperties, callback) {
  const properties = this._properties;
  const __graphName = `${properties.keyspace}_graph`;
  const __vertexLabel = properties.table_name;
  let script = `
    graph = ConfiguredGraphFactory.open(__graphName);
    vertex = graph.addVertex(__vertexLabel);
  `;
  Object.keys(vertexProperties).forEach((property) => {
    script += `vertex.property('${property}', ${property});`;
  });
  script += 'vertex';
  const bindings = _.defaults({}, vertexProperties, {
    __graphName,
    __vertexLabel,
  });
  this._execute_gremlin_script(script, bindings, callback);
};
 
BaseModel.getVertex = function f(__vertexId, callback) {
  const properties = this._properties;
  const __graphName = `${properties.keyspace}_graph`;
  const script = `
    graph = ConfiguredGraphFactory.open(__graphName);
    g = graph.traversal();
    vertex = g.V(__vertexId);
  `;
  const bindings = {
    __graphName,
    __vertexId,
  };
  this._execute_gremlin_script(script, bindings, callback);
};
 
BaseModel.updateVertex = function f(__vertexId, vertexProperties, callback) {
  const properties = this._properties;
  const __graphName = `${properties.keyspace}_graph`;
  let script = `
    graph = ConfiguredGraphFactory.open(__graphName);
    g = graph.traversal();
    vertex = g.V(__vertexId);
  `;
  Object.keys(vertexProperties).forEach((property) => {
    script += `vertex.property('${property}', ${property});`;
  });
  script += 'vertex';
  const bindings = _.defaults({}, vertexProperties, {
    __graphName,
    __vertexId,
  });
  this._execute_gremlin_script(script, bindings, callback);
};
 
BaseModel.deleteVertex = function f(__vertexId, callback) {
  const properties = this._properties;
  const __graphName = `${properties.keyspace}_graph`;
  const script = `
    graph = ConfiguredGraphFactory.open(__graphName);
    g = graph.traversal();
    vertex = g.V(__vertexId);
    vertex.drop();
  `;
  const bindings = {
    __graphName,
    __vertexId,
  };
  this._execute_gremlin_script(script, bindings, callback);
};
 
BaseModel.createEdge = function f(__edgeLabel, __fromVertexId, __toVertexId, edgeProperties, callback) {
  if (arguments.length === 4 && typeof edgeProperties === 'function') {
    callback = edgeProperties;
    edgeProperties = {};
  }
  const properties = this._properties;
  const __graphName = `${properties.keyspace}_graph`;
  let script = `
    graph = ConfiguredGraphFactory.open(__graphName);
    g = graph.traversal();
    fromVertex = g.V(__fromVertexId).next();
    toVertex = g.V(__toVertexId).next();
    edge = fromVertex.addEdge(__edgeLabel, toVertex);
  `;
  Object.keys(edgeProperties).forEach((property) => {
    script += `edge.property('${property}', ${property});`;
  });
  script += 'edge';
  const bindings = _.defaults({}, edgeProperties, {
    __graphName,
    __fromVertexId,
    __toVertexId,
    __edgeLabel,
  });
  this._execute_gremlin_script(script, bindings, callback);
};
 
BaseModel.getEdge = function f(__edgeId, callback) {
  const properties = this._properties;
  const __graphName = `${properties.keyspace}_graph`;
  const script = `
    graph = ConfiguredGraphFactory.open(__graphName);
    g = graph.traversal();
    edge = g.E(__edgeId);
  `;
  const bindings = {
    __graphName,
    __edgeId,
  };
  this._execute_gremlin_script(script, bindings, callback);
};
 
BaseModel.updateEdge = function f(__edgeId, edgeProperties, callback) {
  const properties = this._properties;
  const __graphName = `${properties.keyspace}_graph`;
  let script = `
    graph = ConfiguredGraphFactory.open(__graphName);
    g = graph.traversal();
    edge = g.E(__edgeId);
  `;
  Object.keys(edgeProperties).forEach((property) => {
    script += `edge.property('${property}', ${property});`;
  });
  script += 'edge';
  const bindings = _.defaults({}, edgeProperties, {
    __graphName,
    __edgeId,
  });
  this._execute_gremlin_script(script, bindings, callback);
};
 
BaseModel.deleteEdge = function f(__edgeId, callback) {
  const properties = this._properties;
  const __graphName = `${properties.keyspace}_graph`;
  const script = `
    graph = ConfiguredGraphFactory.open(__graphName);
    g = graph.traversal();
    edge = g.E(__edgeId);
    edge.drop();
  `;
  const bindings = {
    __graphName,
    __edgeId,
  };
  this._execute_gremlin_script(script, bindings, callback);
};
 
BaseModel.graphQuery = function f(query, params, callback) {
  const properties = this._properties;
  const __graphName = `${properties.keyspace}_graph`;
  const __vertexLabel = properties.table_name;
  let script = `
    graph = ConfiguredGraphFactory.open(__graphName);
    g = graph.traversal();
    vertices = g.V().hasLabel(__vertexLabel);
  `;
  script += query;
  const bindings = _.defaults({}, params, {
    __graphName,
    __vertexLabel,
  });
  this._execute_gremlin_query(script, bindings, callback);
};
 
BaseModel.search = function f(queryObject, callback) {
  const esClient = this.get_es_client();
  const indexName = `${this._properties.keyspace}_${this._properties.table_name}`;
 
  const query = _.defaults({}, queryObject, {
    index: indexName,
    type: this._properties.table_name,
  });
  esClient.search(query, (err, response) => {
    Iif (err) {
      callback(err);
      return;
    }
    callback(null, response);
  });
};
 
BaseModel.find = function f(queryObject, options, callback) {
  if (arguments.length === 2 && typeof options === 'function') {
    callback = options;
    options = {};
  }
  Iif (typeof callback !== 'function' && !options.return_query) {
    throw (buildError('model.find.cberror'));
  }
 
  const defaults = {
    raw: false,
    prepare: true,
  };
 
  options = _.defaultsDeep({}, options, defaults);
 
  // set raw true if select is used,
  // because casting to model instances may lead to problems
  if (options.select) options.raw = true;
 
  let queryParams = [];
 
  let query;
  try {
    const findQuery = this.get_find_query(queryObject, options);
    query = findQuery.query;
    queryParams = queryParams.concat(findQuery.params);
  } catch (e) {
    parser.callback_or_throw(e, callback);
    return {};
  }
 
  if (options.return_query) {
    return { query, params: queryParams };
  }
 
  const queryOptions = normalizer.normalize_query_option(options);
 
  this._execute_table_query(query, queryParams, queryOptions, (err, results) => {
    Iif (err) {
      callback(buildError('model.find.dberror', err));
      return;
    }
    if (!options.raw) {
      const ModelConstructor = this._properties.get_constructor();
      results = results.rows.map((res) => {
        delete (res.columns);
        const o = new ModelConstructor(res);
        o._modified = {};
        return o;
      });
      callback(null, results);
    } else {
      results = results.rows.map((res) => {
        delete (res.columns);
        return res;
      });
      callback(null, results);
    }
  });
 
  return {};
};
 
BaseModel.findOne = function f(queryObject, options, callback) {
  if (arguments.length === 2 && typeof options === 'function') {
    callback = options;
    options = {};
  }
  Iif (typeof callback !== 'function' && !options.return_query) {
    throw (buildError('model.find.cberror'));
  }
 
  queryObject.$limit = 1;
 
  return this.find(queryObject, options, (err, results) => {
    Iif (err) {
      callback(err);
      return;
    }
    if (results.length > 0) {
      callback(null, results[0]);
      return;
    }
    callback();
  });
};
 
BaseModel.update = function f(queryObject, updateValues, options, callback) {
  if (arguments.length === 3 && typeof options === 'function') {
    callback = options;
    options = {};
  }
 
  const schema = this._properties.schema;
 
  const defaults = {
    prepare: true,
  };
 
  options = _.defaultsDeep({}, options, defaults);
 
  Iif (typeof schema.before_update === 'function' && schema.before_update(queryObject, updateValues, options) === false) {
    parser.callback_or_throw(buildError('model.update.before.error'), callback);
    return {};
  }
 
  const { updateClauses, queryParams, errorHappened } = parser.get_update_value_expression(
    this,
    schema,
    updateValues,
    callback,
  );
 
  if (errorHappened) return {};
 
  let query = 'UPDATE "%s"';
  let finalParams = queryParams;
  if (_.isNumber(options.ttl)) {
    query += ' USING TTL ?';
    finalParams = [options.ttl].concat(finalParams);
  }
  query += ' SET %s %s';
 
  let where = '';
  try {
    const whereClause = parser.get_where_clause(schema, queryObject);
    where = whereClause.query;
    finalParams = finalParams.concat(whereClause.params);
  } catch (e) {
    parser.callback_or_throw(e, callback);
    return {};
  }
 
  query = util.format(query, this._properties.table_name, updateClauses.join(', '), where);
 
  if (options.conditions) {
    const ifClause = parser.get_if_clause(schema, options.conditions);
    Eif (ifClause.query) {
      query += util.format(' %s', ifClause.query);
      finalParams = finalParams.concat(ifClause.params);
    }
  } else if (options.if_exists) {
    query += ' IF EXISTS';
  }
 
  query += ';';
 
  if (options.return_query) {
    const returnObj = {
      query,
      params: finalParams,
      after_hook: () => {
        Iif (typeof schema.after_update === 'function' && schema.after_update(queryObject, updateValues, options) === false) {
          return buildError('model.update.after.error');
        }
        return true;
      },
    };
    return returnObj;
  }
 
  const queryOptions = normalizer.normalize_query_option(options);
 
  this._execute_table_query(query, finalParams, queryOptions, (err, results) => {
    Eif (typeof callback === 'function') {
      Iif (err) {
        callback(buildError('model.update.dberror', err));
        return;
      }
      Iif (typeof schema.after_update === 'function' && schema.after_update(queryObject, updateValues, options) === false) {
        callback(buildError('model.update.after.error'));
        return;
      }
      callback(null, results);
    } else if (err) {
      throw (buildError('model.update.dberror', err));
    } else if (typeof schema.after_update === 'function' && schema.after_update(queryObject, updateValues, options) === false) {
      throw (buildError('model.update.after.error'));
    }
  });
 
  return {};
};
 
BaseModel.delete = function f(queryObject, options, callback) {
  if (arguments.length === 2 && typeof options === 'function') {
    callback = options;
    options = {};
  }
 
  const schema = this._properties.schema;
 
  const defaults = {
    prepare: true,
  };
 
  options = _.defaultsDeep({}, options, defaults);
 
  Iif (typeof schema.before_delete === 'function' && schema.before_delete(queryObject, options) === false) {
    parser.callback_or_throw(buildError('model.delete.before.error'), callback);
    return {};
  }
 
  let queryParams = [];
 
  let query = 'DELETE FROM "%s" %s;';
  let where = '';
  try {
    const whereClause = parser.get_where_clause(schema, queryObject);
    where = whereClause.query;
    queryParams = queryParams.concat(whereClause.params);
  } catch (e) {
    parser.callback_or_throw(e, callback);
    return {};
  }
 
  query = util.format(query, this._properties.table_name, where);
 
  if (options.return_query) {
    const returnObj = {
      query,
      params: queryParams,
      after_hook: () => {
        Iif (typeof schema.after_delete === 'function' && schema.after_delete(queryObject, options) === false) {
          return buildError('model.delete.after.error');
        }
        return true;
      },
    };
    return returnObj;
  }
 
  const queryOptions = normalizer.normalize_query_option(options);
 
  this._execute_table_query(query, queryParams, queryOptions, (err, results) => {
    Eif (typeof callback === 'function') {
      Iif (err) {
        callback(buildError('model.delete.dberror', err));
        return;
      }
      Iif (typeof schema.after_delete === 'function' && schema.after_delete(queryObject, options) === false) {
        callback(buildError('model.delete.after.error'));
        return;
      }
      callback(null, results);
    } else if (err) {
      throw (buildError('model.delete.dberror', err));
    } else if (typeof schema.after_delete === 'function' && schema.after_delete(queryObject, options) === false) {
      throw (buildError('model.delete.after.error'));
    }
  });
 
  return {};
};
 
BaseModel.truncate = function f(callback) {
  const properties = this._properties;
  const tableName = properties.table_name;
 
  const query = util.format('TRUNCATE TABLE "%s";', tableName);
  this._execute_table_query(query, [], callback);
};
 
BaseModel.prototype.get_data_types = function f() {
  return cql.types;
};
 
BaseModel.prototype.get_table_name = function f() {
  return this.constructor.get_table_name();
};
 
BaseModel.prototype.get_keyspace_name = function f() {
  return this.constructor.get_keyspace_name();
};
 
BaseModel.prototype._get_default_value = function f(fieldname) {
  const properties = this.constructor._properties;
  const schema = properties.schema;
 
  if (_.isPlainObject(schema.fields[fieldname]) && schema.fields[fieldname].default !== undefined) {
    if (typeof schema.fields[fieldname].default === 'function') {
      return schema.fields[fieldname].default.call(this);
    }
    return schema.fields[fieldname].default;
  }
  return undefined;
};
 
BaseModel.prototype.validate = function f(propertyName, value) {
  value = value || this[propertyName];
  this._validators = this._validators || {};
  return schemer.get_validation_message(this._validators[propertyName] || [], value);
};
 
BaseModel.prototype.save = function fn(options, callback) {
  if (arguments.length === 1 && typeof options === 'function') {
    callback = options;
    options = {};
  }
 
  const properties = this.constructor._properties;
  const schema = properties.schema;
 
  const defaults = {
    prepare: true,
  };
 
  options = _.defaultsDeep({}, options, defaults);
 
  Iif (typeof schema.before_save === 'function' && schema.before_save(this, options) === false) {
    parser.callback_or_throw(buildError('model.save.before.error'), callback);
    return {};
  }
 
  const {
    identifiers,
    values,
    queryParams,
    errorHappened,
  } = parser.get_save_value_expression(this, schema, callback);
 
  if (errorHappened) return {};
 
  let query = util.format(
    'INSERT INTO "%s" ( %s ) VALUES ( %s )',
    properties.table_name,
    identifiers.join(' , '),
    values.join(' , '),
  );
 
  if (options.if_not_exist) query += ' IF NOT EXISTS';
 
  let finalParams = queryParams;
  if (_.isNumber(options.ttl)) {
    query += ' USING TTL ?';
    finalParams = finalParams.concat([options.ttl]);
  }
 
  query += ';';
 
  if (options.return_query) {
    const returnObj = {
      query,
      params: finalParams,
      after_hook: () => {
        Iif (typeof schema.after_save === 'function' && schema.after_save(this, options) === false) {
          return buildError('model.save.after.error');
        }
        return true;
      },
    };
    return returnObj;
  }
 
  const queryOptions = normalizer.normalize_query_option(options);
 
  this.constructor._execute_table_query(query, finalParams, queryOptions, (err, result) => {
    Eif (typeof callback === 'function') {
      Iif (err) {
        callback(buildError('model.save.dberror', err));
        return;
      }
      if (!options.if_not_exist || (result.rows && result.rows[0] && result.rows[0]['[applied]'])) {
        this._modified = {};
      }
      Iif (typeof schema.after_save === 'function' && schema.after_save(this, options) === false) {
        callback(buildError('model.save.after.error'));
        return;
      }
      callback(null, result);
    } else if (err) {
      throw (buildError('model.save.dberror', err));
    } else if (typeof schema.after_save === 'function' && schema.after_save(this, options) === false) {
      throw (buildError('model.save.after.error'));
    }
  });
 
  return {};
};
 
BaseModel.prototype.delete = function f(options, callback) {
  if (arguments.length === 1 && typeof options === 'function') {
    callback = options;
    options = {};
  }
 
  const schema = this.constructor._properties.schema;
  const deleteQuery = {};
 
  for (let i = 0; i < schema.key.length; i++) {
    const fieldKey = schema.key[i];
    if (_.isArray(fieldKey)) {
      for (let j = 0; j < fieldKey.length; j++) {
        deleteQuery[fieldKey[j]] = this[fieldKey[j]];
      }
    } else {
      deleteQuery[fieldKey] = this[fieldKey];
    }
  }
 
  return this.constructor.delete(deleteQuery, options, callback);
};
 
BaseModel.prototype.toJSON = function toJSON() {
  const object = {};
  const schema = this.constructor._properties.schema;
 
  Object.keys(schema.fields).forEach((field) => {
    object[field] = this[field];
  });
 
  return object;
};
 
BaseModel.prototype.isModified = function isModified(propName) {
  if (propName) {
    return Object.prototype.hasOwnProperty.call(this._modified, propName);
  }
  return Object.keys(this._modified).length !== 0;
};
 
module.exports = BaseModel;