<commit_before>"use strict";
/* jshint node: true */

var _ = require('lodash');
var util = require('util');
var P = require('bluebird');
var moment = require('moment');
var Session = require('./session.js');

const cuMethods = ['insert', 'insertIn', 'update', 'updateIn', 'refresh', 'refreshIn'];

// to build a Model dynamically
module.exports = function(em, entityName, entity) {
  /**
   * @example
   * var user = new User({ nick: 'foo', age: 22 });
   *
   * @param {object} data
   * @constructor
   */
  function Model(data) {
    if (data)
      Model.assign(this, data);
  }

  /**
   * Assign specified properties of source object to target object, and convert value
   * to proper type base on Model defintion.
   *
   * @param {object}  target
   * @param {object}  source
   * @param {bollean} input     indicate source object is user input
   * @param {newErr}  err       customize error
   * @private
   */
  Model.assign = function(target, source, input, err) {
    err = err || em.newModelErr;
    var properties = _.keys(source);
    if (input) properties = _.intersection(properties, entity.inputableNames);
    
    for (var i = 0, j = properties.length; i < j; i++) {
      var name = properties[i];
      var value = source[name];
      var property = entity.properties[name];
      if (property) {
        var type = property.type;
        var invalid = false;

        if (_.isString(value)) {
          switch (type) {
            case 'string':
              if (property.autoTrim !== false) {
                value = _.trim(value);
                if (property.autoTrim === 'length' && property.length > 0 && value.length > property.length)
                  value = value.substring(0, property.length);
              }
              break;
            case 'boolean':
              value = !!value;
              break;
            case 'tinyint':
            case 'smallint':
            case 'int':
            case 'integer':
            case 'smallint':
            case 'bigint':
            case 'decimal':
            case 'numeric':
            case 'float':
            case 'real':
            case 'money':
            case 'single':
            case 'double':
              value *= 1;
              invalid = isNaN(value);
              break;
            case 'date':
            case 'time':
            case 'datetime':
            case 'timestamp':
            case 'timestamptz':
              value = input ? moment(value, property.dateFormat || 'ISO8601') : em.agent.convertDate(value, property);
              invalid = value.isValid() === false;
              break;
            default:
              throw new Error(util.format("Shoo, unknow type %s of %s.%s", type, entityName, name));
          }
          if (invalid)
            throw err('E_TYPE_ERROR', {
              entityName: entityName,
              entity: entity,
              propertyName: name,
              property: property,
              reason: type
            });
        }
      }
      target[name] = value;
    }
    return target;
  };

  /**
   * Validate current instance
   *
   * @param {string}    method    validate purpose: update/insert
   * @param {newErr}    err       customize err instance
   */
  Model.prototype.validate = function(method, err) {
    err = err || em.newModelErr;
    // run validation
    var thisKeys = _.keys(this);
    var shareKeys = _.intersection(thisKeys, entity.propertyNames); 

    if (_.isEmpty(shareKeys)) // make sure this is not a empty object
      return P.reject(err('E_DATA_EMPTY'));

    var validateKeys;
    if (method === 'insert') {
      validateKeys = _.union(entity.requiredNames, shareKeys);
    } else if (method === 'update') {
      validateKeys = _.union(entity.primaryKeyNames, shareKeys);
    } else {
      throw new Error('Validate method can only be "insert" or "update", but got ' + method);
    }

    for (var i = 0, j = validateKeys.length; i < j; i++) {<commit_msg>[feature] add refresh validation to skip primarkey validation<commit_after>"use strict";
/* jshint node: true */

var _ = require('lodash');
var util = require('util');
var P = require('bluebird');
var moment = require('moment');
var Session = require('./session.js');

const cuMethods = ['insert', 'insertIn', 'update', 'updateIn', 'refresh', 'refreshIn'];

// to build a Model dynamically
module.exports = function(em, entityName, entity) {
  /**
   * @example
   * var user = new User({ nick: 'foo', age: 22 });
   *
   * @param {object} data
   * @constructor
   */
  function Model(data) {
    if (data)
      Model.assign(this, data);
  }

  /**
   * Assign specified properties of source object to target object, and convert value
   * to proper type base on Model defintion.
   *
   * @param {object}  target
   * @param {object}  source
   * @param {bollean} input     indicate source object is user input
   * @param {newErr}  err       customize error
   * @private
   */
  Model.assign = function(target, source, input, err) {
    err = err || em.newModelErr;
    var properties = _.keys(source);
    if (input) properties = _.intersection(properties, entity.inputableNames);
    
    for (var i = 0, j = properties.length; i < j; i++) {
      var name = properties[i];
      var value = source[name];
      var property = entity.properties[name];
      if (property) {
        var type = property.type;
        var invalid = false;

        if (_.isString(value)) {
          switch (type) {
            case 'string':
              if (property.autoTrim !== false) {
                value = _.trim(value);
                if (property.autoTrim === 'length' && property.length > 0 && value.length > property.length)
                  value = value.substring(0, property.length);
              }
              break;
            case 'boolean':
              value = !!value;
              break;
            case 'tinyint':
            case 'smallint':
            case 'int':
            case 'integer':
            case 'smallint':
            case 'bigint':
            case 'decimal':
            case 'numeric':
            case 'float':
            case 'real':
            case 'money':
            case 'single':
            case 'double':
              value *= 1;
              invalid = isNaN(value);
              break;
            case 'date':
            case 'time':
            case 'datetime':
            case 'timestamp':
            case 'timestamptz':
              value = input ? moment(value, property.dateFormat || 'ISO8601') : em.agent.convertDate(value, property);
              invalid = value.isValid() === false;
              break;
            default:
              throw new Error(util.format("Shoo, unknow type %s of %s.%s", type, entityName, name));
          }
          if (invalid)
            throw err('E_TYPE_ERROR', {
              entityName: entityName,
              entity: entity,
              propertyName: name,
              property: property,
              reason: type
            });
        }
      }
      target[name] = value;
    }
    return target;
  };

  /**
   * Validate current instance
   *
   * @param {string}    method    validate purpose: update/insert
   * @param {newErr}    err       customize err instance
   */
  Model.prototype.validate = function(method, err) {
    err = err || em.newModelErr;
    // run validation
    var thisKeys = _.keys(this);
    var shareKeys = _.intersection(thisKeys, entity.propertyNames); 

    if (_.isEmpty(shareKeys)) // make sure this is not a empty object
      return P.reject(err('E_DATA_EMPTY'));

    var validateKeys;
    if (method === 'insert') {
      validateKeys = _.union(entity.requiredNames, shareKeys);
    } else if (method === 'update') {
      validateKeys = _.union(entity.primaryKeyNames, shareKeys);

    } else if (method === 'refresh') {
      validateKeys = shareKeys;
    } else {
      throw new Error('Validate method can only be "insert" or "update", but got ' + method);
    }

    for (var i = 0, j = validateKeys.length; i < j; i++) {
{'fraction_non_alphanumeric': 0.1276358223765815, 'fraction_numerical': 0.0027288514016373107, 'mean_word_length': 1.9055855855855857, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3892290', 'n_tokens_mistral': 2257, 'n_tokens_neox': 2218, 'n_words': 665}