Returns a dictionary of {field_name: (field_name_other_table, other_table)}
        representing all relationships to the given table.
558831
def get_relations(self, cursor, table_name):
        
        cursor.execute(self._get_relations_query, {
            'schema': self.connection.schema_name,
            'table': table_name
        })
        relations = {}
        for row in cursor.fetchall():
            relations[row[1]] = (row[2], row[0])

        return relations
835285
def _serialize_model_helper(self, model, field_dict=None):
        
        field_dict = field_dict or self.dot_field_list_to_dict()
        if model is None:
            return None

        if isinstance(model, Query):
            model = model.all()

        if isinstance(model, (list, set)):
            return [self.serialize_model(m, field_dict=field_dict) for m in model]

        model_dict = {}
        for name, sub in six.iteritems(field_dict):
            value = getattr(model, name)
            if sub:
                value = self.serialize_model(value, field_dict=sub)
            model_dict[name] = value
        return model_dict
1056937
def _related_field_data(field, obj):
    
    data = _basic_field_data(field, obj)
    relation_info = {
        Field.REL_DB_TABLE: field.rel.to._meta.db_table,
        Field.REL_APP: field.rel.to._meta.app_label,
        Field.REL_MODEL: field.rel.to.__name__
    }
    data[Field.TYPE] = FieldType.REL
    data[Field.REL] = relation_info
    return data
1168957
def relations(cls):
        
        return [c.key for c in cls.__mapper__.iterate_properties
                if isinstance(c, RelationshipProperty)]
616251
def get_table_info(*table_names):
    
    ret = {}
    if table_names:
        for table_name in table_names:
            for name, inter in get_interfaces().items():
                if inter.has_table(table_name):
                    yield table_name, inter, inter.get_fields(table_name)

    else:
        for name, inter in get_interfaces().items():
            table_names = inter.get_tables()
            for table_name in table_names:
                yield table_name, inter, inter.get_fields(table_name)
1097111
def get_relations(self, cursor, table_name):
        
        # pylint:disable=global-statement,too-many-locals,too-many-nested-blocks,unused-argument
        def table2model(table_name):
            return SfProtectName(table_name).title().replace(' ', '').replace('-', '')
        global last_introspected_model, last_read_only, last_refs
        global last_with_important_related_name  # pylint:disable=invalid-name
        result = {}
        reverse = {}
        last_with_important_related_name = []
        last_read_only = {}
        last_refs = {}
        for _, field in enumerate(self.table_description_cache(table_name)['fields']):
            if field['type'] == 'reference' and field['referenceTo']:
                reference_to_name = SfProtectName(field['referenceTo'][0])
                relationship_order = field['relationshipOrder']
                if relationship_order is None:
                    relationship_tmp = set()
                    for rel in field['referenceTo']:
                        for chld in self.table_description_cache(rel)['childRelationships']:
                            if chld['childSObject'] == table_name and chld['field'] == field['name']:
                                relationship_tmp.add(chld['cascadeDelete'])
                    assert len(relationship_tmp) <= 1
                    if True in relationship_tmp:
                        relationship_order = '*'
                last_refs[field['name']] = (field['referenceTo'], relationship_order)
                result[field['name']] = ('Id', reference_to_name)
                reverse.setdefault(reference_to_name, []).append(field['name'])
                if not field['updateable'] or not field['createable']:
                    sf_read_only = (0 if field['updateable'] else 1) | (0 if field['createable'] else 2)
                    # use symbolic names NOT_UPDATEABLE, NON_CREATABLE, READ_ONLY instead of 1, 2, 3
                    last_read_only[field['name']] = reverse_models_names[sf_read_only]
        for ref, ilist in reverse.items():
            # Example of back_collision: a class Aaa has a ForeignKey to a class
            # Bbb and the class Bbb has any field with the name 'aaa'.
            back_name_collisions = [
                x['name'] for x in self.table_description_cache(ref)['fields']
                if re.sub('Id$' if x['type'] == 'reference' else '', '',
                          re.sub('__c$', '', x['name'])
                          ).replace('_', '').lower() == table2model(table_name).lower()]
            # add `related_name` only if necessary
            if len(ilist) > 1 or back_name_collisions:
                last_with_important_related_name.extend(ilist)
        last_introspected_model = table2model(table_name)
        return result
484124
def _get_all_relationships(self):
        """"""
        relationships_all = set()
        for goterm in self.go2obj.values():
            if goterm.relationship:
                relationships_all.update(goterm.relationship)
            if goterm.relationship_rev:
                relationships_all.update(goterm.relationship_rev)
        return relationships_all
692747
def schema_map(schema):
    """"""
    mapper = {}
    for name in getFieldNames(schema):
        mapper[name] = name
    return mapper
