Maps a relationship as a connection property to a given type
@param {*} rel
@param {*} modelName
@param {*} relName
541357
function mapRelation(rel, modelName, relName) {
    let acceptingParams = Object.assign({}, {
        filter: {
            generated: false,
            type: 'JSON'
        }
    }, connectionArgs);
    types[modelName].meta.fields[relName] = {
        generated: true,
        meta: {
            relation: true,
            connection: true,
            relationType: rel.type,
            isMany: isManyRelation(rel.type),
            embed: rel.embed,
            type: rel.modelTo.modelName,
            args: acceptingParams,
        },
        resolve: (obj, args, context, info) => {

            const ctxOptions = { accessToken: context.req.accessToken }
            const modelId = args && args.id;

            const method = rel.modelTo.sharedClass.findMethodByName('find');
            // TODO: ...
            return new Promise((resolve, reject) => { resolve(true) }).then(() => {
                let params = {};

                _.forEach(acceptingParams, (param, name) => {
                    if (typeof args[name] !== 'undefined' && Object.keys(args[name]).length > 0) {
                        _.merge(params, _.cloneDeep(args[name]));
                    }
                });

                if (isManyRelation(rel.type) === true) {
                    return connectionFromPromisedArray(findRelatedMany(rel, obj, params, context), args, rel.modelTo);
                } else {
                    return findRelatedOne(rel, obj, params, context);
                }

                // let wrap = promisify(model[method.name](...params, ctxOptions));

                // if (typeObj.list) {
                //     return connectionFromPromisedArray(wrap, args, model);
                // } else {
                //     return wrap;
                // }


            }).catch((err) => {
                throw err;
            });
        }
    };
}
728159
function(modelName)
	{
		modelName = modelName || '*';
		if(this._bindingIndex !== null && this.scope.hasOwnProperty(modelName)) return this._bindingIndex;
		if(this.parentView instanceof View) return this.parentView.getBindingIndex(modelName);
		return null;
	}
166515
function (connectionName, collectionName, obj, cb) {
        if (_.isObject(obj)) {
            try {
                var modelInstance = new this._model(obj);
                return cb(null, modelInstance);
            }
            catch (err) {
                return cb(err, null);
            }
        }
    }
1000324
def add_rel(self, source_node_id, target_node_id, rel):
        

        # Add the relationship
        n1_ref = self.graph_db.get_indexed_node('Node', 'node_id', source_node_id)
        n2_ref = self.graph_db.get_indexed_node('Node', 'node_id', target_node_id)

        # Sanity check
        if not n1_ref or not n2_ref:
            print 'Cannot add relationship between unfound nodes: %s --> %s' % (source_node_id, target_node_id)
            return
        path = neo4j.Path(n1_ref, rel, n2_ref)
        path.get_or_create(self.graph_db)
1144419
function getModel (app, name, Model) {
  const mongooseClient = app.get('mongoose');
  assert(mongooseClient, 'mongoose client not set by app');
  const modelNames = mongooseClient.modelNames();
  if (modelNames.includes(name)) {
    return mongooseClient.model(name);
  } else {
    assert(Model && typeof Model === 'function', 'Model function not privided.');
    return Model(app, name);
  }
}
597096
function Model(collectionName, attributes, values) {
    this.collectionName = collectionName;
    this.idAttribute = Model.getId(attributes);
    this.attributes = attributeValidator.validate(attributes);
    this.values = { };
    this.virtuals = { };

    // initially add the null value from all attributes
    for (var key in this.attributes) {
        this.values[key] = undefined;
    }

    // prevents from modifying values and adding properties
    Object.freeze(this.attributes);

    // prevents from adding new properties
    Object.seal(this.values);

    // sets the initial values
    this.set(values);
}
801871
function buildWhereRelation (name, value) {
    // require valid relation
    assert.ok(typeof value === 'object', 'invalid relation '+typeof value)
    // get relation
    var relation = this.model.relation(value.name)
    // build relation query
    return defined(relation.via)
        ? this.buildWhereRelationVia(name, value, relation)
        : this.buildWhereRelationDirect(name, value, relation)
}
1046618
function Link (rel, value) {
    if (!(this instanceof Link)) {
      return new Link(rel, value);
    }

    if (!rel) throw new Error('Required <link> attribute "rel"');

    this.rel = rel;

    if (typeof value === 'object') {

      // If value is a hashmap, just copy properties
      if (!value.href) throw new Error('Required <link> attribute "href"');
      var expectedAttributes = ['rel', 'href', 'name', 'hreflang', 'title', 'templated', 'icon', 'align', 'method'];
      for (var attr in value) {
        if (value.hasOwnProperty(attr)) {
          if (!~expectedAttributes.indexOf(attr)) {
            // Unexpected attribute: ignore it
            continue;
          }
          this[attr] = value[attr];
        }
      }

    } else {

      // value is a scalar: use its value as href
      if (!value) throw new Error('Required <link> attribute "href"');
      this.href = String(value);

    }
  }
