Generates the foreign key declaration for a given Constraint object.
774637
private void getFKStatement(StringBuffer a) {

        if (!getName().isReservedName()) {
            a.append(Tokens.T_CONSTRAINT).append(' ');
            a.append(getName().statementName);
            a.append(' ');
        }

        a.append(Tokens.T_FOREIGN).append(' ').append(Tokens.T_KEY);

        int[] col = getRefColumns();

        getColumnList(getRef(), col, col.length, a);
        a.append(' ').append(Tokens.T_REFERENCES).append(' ');
        a.append(getMain().getName().getSchemaQualifiedStatementName());

        col = getMainColumns();

        getColumnList(getMain(), col, col.length, a);

        if (getDeleteAction() != Constraint.NO_ACTION) {
            a.append(' ').append(Tokens.T_ON).append(' ').append(
                Tokens.T_DELETE).append(' ');
            a.append(getDeleteActionString());
        }

        if (getUpdateAction() != Constraint.NO_ACTION) {
            a.append(' ').append(Tokens.T_ON).append(' ').append(
                Tokens.T_UPDATE).append(' ');
            a.append(getUpdateActionString());
        }
    }
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
433142
def _set_foreign_attributes_for_create(self, model):
        
        model.set_attribute(self.get_plain_foreign_key(), self.get_parent_key())

        model.set_attribute(self.get_plain_morph_type(), self._morph_class)
1122293
def add_constraints(self):
        
        if self._constraints:
            self._query.where(self._foreign_key, "=", self.get_parent_key())
24505
def get_key_columns(self, cursor, table_name):
        
        source_field_dict = self._name_to_index(cursor, table_name)

        sql = """
select
    COLUMN_NAME = fk_cols.COLUMN_NAME,
    REFERENCED_TABLE_NAME = pk.TABLE_NAME,
    REFERENCED_COLUMN_NAME = pk_cols.COLUMN_NAME
from INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS ref_const
join INFORMATION_SCHEMA.TABLE_CONSTRAINTS fk
    on ref_const.CONSTRAINT_CATALOG = fk.CONSTRAINT_CATALOG
    and ref_const.CONSTRAINT_SCHEMA = fk.CONSTRAINT_SCHEMA
    and ref_const.CONSTRAINT_NAME = fk.CONSTRAINT_NAME
    and fk.CONSTRAINT_TYPE = 'FOREIGN KEY'

join INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk
    on ref_const.UNIQUE_CONSTRAINT_CATALOG = pk.CONSTRAINT_CATALOG
    and ref_const.UNIQUE_CONSTRAINT_SCHEMA = pk.CONSTRAINT_SCHEMA
    and ref_const.UNIQUE_CONSTRAINT_NAME = pk.CONSTRAINT_NAME
    And pk.CONSTRAINT_TYPE = 'PRIMARY KEY'

join INFORMATION_SCHEMA.KEY_COLUMN_USAGE fk_cols
    on ref_const.CONSTRAINT_NAME = fk_cols.CONSTRAINT_NAME

join INFORMATION_SCHEMA.KEY_COLUMN_USAGE pk_cols
    on pk.CONSTRAINT_NAME = pk_cols.CONSTRAINT_NAME
where
    fk.TABLE_NAME = %s"""

        cursor.execute(sql,[table_name])
        relations = cursor.fetchall()

        key_columns = []
        key_columns.extend([(source_column, target_table, target_column) \
            for source_column, target_table, target_column in relations])
        return key_columns
754336
public static ForeignKeyConstraint of(String name, Attribute attribute, Attribute reference) {
		return new Builder((DatabaseRelationDefinition)attribute.getRelation(), 
							(DatabaseRelationDefinition)reference.getRelation())
									.add(attribute, reference).build(name);
	}
333432
def get_create_foreign_key_sql(self, foreign_key, table):
        
        if isinstance(table, Table):
            table = table.get_quoted_name(self)

        query = "ALTER TABLE %s ADD %s" % (
            table,
            self.get_foreign_key_declaration_sql(foreign_key),
        )

        return query