861584
public List<ExtendedRelation> getRelatedTableRelations(String relatedTable)
			throws SQLException {
		return queryForEq(ExtendedRelation.COLUMN_RELATED_TABLE_NAME,
				relatedTable);
	}
122071
def extract_relationships(cls, fields, resource, resource_instance):
        
        # Avoid circular deps
        from rest_framework_json_api.relations import ResourceRelatedField

        data = OrderedDict()

        # Don't try to extract relationships from a non-existent resource
        if resource_instance is None:
            return

        for field_name, field in six.iteritems(fields):
            # Skip URL field
            if field_name == api_settings.URL_FIELD_NAME:
                continue

            # don't output a key for write only fields
            if fields[field_name].write_only:
                continue

            # Skip fields without relations
            if not isinstance(
                field, (relations.RelatedField, relations.ManyRelatedField, BaseSerializer)
            ):
                continue

            source = field.source
            relation_type = utils.get_related_resource_type(field)

            if isinstance(field, relations.HyperlinkedIdentityField):
                resolved, relation_instance = utils.get_relation_instance(
                    resource_instance, source, field.parent
                )
                if not resolved:
                    continue
                # special case for HyperlinkedIdentityField
                relation_data = list()

                # Don't try to query an empty relation
                relation_queryset = relation_instance \
                    if relation_instance is not None else list()

                for related_object in relation_queryset:
                    relation_data.append(
                        OrderedDict([
                            ('type', relation_type),
                            ('id', encoding.force_text(related_object.pk))
                        ])
                    )

                data.update({field_name: {
                    'links': {
                        "related": resource.get(field_name)},
                    'data': relation_data,
                    'meta': {
                        'count': len(relation_data)
                    }
                }})
                continue

            relation_data = {}
            if isinstance(field, HyperlinkedMixin):
                field_links = field.get_links(resource_instance, field.related_link_lookup_field)
                relation_data.update({'links': field_links} if field_links else dict())
                data.update({field_name: relation_data})

            if isinstance(field, (ResourceRelatedField, )):
                if not isinstance(field, SkipDataMixin):
                    relation_data.update({'data': resource.get(field_name)})

                data.update({field_name: relation_data})
                continue

            if isinstance(
                    field, (relations.PrimaryKeyRelatedField, relations.HyperlinkedRelatedField)
            ):
                resolved, relation = utils.get_relation_instance(
                    resource_instance, '%s_id' % source, field.parent
                )
                if not resolved:
                    continue
                relation_id = relation if resource.get(field_name) else None
                relation_data = {
                    'data': (
                        OrderedDict([
                            ('type', relation_type), ('id', encoding.force_text(relation_id))
                        ])
                        if relation_id is not None else None)
                }

                if (
                    isinstance(field, relations.HyperlinkedRelatedField) and
                    resource.get(field_name)
                ):
                    relation_data.update(
                        {
                            'links': {
                                'related': resource.get(field_name)
                            }
                        }
                    )
                data.update({field_name: relation_data})
                continue

            if isinstance(field, relations.ManyRelatedField):
                resolved, relation_instance = utils.get_relation_instance(
                    resource_instance, source, field.parent
                )
                if not resolved:
                    continue

                relation_data = {}

                if isinstance(resource.get(field_name), Iterable):
                    relation_data.update(
                        {
                            'meta': {'count': len(resource.get(field_name))}
                        }
                    )

                if isinstance(field.child_relation, ResourceRelatedField):
                    # special case for ResourceRelatedField
                    relation_data.update(
                        {'data': resource.get(field_name)}
                    )

                if isinstance(field.child_relation, HyperlinkedMixin):
                    field_links = field.child_relation.get_links(
                        resource_instance,
                        field.child_relation.related_link_lookup_field
                    )
                    relation_data.update(
                        {'links': field_links}
                        if field_links else dict()
                    )

                    data.update({field_name: relation_data})
                    continue

                relation_data = list()
                for nested_resource_instance in relation_instance:
                    nested_resource_instance_type = (
                        relation_type or
                        utils.get_resource_type_from_instance(nested_resource_instance)
                    )

                    relation_data.append(OrderedDict([
                        ('type', nested_resource_instance_type),
                        ('id', encoding.force_text(nested_resource_instance.pk))
                    ]))
                data.update({
                    field_name: {
                        'data': relation_data,
                        'meta': {
                            'count': len(relation_data)
                        }
                    }
                })
                continue

            if isinstance(field, ListSerializer):
                resolved, relation_instance = utils.get_relation_instance(
                    resource_instance, source, field.parent
                )
                if not resolved:
                    continue

                relation_data = list()

                serializer_data = resource.get(field_name)
                resource_instance_queryset = list(relation_instance)
                if isinstance(serializer_data, list):
                    for position in range(len(serializer_data)):
                        nested_resource_instance = resource_instance_queryset[position]
                        nested_resource_instance_type = (
                            relation_type or
                            utils.get_resource_type_from_instance(nested_resource_instance)
                        )

                        relation_data.append(OrderedDict([
                            ('type', nested_resource_instance_type),
                            ('id', encoding.force_text(nested_resource_instance.pk))
                        ]))

                    data.update({field_name: {'data': relation_data}})
                    continue

            if isinstance(field, Serializer):
                relation_instance_id = getattr(resource_instance, source + "_id", None)
                if not relation_instance_id:
                    resolved, relation_instance = utils.get_relation_instance(
                        resource_instance, source, field.parent
                    )
                    if not resolved:
                        continue

                    if relation_instance is not None:
                        relation_instance_id = relation_instance.pk

                data.update({
                    field_name: {
                        'data': (
                            OrderedDict([
                                ('type', relation_type),
                                ('id', encoding.force_text(relation_instance_id))
                            ]) if resource.get(field_name) else None)
                    }
                })
                continue

        return utils._format_object(data)