5056
function ModelType(name, prefix, endp) {
  this.name = name;
  this.prefix = prefix;
  this.endp = endp;
}
573280
public OrdinalSet getConnectionSet(String connectionModel, String nodeType, int ordinal, String propertyName) {
    	int connectionModelIndex = modelHolder.getModelIndex(connectionModel);
        return getConnectionSet(connectionModelIndex, nodeType, ordinal, propertyName);
    }
706464
function hasOneRemoting (relationName, relation, define) {
  var pathName = (relation.options.http && relation.options.http.path) ||
    relationName
  var toModelName = relation.modelTo.modelName

  define('__get__' + relationName, {
    isStatic: false,
    accessType: 'READ',
    description: 'Fetches hasOne relation ' + relationName + '.',
    http: {
      verb: 'get',
      path: '/' + pathName
    },
    accepts: {
      arg: 'refresh',
      type: 'boolean',
      http: {
        source: 'query'
      }
    },
    returns: {
      arg: relationName,
      type: relation.modelTo.modelName,
      root: true
    }
  })

  var findHasOneRelationshipsFunc = function (cb) {
    this['__get__' + pathName](cb)
  }

  define(
    '__findRelationships__' + relationName,
    {
      isStatic: false,
      accessType: 'READ',
      description: 'Find relations for ' + relationName + '.',
      http: {
        verb: 'get',
        path: '/relationships/' + pathName
      },
      returns: {
        arg: 'result',
        type: toModelName,
        root: true
      }
    },
    findHasOneRelationshipsFunc
  )
}
1207925
function prepOne(modelName, definition)
	{
		definition = _.clone(definition);

		// inherit options from defineOptions (except fields and through-related options)
		var fields = definition.fields = _.clone(definition.fields || {}),
			options = definition.options = _.clone(definition.options || {});

		utils.defaultsNoUndef(options, defineOptions);
		['fields', 'associateThrough', 'skipFieldsOnThrough', 'camelThrough'].forEach(function(fieldName) {
			delete options[fieldName];
		});

		if (options.primaryKeyType) {
			options.primaryKeyAttributes.type = options.primaryKeyType;
			delete options.primaryKeyType;
		}

		options.primaryKeyAttributes = _.defaults({
			primaryKey: true,
			_autoGenerated: true
		}, options.primaryKeyAttributes, defineOptions.primaryKeyAttributes, {
			allowNull: false
		});

		if ([Sequelize.INTEGER.key, Sequelize.BIGINT.key].indexOf(options.primaryKeyAttributes.type.key) != -1) options.primaryKeyAttributes.autoIncrement = true;
		if (options.primaryKeyAttributes.type.key == Sequelize.UUID.key && !options.primaryKeyAttributes.defaultValue) options.primaryKeyAttributes.defaultValue = Sequelize.UUIDV4;

		// add additional fields
		if (defineOptions.fields && !options.skipFields) {
			_.forIn(defineOptions.fields, function(field, fieldName) {
				if (fields[fieldName] !== undefined) return;
				field = utils.functionValue(field, modelName, definition, definitions);
				if (field instanceof Sequelize.ABSTRACT) field = {type: field};
				fields[fieldName] = _.clone(field);
			});
		}

		// delete empty fields and set field type where shorthand definition used
		_.forIn(fields, function(field, fieldName) {
			if (!field) {
				delete fields[fieldName];
			} else if (!_.isPlainObject(field)) {
				fields[fieldName] = {type: field};
			}
		});

		// find primary key
		var key;
		_.forIn(fields, function(field, fieldName) {
			if (field.primaryKey) {
				key = fieldName;
				return false;
			}
		});

		// if no primary key, create primary key column
		if (!key) {
			if (!options.primaryKey) throw new Sequelize.DefinerError("Model '" + modelName + "' has no primary key defined");

			key = utils.functionValue(options.primaryKey, modelName, definition, definitions);

			if (options.primaryKeyFirst) {
				utils.unshift(fields, key, options.primaryKeyAttributes);
			} else {
				fields[key] = options.primaryKeyAttributes;
			}
		}

		definition.primaryKey = key;
		primaryKeys[modelName + Utils.uppercaseFirst(key)] = primaryKeys[modelName + '_' + key] = {model: modelName, field: key};

		// get table name
		utils.defaultNoUndef(options, 'tableName', options.freezeTableName ? modelName : patches.underscoredIf(Utils.pluralize(modelName), options.underscoredAll));

		// return definition
		return definition;
	}
