sqlalchemy.sa_schema.ForeignKeyConstraint

Here are the examples of the python api sqlalchemy.sa_schema.ForeignKeyConstraint taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

5 Examples 7

Example 1

Project: alembic Source File: compare.py
def _make_foreign_key(params, conn_table):
    tname = params['referred_table']
    if params['referred_schema']:
        tname = "%s.%s" % (params['referred_schema'], tname)

    options = params.get('options', {})

    const = sa_schema.ForeignKeyConstraint(
        [conn_table.c[cname] for cname in params['constrained_columns']],
        ["%s.%s" % (tname, n) for n in params['referred_columns']],
        onupdate=options.get('onupdate'),
        ondelete=options.get('ondelete'),
        deferrable=options.get('deferrable'),
        initially=options.get('initially'),
        name=params['name']
    )
    # needed by 0.7
    conn_table.append_constraint(const)
    return const

Example 2

Project: alembic Source File: schemaobj.py
    def generic_constraint(self, name, table_name, type_, schema=None, **kw):
        t = self.table(table_name, schema=schema)
        types = {
            'foreignkey': lambda name: sa_schema.ForeignKeyConstraint(
                [], [], name=name),
            'primary': sa_schema.PrimaryKeyConstraint,
            'unique': sa_schema.UniqueConstraint,
            'check': lambda name: sa_schema.CheckConstraint("", name=name),
            None: sa_schema.Constraint
        }
        try:
            const = types[type_]
        except KeyError:
            raise TypeError("'type' can be one of %s" %
                            ", ".join(sorted(repr(x) for x in types)))
        else:
            const = const(name=name)
            t.append_constraint(const)
            return const

Example 3

Project: alembic Source File: compare.py
@comparators.dispatch_for("table")
def _compare_foreign_keys(
    autogen_context, modify_table_ops, schema, tname, conn_table,
        metadata_table):

    # if we're doing CREATE TABLE, all FKs are created
    # inline within the table def
    if conn_table is None:
        return

    inspector = autogen_context.inspector
    metadata_fks = set(
        fk for fk in metadata_table.constraints
        if isinstance(fk, sa_schema.ForeignKeyConstraint)
    )

    conn_fks = inspector.get_foreign_keys(tname, schema=schema)

    backend_reflects_fk_options = conn_fks and 'options' in conn_fks[0]

    conn_fks = set(_make_foreign_key(const, conn_table) for const in conn_fks)

    # give the dialect a chance to correct the FKs to match more
    # closely
    autogen_context.migration_context.impl.\
        correct_for_autogen_foreignkeys(
            conn_fks, metadata_fks,
        )

    metadata_fks = set(
        _fk_constraint_sig(fk, include_options=backend_reflects_fk_options)
        for fk in metadata_fks
    )

    conn_fks = set(
        _fk_constraint_sig(fk, include_options=backend_reflects_fk_options)
        for fk in conn_fks
    )

    conn_fks_by_sig = dict(
        (c.sig, c) for c in conn_fks
    )
    metadata_fks_by_sig = dict(
        (c.sig, c) for c in metadata_fks
    )

    metadata_fks_by_name = dict(
        (c.name, c) for c in metadata_fks if c.name is not None
    )
    conn_fks_by_name = dict(
        (c.name, c) for c in conn_fks if c.name is not None
    )

    def _add_fk(obj, compare_to):
        if autogen_context.run_filters(
                obj.const, obj.name, "foreign_key_constraint", False,
                compare_to):
            modify_table_ops.ops.append(
                ops.CreateForeignKeyOp.from_constraint(const.const)
            )

            log.info(
                "Detected added foreign key (%s)(%s) on table %s%s",
                ", ".join(obj.source_columns),
                ", ".join(obj.target_columns),
                "%s." % obj.source_schema if obj.source_schema else "",
                obj.source_table)

    def _remove_fk(obj, compare_to):
        if autogen_context.run_filters(
                obj.const, obj.name, "foreign_key_constraint", True,
                compare_to):
            modify_table_ops.ops.append(
                ops.DropConstraintOp.from_constraint(obj.const)
            )
            log.info(
                "Detected removed foreign key (%s)(%s) on table %s%s",
                ", ".join(obj.source_columns),
                ", ".join(obj.target_columns),
                "%s." % obj.source_schema if obj.source_schema else "",
                obj.source_table)

    # so far it appears we don't need to do this by name at all.
    # SQLite doesn't preserve constraint names anyway

    for removed_sig in set(conn_fks_by_sig).difference(metadata_fks_by_sig):
        const = conn_fks_by_sig[removed_sig]
        if removed_sig not in metadata_fks_by_sig:
            compare_to = metadata_fks_by_name[const.name].const \
                if const.name in metadata_fks_by_name else None
            _remove_fk(const, compare_to)

    for added_sig in set(metadata_fks_by_sig).difference(conn_fks_by_sig):
        const = metadata_fks_by_sig[added_sig]
        if added_sig not in conn_fks_by_sig:
            compare_to = conn_fks_by_name[const.name].const \
                if const.name in conn_fks_by_name else None
            _add_fk(const, compare_to)

