查找相关的数据, 更新或者插入
@param {object} source source model
@param {string} model target model
@param {object|array} args 要生成的参数
@param {any} t 事务标志
@return {Promise.<void>}
@this model
513797
async function one2many (source, model, args = [], t) {
  let sourceId = `${this.name}Id`
  let previous = await this.models[model].findAll({
    where: {[sourceId]: source.id},
    transaction: t
  })
  let deletedIds = []
  let currentIds = args.map(i => i.id)

  previous.forEach(i => {
    if (!currentIds.includes(i.id)) {
      deletedIds.push(i.id)
    }
  })
  if (deletedIds.length !== 0) {
    await this.models[model].update({[sourceId]: null}, {
      where: {id: {[Op.in]: deletedIds}},
      transaction: t
    })
  }

  for (let arg of args) {
    if (!arg.hasOwnProperty(sourceId)) {
      arg[sourceId] = source.id
    }
  }

  await util.insertOrUpdate(this.models[model], args, t)
}
103668
private static SqlInfo doBuildSqlInfo(BuildSource source, TagHandler th) {
        try {
            // 使用反射获取该Handler对应的实例，并执行方法
            IConditHandler handler = th.getHandlerCls().newInstance();
            return handler.buildSqlInfo(source);
        } catch (InstantiationException e) {
            log.error("实例化IConditHandler的实现类出错!", e);
        } catch (IllegalAccessException e) {
            log.error("访问Handler的实现类出错!", e);
        }
        return source.getSqlInfo();
    }