205332
function Model (attrs) {
        // console.log('Model#init', attrs)

        // cache the attrs so we can check
        // for dirty values on upate...
        this._props = {};

        // should we eager load a relationship?
        this._eager = {};

        // placeholder for errors...
        this._errors = {};

        // which values need to be written.
        this._dirty = {};

        // array of extra properties
        // we want to serialize as JSON
        this._externals = [];

        this._cftimestamp = {};

        this.initialize(attrs);

        // default all hasMany properties...
        for (var p in this._hasMany){
            this[p] = [];
        }

        return this;
    }
566037
function( relation ) {
			var exists = _.any( this._reverseRelations, function( rel ) {
				return _.all( relation, function( val, key ) {
					return val === rel[ key ];
				});
			});
			
			if ( !exists && relation.model && relation.type ) {
				this._reverseRelations.push( relation );
				
				if ( !relation.model.prototype.relations ) {
					relation.model.prototype.relations = [];
				}
				relation.model.prototype.relations.push( relation );
				
				this.retroFitRelation( relation );
			}
		}
397880
function (schema, models, modelsToIgnore, modelPropertyMacro) {
    // Resolve the schema (Handle nested schemas)
    schema = resolveSchema(schema);

    if(typeof modelPropertyMacro !== 'function') {
      modelPropertyMacro = function(prop){
        return (prop || {}).default;
      };
    }

    modelsToIgnore= modelsToIgnore || {};

    var type = schema.type || 'object';
    var format = schema.format;
    var model;
    var output;

    if (!_.isUndefined(schema.example)) {
      output = schema.example;
    } else if (_.isUndefined(schema.items) && _.isArray(schema.enum)) {
      output = schema.enum[0];
    }

    if (_.isUndefined(output)) {
      if (schema.$ref) {
        model = models[simpleRef(schema.$ref)];

        if (!_.isUndefined(model)) {
          if (_.isUndefined(modelsToIgnore[model.name])) {
            modelsToIgnore[model.name] = model;
            output = schemaToJSON(model.definition, models, modelsToIgnore, modelPropertyMacro);
            delete modelsToIgnore[model.name];
          } else {
            if (model.type === 'array') {
              output = [];
            } else {
              output = {};
            }
          }
        }
      } else if (!_.isUndefined(schema.default)) {
        output = schema.default;
      } else if (type === 'string') {
        if (format === 'date-time') {
          output = new Date().toISOString();
        } else if (format === 'date') {
          output = new Date().toISOString().split('T')[0];
        } else {
          output = 'string';
        }
      } else if (type === 'integer') {
        output = 0;
      } else if (type === 'number') {
        output = 0.0;
      } else if (type === 'boolean') {
        output = true;
      } else if (type === 'object') {
        output = {};

        _.forEach(schema.properties, function (property, name) {
          var cProperty = _.cloneDeep(property);

          // Allow macro to set the default value
          cProperty.default = modelPropertyMacro(property);

          output[name] = schemaToJSON(cProperty, models, modelsToIgnore, modelPropertyMacro);
        });
      } else if (type === 'array') {
        output = [];

        if (_.isArray(schema.items)) {
          _.forEach(schema.items, function (item) {
            output.push(schemaToJSON(item, models, modelsToIgnore, modelPropertyMacro));
          });
        } else if (_.isPlainObject(schema.items)) {
          output.push(schemaToJSON(schema.items, models, modelsToIgnore, modelPropertyMacro));
        } else if (_.isUndefined(schema.items)) {
          output.push({});
        } else {
          console.log('Array type\'s \'items\' property is not an array or an object, cannot process');
        }
      }
    }

    return output;
  }
