Show the entity and it's fields and relationships in console
198991
function logFieldsAndRelationships() {
    const context = this.context;
    if (context.fields.length > 0 || context.relationships.length > 0) {
        this.log(chalk.red(chalk.white('\n================= ') + context.entityNameCapitalized + chalk.white(' =================')));
    }
    if (context.fields.length > 0) {
        this.log(chalk.white('Fields'));
        context.fields.forEach(field => {
            const validationDetails = [];
            const fieldValidate = _.isArray(field.fieldValidateRules) && field.fieldValidateRules.length >= 1;
            if (fieldValidate === true) {
                if (field.fieldValidateRules.includes('required')) {
                    validationDetails.push('required');
                }
                if (field.fieldValidateRules.includes('unique')) {
                    validationDetails.push('unique');
                }
                if (field.fieldValidateRules.includes('minlength')) {
                    validationDetails.push(`minlength='${field.fieldValidateRulesMinlength}'`);
                }
                if (field.fieldValidateRules.includes('maxlength')) {
                    validationDetails.push(`maxlength='${field.fieldValidateRulesMaxlength}'`);
                }
                if (field.fieldValidateRules.includes('pattern')) {
                    validationDetails.push(`pattern='${field.fieldValidateRulesPattern}'`);
                }
                if (field.fieldValidateRules.includes('min')) {
                    validationDetails.push(`min='${field.fieldValidateRulesMin}'`);
                }
                if (field.fieldValidateRules.includes('max')) {
                    validationDetails.push(`max='${field.fieldValidateRulesMax}'`);
                }
                if (field.fieldValidateRules.includes('minbytes')) {
                    validationDetails.push(`minbytes='${field.fieldValidateRulesMinbytes}'`);
                }
                if (field.fieldValidateRules.includes('maxbytes')) {
                    validationDetails.push(`maxbytes='${field.fieldValidateRulesMaxbytes}'`);
                }
            }
            this.log(
                chalk.red(field.fieldName) +
                    chalk.white(` (${field.fieldType}${field.fieldTypeBlobContent ? ` ${field.fieldTypeBlobContent}` : ''}) `) +
                    chalk.cyan(validationDetails.join(' '))
            );
        });
        this.log();
    }
    if (context.relationships.length > 0) {
        this.log(chalk.white('Relationships'));
        context.relationships.forEach(relationship => {
            const validationDetails = [];
            if (relationship.relationshipValidateRules && relationship.relationshipValidateRules.includes('required')) {
                validationDetails.push('required');
            }
            this.log(
                `${chalk.red(relationship.relationshipName)} ${chalk.white(`(${_.upperFirst(relationship.otherEntityName)})`)} ${chalk.cyan(
                    relationship.relationshipType
                )} ${chalk.cyan(validationDetails.join(' '))}`
            );
        });
        this.log();
    }
}
168156
function findMany(repository, options) {
    const entityColumns = repository.metadata.columns.map((columnMetadata) => columnMetadata.propertyName);
    const entityManyToOneRelationColumns = repository
        .metadata
        .relations
        .filter((relationMetadata) => relationMetadata.relationType === 'many-to-one' || relationMetadata.relationType === 'one-to-one')
        .map((relationMetadata) => relationMetadata.propertyName);
    return function (source, args, context, info) {
        return __awaiter(this, void 0, void 0, function* () {
            const selectedColumns = Object.keys(graphqlFields(info));
            const selectQueryBuilder = repository.createQueryBuilder(repository.metadata.name.toLowerCase());
            /** Select **/
            const selectFactory = new select_factory_1.SelectFactory(selectQueryBuilder);
            selectFactory
                .select(selectedColumns.filter((select) => entityColumns.includes(select)));
            /** Where **/
            const whereFactory = new where_factory_1.WhereFactory(selectQueryBuilder, entityManyToOneRelationColumns);
            whereFactory
                .where(lodash_1.get(args, 'filter', {}));
            /** Joins **/
            const joinsFactory = new joins_factory_1.JoinsFactory(selectQueryBuilder);
            joinsFactory
                .join(selectedColumns
                .filter((select) => entityManyToOneRelationColumns.includes(select))
                .reduce((selectedRelationColumns, selectedRelationColumn) => {
                selectedRelationColumns[selectQueryBuilder.alias] = selectedRelationColumn;
                return selectedRelationColumns;
            }, {}))
                .join(whereFactory.selectedManyToOneOrOneToOneRelationColumns);
            /** Pagination **/
            const paginateFactory = new paginate_factory_1.PaginateFactory(selectQueryBuilder);
            paginateFactory
                .paginate(lodash_1.get(args, 'pagination', {}));
            /** Order by **/
            const orderFactory = new order_factory_1.OrderFactory(selectQueryBuilder);
            orderFactory
                .order(lodash_1.get(args, 'orderBy', []));
            /** Extend **/
            if (lodash_1.get(options, 'extend')) {
                yield options.extend(selectQueryBuilder);
            }
            /** Execute get many method **/
            return yield selectQueryBuilder.getMany();
        });
    };
}
563198
def _create_relational_field(self, attr, options):
        """"""
        options['entity_class'] = attr.py_type
        options['allow_empty'] = not attr.is_required
        return EntityField, options
