Returns the FOREIGN KEY query section dealing with non-standard options
        as MATCH, INITIALLY DEFERRED, ON UPDATE, ...

        :param foreign_key: The foreign key
        :type foreign_key: ForeignKeyConstraint

        :rtype: str
964297
def get_advanced_foreign_key_options_sql(self, foreign_key):
        
        query = ""
        if self.supports_foreign_key_on_update() and foreign_key.has_option(
            "on_update"
        ):
            query += " ON UPDATE %s" % self.get_foreign_key_referential_action_sql(
                foreign_key.get_option("on_update")
            )

        if foreign_key.has_option("on_delete"):
            query += " ON DELETE %s" % self.get_foreign_key_referential_action_sql(
                foreign_key.get_option("on_delete")
            )

        return query
209724
def handle_fk_field(self, obj, field):
        
        self._start_relational_field(field)
        related = getattr(obj, field.name)
        if related is not None:
            if self.use_natural_keys and hasattr(related, 'natural_key'):
                # If related object has a natural key, use it
                related = related.natural_key()
                # Iterable natural keys are rolled out as subelements
                for key_value in related:
                    self.xml.startElement("natural", {})
                    self.xml.characters(smart_unicode(key_value))
                    self.xml.endElement("natural")
            else:
                if field.rel.field_name == related._meta.pk.name:
                    # Related to remote object via primary key
                    related = related._get_pk_val()
                else:
                    # Related to remote object via other field
                    related = getattr(related, field.rel.field_name)
                self.xml.characters(smart_unicode(related))
        else:
            self.xml.addQuickElement("None")
        self.xml.endElement("field")
938187
def get_foreign_keys(self, connection, table_name, schema=None, **kw):
        
        constraints = self._get_redshift_constraints(connection, table_name,
                                                     schema, **kw)
        fk_constraints = [c for c in constraints if c.contype == 'f']
        uniques = defaultdict(lambda: defaultdict(dict))
        for con in fk_constraints:
            uniques[con.conname]["key"] = con.conkey
            uniques[con.conname]["condef"] = con.condef
        fkeys = []
        for conname, attrs in uniques.items():
            m = FOREIGN_KEY_RE.match(attrs['condef'])
            colstring = m.group('referred_columns')
            referred_columns = SQL_IDENTIFIER_RE.findall(colstring)
            referred_table = m.group('referred_table')
            referred_schema = m.group('referred_schema')
            colstring = m.group('columns')
            constrained_columns = SQL_IDENTIFIER_RE.findall(colstring)
            fkey_d = {
                'name': conname,
                'constrained_columns': constrained_columns,
                'referred_schema': referred_schema,
                'referred_table': referred_table,
                'referred_columns': referred_columns,
            }
            fkeys.append(fkey_d)
        return fkeys
979220
def get_foreign_keys(cls):
        
        foreign_keys = {}
        for field in cls._meta.fields:
            if (
                field.get_internal_type() == 'ForeignKey' and
                field.name != 'parent'
            ):
                if django.VERSION >= (1, 9):
                    foreign_keys[field.name] = field.remote_field.model
                else:
                    foreign_keys[field.name] = field.rel.to
        return foreign_keys
450471
def add_constraints(self):
        
        if self._constraints:
            foreign_key = getattr(self._parent, self._foreign_key, None)
            if foreign_key is None:
                self._query = None
            else:
                table = self._related.get_table()

                self._query.where(
                    "{}.{}".format(table, self._other_key), "=", foreign_key
                )
1122103
def get_column_for_modelfield(model_field):
    

    # If the field points to another model, we want to get the pk field of that other model and use
    # that as the real field.  It is possible that a ForeignKey points to a model with table
    # inheritance, however, so we need to traverse the internal OneToOneField as well, so this will
    # climb the 'pk' field chain until we have something real.
    while model_field.related_model:
        model_field = model_field.related_model._meta.pk
    for ColumnClass, modelfield_classes in COLUMN_CLASSES:
        if isinstance(model_field, tuple(modelfield_classes)):
            return ColumnClass
222179
def foreignkey_autocomplete(self, request):
        
        query = request.GET.get('q', None)
        app_label = request.GET.get('app_label', None)
        model_name = request.GET.get('model_name', None)
        search_fields = request.GET.get('search_fields', None)
        object_pk = request.GET.get('object_pk', None)

        try:
            to_string_function = self.related_string_functions[model_name]
        except KeyError:
            if six.PY3:
                to_string_function = lambda x: x.__str__()
            else:
                to_string_function = lambda x: x.__unicode__()

        if search_fields and app_label and model_name and (query or object_pk):
            def construct_search(field_name):
                # use different lookup methods depending on the notation
                if field_name.startswith('^'):
                    return "%s__istartswith" % field_name[1:]
                elif field_name.startswith('='):
                    return "%s__iexact" % field_name[1:]
                elif field_name.startswith('@'):
                    return "%s__search" % field_name[1:]
                else:
                    return "%s__icontains" % field_name

            model = apps.get_model(app_label, model_name)

            queryset = model._default_manager.all()
            data = ''
            if query:
                for bit in query.split():
                    or_queries = [models.Q(**{construct_search(smart_str(field_name)): smart_str(bit)}) for field_name in search_fields.split(',')]
                    other_qs = QuerySet(model)
                    other_qs.query.select_related = queryset.query.select_related
                    other_qs = other_qs.filter(reduce(operator.or_, or_queries))
                    queryset = queryset & other_qs

                additional_filter = self.get_related_filter(model, request)
                if additional_filter:
                    queryset = queryset.filter(additional_filter)

                if self.autocomplete_limit:
                    queryset = queryset[:self.autocomplete_limit]

                data = ''.join([six.u('%s|%s\n') % (to_string_function(f), f.pk) for f in queryset])
            elif object_pk:
                try:
                    obj = queryset.get(pk=object_pk)
                except Exception:  # FIXME: use stricter exception checking
                    pass
                else:
                    data = to_string_function(obj)
            return HttpResponse(data, content_type='text/plain')
        return HttpResponseNotFound()