878436
def _get_rel_of_type(self, reltype):
        
        matching = [rel for rel in self.values() if rel.reltype == reltype]
        if len(matching) == 0:
            tmpl = "no relationship of type '%s' in collection"
            raise KeyError(tmpl % reltype)
        if len(matching) > 1:
            tmpl = "multiple relationships of type '%s' in collection"
            raise ValueError(tmpl % reltype)
        return matching[0]
382771
function Model(schema, config = {}) {
  let relationshipMap = {};
  let jsonSchema = schema.jsonSchema.withoutRefs;

  const {
    tableName,
    timestamps = false,
    validateOnInit = false,
    idColumn: idColumnInput,
    deletedAtColumn = null,
    createdAtColumn,
    updatedAtColumn,
    modelName,
    autoRestEnabled
  } = config;

  Object.keys(schema._formatted).forEach((key) => {
    if ([Types.Models, Types.Model].includes(schema._formatted[key].type)) {
      relationshipMap[key] = schema._formatted[key];
    }
  });

  const ajv = new AJV({
    allErrors: true,
    coerceTypes: true
  });

  /**
   * @prop {knex.Knex} knex A context specific knex instance
   * 
   * @class ModelInstance
   */
  return class extends Strategy {
    /**
     * Creates an instance of ModelInstance.
     * @param {object} props 
     * @memberof ModelInstance
     */
    constructor(props) {
      super();

      let validate = ajv.compile(jsonSchema);
      let result = validate(props);

      if (!result && validateOnInit) {
        throw validate.errors;
      }

      this._setProps(props);

      // default to not-persisted
      this._persisted = false;
      this._fetching = false;
      this._relationships = {};
    }

    static formatRelationship({
      relatedModel,
      foreignField,
      localField,
      type,
      through,
      throughLocalField,
      throughForeignField
    }, attr) {
      if (!relatedModel) {
        let formattedRelatedAttr = attr[0].toUpperCase() + attr.slice(1);
        relatedModel = inflect.singular(formattedRelatedAttr);
      }

      if (is(String)(relatedModel)) relatedModel = this.registry[relatedModel];

      const many = type === Types.Models;
      
      localField = localField || (many ? this.idColumn : this.guessColumnName(relatedModel.tableName, relatedModel.idColumn));

      foreignField = foreignField || (many ? this.guessColumnName(this.tableName, this.idColumn) : relatedModel.idColumn);

      if (through) {
        if (!is(String)(through)) through = this.guessTableName(this.tableName, relatedModel.tableName, true);
 
        throughLocalField = throughLocalField || this.guessColumnName(this.tableName, this.idColumn);
        throughForeignField = throughForeignField || this.guessColumnName(relatedModel.tableName, relatedModel.idColumn);
      }

      return {
        relatedModel,
        foreignField,
        localField,
        type,
        through,
        throughLocalField,
        throughForeignField,
        many
      };
    }

    static get tableName() {
      return tableName || inflect.plural(this.modelName);
    }

    get tableName() {
      return this.constructor.tableName;
    }

    static get relationshipMap() {
      return relationshipMap;
    }

    static get schema() {
      return schema;
    }

    static get autoRestEnabled() {
      return autoRestEnabled;
    }

    static get toSwagger() {
      return schema.jsonSchema.withRefs;
    }

    static get modelName() {
      return modelName || this.name;
    }

    static get idColumn() {
      return idColumnInput || this.guessIdColumn();
    }

    get idColumn() {
      return this.constructor.idColumn;
    }

    static get _softDelete() {
      return isString(deletedAtColumn);
    }
    /**
     * @param {object} registry
     * 
     * @private
     * @static
     * @memberof ModelInstance
     */
    static attachToRegistry(registry) {
      registry[this.modelName] = this;
      this.registry = registry;
    }

    /**
     * Returns a query with configuration parameters applied
     * 
     * @static
     * @returns Knex.Knex
     * @memberof ModelInstance
     */
    static getQuery() {
      let query = this.knex(this.tableName);
      if (this._softDelete) {
        query.whereNull(deletedAtColumn);
      }
      return query;
    }

    static create(props) {
      let newInstance = new this(props);
      return newInstance.save();
    }

    static async find(queryInput, {fields = '*', withRelated = []} = {}) {
      let query = this.getQuery().select(fields);
      
      if (isFunction(queryInput)) {
        queryInput(query);
      } else if (isObject(queryInput)) {
        query.where(queryInput);
      }

      let foundRows = (await query).map(row => {
        row = new this(row);
        row._persisted = true;
        return row;
      });

      for (let i = 0; i < withRelated.length; i++) {
        await this._handleWithRelated(foundRows, withRelated[i]);
      }

      return foundRows;
    }

    static async _handleWithRelated(instances, withRelated) {
      let relatedTree = withRelated.split('.').filter(val => val);

      if (instances.length > 0) {
        let [relatedAttr] = relatedTree;

        if (!relationshipMap[relatedAttr]) throw new ReferenceError('No such attribute ' + relatedAttr);
        
        let relDef = Object.assign({ instances }, this.formatRelationship(relationshipMap[relatedAttr], relatedAttr));

        let { relatedModel } = relDef;

        let results;

        if (!instances[0]._relationships[relatedAttr]) {
          results = await this._pullRelated(relDef, true);
          instances.forEach(instance => instance._relationships[relatedAttr] = results);
        } else {
          results = instances[0]._relationships[relatedAttr];
        }
        let relatedRelDef;

        Object.keys(relatedModel.relationshipMap).forEach(relName => {
          let currentRelDef = relatedModel.formatRelationship(relatedModel.relationshipMap[relName], relName);
          if (currentRelDef.foreignField === relDef.localField ||
            (
              currentRelDef.through && relDef.through &&
              currentRelDef.through === relDef.through &&
              currentRelDef.throughForeignField === relDef.throughLocalField &&
              currentRelDef.throughLocalField === relDef.throughForeignField
            )
            ) {
            relatedRelDef = Object.assign({ relName }, currentRelDef);
          }
        });

        instances.forEach(instance => {
          instance[relatedAttr] = results.map[instance[relDef.localField]];
          if (!instance[relatedAttr] && (relDef.type === Types.Models)) {
            instance[relatedAttr] = [];
          }
          if (relatedRelDef) {
            results.array.forEach(result => {
              if (!relatedRelDef.through && (result[relatedRelDef.localField] === instance[relDef.localField])) {
                if (relatedRelDef.type === Types.Models) {
                  (result[relatedRelDef.relName] = result[relatedRelDef.relName] || []).push(instance);
                  result;
                } else {
                  result[relatedRelDef.relName] = instance;
                }
              }
            });
          }
        });
        if (relatedTree.length > 1) {
          await relatedModel._handleWithRelated(results.array, relatedTree.slice(1).join('.'));
        }
      } else {
        return instances;
      }
    }

    static async findById(id, {fields = '*', withRelated = []} = {}) {
      let [props] = await this.getQuery().where(this.idColumn, id).select(fields);
      if (props) {
        let foundRecord = new this(props);
        for (let i = 0; i < withRelated.length; i++) {
          await this._handleWithRelated([foundRecord], withRelated[i]);
        }
        foundRecord._persisted = true;
        return foundRecord;
      } else {
        return null;
      }
    }

    static update(query, updates) {
      let updateQuery = this.getQuery();
      if (isFunction(query)) {
        query(updateQuery);
      } else {
        updateQuery.where(query);
      }

      return updateQuery.update(updates, '*');
    }

    static async restore(id) {
      if (!this._softDelete) {
        throw new ReferenceError(this.modelName + ' does not support soft deletes');
      }
      await this.knex(this.tableName)
        .where(this.idColumn, id)
        .update(deletedAtColumn, null);
    }

    static async remove(queryInput) {
      let results = await this.find(queryInput);
      return Promise.all(results.map(async result => result.destroy()));
    }

    get changes() {
      return clone(this._changes);
    }

    get knex() {
      return this.constructor.knex;
    }

    get query() {
      return this.constructor.getQuery();
    }

    async save(options = defaultSaveOptions) {

      if (options.validate && !this.validate()) {
        throw this.errors;
      }

      if (timestamps) {
        if (!this._persisted) {
          this._props[createdAtColumn || this.constructor.guessColumnName('created', 'at')] = new Date();
        }

        this._props[updatedAtColumn || this.constructor.guessColumnName('updated', 'at')] = new Date();
      }

      if (this._persisted) {
        await this.knex(this.tableName)
          .where(this.idColumn, this[this.idColumn])
          .update(this._changes);

      } else {
        let results = await this.knex(this.tableName).insert(this._props).returning('id');
        this._props[this.idColumn] = results[0];
        this._persisted = true;
      }
      this._setProps(this._props);
      return this;
    }

    reset() {
      this._setProps(this._original);
    }

    destroy() {
      let deleteQuery = this.query
        .where(this.idColumn, this[this.idColumn]);
      if (this.constructor._softDelete) {
        return deleteQuery.update(deletedAtColumn, new Date);
      } else {
        return deleteQuery.del();
      }
    }

    _setProps(props) {
      this._original = clone(props);
      this._props = props;
      this._changes = {};

      for (let key in props) {
        this.__defineGetter__(key, () => this._props[key]);
        this.__defineSetter__(key, (value) => {
          this._props[key] = value;

          this._changes[key] = value;
        });
      }
    }

    toJSON(ignoredRecord) {
      let relMap = Object.keys(relationshipMap).reduce((map, relName) => {
        if (this[relName] && (this[relName] !== ignoredRecord)) {
          map[relName] = is(Array)(this[relName]) ?
            this[relName].filter(rec => rec !== ignoredRecord).map(rec => rec.toJSON(this)) :
            this[relName].toJSON(this);
        }
        return map;
      }, {});
      return Object.assign(relMap, this._props);
    }

    validate() {
      let valid = ajv.validate(jsonSchema, this);
      this.errors = ajv.errors;
      return valid;
    }

    async pullRelated(key) {
      let relDef = relationshipMap[key.tableName || key];
      if (relDef) {
        relDef = this.constructor.formatRelationship(relDef, key);
        return this[key] = (await this.constructor._pullRelated(Object.assign({ instances: this }, relDef))).array;
      } else {
        throw new ReferenceError('No such relationship: ' + key);
      }
    }

    static async _pullRelated(relDef) {
      const {
        relatedModel,
        foreignField,
        localField,
        through,
        throughLocalField,
        throughForeignField,
        many
      } = this.formatRelationship(relDef);
      const { instances } = relDef;
      let relatedValue = is(Array)(instances) ? pluck(localField)(instances) : [instances[localField]];

      let relatedQuery;

      switch (relatedValue.length) {
      case 1:
        relatedQuery = query => {
          query.where(foreignField, relatedValue[0]);
          return query;
        };
        break;
      default:
        relatedQuery = query => {
          query.whereIn(foreignField, relatedValue);
          return query;
        };
      }

      if (through) {
        relatedQuery = query => {
          query.join(through, `${relatedModel.tableName}.${relatedModel.idColumn}`, `${through}.${throughForeignField}`);

          query.whereIn(`${throughLocalField}`, relatedValue);

          return query;
        };
      }

      let results = await relatedModel.find(relatedQuery, {}, true);

      let map = {};
      results.forEach(result => {
        const mapKey = through ? result[throughLocalField] : result[foreignField];
        if (many) {
          (map[mapKey] = map[mapKey] || []).push(result);
        } else {
          map[mapKey] = result;
        }
      });
      return {map, array: results};
    }
  };
}