473674
def get_field_info(wrapper,entity_type):
    ''
    fields = wrapper.new('GetFieldInfo')
    fields.psObjectType = entity_type
    return wrapper.GetFieldInfo(fields)
1259843
def _render_full_resource(self, instance, include, fields):
        
        api_type = instance.__jsonapi_type__
        orm_desc_keys = instance.__mapper__.all_orm_descriptors.keys()
        to_ret = {
            'id': instance.id,
            'type': api_type,
            'attributes': {},
            'relationships': {},
            'included': {}
        }
        attrs_to_ignore = {'__mapper__', 'id'}
        if api_type in fields.keys():
            local_fields = list(map((
                lambda x: instance.__jsonapi_map_to_py__[x]),
                fields[api_type]))
        else:
            local_fields = orm_desc_keys

        for key, relationship in instance.__mapper__.relationships.items():
            attrs_to_ignore |= set([c.name for c in relationship.local_columns
                                    ]) | {key}

            api_key = instance.__jsonapi_map_to_api__[key]

            try:
                desc = get_rel_desc(instance, key, RelationshipActions.GET)
            except PermissionDeniedError:
                continue

            if relationship.direction == MANYTOONE:
                if key in local_fields:
                    to_ret['relationships'][api_key] = {
                        'links': self._lazy_relationship(api_type, instance.id,
                                                         api_key)
                    }

                if api_key in include.keys():
                    related = desc(instance)
                    if related is not None:
                        perm = get_permission_test(
                            related, None, Permissions.VIEW)
                    if (key in local_fields
                            and (related is None or not perm(related))):
                        to_ret['relationships'][api_key]['data'] = None
                        continue
                    if key in local_fields:
                        to_ret['relationships'][api_key]['data'] = self._render_short_instance(related)  # NOQA
                    new_include = self._parse_include(include[api_key])
                    built = self._render_full_resource(
                        related, new_include, fields)
                    included = built.pop('included')
                    to_ret['included'].update(included)
                    to_ret['included'][(related.__jsonapi_type__, related.id)] = built  # NOQA

            else:

                if key in local_fields:
                    to_ret['relationships'][api_key] = {
                        'links': self._lazy_relationship(
                            api_type, instance.id, api_key),
                    }

                if api_key not in include.keys():
                    continue

                if key in local_fields:
                    to_ret['relationships'][api_key]['data'] = []

                related = desc(instance)

                for item in related:
                    try:
                        check_permission(item, None, Permissions.VIEW)
                    except PermissionDeniedError:
                        continue

                    if key in local_fields:
                        to_ret['relationships'][api_key]['data'].append(
                            self._render_short_instance(item))

                    new_include = self._parse_include(include[api_key])
                    built = self._render_full_resource(item, new_include,
                                                       fields)
                    included = built.pop('included')
                    to_ret['included'].update(included)
                    to_ret['included'][(item.__jsonapi_type__, item.id)] = built  # NOQA

        for key in set(orm_desc_keys) - attrs_to_ignore:
            try:
                desc = get_attr_desc(instance, key, AttributeActions.GET)
                if key in local_fields:
                    to_ret['attributes'][instance.__jsonapi_map_to_api__[key]] = desc(instance)  # NOQA
            except PermissionDeniedError:
                continue

        return to_ret