Example 4

Project: alembic Source File: render.py
@_constraint_renderers.dispatch_for(sa_schema.ForeignKeyConstraint)
def _render_foreign_key(constraint, autogen_context):
    rendered = _user_defined_render("foreign_key", constraint, autogen_context)
    if rendered is not False:
        return rendered

    opts = []
    if constraint.name:
        opts.append(("name", repr(
            _render_gen_name(autogen_context, constraint.name))))

    _populate_render_fk_opts(constraint, opts)

    apply_metadata_schema = constraint.parent.metadata.schema
    return "%(prefix)sForeignKeyConstraint([%(cols)s], "\
        "[%(refcols)s], %(args)s)" % {
            "prefix": _sqlalchemy_autogenerate_prefix(autogen_context),
            "cols": ", ".join(
                "%r" % _ident(f.parent.name) for f in constraint.elements),
            "refcols": ", ".join(repr(_fk_colspec(f, apply_metadata_schema))
                                 for f in constraint.elements),
            "args": ", ".join(
                    ["%s=%s" % (kwname, val) for kwname, val in opts]
            ),
        }

Example 5

Project: kokoropy Source File: operations.py
Function: drop_constraint
    @util._with_legacy_names([("type", "type_")])
    def drop_constraint(self, name, table_name, type_=None, schema=None):
        """Drop a constraint of the given name, typically via DROP CONSTRAINT.

        :param name: name of the constraint.
        :param table_name: table name.

         .. versionchanged:: 0.5.0
            The ``tablename`` parameter is now named ``table_name``.
            As this is a positional argument, the old name is no
            longer present.

        :param ``type_``: optional, required on MySQL.  can be
         'foreignkey', 'primary', 'unique', or 'check'.

         .. versionchanged:: 0.5.0
            The ``type`` parameter is now named ``type_``.  The old name
            ``type`` will remain for backwards compatibility.

         .. versionadded:: 0.3.6 'primary' qualfier to enable
            dropping of MySQL primary key constraints.

        :param schema: Optional schema name to operate within.

         .. versionadded:: 0.4.0

        """

        t = self._table(table_name, schema=schema)
        types = {
            'foreignkey': lambda name: sa_schema.ForeignKeyConstraint(
                                [], [], name=name),
            'primary': sa_schema.PrimaryKeyConstraint,
            'unique': sa_schema.UniqueConstraint,
            'check': lambda name: sa_schema.CheckConstraint("", name=name),
            None: sa_schema.Constraint
        }
        try:
            const = types[type_]
        except KeyError:
            raise TypeError("'type' can be one of %s" %
                        ", ".join(sorted(repr(x) for x in types)))

        const = const(name=name)
        t.append_constraint(const)
        self.impl.drop_constraint(const)