Here are the examples of the python api sqlalchemy.ForeignKeyConstraint taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
103 Examples
3
Source : test_basic.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_table_args_no_dict(self):
class Foo1(Base):
__tablename__ = "foo"
__table_args__ = (ForeignKeyConstraint(["id"], ["foo.bar"]),)
id = Column("id", Integer, primary_key=True)
bar = Column("bar", Integer)
assert Foo1.__table__.c.id.references(Foo1.__table__.c.bar)
def test_table_args_type(self):
3
Source : test_basic.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_table_args_type(self):
def err():
class Foo1(Base):
__tablename__ = "foo"
__table_args__ = ForeignKeyConstraint(["id"], ["foo.id"])
id = Column("id", Integer, primary_key=True)
assert_raises_message(
sa.exc.ArgumentError, "__table_args__ value must be a tuple, ", err
)
def test_table_args_none(self):
3
Source : test_constraints.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_deferrable_table_fk(self):
def factory(**kw):
return ForeignKeyConstraint(["b"], ["tbl.a"], **kw)
self._test_deferrable(factory)
def test_deferrable_column_fk(self):
3
Source : test_constraints.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_render_add_fk_constraint_stringcol(self):
t, t2 = self._constraint_create_fixture()
constraint = ForeignKeyConstraint(["b"], ["t2.a"])
t.append_constraint(constraint)
self.assert_compile(
schema.AddConstraint(constraint),
"ALTER TABLE tbl ADD FOREIGN KEY(b) REFERENCES t2 (a)",
)
def test_render_add_fk_constraint_realcol(self):
3
Source : test_constraints.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_render_add_fk_constraint_realcol(self):
t, t2 = self._constraint_create_fixture()
constraint = ForeignKeyConstraint([t.c.a], [t2.c.b])
t.append_constraint(constraint)
self.assert_compile(
schema.AddConstraint(constraint),
"ALTER TABLE tbl ADD FOREIGN KEY(a) REFERENCES t2 (b)",
)
def test_render_add_uq_constraint_stringcol(self):
3
Source : test_metadata.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_fk_construct(self):
c1 = Column("foo", Integer)
c2 = Column("bar", Integer)
m = MetaData()
t1 = Table("t", m, c1, c2)
fk1 = ForeignKeyConstraint(("foo",), ("bar",), table=t1)
assert fk1 in t1.constraints
def test_fk_constraint_col_collection_w_table(self):
3
Source : test_metadata.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_fk_constraint_col_collection_w_table(self):
c1 = Column("foo", Integer)
c2 = Column("bar", Integer)
m = MetaData()
t1 = Table("t", m, c1, c2)
fk1 = ForeignKeyConstraint(("foo",), ("bar",), table=t1)
eq_(dict(fk1.columns), {"foo": c1})
def test_fk_constraint_col_collection_no_table(self):
3
Source : test_metadata.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_fk_constraint_col_collection_no_table(self):
fk1 = ForeignKeyConstraint(("foo", "bat"), ("bar", "hoho"))
eq_(dict(fk1.columns), {})
eq_(fk1.column_keys, ["foo", "bat"])
eq_(fk1._col_description, "foo, bat")
eq_(fk1._elements, {"foo": fk1.elements[0], "bat": fk1.elements[1]})
def test_fk_constraint_col_collection_no_table_real_cols(self):
3
Source : test_metadata.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_fk_constraint_col_collection_no_table_real_cols(self):
c1 = Column("foo", Integer)
c2 = Column("bar", Integer)
fk1 = ForeignKeyConstraint((c1,), (c2,))
eq_(dict(fk1.columns), {})
eq_(fk1.column_keys, ["foo"])
eq_(fk1._col_description, "foo")
eq_(fk1._elements, {"foo": fk1.elements[0]})
def test_fk_constraint_col_collection_added_to_table(self):
3
Source : test_metadata.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_fk_constraint_col_collection_added_to_table(self):
c1 = Column("foo", Integer)
m = MetaData()
fk1 = ForeignKeyConstraint(("foo",), ("bar",))
Table("t", m, c1, fk1)
eq_(dict(fk1.columns), {"foo": c1})
eq_(fk1._elements, {"foo": fk1.elements[0]})
def test_fk_constraint_col_collection_via_fk(self):
3
Source : test_metadata.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_fk_no_such_parent_col_error(self):
meta = MetaData()
a = Table("a", meta, Column("a", Integer))
Table("b", meta, Column("b", Integer))
def go():
a.append_constraint(ForeignKeyConstraint(["x"], ["b.b"]))
assert_raises_message(
exc.ArgumentError,
"Can't create ForeignKeyConstraint on "
"table 'a': no column named 'x' is present.",
go,
)
def test_fk_given_non_col(self):
3
Source : test_metadata.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_fk_no_such_target_col_error_upfront(self):
meta = MetaData()
a = Table("a", meta, Column("a", Integer))
Table("b", meta, Column("b", Integer))
a.append_constraint(ForeignKeyConstraint(["a"], ["b.x"]))
assert_raises_message(
exc.NoReferencedColumnError,
"Could not initialize target column for ForeignKey 'b.x' on "
"table 'a': table 'b' has no column named 'x'",
getattr,
list(a.foreign_keys)[0],
"column",
)
def test_fk_no_such_target_col_error_delayed(self):
3
Source : test_metadata.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_fk_no_such_target_col_error_delayed(self):
meta = MetaData()
a = Table("a", meta, Column("a", Integer))
a.append_constraint(ForeignKeyConstraint(["a"], ["b.x"]))
Table("b", meta, Column("b", Integer))
assert_raises_message(
exc.NoReferencedColumnError,
"Could not initialize target column for ForeignKey 'b.x' on "
"table 'a': table 'b' has no column named 'x'",
getattr,
list(a.foreign_keys)[0],
"column",
)
def test_fk_mismatched_local_remote_cols(self):
3
Source : test_metadata.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_foreignkey_constraint_info(self):
fkc = ForeignKeyConstraint(["a"], ["b"], name="bar")
eq_(fkc.info, {})
fkc = ForeignKeyConstraint(
["a"], ["b"], name="bar", info={"foo": "bar"}
)
eq_(fkc.info, {"foo": "bar"})
def test_foreignkey_info(self):
3
Source : test_metadata.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_invalid_composite_fk_check_strings(self):
m = MetaData()
assert_raises_message(
exc.ArgumentError,
r"ForeignKeyConstraint on t1\(x, y\) refers to "
"multiple remote tables: t2 and t3",
Table,
"t1",
m,
Column("x", Integer),
Column("y", Integer),
ForeignKeyConstraint(["x", "y"], ["t2.x", "t3.y"]),
)
def test_invalid_composite_fk_check_columns(self):
3
Source : test_metadata.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_invalid_composite_fk_check_columns(self):
m = MetaData()
t2 = Table("t2", m, Column("x", Integer))
t3 = Table("t3", m, Column("y", Integer))
assert_raises_message(
exc.ArgumentError,
r"ForeignKeyConstraint on t1\(x, y\) refers to "
"multiple remote tables: t2 and t3",
Table,
"t1",
m,
Column("x", Integer),
Column("y", Integer),
ForeignKeyConstraint(["x", "y"], [t2.c.x, t3.c.y]),
)
def test_invalid_composite_fk_check_columns_notattached(self):
3
Source : test_metadata.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_invalid_composite_fk_check_columns_notattached(self):
m = MetaData()
x = Column("x", Integer)
y = Column("y", Integer)
# no error is raised for this one right now.
# which is a minor bug.
Table(
"t1",
m,
Column("x", Integer),
Column("y", Integer),
ForeignKeyConstraint(["x", "y"], [x, y]),
)
Table("t2", m, x)
Table("t3", m, y)
def test_constraint_copied_to_proxy_ok(self):
3
Source : test_metadata.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_auto_append_lowercase_table(self):
from sqlalchemy import table, column
t = table("t", column("a"))
t2 = table("t2", column("a"))
for c in (
UniqueConstraint(t.c.a),
CheckConstraint(t.c.a > 5),
ForeignKeyConstraint([t.c.a], [t2.c.a]),
PrimaryKeyConstraint(t.c.a),
Index("foo", t.c.a),
):
assert True
def test_tometadata_ok(self):
3
Source : test_autogen_diffs.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def setUp(self):
self.metadata = m = MetaData()
t = Table(
"t",
m,
Column("id", Integer(), primary_key=True),
Column("x", Integer()),
)
self.ix = Index("ix1", t.c.id)
fk = ForeignKeyConstraint(["t_id"], ["t.id"])
q = Table("q", m, Column("t_id", Integer()), fk)
self.table = t
self.fk = fk
self.ck = CheckConstraint(t.c.x > 5)
t.append_constraint(self.ck)
self.uq = UniqueConstraint(q.c.t_id)
self.pk = t.primary_key
def test_drop_fk(self):
3
Source : test_autogen_render.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_add_fk_constraint(self):
m = MetaData()
Table("a", m, Column("id", Integer, primary_key=True))
b = Table("b", m, Column("a_id", Integer, ForeignKey("a.id")))
fk = ForeignKeyConstraint(["a_id"], ["a.id"], name="fk_a_id")
b.append_constraint(fk)
op_obj = ops.AddConstraintOp.from_constraint(fk)
eq_ignore_whitespace(
autogenerate.render_op_text(self.autogen_context, op_obj),
"op.create_foreign_key('fk_a_id', 'b', 'a', ['a_id'], ['id'])",
)
def test_add_fk_constraint_batch(self):
3
Source : test_autogen_render.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_add_fk_constraint_batch(self):
m = MetaData()
Table("a", m, Column("id", Integer, primary_key=True))
b = Table("b", m, Column("a_id", Integer, ForeignKey("a.id")))
fk = ForeignKeyConstraint(["a_id"], ["a.id"], name="fk_a_id")
b.append_constraint(fk)
op_obj = ops.AddConstraintOp.from_constraint(fk)
with self.autogen_context._within_batch():
eq_ignore_whitespace(
autogenerate.render_op_text(self.autogen_context, op_obj),
"batch_op.create_foreign_key"
"('fk_a_id', 'a', ['a_id'], ['id'])",
)
def test_add_fk_constraint_kwarg(self):
3
Source : test_autogen_render.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_drop_fk_constraint(self):
m = MetaData()
Table("a", m, Column("id", Integer, primary_key=True))
b = Table("b", m, Column("a_id", Integer, ForeignKey("a.id")))
fk = ForeignKeyConstraint(["a_id"], ["a.id"], name="fk_a_id")
b.append_constraint(fk)
op_obj = ops.DropConstraintOp.from_constraint(fk)
eq_ignore_whitespace(
autogenerate.render_op_text(self.autogen_context, op_obj),
"op.drop_constraint('fk_a_id', 'b', type_='foreignkey')",
)
def test_drop_fk_constraint_batch(self):
3
Source : test_autogen_render.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_drop_fk_constraint_batch(self):
m = MetaData()
Table("a", m, Column("id", Integer, primary_key=True))
b = Table("b", m, Column("a_id", Integer, ForeignKey("a.id")))
fk = ForeignKeyConstraint(["a_id"], ["a.id"], name="fk_a_id")
b.append_constraint(fk)
op_obj = ops.DropConstraintOp.from_constraint(fk)
with self.autogen_context._within_batch():
eq_ignore_whitespace(
autogenerate.render_op_text(self.autogen_context, op_obj),
"batch_op.drop_constraint('fk_a_id', type_='foreignkey')",
)
def test_drop_fk_constraint_schema(self):
3
Source : test_batch.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_drop_fk(self):
impl = self._named_fk_fixture()
fk = ForeignKeyConstraint([], [], name="ufk")
impl.drop_constraint(fk)
new_table = self._assert_impl(
impl,
colnames=["id", "email", "user_id"],
ddl_not_contains="CONSTRANT fk1",
)
eq_(list(new_table.foreign_keys), [])
def test_add_uq(self):
3
Source : test_metadata.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_auto_append_lowercase_table(self):
from sqlalchemy import table, column
t = table("t", column("a"))
t2 = table("t2", column("a"))
for c in (
UniqueConstraint(t.c.a),
CheckConstraint(t.c.a > 5),
ForeignKeyConstraint([t.c.a], [t2.c.a]),
PrimaryKeyConstraint(t.c.a),
Index("foo", t.c.a),
):
assert True
def test_to_metadata_ok(self):
0
Source : util.py
with MIT License
from analyzeDFIR
with MIT License
from analyzeDFIR
def drop_all_tables(engine, inspector, schema=None, include_names=None):
from sqlalchemy import Column, Table, Integer, MetaData, \
ForeignKeyConstraint
from sqlalchemy.schema import DropTable, DropConstraint
if include_names is not None:
include_names = set(include_names)
with engine.connect() as conn:
for tname, fkcs in reversed(
inspector.get_sorted_table_and_fkc_names(schema=schema)):
if tname:
if include_names is not None and tname not in include_names:
continue
conn.execute(DropTable(
Table(tname, MetaData(), schema=schema)
))
elif fkcs:
if not engine.dialect.supports_alter:
continue
for tname, fkc in fkcs:
if include_names is not None and \
tname not in include_names:
continue
tb = Table(
tname, MetaData(),
Column('x', Integer),
Column('y', Integer),
schema=schema
)
conn.execute(DropConstraint(
ForeignKeyConstraint(
[tb.c.x], [tb.c.y], name=fkc)
))
def teardown_events(event_cls):
0
Source : history_meta.py
with MIT License
from cds-snc
with MIT License
from cds-snc
def _history_mapper(local_mapper): # noqa (C901 too complex)
cls = local_mapper.class_
# set the "active_history" flag
# on on column-mapped attributes so that the old version
# of the info is always loaded (currently sets it on all attributes)
for prop in local_mapper.iterate_properties:
getattr(local_mapper.class_, prop.key).impl.active_history = True
super_mapper = local_mapper.inherits
super_history_mapper = getattr(cls, "__history_mapper__", None)
polymorphic_on = None
super_fks = []
def _col_copy(col):
orig = col
col = col.copy()
orig.info["history_copy"] = col
col.unique = False
# if the column is nullable, we could end up overwriting an on-purpose null value with a default.
# if it's not nullable, however, the default may be relied upon to correctly set values within the database,
# so we should preserve it
if col.nullable:
col.default = col.server_default = None
return col
properties = util.OrderedDict()
if not super_mapper or local_mapper.local_table is not super_mapper.local_table:
cols = []
version_meta = {"version_meta": True}
for column in local_mapper.local_table.c:
if _is_versioning_col(column):
continue
col = _col_copy(column)
if super_mapper and col_references_table(column, super_mapper.local_table):
super_fks.append((col.key, list(super_history_mapper.local_table.primary_key)[0]))
cols.append(col)
if column is local_mapper.polymorphic_on:
polymorphic_on = col
orig_prop = local_mapper.get_property_by_column(column)
# carry over column re-mappings
if len(orig_prop.columns) > 1 or orig_prop.columns[0].key != orig_prop.key:
properties[orig_prop.key] = tuple(col.info["history_copy"] for col in orig_prop.columns)
if super_mapper:
super_fks.append(("version", super_history_mapper.local_table.c.version))
# "version" stores the integer version id. This column is
# required.
cols.append(
Column(
"version",
Integer,
primary_key=True,
autoincrement=False,
info=version_meta,
)
)
if super_fks:
cols.append(ForeignKeyConstraint(*zip(*super_fks)))
table = Table(
local_mapper.local_table.name + "_history",
local_mapper.local_table.metadata,
*cols,
schema=local_mapper.local_table.schema,
)
else:
# single table inheritance. take any additional columns that may have
# been added and add them to the history table.
for column in local_mapper.local_table.c:
if column.key not in super_history_mapper.local_table.c:
col = _col_copy(column)
super_history_mapper.local_table.append_column(col)
table = None
if super_history_mapper:
bases = (super_history_mapper.class_,)
if table is not None:
properties["changed"] = (table.c.changed,) + tuple(super_history_mapper.attrs.changed.columns)
else:
bases = local_mapper.base_mapper.class_.__bases__
versioned_cls = type.__new__(type, "%sHistory" % cls.__name__, bases, {})
m = mapper(
versioned_cls,
table,
inherits=super_history_mapper,
polymorphic_on=polymorphic_on,
polymorphic_identity=local_mapper.polymorphic_identity,
properties=properties,
)
cls.__history_mapper__ = m
if not super_history_mapper:
local_mapper.local_table.append_column(Column("version", Integer, default=1, nullable=False))
local_mapper.add_property("version", local_mapper.local_table.c.version)
class Versioned(object):
0
Source : util.py
with MIT License
from dhina016
with MIT License
from dhina016
def drop_all_tables(engine, inspector, schema=None, include_names=None):
from sqlalchemy import (
Column,
Table,
Integer,
MetaData,
ForeignKeyConstraint,
)
from sqlalchemy.schema import DropTable, DropConstraint
if include_names is not None:
include_names = set(include_names)
with engine.connect() as conn:
for tname, fkcs in reversed(
inspector.get_sorted_table_and_fkc_names(schema=schema)
):
if tname:
if include_names is not None and tname not in include_names:
continue
conn.execute(
DropTable(Table(tname, MetaData(), schema=schema))
)
elif fkcs:
if not engine.dialect.supports_alter:
continue
for tname, fkc in fkcs:
if (
include_names is not None
and tname not in include_names
):
continue
tb = Table(
tname,
MetaData(),
Column("x", Integer),
Column("y", Integer),
schema=schema,
)
conn.execute(
DropConstraint(
ForeignKeyConstraint([tb.c.x], [tb.c.y], name=fkc)
)
)
def teardown_events(event_cls):
0
Source : history_meta.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def _history_mapper(local_mapper):
cls = local_mapper.class_
# set the "active_history" flag
# on on column-mapped attributes so that the old version
# of the info is always loaded (currently sets it on all attributes)
for prop in local_mapper.iterate_properties:
getattr(local_mapper.class_, prop.key).impl.active_history = True
super_mapper = local_mapper.inherits
super_history_mapper = getattr(cls, "__history_mapper__", None)
polymorphic_on = None
super_fks = []
def _col_copy(col):
orig = col
col = col.copy()
orig.info["history_copy"] = col
col.unique = False
col.default = col.server_default = None
col.autoincrement = False
return col
properties = util.OrderedDict()
if (
not super_mapper
or local_mapper.local_table is not super_mapper.local_table
):
cols = []
version_meta = {"version_meta": True} # add column.info to identify
# columns specific to versioning
for column in local_mapper.local_table.c:
if _is_versioning_col(column):
continue
col = _col_copy(column)
if super_mapper and col_references_table(
column, super_mapper.local_table
):
super_fks.append(
(
col.key,
list(super_history_mapper.local_table.primary_key)[0],
)
)
cols.append(col)
if column is local_mapper.polymorphic_on:
polymorphic_on = col
orig_prop = local_mapper.get_property_by_column(column)
# carry over column re-mappings
if (
len(orig_prop.columns) > 1
or orig_prop.columns[0].key != orig_prop.key
):
properties[orig_prop.key] = tuple(
col.info["history_copy"] for col in orig_prop.columns
)
if super_mapper:
super_fks.append(
("version", super_history_mapper.local_table.c.version)
)
# "version" stores the integer version id. This column is
# required.
cols.append(
Column(
"version",
Integer,
primary_key=True,
autoincrement=False,
info=version_meta,
)
)
# "changed" column stores the UTC timestamp of when the
# history row was created.
# This column is optional and can be omitted.
cols.append(
Column(
"changed",
DateTime,
default=datetime.datetime.utcnow,
info=version_meta,
)
)
if super_fks:
cols.append(ForeignKeyConstraint(*zip(*super_fks)))
table = Table(
local_mapper.local_table.name + "_history",
local_mapper.local_table.metadata,
*cols,
schema=local_mapper.local_table.schema
)
else:
# single table inheritance. take any additional columns that may have
# been added and add them to the history table.
for column in local_mapper.local_table.c:
if column.key not in super_history_mapper.local_table.c:
col = _col_copy(column)
super_history_mapper.local_table.append_column(col)
table = None
if super_history_mapper:
bases = (super_history_mapper.class_,)
if table is not None:
properties["changed"] = (table.c.changed,) + tuple(
super_history_mapper.attrs.changed.columns
)
else:
bases = local_mapper.base_mapper.class_.__bases__
versioned_cls = type.__new__(type, "%sHistory" % cls.__name__, bases, {})
m = mapper(
versioned_cls,
table,
inherits=super_history_mapper,
polymorphic_on=polymorphic_on,
polymorphic_identity=local_mapper.polymorphic_identity,
properties=properties,
)
cls.__history_mapper__ = m
if not super_history_mapper:
local_mapper.local_table.append_column(
Column("version", Integer, default=1, nullable=False)
)
local_mapper.add_property(
"version", local_mapper.local_table.c.version
)
if cls.use_mapper_versioning:
local_mapper.version_id_col = local_mapper.local_table.c.version
class Versioned(object):
0
Source : test_reflection.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_oracle_has_no_on_update_cascade(self):
bar = Table(
"bar",
self.metadata,
Column("id", Integer, primary_key=True),
Column(
"foo_id", Integer, ForeignKey("foo.id", onupdate="CASCADE")
),
)
assert_raises(exc.SAWarning, bar.create)
bat = Table(
"bat",
self.metadata,
Column("id", Integer, primary_key=True),
Column("foo_id", Integer),
ForeignKeyConstraint(["foo_id"], ["foo.id"], onupdate="CASCADE"),
)
assert_raises(exc.SAWarning, bat.create)
def test_reflect_check_include_all(self):
0
Source : test_basic.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_table_args_tuple_format(self):
class Foo2(Base):
__tablename__ = "foo"
__table_args__ = {"mysql_engine": "InnoDB"}
id = Column("id", Integer, primary_key=True)
class Bar(Base):
__tablename__ = "bar"
__table_args__ = (
ForeignKeyConstraint(["id"], ["foo.id"]),
{"mysql_engine": "InnoDB"},
)
id = Column("id", Integer, primary_key=True)
assert Bar.__table__.c.id.references(Foo2.__table__.c.id)
assert Bar.__table__.kwargs["mysql_engine"] == "InnoDB"
def test_table_cls_attribute(self):
0
Source : test_lazy_relations.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def define_tables(cls, metadata):
Table(
"a",
metadata,
Column("id1", Integer, primary_key=True),
Column("id2", Integer, primary_key=True),
)
Table(
"b_sameorder",
metadata,
Column("id", Integer, primary_key=True),
Column("a_id1", Integer),
Column("a_id2", Integer),
ForeignKeyConstraint(["a_id1", "a_id2"], ["a.id1", "a.id2"]),
)
Table(
"b_differentorder",
metadata,
Column("id", Integer, primary_key=True),
Column("a_id1", Integer),
Column("a_id2", Integer),
ForeignKeyConstraint(["a_id1", "a_id2"], ["a.id1", "a.id2"]),
)
@classmethod
0
Source : test_relationships.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def _fixture_one(
self,
add_b_a=False,
add_b_a_viewonly=False,
add_b_amember=False,
add_bsub1_a=False,
add_bsub2_a_viewonly=False,
):
Base = declarative_base(metadata=self.metadata)
class A(Base):
__tablename__ = "a"
id = Column(Integer, primary_key=True)
a_members = relationship("AMember", backref="a")
class AMember(Base):
__tablename__ = "a_member"
a_id = Column(Integer, ForeignKey("a.id"), primary_key=True)
a_member_id = Column(Integer, primary_key=True)
class B(Base):
__tablename__ = "b"
__mapper_args__ = {"polymorphic_on": "type"}
id = Column(Integer, primary_key=True)
type = Column(String(20))
a_id = Column(Integer, ForeignKey("a.id"), nullable=False)
a_member_id = Column(Integer)
__table_args__ = (
ForeignKeyConstraint(
("a_id", "a_member_id"),
("a_member.a_id", "a_member.a_member_id"),
),
)
# if added and viewonly is not true, this relationship
# writes to B.a_id, which conflicts with BSub2.a_member,
# so should warn
if add_b_a:
a = relationship("A", viewonly=add_b_a_viewonly)
# if added, this relationship writes to B.a_id, which conflicts
# with BSub1.a
if add_b_amember:
a_member = relationship("AMember")
# however, *no* warning should be emitted otherwise.
class BSub1(B):
if add_bsub1_a:
a = relationship("A")
__mapper_args__ = {"polymorphic_identity": "bsub1"}
class BSub2(B):
if add_bsub2_a_viewonly:
a = relationship("A", viewonly=True)
a_member = relationship("AMember")
__mapper_args__ = {"polymorphic_identity": "bsub2"}
configure_mappers()
self.metadata.create_all()
return A, AMember, B, BSub1, BSub2
@testing.provide_metadata
0
Source : test_relationships.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def define_tables(cls, metadata):
Table(
"company_t",
metadata,
Column(
"company_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("name", String(30)),
)
Table(
"employee_t",
metadata,
Column("company_id", Integer, primary_key=True),
Column("emp_id", Integer, primary_key=True),
Column("name", String(30)),
Column("reports_to_id", Integer),
sa.ForeignKeyConstraint(["company_id"], ["company_t.company_id"]),
sa.ForeignKeyConstraint(
["company_id", "reports_to_id"],
["employee_t.company_id", "employee_t.emp_id"],
),
)
@classmethod
0
Source : test_relationships.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def define_tables(cls, metadata):
Table(
"parent",
metadata,
Column("x", Integer, primary_key=True),
Column("y", Integer, primary_key=True),
Column("z", Integer),
)
Table(
"child",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("x", Integer),
Column("y", Integer),
Column("z", Integer),
# note 'z' is not here
sa.ForeignKeyConstraint(["x", "y"], ["parent.x", "parent.y"]),
)
@classmethod
0
Source : test_rel_fn.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def setup_class(cls):
m = MetaData()
cls.left = Table(
"lft",
m,
Column("id", Integer, primary_key=True),
Column("x", Integer),
Column("y", Integer),
)
cls.right = Table(
"rgt",
m,
Column("id", Integer, primary_key=True),
Column("lid", Integer, ForeignKey("lft.id")),
Column("x", Integer),
Column("y", Integer),
)
cls.right_multi_fk = Table(
"rgt_multi_fk",
m,
Column("id", Integer, primary_key=True),
Column("lid1", Integer, ForeignKey("lft.id")),
Column("lid2", Integer, ForeignKey("lft.id")),
)
cls.selfref = Table(
"selfref",
m,
Column("id", Integer, primary_key=True),
Column("sid", Integer, ForeignKey("selfref.id")),
)
cls.composite_selfref = Table(
"composite_selfref",
m,
Column("id", Integer, primary_key=True),
Column("group_id", Integer, primary_key=True),
Column("parent_id", Integer),
ForeignKeyConstraint(
["parent_id", "group_id"],
["composite_selfref.id", "composite_selfref.group_id"],
),
)
cls.m2mleft = Table(
"m2mlft", m, Column("id", Integer, primary_key=True)
)
cls.m2mright = Table(
"m2mrgt", m, Column("id", Integer, primary_key=True)
)
cls.m2msecondary = Table(
"m2msecondary",
m,
Column("lid", Integer, ForeignKey("m2mlft.id"), primary_key=True),
Column("rid", Integer, ForeignKey("m2mrgt.id"), primary_key=True),
)
cls.m2msecondary_no_fks = Table(
"m2msecondary_no_fks",
m,
Column("lid", Integer, primary_key=True),
Column("rid", Integer, primary_key=True),
)
cls.m2msecondary_ambig_fks = Table(
"m2msecondary_ambig_fks",
m,
Column("lid1", Integer, ForeignKey("m2mlft.id"), primary_key=True),
Column("rid1", Integer, ForeignKey("m2mrgt.id"), primary_key=True),
Column("lid2", Integer, ForeignKey("m2mlft.id"), primary_key=True),
Column("rid2", Integer, ForeignKey("m2mrgt.id"), primary_key=True),
)
cls.base_w_sub_rel = Table(
"base_w_sub_rel",
m,
Column("id", Integer, primary_key=True),
Column("sub_id", Integer, ForeignKey("rel_sub.id")),
)
cls.rel_sub = Table(
"rel_sub",
m,
Column(
"id",
Integer,
ForeignKey("base_w_sub_rel.id"),
primary_key=True,
),
)
cls.base = Table(
"base",
m,
Column("id", Integer, primary_key=True),
Column("flag", Boolean),
)
cls.sub = Table(
"sub",
m,
Column("id", Integer, ForeignKey("base.id"), primary_key=True),
)
cls.sub_w_base_rel = Table(
"sub_w_base_rel",
m,
Column("id", Integer, ForeignKey("base.id"), primary_key=True),
Column("base_id", Integer, ForeignKey("base.id")),
)
cls.sub_w_sub_rel = Table(
"sub_w_sub_rel",
m,
Column("id", Integer, ForeignKey("base.id"), primary_key=True),
Column("sub_id", Integer, ForeignKey("sub.id")),
)
cls.right_w_base_rel = Table(
"right_w_base_rel",
m,
Column("id", Integer, primary_key=True),
Column("base_id", Integer, ForeignKey("base.id")),
)
cls.three_tab_a = Table(
"three_tab_a", m, Column("id", Integer, primary_key=True)
)
cls.three_tab_b = Table(
"three_tab_b",
m,
Column("id", Integer, primary_key=True),
Column("aid", Integer, ForeignKey("three_tab_a.id")),
)
cls.three_tab_c = Table(
"three_tab_c",
m,
Column("id", Integer, primary_key=True),
Column("aid", Integer, ForeignKey("three_tab_a.id")),
Column("bid", Integer, ForeignKey("three_tab_b.id")),
)
cls.composite_target = Table(
"composite_target",
m,
Column("uid", Integer, primary_key=True),
Column("oid", Integer, primary_key=True),
)
cls.composite_multi_ref = Table(
"composite_multi_ref",
m,
Column("uid1", Integer),
Column("uid2", Integer),
Column("oid", Integer),
ForeignKeyConstraint(
("uid1", "oid"),
("composite_target.uid", "composite_target.oid"),
),
ForeignKeyConstraint(
("uid2", "oid"),
("composite_target.uid", "composite_target.oid"),
),
)
cls.purely_single_col = Table(
"purely_single_col", m, Column("path", String)
)
def _join_fixture_overlapping_three_tables(self, **kw):
0
Source : test_selectin_relations.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def setup_classes(cls):
Base = cls.DeclarativeBasic
class A(fixtures.ComparableEntity, Base):
__tablename__ = "a"
id1 = Column(Integer, primary_key=True)
id2 = Column(Integer, primary_key=True)
bs = relationship("B", order_by="B.id", back_populates="a")
class B(fixtures.ComparableEntity, Base):
__tablename__ = "b"
id = Column(Integer, primary_key=True)
a_id1 = Column()
a_id2 = Column()
a = relationship("A", back_populates="bs")
__table_args__ = (
ForeignKeyConstraint(["a_id1", "a_id2"], ["a.id1", "a.id2"]),
)
@classmethod
0
Source : test_unitofwork.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def define_tables(cls, metadata):
Table(
"mytable",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("data", String(30)),
test_needs_fk=True,
)
Table(
"myothertable",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("parent_id", Integer),
Column("data", String(30)),
sa.ForeignKeyConstraint(
["parent_id"], ["mytable.id"], ondelete="CASCADE"
),
test_needs_fk=True,
)
@classmethod
0
Source : test_unitofwork.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def define_tables(cls, metadata):
Table(
"mytable",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("data", String(30)),
test_needs_fk=True,
)
Table(
"myothertable",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("parent_id", Integer),
Column("data", String(30)),
# no CASCADE, the same as ON DELETE RESTRICT
sa.ForeignKeyConstraint(["parent_id"], ["mytable.id"]),
test_needs_fk=True,
)
@classmethod
0
Source : test_constraints.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_pk_fk_constraint_create(self):
metadata = self.metadata
Table(
"employees",
metadata,
Column("id", Integer),
Column("soc", String(40)),
Column("name", String(30)),
PrimaryKeyConstraint("id", "soc"),
)
Table(
"elements",
metadata,
Column("id", Integer),
Column("stuff", String(30)),
Column("emp_id", Integer),
Column("emp_soc", String(40)),
PrimaryKeyConstraint("id", name="elements_primkey"),
ForeignKeyConstraint(
["emp_id", "emp_soc"], ["employees.id", "employees.soc"]
),
)
self.assert_sql_execution(
testing.db,
lambda: metadata.create_all(checkfirst=False),
CompiledSQL(
"CREATE TABLE employees ("
"id INTEGER NOT NULL, "
"soc VARCHAR(40) NOT NULL, "
"name VARCHAR(30), "
"PRIMARY KEY (id, soc)"
")"
),
CompiledSQL(
"CREATE TABLE elements ("
"id INTEGER NOT NULL, "
"stuff VARCHAR(30), "
"emp_id INTEGER, "
"emp_soc VARCHAR(40), "
"CONSTRAINT elements_primkey PRIMARY KEY (id), "
"FOREIGN KEY(emp_id, emp_soc) "
"REFERENCES employees (id, soc)"
")"
),
)
@testing.force_drop_names("a", "b")
0
Source : test_constraints.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_fk_cant_drop_cycled_unnamed(self):
metadata = MetaData()
Table(
"a",
metadata,
Column("id", Integer, primary_key=True),
Column("bid", Integer),
ForeignKeyConstraint(["bid"], ["b.id"]),
)
Table(
"b",
metadata,
Column("id", Integer, primary_key=True),
Column("aid", Integer),
ForeignKeyConstraint(["aid"], ["a.id"]),
)
metadata.create_all(testing.db)
if testing.db.dialect.supports_alter:
assert_raises_message(
exc.CircularDependencyError,
"Can't sort tables for DROP; an unresolvable foreign key "
"dependency exists between tables: a, b. Please ensure "
"that the ForeignKey and ForeignKeyConstraint objects "
"involved in the cycle have names so that they can be "
"dropped using DROP CONSTRAINT.",
metadata.drop_all,
testing.db,
)
else:
with expect_warnings(
"Can't sort tables for DROP; an unresolvable "
"foreign key dependency "
):
with self.sql_execution_asserter() as asserter:
metadata.drop_all(testing.db, checkfirst=False)
asserter.assert_(
AllOf(CompiledSQL("DROP TABLE a"), CompiledSQL("DROP TABLE b"))
)
@testing.provide_metadata
0
Source : test_constraints.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_fk_table_auto_alter_constraint_create(self):
metadata = self.metadata
Table(
"a",
metadata,
Column("id", Integer, primary_key=True),
Column("bid", Integer),
ForeignKeyConstraint(["bid"], ["b.id"]),
)
Table(
"b",
metadata,
Column("id", Integer, primary_key=True),
Column("aid", Integer),
ForeignKeyConstraint(["aid"], ["a.id"], name="bfk"),
)
self._assert_cyclic_constraint(
metadata, auto=True, sqlite_warning=True
)
@testing.provide_metadata
0
Source : test_constraints.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_fk_table_use_alter_constraint_create(self):
metadata = self.metadata
Table(
"a",
metadata,
Column("id", Integer, primary_key=True),
Column("bid", Integer),
ForeignKeyConstraint(["bid"], ["b.id"]),
)
Table(
"b",
metadata,
Column("id", Integer, primary_key=True),
Column("aid", Integer),
ForeignKeyConstraint(
["aid"], ["a.id"], use_alter=True, name="bfk"
),
)
self._assert_cyclic_constraint(metadata)
@testing.provide_metadata
0
Source : test_constraints.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_create_table_omit_fks(self):
fkcs = [
ForeignKeyConstraint(["a"], ["remote.id"], name="foo"),
ForeignKeyConstraint(["b"], ["remote.id"], name="bar"),
ForeignKeyConstraint(["c"], ["remote.id"], name="bat"),
]
m = MetaData()
t = Table(
"t",
m,
Column("a", Integer),
Column("b", Integer),
Column("c", Integer),
*fkcs
)
Table("remote", m, Column("id", Integer, primary_key=True))
self.assert_compile(
schema.CreateTable(t, include_foreign_key_constraints=[]),
"CREATE TABLE t (a INTEGER, b INTEGER, c INTEGER)",
)
self.assert_compile(
schema.CreateTable(t, include_foreign_key_constraints=fkcs[0:2]),
"CREATE TABLE t (a INTEGER, b INTEGER, c INTEGER, "
"CONSTRAINT foo FOREIGN KEY(a) REFERENCES remote (id), "
"CONSTRAINT bar FOREIGN KEY(b) REFERENCES remote (id))",
)
def test_deferrable_unique(self):
0
Source : test_metadata.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_fk_copy(self):
c1 = Column("foo", Integer)
c2 = Column("bar", Integer)
m = MetaData()
t1 = Table("t", m, c1, c2)
kw = dict(
onupdate="X",
ondelete="Y",
use_alter=True,
name="f1",
deferrable="Z",
initially="Q",
link_to_name=True,
)
fk1 = ForeignKey(c1, **kw)
fk2 = ForeignKeyConstraint((c1,), (c2,), **kw)
t1.append_constraint(fk2)
fk1c = fk1.copy()
fk2c = fk2.copy()
for k in kw:
eq_(getattr(fk1c, k), kw[k])
eq_(getattr(fk2c, k), kw[k])
def test_check_constraint_copy(self):
0
Source : test_metadata.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_foreign_key_constraints_collection(self):
metadata = MetaData()
t1 = Table("foo", metadata, Column("a", Integer))
eq_(t1.foreign_key_constraints, set())
fk1 = ForeignKey("q.id")
fk2 = ForeignKey("j.id")
fk3 = ForeignKeyConstraint(["b", "c"], ["r.x", "r.y"])
t1.append_column(Column("b", Integer, fk1))
eq_(t1.foreign_key_constraints, set([fk1.constraint]))
t1.append_column(Column("c", Integer, fk2))
eq_(t1.foreign_key_constraints, set([fk1.constraint, fk2.constraint]))
t1.append_constraint(fk3)
eq_(
t1.foreign_key_constraints,
set([fk1.constraint, fk2.constraint, fk3]),
)
def test_c_immutable(self):
0
Source : test_metadata.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_type_propagate_composite_fk_string(self):
metadata = MetaData()
Table(
"a",
metadata,
Column("key1", Integer, primary_key=True),
Column("key2", String(40), primary_key=True),
)
b = Table(
"b",
metadata,
Column("a_key1", None),
Column("a_key2", None),
Column("id", Integer, primary_key=True),
ForeignKeyConstraint(["a_key1", "a_key2"], ["a.key1", "a.key2"]),
)
assert isinstance(b.c.a_key1.type, Integer)
assert isinstance(b.c.a_key2.type, String)
def test_type_propagate_composite_fk_col(self):
0
Source : test_metadata.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_type_propagate_composite_fk_col(self):
metadata = MetaData()
a = Table(
"a",
metadata,
Column("key1", Integer, primary_key=True),
Column("key2", String(40), primary_key=True),
)
b = Table(
"b",
metadata,
Column("a_key1", None),
Column("a_key2", None),
Column("id", Integer, primary_key=True),
ForeignKeyConstraint(["a_key1", "a_key2"], [a.c.key1, a.c.key2]),
)
assert isinstance(b.c.a_key1.type, Integer)
assert isinstance(b.c.a_key2.type, String)
def test_type_propagate_standalone_fk_string(self):
0
Source : test_metadata.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_auto_append_constraint(self):
m = MetaData()
t = Table("tbl", m, Column("a", Integer), Column("b", Integer))
t2 = Table("t2", m, Column("a", Integer), Column("b", Integer))
for c in (
UniqueConstraint(t.c.a),
CheckConstraint(t.c.a > 5),
ForeignKeyConstraint([t.c.a], [t2.c.a]),
PrimaryKeyConstraint(t.c.a),
):
assert c in t.constraints
t.append_constraint(c)
assert c in t.constraints
c = Index("foo", t.c.a)
assert c in t.indexes
def test_auto_append_lowercase_table(self):
0
Source : test_metadata.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_tometadata_ok(self):
m = MetaData()
t = Table("tbl", m, Column("a", Integer), Column("b", Integer))
t2 = Table("t2", m, Column("a", Integer), Column("b", Integer))
UniqueConstraint(t.c.a)
CheckConstraint(t.c.a > 5)
ForeignKeyConstraint([t.c.a], [t2.c.a])
PrimaryKeyConstraint(t.c.a)
m2 = MetaData()
t3 = t.tometadata(m2)
eq_(len(t3.constraints), 4)
for c in t3.constraints:
assert c.table is t3
def test_check_constraint_copy(self):
See More Examples