296726
protected function renderRelations()
    {
        foreach ($this->schemas as $schema) {
            foreach ($schema->getRelations() as $name => $relation) {

                //Source context defines where relation comes from
                $sourceContext = RelationContext::createContent(
                    $schema,
                    $this->requestTable($schema->getTable(), $schema->getDatabase())
                );

                //Target context might only exist if relation points to another record in ORM,
                //in some cases it might point outside of ORM scope
                $targetContext = null;

                if ($this->hasSchema($relation->getTarget())) {
                    $target = $this->getSchema($relation->getTarget());

                    $targetContext = RelationContext::createContent(
                        $target,
                        $this->requestTable($target->getTable(), $target->getDatabase())
                    );
                }

                $this->relations->registerRelation(
                    $this,
                    $relation->withContext($sourceContext, $targetContext)
                );
            }
        }
    }
329642
def show():
    """"""
    items = list(collection.find())
    # JSON conversion chokes on the _id objects, so we convert
    # them to strings here
    for i in items:
        i['_id'] = str(i['_id'])
    return items
1178768
function View(primaryModel, relatedModels, attributes) {
  if (false === (this instanceof View)) throw new Error('new operator required');
  if (!(primaryModel instanceof Model)) throw new Error('argument must be a Model');
  if (typeof relatedModels != 'object') throw new Error('object expected');
  if (!(attributes instanceof Array)) throw new Error('array of attributes expected');
  this.primaryModel = primaryModel;
  this.relatedModels = relatedModels;
  this.attributes = attributes;
  var id = new Attribute('id', 'ID');
  id.model = primaryModel;
  this.attributes.unshift(id);

  /**
   * Make sure relatedModels valid
   */
  for (var relatedModel in relatedModels) {
    if (relatedModels.hasOwnProperty(relatedModel)) {
      var obj = relatedModels[relatedModel];
      //console.log('relatedModel ' + relatedModel);
      //console.log('obj ' + JSON.stringify(obj));
      if (typeof obj != 'object') throw new Error('relatedModel key values expect object');
      if (obj.id === undefined) throw new Error('relatedModel key values expect object with id key');
      if (obj.model === undefined) throw new Error('relatedModel key values expect object with model key');
      if (!(obj.id instanceof Attribute)) throw new Error('relatedModel id must be a Attribute');
      if (!(obj.model instanceof Model)) throw new Error('relatedModel model must be a Model');
    }
  }
  /**
   * Check attributes
   */
  for (var i = 0; i < attributes.length; i++) {
    var attribute = attributes[i];
    if (!(attribute instanceof Attribute)) throw new Error('attribute array must contain Attributes');
    if (!(attribute.model instanceof Model)) {
      throw new Error('attribute array must contain Attributes with model references');
    }

  }
}
1238702
def get_entity_text_for_relation(self, node, relation):
        """"""

        G = self.G
        related_node = self.get_related_node(node, relation)
        if related_node is not None:
            if not G.node[related_node]['is_event']:
                return G.node[related_node]['text']
            else:
                return None
        else:
            return None
517831
def read(self, entity=None, attrs=None, ignore=None, params=None):
        
        if entity is None:
            entity = type(self)(
                self._server_config,
                **{self._parent_type: self._parent_id}
            )
        if ignore is None:
            ignore = set()
        for field_name in self._path_fields:
            ignore.add(field_name)
        return super(Parameter, self).read(entity, attrs, ignore, params)