378632
public String getRelationshipName()
    {
        String ret;
        if (tableAB == null /* && multipleRelationsBetweenTables */)
        {
            ret = concatenateColumnNames(this);
            ret = ret.substring(1); // remove leading _.
        }
        else // Many-to-Many relationship
        {
            ForeignKey[] fks = tableAB.getForeignKeys().values().toArray(new ForeignKey[2]);
            ret = ForeignKey.concatenateColumnNames(fks[1]).substring(1);
        }

        String multiplicity = getTableBMultiplicity();
        if (!multiplicity.equals("one"))
            ret = StringUtility.englishPluralize(ret);
        return ret;
    }
590113
def extract_relation_instance(cls, field_name, field, resource_instance, serializer):
        
        relation_instance = None

        try:
            relation_instance = getattr(resource_instance, field_name)
        except AttributeError:
            try:
                # For ManyRelatedFields if `related_name` is not set
                # we need to access `foo_set` from `source`
                relation_instance = getattr(resource_instance, field.child_relation.source)
            except AttributeError:
                if hasattr(serializer, field.source):
                    serializer_method = getattr(serializer, field.source)
                    relation_instance = serializer_method(resource_instance)
                else:
                    # case when source is a simple remap on resource_instance
                    try:
                        relation_instance = getattr(resource_instance, field.source)
                    except AttributeError:
                        pass

        return relation_instance
1038405
def _get_fields_for_model(model):
    
    fields = []
    for name in model._sa_class_manager:
        prop = getattr(model, name)
        if isinstance(prop.property, RelationshipProperty):
            for pk in prop.property.mapper.primary_key:
                fields.append('{0}.{1}'.format(name, pk.name))
        else:
            fields.append(name)
    return tuple(fields)
416952
def bind_fields_to_model_cls(cls, model_fields):
        """"""
        return dict(
            (field.name, field.bind_model_cls(cls)) for field in model_fields)
1348538
def _get_model_fields(self, field_names, declared_fields, extra_kwargs):
        
        model = getattr(self.Meta, 'model')
        model_fields = {}

        for field_name in field_names:
            if field_name in declared_fields:
                # If the field is declared on the serializer
                field = declared_fields[field_name]
                source = field.source or field_name
            else:
                try:
                    source = extra_kwargs[field_name]['source']
                except KeyError:
                    source = field_name

            if '.' in source or source == '*':
                # Model fields will always have a simple source mapping,
                # they can't be nested attribute lookups.
                continue

            try:
                field = model._meta.get_field(source)
                if isinstance(field, DjangoModelField):
                    model_fields[source] = field
            except FieldDoesNotExist:
                pass

        return model_fields
805495
def _get_mapping(self, schema):
        
        properties = {}
        for field, field_schema in schema.items():
            field_mapping = self._get_field_mapping(field_schema)
            if field_mapping:
                properties[field] = field_mapping
        return {'properties': properties}
1191834
def _get_forward_relationships(opts):
    
    forward_relations = OrderedDict()
    for field in [field for field in opts.fields if field.serialize and field.rel]:
        forward_relations[field.name] = RelationInfo(
            model_field=field,
            related_model=_resolve_model(field.rel.to),
            to_many=False,
            to_field=_get_to_field(field),
            has_through_model=False
        )

    # Deal with forward many-to-many relationships.
    for field in [field for field in opts.many_to_many if field.serialize]:
        forward_relations[field.name] = RelationInfo(
            model_field=field,
            related_model=_resolve_model(field.rel.to),
            to_many=True,
            # manytomany do not have to_fields
            to_field=None,
            has_through_model=(
                not field.rel.through._meta.auto_created
            )
        )

    return forward_relations