1308977
def _get_foreign_keys_in_altered_table(self, diff):
        
        foreign_keys = diff.from_table.get_foreign_keys()
        column_names = self._get_column_names_in_altered_table(diff)

        for key, constraint in foreign_keys.items():
            changed = False
            local_columns = []
            for column_name in constraint.get_local_columns():
                normalized_column_name = column_name.lower()
                if normalized_column_name not in column_names:
                    del foreign_keys[key]
                    break
                else:
                    local_columns.append(column_names[normalized_column_name])
                    if column_name != column_names[normalized_column_name]:
                        changed = True

            if changed:
                foreign_keys[key] = ForeignKeyConstraint(
                    local_columns,
                    constraint.get_foreign_table_name(),
                    constraint.get_foreign_columns(),
                    constraint.get_name(),
                    constraint.get_options(),
                )

        for constraint in diff.removed_foreign_keys:
            constraint_name = constraint.get_name().lower()
            if constraint_name and constraint_name in foreign_keys:
                del foreign_keys[constraint_name]

        foreign_keys_diff = diff.changed_foreign_keys + diff.added_foreign_keys
        for constraint in foreign_keys_diff:
            constraint_name = constraint.get_name().lower()
            if constraint_name:
                foreign_keys[constraint_name] = constraint
            else:
                foreign_keys[len(foreign_keys)] = constraint

        return foreign_keys
686558
def modify_fk_constraint(apps, schema_editor):
    
    model = apps.get_model("message_sender", "OutboundSendFailure")
    table = model._meta.db_table

    with schema_editor.connection.cursor() as cursor:
        constraints = schema_editor.connection.introspection.get_constraints(
            cursor, table
        )
        [constraint] = filter(lambda c: c[1]["foreign_key"], constraints.items())
        [name, _] = constraint
    sql_delete_fk = (
        "SET CONSTRAINTS {name} IMMEDIATE; "
        "ALTER TABLE {table} DROP CONSTRAINT {name}"
    ).format(table=schema_editor.quote_name(table), name=schema_editor.quote_name(name))
    schema_editor.execute(sql_delete_fk)

    field = model.outbound.field
    to_table = field.remote_field.model._meta.db_table
    to_column = field.remote_field.model._meta.get_field(
        field.remote_field.field_name
    ).column
    sql_create_fk = (
        "ALTER TABLE {table} ADD CONSTRAINT {name} FOREIGN KEY "
        "({column}) REFERENCES {to_table} ({to_column}) "
        "ON DELETE CASCADE {deferrable};"
    ).format(
        table=schema_editor.quote_name(table),
        name=schema_editor.quote_name(name),
        column=schema_editor.quote_name(field.column),
        to_table=schema_editor.quote_name(to_table),
        to_column=schema_editor.quote_name(to_column),
        deferrable=schema_editor.connection.ops.deferrable_sql(),
    )
    schema_editor.execute(sql_create_fk)
431279
def constraint(self):
        """"""
        constraint_arr = []
        if self._not_null:
            constraint_arr.append("PRIMARY KEY" if self._pk else "NOT NULL")
        if self._unique:
            constraint_arr.append("UNIQUE")

        return " ".join(constraint_arr)
496313
private void checkPrimaryKey(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException
    {
        if (CHECKLEVEL_NONE.equals(checkLevel))
        {
            return;
        }

        if (classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true) &&
            classDef.getPrimaryKeys().isEmpty())
        {
            LogHelper.warn(true,
                           getClass(),
                           "checkPrimaryKey",
                           "The class "+classDef.getName()+" has no primary key");
        }
    }
555326
private ConstraintRelationshipInfo relationshipInfoFromConstraintDefinition(ConstraintDefinition constraintDefinition) {
        return new ConstraintRelationshipInfo(
                String.format("CONSTRAINT %s", constraintDefinition.toString()),
                constraintDefinition.getConstraintType().name(),
                Iterables.asList(constraintDefinition.getPropertyKeys()),
                ""
        );
    }
860364
def store_constraint(constr)
      # Update the constraint to track the index in the model
      constr.model = self

      # Set constraint properties
      Cbc.Cbc_setRowName(@ptr, constr.index, constr.name) unless constr.name.nil?
      store_constraint_bounds constr.index, constr.sense, constr.rhs
    end
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
1039705
def _set_foreign_attributes_for_create(self, model):
        
        model.set_attribute(self.get_plain_foreign_key(), self.get_parent_key())

        model.set_attribute(self.get_plain_morph_type(), self._morph_name)
885131
def generic_find_fk_constraint_names(table, columns, referenced, insp):
    """"""
    names = set()

    for fk in insp.get_foreign_keys(table):
        if fk['referred_table'] == referenced and set(fk['referred_columns']) == columns:
            names.add(fk['name'])

    return names
19013
private ImmutableList<TargetAtom> getRefCQ(ForeignKeyConstraint fk) {
        ImmutableTerm sub = generateSubject(fk.getRelation(), true);
		ImmutableTerm obj = generateSubject(fk.getReferencedRelation(), true);

		TargetAtom atom = getAtom(getReferencePropertyIRI(fk), sub, obj);
		return ImmutableList.of(atom);
	}