24734
async function emitAsync (eventName, ...args) {
  // using a copy to avoid error when listener array changed
  let listeners = this.listeners(eventName)
  for (let i = 0; i < listeners.length; i++) {
    let fn = listeners[i]
    let obj = fn(...args)
    if (!!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function') obj = await obj
    if (obj !== undefined) return obj
  }
}
295153
public EventBus emitSync(String event, Object... args) {
        return _emitWithOnceBus(eventContextSync(event, args));
    }
684116
function async (f, args) {
    new Promise(invoke).then(function asyncFulfill () {
      return f.apply(null, args);
    });
  }
570484
function insert(model) {
      model = this.records.add(model, { merge: true });
      return Promise.resolve(model);
    }
702752
function ArrayEmitter(...args) {

  // Need to generate an actual array here for proper behaviour (in a full ES6 environment we
  // should be able to subclass array. But alas)
  var arr = new Array(...args);

  // Non enumerable so that we can send the array over postMessage
  Object.defineProperty(arr, '$emitter', {
    enumerable: false,
    value: new EventEmitter()
  });

  // Generate our Array Emitter methods
  var ArrayEmitterMethods = {};
  ['on', 'once', 'addListener', 'removeListener'].forEach(function(key) {
    ArrayEmitterMethods[key] = {
      enumerable: false,
      value: function(...args) {
        return this.$emitter[key](...args);
      }
    };
  });

  // These methods create new arrays
  ['reverse', 'sort', 'splice'].forEach(function(key) {
    ArrayEmitterMethods[key] = {
      enumerable: false,
      value: function(...args) {
        var _emitter = this.$emitter;
        incrMaxListeners(_emitter);
        _emitter.on('update', () => {
          ArrayProto[key].apply(this, args);
        });

        ArrayProto[key].apply(this, args);
        return this;
      }
    };
  });

  ['filter', 'map', 'slice'].forEach(function(key) {
    ArrayEmitterMethods[key] = {
      enumerable: false,
      value: function(...args) {
        var newArr = new ArrayEmitter();
        var _emitter = this.$emitter;
        incrMaxListeners(_emitter);
        _emitter.on('update', () => {
          updateNewArr(ArrayProto[key].apply(this, args));
          newArr.$emitter.emit('update', newArr);
        });

        updateNewArr(ArrayProto[key].apply(this, args));

        function updateNewArr(arr) {
          newArr.length = 0;
          for (var i = 0; i < arr.length; i++) {
            newArr.push(arr[i]);
          }
        }

        return newArr;
      }
    };
  });

  ArrayEmitterMethods.concat = {
    enumerable: false,
    value: function(...args) {
      var newArr = new ArrayEmitter();
      var allArrs = [this, ...args];
      var qries = allArrs.filter((obj) => (Array.isArray(obj) && obj.$emitter));
      qries.forEach((_qry) => {
        var _emitter = _qry.$emitter;
        incrMaxListeners(_emitter);
        _emitter.on('update', () => {
          updateConcat();
          newArr.$emitter.emit('update', newArr);
        });
      });

      updateConcat();

      return newArr;

      function updateConcat() {
        var concatted = ArrayProto.concat.call(...allArrs);
        newArr.length = 0;
        newArr.push(...concatted);
      }
    }
  };

  Object.defineProperties(arr, ArrayEmitterMethods);

  return arr;
}
1274558
function() {
    return new Promise((resolve, reject) => {
      let instance;
      if (this.modelElement.name === this.node.getName()) {
        instance = this.node;
      } else {
        instance = this.mapper.getObject(this.modelElement.path());
      }

      if (instance) {
        if (instance.isStarted()) {
          instance.__update__(timesUp('update(...)', 30000, (err) => {
            if (err) {
              this.log.error('Unable to update ' + instance.getPath());
              reject(err);
            } else {
              this.log.debug(instance.getPath());
              this.node.kCore.emitter.emit('instanceUpdated', instance);
              resolve();
            }
          }));
        }
      } else {
        reject(new Error(this.toString() + ' error: unable to update instance ' + this.modelElement.name));
      }
    });
  }
143544
function query(){
		//console.log(arguments[0]);
		var self = this;
		var args = arguments;
		var last_arg = args[args.length - 1];
		var bHasCallback = (typeof last_arg === 'function');
		if (!bHasCallback) // no callback
			last_arg = function(){};

		var count_arguments_without_callback = bHasCallback ? (args.length-1) : args.length;
		var new_args = [];

		for (var i=0; i<count_arguments_without_callback; i++) // except callback
			new_args.push(args[i]);
		if (!bHasCallback && !bCordova)
			return new Promise(function(resolve){
				new_args.push(resolve);
				self.query.apply(self, new_args);
			});
		takeConnectionFromPool(function(connection){
			// add callback that releases the connection before calling the supplied callback
			new_args.push(function(rows){
				connection.release();
				last_arg(rows);
			});
			connection.query.apply(connection, new_args);
		});
	}
737012
function (args) {
    //console.log('PutModel messageContents: json  ' + JSON.stringify(messageContents));
    Model.call(this, args);
    this.modelType = messageContents.modelType;
    this.attributes = [];
    var a, attrib, v;
    for (a in messageContents.attributes) {
      //console.log('PutModel Attribute: json  ' + JSON.stringify(messageContents.attributes[a]));
      if (messageContents.attributes[a].type == 'Model') {
        v = new Attribute.ModelID(createModelFromModelType(messageContents.attributes[a].modelType));
        v.value = messageContents.attributes[a].value.value;
        if (messageContents.attributes[a].value.name)
          v.name = messageContents.attributes[a].value.name;
        attrib = new Attribute({name: messageContents.attributes[a].name, type: 'Model', value: v});
      } else if (messageContents.attributes[a].type == 'Date') {
        attrib = new Attribute(messageContents.attributes[a].name, messageContents.attributes[a].type);
        try {
          attrib.value = messageContents.attributes[a].value === null ? null : new Date(messageContents.attributes[a].value);
        } catch (e) {
          attrib.value = null;
        }
      } else {
        attrib = new Attribute(messageContents.attributes[a].name, messageContents.attributes[a].type);
        if (attrib.name == 'id') { // TODO only If mongo! or refactor mongo to normalize IDs
          if (attrib.value != messageContents.attributes[a].value)
            attrib.value = messageContents.attributes[a].value;
        } else {
          attrib.value = messageContents.attributes[a].value;
        }
      }
      this.attributes.push(attrib);
    }
  }
862379
function(arg, handler) {
		handler = handler ? handler : this.spirit;
		gui.Array.make(arg).forEach(function(type) {
			if (this._addchecks(type, [handler])) {
				if (!this._handlers[type]) {
					this._handlers[type] = [];
				}
				this._handlers[type].push(handler);
			}
		}, this);
		return this.spirit;
	}
544113
public EventBus emitAsync(ActEvent event, Object... args) {
        return _emitWithOnceBus(eventContextAsync(event, args));
    }
826078
function callPromise(fn, args) {
	return new Promise((resolve, reject) => {
		// promisified callback
		function callback(err,other) {
			// check if the 'err' is boolean, if so then this is a 'exists' callback special case
			if (err && (typeof err !== 'boolean')) return reject(err);
			// convert arguments to proper array, ignoring error argument
			let args = Array.prototype.slice.call(arguments, 1);
			// if arguments length is one or more resolve arguments as array,
			// otherwise resolve the argument as is.
			return resolve(args.length < 2 ? args[0] : args);
		}
		fn.apply(null, args.concat([callback]));
	});
}
767041
def create_new_model(model, from_method)
      if model.is_a?(Model)
        if model.buffer?
          fail "The #{from_method} does not take a buffer.  Call .save! on buffer's to persist them."
        end

        # Set the new path and the persistor.
        model.options = @options.merge(parent: self, path: @options[:path] + [:[]])
      else
        model = wrap_values([model]).first
      end


      if model.is_a?(Model)
        promise = model.can_create?.then do |can_create|
          unless can_create
            fail "permissions did not allow create for #{model.inspect}"
          end
        end.then do

          # Add it to the array and trigger any watches or on events.
          reactive_array_append(model)

          @persistor.added(model, @array.size - 1)
        end.then do
          nil.then do
            # Validate and save
            model.run_changed
          end.then do
            # Mark the model as not new
            model.instance_variable_set('@new', false)

            # Mark the model as loaded
            model.change_state_to(:loaded_state, :loaded)

          end.fail do |err|
            # remove from the collection because it failed to save on the server
            # we don't need to call delete on the server.
            index = @array.index(model)
            delete_at(index, true)

            # remove from the id list
            @persistor.try(:remove_tracking_id, model)

            # re-raise, err might not be an Error object, so we use a rejected promise to re-raise
            Promise.new.reject(err)
          end
        end
      else
        promise = nil.then do
          # Add it to the array and trigger any watches or on events.
          reactive_array_append(model)

          @persistor.added(model, @array.size - 1)
        end
      end

      promise = promise.then do
        # resolve the model
        model
      end

      # unwrap the promise if the persistor is synchronus.
      # This will return the value or raise the exception.
      promise = promise.unwrap unless @persistor.async?

      # return
      promise
    end
827293
@SuppressWarnings("unchecked")
	public T create(Object[] args)
	{
		for(int i=0, n=args.length; i<n; i++)
		{
			if(arguments[i] instanceof FactoryDefinition.InjectedArgument)
			{
				args[i] = arguments[i].getValue(null);
			}
		}

		try
		{
			return (T) raw.newInstance(args);
		}
		catch(IllegalArgumentException e)
		{
			throw new SerializationException("Unable to create; " + e.getMessage(), e);
		}
		catch(InstantiationException e)
		{
			throw new SerializationException("Unable to create; " + e.getMessage(), e);
		}
		catch(IllegalAccessException e)
		{
			throw new SerializationException("Unable to create; " + e.getMessage(), e);
		}
		catch(InvocationTargetException e)
		{
			throw new SerializationException("Unable to create; " + e.getCause().getMessage(), e.getCause());
		}
	}
46156
def get_source_handler(self, model, source):
        
        if isinstance(source, Column):
            return source

        # Generate a generic handler for the source
        modelfield = resolve_orm_path(model, source)
        column_class = get_column_for_modelfield(modelfield)
        return column_class()
731084
function processBranch (args, resolve, reject) {
  let condition = args.shift()
  let val = args.shift()
  let las = _.last(args)

  return Promise.resolve(condition)
    .then(c => {
      if (c === true) {
        return Promise.resolve(_.isFunction(val) ? val() : val)
          .then(resolve, reject)
      } else if (args.length === 1) {
        return Promise.resolve(_.isFunction(las) ? las() : las)
          .then(resolve, reject)
      } else {
        return processBranch(args, resolve, reject)
      }
    }, reject)
}