323534
function (model, data, action, options) {
                var schema = model.schema,
                    schemaDefinition,
                    schemaType,
                    value,
                    factory,
                    newData = {};

                // convert top level properties to Models respective to there schema
                for (var key in schema) {
                    if (schema.hasOwnProperty(key)) {

                        schemaDefinition = schema[key];
                        schemaType = schemaDefinition.type;
                        value = this._getValueForKey(data, key, schemaType, schemaDefinition);

                        factory = null;
                        var typeResolver,
                            entity,
                            i,
                            list;
                        if (schemaType instanceof Array) {
                            if (schemaType.length === 1) {
                                typeResolver = schemaType[0];
                            } else if (schemaType.length === 0) {
                                this.log('ModelFactory for ListItem for "' + key + '" not defined', 'warn');
                                factory = Entity;
                            } else {
                                throw "Cannot determinate ModelFactory. Multiple factories defined for '" + key + "'.";
                            }

                            if (typeResolver instanceof Function) {
                                factory = typeResolver;
                                typeResolver = null;
                            }

                            if (value && value instanceof Array) {
                                // only create the list if items are there
                                list = newData[key] = new List();

                                for (i = 0; i < value.length; i++) {

                                    if (typeResolver) {
                                        factory = typeResolver.resolve(value[i], key);
                                    }

                                    if ((factory && factory.classof(Entity))) {
                                        entity = this.$dataSource._getContext(factory, model, value[i]).createEntity(factory, this._getIdForValue(value[i], factory));
                                        if (entity instanceof Entity && !(entity instanceof Model)) {
                                            entity.$parent = model;
                                            entity.$parentEntity = model;
                                        }
                                        entity.set(this._parseModel(entity, value[i], action, options));

                                        list.add(entity);
                                    } else {
                                        list.add(value[i]);
                                    }

                                }
                            }


                        } else if (Collection && schemaType.classof(Collection)) {
                            var contextForChildren = this.$dataSource._getContext(schemaType, model, value);
                            if (contextForChildren) {
                                if (model.$[key] instanceof Collection) {
                                    newData[key] = model.$[key];
                                    list = model.$[key];
                                } else {
                                    list = newData[key] = contextForChildren.createCollection(schemaType, (value instanceof Object) && !(value instanceof Array) ? value : null);
                                    list.$parent = contextForChildren.$contextModel;
                                }
                                if (value && value instanceof Array) {
                                    list.reset(this.parseCollection(list, value, action, options));
                                }

                            }
                        } else if (schemaType === Date && value && !(value instanceof Date)) {
                            newData[key] = moment(value, this.$dataSource.$.dateFormat).toDate();
                        } else if (schemaType.classof(Entity)) {
                            var id;
                            if (value && schemaType instanceof TypeResolver) {
                                factory = schemaType.resolve(value, key);
                            } else {
                                factory = schemaType || Entity;
                            }

                            if (!(factory && factory.classof(Entity))) {
                                throw "Factory for type '" + key + "' isn't an instance of Entity";
                            }

                            if (factory.classof(Model) && factory.prototype.$isDependentObject) {
                                id = key;
                                value = value || {};
                            } else if (value) {
                                id = this._getIdForValue(value, factory);
                            }
                            if (value) {
                                newData[key] = entity = this.$dataSource._getContext(factory, model, value).createEntity(factory, id);
                                if (entity instanceof Entity && !(entity instanceof Model)) {
                                    entity.$parent = model;
                                    entity.$parentEntity = model;
                                }
                                entity.set(this._parseModel(entity, value, action, options));
                            }

                        }
                    }
                }

                // add all values that are not defined in schema ...
                _.defaults(newData, data);

                return model.parse(newData);
            }
584286
function toJS(entity) {
  let data = {};
  Object.keys(entity).forEach(key => {
    if (_.some(customObjects, obj => entity[key] instanceof obj)) {
      data[key] = toJS(entity[key])
    } else {
      data[key] = entity[key]
    }
  });
  return data
}
190545
def inspect
      attrs = [
        [ :repository, repository.name ],
        [ :model,      model           ],
        [ :fields,     fields          ],
        [ :links,      links           ],
        [ :conditions, conditions      ],
        [ :order,      order           ],
        [ :limit,      limit           ],
        [ :offset,     offset          ],
        [ :reload,     reload?         ],
        [ :unique,     unique?         ],
      ]

      "#<#{self.class.name} #{attrs.map { |key, value| "@#{key}=#{value.inspect}" }.join(' ')}>"
    end