23189
def find_or_new(self, id, columns=None):
        
        if columns is None:
            columns = ['*']

        instance = self.find(id, columns)

        if instance is None:
            instance = self._related.new_instance()
            self._set_foreign_attributes_for_create(instance)

        return instance
78963
def _get_delete_query(self):
        
        foreign = self.get_attribute(self.__foreign_key)

        query = self.new_query().where(self.__foreign_key, foreign)

        return query.where(self.__other_key, self.get_attribute(self.__other_key))
822583
def _set_join(self, query=None):
        
        if not query:
            query = self._query

        base_table = self._related.get_table()

        key = '%s.%s' % (base_table, self._related.get_key_name())

        query.join(self._table, key, '=', self.get_other_key())

        return self
532265
def basic_types(self):
        
        if not self.foreign_key_definitions:
            return self.standard_types
        else:
            tmp = self.standard_types
            tmp.append('ForeignKey')
            return tmp
31273
def get_relation_count_query(self, query, parent):
        
        query.select(QueryExpression('COUNT(*)'))

        other_key = self.wrap('%s.%s' % (query.get_model().get_table(), self._other_key))

        return query.where(self.get_qualified_foreign_key(), '=', QueryExpression(other_key))
494422
def dump_foreign_key(foreign_key)
      parts = [
        "add_foreign_key #{remove_prefix_and_suffix(foreign_key.from_table).inspect}",
        remove_prefix_and_suffix(foreign_key.to_table).inspect,
      ]

      if foreign_key.column != foreign_key_column_for(foreign_key.to_table)
        parts << "column: #{foreign_key.column.inspect}"
      end

      if foreign_key.custom_primary_key?
        parts << "primary_key: #{foreign_key.primary_key.inspect}"
      end

      if foreign_key.name !~ /^fk_rails_[0-9a-f]{10}$/
        parts << "name: #{foreign_key.name.inspect}"
      end

      parts << "on_update: #{foreign_key.on_update.inspect}" if foreign_key.on_update
      parts << "on_delete: #{foreign_key.on_delete.inspect}" if foreign_key.on_delete

      parts.join(', ')
    end
1342330
def check_foreign():
    
    if not config.dbserver.multi_user:
        remote_server_path = logs.dbcmd('get_path')
        if different_paths(server_path, remote_server_path):
            return('You are trying to contact a DbServer from another'
                   ' instance (got %s, expected %s)\n'
                   'Check the configuration or stop the foreign'
                   ' DbServer instance') % (remote_server_path, server_path)
847844
@Override
    public String getMethodNameForReference(final ForeignKey foreignKey) {
        final Column c = foreignKey.getColumnReferences().get(0).getForeignKeyColumn();
        // check if only one-column fk
        if (foreignKey.getColumnReferences().size() == 1) {
            return getMethodNameForColumn(c) + getClassNameForTable(c.getReferencedColumn().getParent());
        }

        final StringBuilder nameBuilder = new StringBuilder();
        final List<String> words = new ArrayList<>(Arrays.asList(foreignKey.getName()
                .toLowerCase()
                .replaceAll("(^[0-9]+|[^a-z0-9_-])", "") // Delete every not-alphanumeric or _/- character and numbers at beginning
                .split("_")));
        words.removeAll(Arrays.asList("fk", "", null)); // removes FK_ prefix and empty entries
        final List<String> tableWords = new ArrayList<>(Arrays.asList(c.getParent().getName()
                .toLowerCase()
                .replaceAll("(^[0-9]+|[^a-z0-9_-])", "") // Delete every not-alphanumeric or _/- character and numbers at beginning
                .split("_")));
        words.removeAll(tableWords);
        nameBuilder.append(words.get(0));
        for (int i = 1; i < words.size(); i++) {
            String word = words.get(i);

            nameBuilder.append(word.substring(0, 1).toUpperCase());
            nameBuilder.append(word.substring(1));
        }
        return nameBuilder.toString();
    }
785287
async def expand_foreign_keys(self, database, table, column, values):
        ""
        labeled_fks = {}
        foreign_keys = await self.foreign_keys_for_table(database, table)
        # Find the foreign_key for this column
        try:
            fk = [
                foreign_key for foreign_key in foreign_keys
                if foreign_key["column"] == column
            ][0]
        except IndexError:
            return {}
        label_column = await self.label_column_for_table(database, fk["other_table"])
        if not label_column:
            return {
                (fk["column"], value): str(value)
                for value in values
            }
        labeled_fks = {}
        sql = '''
            select {other_column}, {label_column}
            from {other_table}
            where {other_column} in ({placeholders})
        '''.format(
            other_column=escape_sqlite(fk["other_column"]),
            label_column=escape_sqlite(label_column),
            other_table=escape_sqlite(fk["other_table"]),
            placeholders=", ".join(["?"] * len(set(values))),
        )
        try:
            results = await self.execute(
                database, sql, list(set(values))
            )
        except InterruptedError:
            pass
        else:
            for id, value in results:
                labeled_fks[(fk["column"], id)] = value
        return labeled_fks
412390
protected function fetchOneToMany($foreign_class, $foreign_column, $column)
    {
        return $foreign_class::select($this->connection)
            ->where($foreign_column, '=', $this->getRaw($column))
            ->execute();
    }