276495
def write_entity(self, entity):
        
        db, db_object_id = self._split_prefix(entity)
        taxon = normalize_taxon(entity["taxon"]["id"])

        vals = [
            db,
            db_object_id,
            entity.get('label'),
            entity.get('full_name'),
            entity.get('synonyms'),
            entity.get('type'),
            taxon,
            entity.get('parents'),
            entity.get('xrefs'),
            entity.get('properties')
        ]

        self._write_row(vals)
480485
private function displayEntity($entityName, EntityManagerInterface $entityManager, OutputInterface $output)
    {
        $table = new Table($output);

        $table->setHeaders(array('Field', 'Value'));

        $metadata = $this->getClassMetadata($entityName, $entityManager);

        array_map(
            array($table, 'addRow'),
            array_merge(
                array(
                    $this->formatField('Name', $metadata->name),
                    $this->formatField('Root entity name', $metadata->rootEntityName),
                    $this->formatField('Custom generator definition', $metadata->customGeneratorDefinition),
                    $this->formatField('Custom repository class', $metadata->customRepositoryClassName),
                    $this->formatField('Mapped super class?', $metadata->isMappedSuperclass),
                    $this->formatField('Embedded class?', $metadata->isEmbeddedClass),
                    $this->formatField('Parent classes', $metadata->parentClasses),
                    $this->formatField('Sub classes', $metadata->subClasses),
                    $this->formatField('Embedded classes', $metadata->subClasses),
                    $this->formatField('Named queries', $metadata->namedQueries),
                    $this->formatField('Named native queries', $metadata->namedNativeQueries),
                    $this->formatField('SQL result set mappings', $metadata->sqlResultSetMappings),
                    $this->formatField('Identifier', $metadata->identifier),
                    $this->formatField('Inheritance type', $metadata->inheritanceType),
                    $this->formatField('Discriminator column', $metadata->discriminatorColumn),
                    $this->formatField('Discriminator value', $metadata->discriminatorValue),
                    $this->formatField('Discriminator map', $metadata->discriminatorMap),
                    $this->formatField('Generator type', $metadata->generatorType),
                    $this->formatField('Table', $metadata->table),
                    $this->formatField('Composite identifier?', $metadata->isIdentifierComposite),
                    $this->formatField('Foreign identifier?', $metadata->containsForeignIdentifier),
                    $this->formatField('Sequence generator definition', $metadata->sequenceGeneratorDefinition),
                    $this->formatField('Table generator definition', $metadata->tableGeneratorDefinition),
                    $this->formatField('Change tracking policy', $metadata->changeTrackingPolicy),
                    $this->formatField('Versioned?', $metadata->isVersioned),
                    $this->formatField('Version field', $metadata->versionField),
                    $this->formatField('Read only?', $metadata->isReadOnly),

                    $this->formatEntityListeners($metadata->entityListeners),
                ),
                array($this->formatField('Association mappings:', '')),
                $this->formatMappings($metadata->associationMappings),
                array($this->formatField('Field mappings:', '')),
                $this->formatMappings($metadata->fieldMappings)
            )
        );

        $table->render();
    }
207330
function processAllRelations(callback) {
    var i, modelName, relation, relations, result = [];
    for (modelName in relationships) {
        if (relationships.hasOwnProperty(modelName)) {
            relations = relationships[modelName];
            for (i = 0; i < relations.length; i = i + 1) {
                relation = relations[i];
                result.push(callback(modelName, relation.type, relation.model, relation.details));
            }
        }
    }
    return result;
}
429482
def properties_for_entity(entity_name)
      type_definition = metadata.xpath("//EntityType[@Name='#{entity_name}']").first
      raise ArgumentError, "Unknown EntityType: #{entity_name}" if type_definition.nil?
      properties_to_return = {}
      type_definition.xpath('./Property').each do |property_xml|
        property_name, property = process_property_from_xml(property_xml)
        properties_to_return[property_name] = property
      end
      properties_to_return
    end