sqlalchemy.UniqueConstraint

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

75 Examples 7

Example 1

Project: lux
Source File: models.py
View license
    @odm.declared_attr
    def __table_args__(cls):
        name = cls.__name__.lower()
        if name == 'entity':
            return odm.table_args(
                oauth.User,
                UniqueConstraint(
                    'application_id',
                    'username',
                    name='_entity_app_username'
                ),
                UniqueConstraint(
                    'application_id',
                    'email',
                    name='_entity_app_email'
                )
            )
        else:
            return odm.table_args(oauth.User)

Example 2

Project: lux
Source File: models.py
View license
    @odm.declared_attr
    def __table_args__(cls):
        return (
            UniqueConstraint(
                'application_id',
                'name',
                'organisation_id',
                name='_group_app_name'
            ),
        )

Example 3

Project: lux
Source File: models.py
View license
    @odm.declared_attr
    def __table_args__(cls):
        return (
            UniqueConstraint(
                'application_id',
                'name',
                name='_perm_app_name'
            ),
        )

Example 4

Project: lux
Source File: models.py
View license
    @odm.declared_attr
    def __table_args__(cls):
        return (
            UniqueConstraint(
                'application_id',
                'email',
                'topic',
                name='_app_email_topic'
            ),
        )

Example 5

Project: alembic
Source File: test_autogen_indexes.py
View license
    def test_mismatch_db_named_col_flag(self):
        m1 = MetaData()
        m2 = MetaData()
        Table('item', m1,
              Column('x', Integer),
              UniqueConstraint('x', name="db_generated_name")
              )

        # test mismatch between unique=True and
        # named uq constraint
        Table('item', m2,
              Column('x', Integer, unique=True)
              )

        diffs = self._fixture(m1, m2)

        eq_(diffs, [])

Example 6

Project: alembic
Source File: test_autogen_indexes.py
View license
    def test_nothing_changed_unique_w_colkeys(self):
        m1 = MetaData()
        m2 = MetaData()

        Table('nothing_changed', m1,
              Column('x', String(20), key='nx'),
              UniqueConstraint('nx')
              )

        Table('nothing_changed', m2,
              Column('x', String(20), key='nx'),
              UniqueConstraint('nx')
              )

        diffs = self._fixture(m1, m2)
        eq_(diffs, [])

Example 7

Project: alembic
Source File: test_autogen_indexes.py
View license
    def test_uq_added_schema(self):
        m1 = MetaData()
        m2 = MetaData()
        Table('add_uq', m1, Column('x', String(50)), schema="test_schema")
        Table('add_uq', m2, Column('x', String(50)),
              UniqueConstraint('x', name='ix_1'), schema="test_schema")

        diffs = self._fixture(m1, m2, include_schemas=True)
        eq_(diffs[0][0], "add_constraint")
        eq_(diffs[0][1].name, 'ix_1')

Example 8

Project: alembic
Source File: test_autogen_indexes.py
View license
    def test_uq_unchanged_schema(self):
        m1 = MetaData()
        m2 = MetaData()
        Table('add_uq', m1, Column('x', String(50)),
              UniqueConstraint('x', name='ix_1'),
              schema="test_schema")
        Table('add_uq', m2, Column('x', String(50)),
              UniqueConstraint('x', name='ix_1'),
              schema="test_schema")

        diffs = self._fixture(m1, m2, include_schemas=True)
        eq_(diffs, [])

Example 9

Project: alembic
Source File: test_autogen_indexes.py
View license
    def test_uq_dropped(self):
        m1 = MetaData()
        m2 = MetaData()
        Table(
            'add_uq', m1,
            Column('id', Integer, primary_key=True),
            Column('name', String),
            UniqueConstraint('name', name='uq_name')
        )
        Table(
            'add_uq', m2,
            Column('id', Integer, primary_key=True),
            Column('name', String),
        )
        diffs = self._fixture(m1, m2, include_schemas=True)
        eq_(diffs[0][0], "remove_constraint")
        eq_(diffs[0][1].name, "uq_name")
        eq_(len(diffs), 1)

Example 10

Project: alembic
Source File: test_autogen_indexes.py
View license
    def test_unique_not_reported(self):
        m1 = MetaData()
        Table('order', m1,
              Column('order_id', Integer, primary_key=True),
              Column('amount', Numeric(10, 2), nullable=True),
              Column('user_id', Integer),
              UniqueConstraint('order_id', 'user_id',
                               name='order_order_id_user_id_unique'
                               )
              )

        diffs = self._fixture(m1, m1)
        eq_(diffs, [])

Example 11

Project: alembic
Source File: test_batch.py
View license
    def _uq_fixture(self, table_args=(), table_kwargs={}):
        m = MetaData()
        t = Table(
            'tname', m,
            Column('id', Integer, primary_key=True),
            Column('x', String()),
            Column('y', Integer),
            UniqueConstraint('y', name='uq1')
        )
        return ApplyBatchImpl(t, table_args, table_kwargs, False)

Example 12

Project: sqlalchemy
Source File: test_compiler.py
View license
    def test_table_uc_explicit_nonclustered(self):
        metadata = MetaData()
        tbl = Table('test', metadata,
                    Column('x', Integer, autoincrement=False),
                    Column('y', Integer, autoincrement=False),
                    UniqueConstraint("x", "y", mssql_clustered=False))
        self.assert_compile(
            schema.CreateTable(tbl),
            "CREATE TABLE test (x INTEGER NULL, y INTEGER NULL, "
            "UNIQUE NONCLUSTERED (x, y))"
        )

Example 13

Project: sqlalchemy
Source File: test_compiler.py
View license
    def test_table_uc_clustering(self):
        metadata = MetaData()
        tbl = Table('test', metadata,
                    Column('x', Integer, autoincrement=False),
                    Column('y', Integer, autoincrement=False),
                    PrimaryKeyConstraint("x"),
                    UniqueConstraint("y", mssql_clustered=True))
        self.assert_compile(
            schema.CreateTable(tbl),
            "CREATE TABLE test (x INTEGER NOT NULL, y INTEGER NULL, "
            "PRIMARY KEY (x), UNIQUE CLUSTERED (y))"
        )

Example 14

Project: sqlalchemy
Source File: test_constraints.py
View license
    def test_empty_uc(self):
        # test that an empty constraint is ignored
        metadata = MetaData()
        tbl = Table('test', metadata,
                    Column('x', Integer, autoincrement=False),
                    Column('y', Integer, autoincrement=False),
                    UniqueConstraint())
        self.assert_compile(schema.CreateTable(tbl),
                            "CREATE TABLE test (x INTEGER, y INTEGER)"
                            )

Example 15

Project: sqlalchemy
Source File: test_constraints.py
View license
    def test_render_add_uq_constraint_stringcol(self):
        t, t2 = self._constraint_create_fixture()

        constraint = UniqueConstraint("a", "b", name="uq_cst")
        t2.append_constraint(constraint)
        self.assert_compile(
            schema.AddConstraint(constraint),
            "ALTER TABLE t2 ADD CONSTRAINT uq_cst UNIQUE (a, b)"
        )

Example 16

Project: sqlalchemy
Source File: test_constraints.py
View license
    def test_render_add_uq_constraint_realcol(self):
        t, t2 = self._constraint_create_fixture()

        constraint = UniqueConstraint(t2.c.a, t2.c.b, name="uq_cs2")
        self.assert_compile(
            schema.AddConstraint(constraint),
            "ALTER TABLE t2 ADD CONSTRAINT uq_cs2 UNIQUE (a, b)"
        )

Example 17

Project: kairos
Source File: sql_backend.py
View license
  def __init__(self, *a, **kwargs):
    # TODO: define indices
    # TODO: optionally create separate tables for each interval, like mongo?
    self._table_name = 'histogram'
    super(SqlHistogram,self).__init__(*a, **kwargs)
    self._table = Table(self._table_name, self._metadata,
      Column('name', String(self._str_length), nullable=False),      # stat name
      Column('interval', String(self._str_length), nullable=False),  # interval name
      Column('i_time', Integer, nullable=False),        # interval timestamp
      Column('r_time', Integer, nullable=True),         # resolution timestamp
      Column('value', self._value_type, nullable=False),           # histogram keys
      Column('count', Integer, nullable=False),         # key counts

      # Use a constraint for transaction-less insert vs update
      UniqueConstraint('name', 'interval', 'i_time', 'r_time', 'value', name='unique_value')
    )
    self._metadata.create_all(self._client)

Example 18

Project: kairos
Source File: sql_backend.py
View license
  def __init__(self, *a, **kwargs):
    # TODO: define indices
    # TODO: optionally create separate tables for each interval, like mongo?
    self._table_name = 'count'
    super(SqlCount,self).__init__(*a, **kwargs)
    self._table = Table(self._table_name, self._metadata,
      Column('name', String(self._str_length), nullable=False),      # stat name
      Column('interval', String(self._str_length), nullable=False),  # interval name
      Column('i_time', Integer, nullable=False),        # interval timestamp
      Column('r_time', Integer, nullable=True),         # resolution timestamp
      Column('count', Integer, nullable=False),         # key counts

      # Use a constraint for transaction-less insert vs update
      UniqueConstraint('name', 'interval', 'i_time', 'r_time', name='unique_count')
    )
    self._metadata.create_all(self._client)

Example 19

Project: kairos
Source File: sql_backend.py
View license
  def __init__(self, *a, **kwargs):
    # TODO: define indices
    # TODO: optionally create separate tables for each interval, like mongo?
    self._table_name = 'gauge'
    super(SqlGauge,self).__init__(*a, **kwargs)
    self._table = Table(self._table_name, self._metadata,
      Column('name', String(self._str_length), nullable=False),      # stat name
      Column('interval', String(self._str_length), nullable=False),  # interval name
      Column('i_time', Integer, nullable=False),        # interval timestamp
      Column('r_time', Integer, nullable=True),         # resolution timestamp
      Column('value', self._value_type, nullable=False),           # key counts

      # Use a constraint for transaction-less insert vs update
      UniqueConstraint('name', 'interval', 'i_time', 'r_time', name='unique_count')
    )
    self._metadata.create_all(self._client)

Example 20

Project: guardrail
Source File: sqlalchemy.py
View license
    def _make_schema_dict(self, agent, target):
        return dict(
            __tablename__=self._make_table_name(agent, target),
            __table_args__=(
                sa.UniqueConstraint('agent_id', 'target_id', 'permission'),
            ),
            id=sa.Column(sa.Integer, primary_key=True),
            agent_id=_reference_column(agent, nullable=False, index=True),
            agent=sa.orm.relationship(agent),
            target_id=_reference_column(target, nullable=False, index=True),
            target=sa.orm.relationship(target),
            permission=sa.Column(sa.String, nullable=False, index=True),
        )

Example 21

Project: guardrail
Source File: sqlalchemy.py
View license
    def _make_schema_dict(self, agent, target):
        return dict(
            __tablename__=self._make_table_name(agent, target),
            __table_args__=(
                sa.UniqueConstraint('agent_id', 'target_id', 'permission'),
            ),
            id=sa.Column(sa.Integer, primary_key=True),
            agent_id=_reference_column(agent, nullable=False, index=True),
            agent=sa.orm.relationship(agent),
            target_id=_reference_column(target, nullable=False, index=True),
            target=sa.orm.relationship(target),
            permission=sa.Column(sa.String, nullable=False, index=True),
        )

Example 22

Project: DataGristle
Source File: test_simplesql.py
View license
    def table_create(self):
        self._table_name = 'person'
        self.person = Table(self._table_name    ,
                        self.metadata           ,
                        Column('id'             ,
                               Integer          ,
                               nullable=False   ,
                               primary_key=True),
                        Column('person_name'    ,
                               String(40)       ,
                               nullable=False)  ,
                        Column('person_desc'    ,
                               String(255)      ,
                               nullable=False)  ,
                        UniqueConstraint('person_name', name='person_uk1'))
        self._table      = self.person
        return self._table

Example 23

Project: DataGristle
Source File: test_simplesql.py
View license
    def table_create(self):
        self._table_name = 'person'
        self.person = Table(self._table_name    ,
                        self.metadata           ,
                        Column('id'             ,
                               Integer          ,
                               nullable=False   ,
                               primary_key=True),
                        Column('person_name'    ,
                               String(40)       ,
                               nullable=False)  ,
                        Column('person_desc'    ,
                               String(255)      ,
                               nullable=False)  ,
                        UniqueConstraint('person_name', name='person_uk1'))
        self._table      = self.person
        return self._table

Example 24

Project: iktomi
Source File: declarative.py
View license
    def test_positional(self):
        args = {'dialect1_a': 11, 'dialect2_b': 12}
        Base = declarative_base(name='Base', metaclass=TableArgsMeta(args))
        class A(Base):
            __tablename__ = 'A'
            id = Column(Integer)
            data = Column(Integer)
            __table_args__ = (
                PrimaryKeyConstraint(id),
                UniqueConstraint(data),
            )
        self.assertEqual(len(A.__table_args__), 3)
        self.assertIsInstance(A.__table_args__[0], PrimaryKeyConstraint)
        self.assertIsInstance(A.__table_args__[1], UniqueConstraint)
        self.assertEqual(A.__table_args__[2], args)
        class B(Base):
            __tablename__ = 'B'
            id = Column(Integer, primary_key=True)
            data = Column(Integer)
            __table_args__ = (
                PrimaryKeyConstraint(id),
                UniqueConstraint(id),
                {'dialect2_b': 22,
                 'dialect3_c': 23},
            )
        self.assertEqual(len(B.__table_args__), 3)
        self.assertIsInstance(B.__table_args__[0], PrimaryKeyConstraint)
        self.assertIsInstance(B.__table_args__[1], UniqueConstraint)
        self.assertEqual(B.__table_args__[2], {'dialect1_a': 11,
                                               'dialect2_b': 22,
                                               'dialect3_c': 23})

Example 25

Project: alembic
Source File: test_autogen_diffs.py
View license
    @classmethod
    def _get_model_schema(cls):
        schema = cls.schema

        m = MetaData(schema=schema)

        Table('user', m,
              Column('id', Integer, primary_key=True),
              Column('name', String(50), nullable=False),
              Column('a1', Text, server_default="x")
              )

        Table('address', m,
              Column('id', Integer, primary_key=True),
              Column('email_address', String(100), nullable=False),
              Column('street', String(50)),
              UniqueConstraint('email_address', name="uq_email")
              )

        Table('order', m,
              Column('order_id', Integer, primary_key=True),
              Column('amount', Numeric(10, 2), nullable=True,
                     server_default=text("0")),
              Column('user_id', Integer, ForeignKey('user.id')),
              CheckConstraint('amount > -1', name='ck_order_amount'),
              )

        Table('item', m,
              Column('id', Integer, primary_key=True),
              Column('description', String(100)),
              Column('order_id', Integer, ForeignKey('order.order_id')),
              CheckConstraint('len(description) > 5')
              )
        return m

Example 26

Project: alembic
Source File: test_autogen_diffs.py
View license
    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

Example 27

Project: alembic
Source File: test_autogen_indexes.py
View license
    def test_index_flag_becomes_named_unique_constraint(self):
        m1 = MetaData()
        m2 = MetaData()

        Table('user', m1,
              Column('id', Integer, primary_key=True),
              Column('name', String(50), nullable=False, index=True),
              Column('a1', String(10), server_default="x")
              )

        Table('user', m2,
              Column('id', Integer, primary_key=True),
              Column('name', String(50), nullable=False),
              Column('a1', String(10), server_default="x"),
              UniqueConstraint("name", name="uq_user_name")
              )

        diffs = self._fixture(m1, m2)

        if self.reports_unique_constraints:
            eq_(diffs[0][0], "add_constraint")
            eq_(diffs[0][1].name, "uq_user_name")

            eq_(diffs[1][0], "remove_index")
            eq_(diffs[1][1].name, "ix_user_name")
        else:
            eq_(diffs[0][0], "remove_index")
            eq_(diffs[0][1].name, "ix_user_name")

Example 28

Project: alembic
Source File: test_autogen_indexes.py
View license
    def test_add_unique_constraint(self):
        m1 = MetaData()
        m2 = MetaData()
        Table('address', m1,
              Column('id', Integer, primary_key=True),
              Column('email_address', String(100), nullable=False),
              Column('qpr', String(10), index=True),
              )
        Table('address', m2,
              Column('id', Integer, primary_key=True),
              Column('email_address', String(100), nullable=False),
              Column('qpr', String(10), index=True),
              UniqueConstraint("email_address", name="uq_email_address")
              )

        diffs = self._fixture(m1, m2)

        if self.reports_unique_constraints:
            eq_(diffs[0][0], "add_constraint")
            eq_(diffs[0][1].name, "uq_email_address")
        else:
            eq_(diffs, [])

Example 29

Project: alembic
Source File: test_autogen_indexes.py
View license
    def test_index_becomes_unique(self):
        m1 = MetaData()
        m2 = MetaData()
        Table('order', m1,
              Column('order_id', Integer, primary_key=True),
              Column('amount', Numeric(10, 2), nullable=True),
              Column('user_id', Integer),
              UniqueConstraint('order_id', 'user_id',
                               name='order_order_id_user_id_unique'
                               ),
              Index('order_user_id_amount_idx', 'user_id', 'amount')
              )

        Table('order', m2,
              Column('order_id', Integer, primary_key=True),
              Column('amount', Numeric(10, 2), nullable=True),
              Column('user_id', Integer),
              UniqueConstraint('order_id', 'user_id',
                               name='order_order_id_user_id_unique'
                               ),
              Index(
                  'order_user_id_amount_idx', 'user_id',
                  'amount', unique=True),
              )

        diffs = self._fixture(m1, m2)
        eq_(diffs[0][0], "remove_index")
        eq_(diffs[0][1].name, "order_user_id_amount_idx")
        eq_(diffs[0][1].unique, False)

        eq_(diffs[1][0], "add_index")
        eq_(diffs[1][1].name, "order_user_id_amount_idx")
        eq_(diffs[1][1].unique, True)

Example 30

Project: alembic
Source File: test_autogen_indexes.py
View license
    def test_named_cols_changed(self):
        m1 = MetaData()
        m2 = MetaData()
        Table('col_change', m1,
              Column('x', Integer),
              Column('y', Integer),
              UniqueConstraint('x', name="nochange")
              )
        Table('col_change', m2,
              Column('x', Integer),
              Column('y', Integer),
              UniqueConstraint('x', 'y', name="nochange")
              )

        diffs = self._fixture(m1, m2)

        if self.reports_unique_constraints:
            eq_(diffs[0][0], "remove_constraint")
            eq_(diffs[0][1].name, "nochange")

            eq_(diffs[1][0], "add_constraint")
            eq_(diffs[1][1].name, "nochange")
        else:
            eq_(diffs, [])

Example 31

Project: alembic
Source File: test_autogen_indexes.py
View license
    def test_unnamed_cols_changed(self):
        m1 = MetaData()
        m2 = MetaData()
        Table('col_change', m1,
              Column('x', Integer),
              Column('y', Integer),
              UniqueConstraint('x')
              )
        Table('col_change', m2,
              Column('x', Integer),
              Column('y', Integer),
              UniqueConstraint('x', 'y')
              )

        diffs = self._fixture(m1, m2)

        diffs = set((cmd,
                     ('x' in obj.name) if obj.name is not None else False)
                    for cmd, obj in diffs)
        if self.reports_unnamed_constraints:
            if self.reports_unique_constraints_as_indexes:
                eq_(
                    diffs,
                    set([("remove_index", True), ("add_constraint", False)])
                )
            else:
                eq_(
                    diffs,
                    set([("remove_constraint", True),
                         ("add_constraint", False)])
                )

Example 32

Project: alembic
Source File: test_autogen_indexes.py
View license
    def test_remove_named_unique_constraint(self):
        m1 = MetaData()
        m2 = MetaData()

        Table('remove_idx', m1,
              Column('x', Integer),
              UniqueConstraint('x', name='xidx')
              )
        Table('remove_idx', m2,
              Column('x', Integer),
              )

        diffs = self._fixture(m1, m2)

        if self.reports_unique_constraints:
            diffs = set((cmd, obj.name) for cmd, obj in diffs)
            if self.reports_unique_constraints_as_indexes:
                eq_(diffs, set([("remove_index", "xidx")]))
            else:
                eq_(diffs, set([("remove_constraint", "xidx")]))
        else:
            eq_(diffs, [])

Example 33

Project: alembic
Source File: test_autogen_indexes.py
View license
    @config.requirements.unique_constraint_reflection
    @config.requirements.reflects_unique_constraints_unambiguously
    def test_remove_connection_uq(self):
        m1 = MetaData()
        m2 = MetaData()

        Table(
            't', m1, Column('x', Integer), Column('y', Integer),
            UniqueConstraint('x', name='uq1'),
            UniqueConstraint('y', name='uq2'),
        )

        Table('t', m2, Column('x', Integer), Column('y', Integer))

        def include_object(object_, name, type_, reflected, compare_to):
            if type_ == 'index':
                return False
            return not (
                isinstance(object_, UniqueConstraint) and
                type_ == 'unique_constraint' and reflected and name == 'uq1')

        diffs = self._fixture(m1, m2, object_filters=include_object)

        eq_(diffs[0][0], 'remove_constraint')
        eq_(diffs[0][1].name, 'uq2')
        eq_(len(diffs), 1)

Example 34

Project: alembic
Source File: test_autogen_indexes.py
View license
    @config.requirements.unique_constraint_reflection
    def test_add_metadata_unique(self):
        m1 = MetaData()
        m2 = MetaData()

        Table('t', m1, Column('x', Integer))

        Table(
            't', m2, Column('x', Integer),
            UniqueConstraint('x', name='uq1'),
            UniqueConstraint('x', name='uq2')
        )

        def include_object(object_, name, type_, reflected, compare_to):
            return not (
                isinstance(object_, UniqueConstraint) and
                type_ == 'unique_constraint' and
                not reflected and name == 'uq1')

        diffs = self._fixture(m1, m2, object_filters=include_object)

        eq_(diffs[0][0], 'add_constraint')
        eq_(diffs[0][1].name, 'uq2')
        eq_(len(diffs), 1)

Example 35

Project: alembic
Source File: test_autogen_indexes.py
View license
    @config.requirements.unique_constraint_reflection
    def test_change_unique(self):
        m1 = MetaData()
        m2 = MetaData()

        Table(
            't', m1, Column('x', Integer),
            Column('y', Integer), Column('z', Integer),
            UniqueConstraint('x', name='uq1'),
            UniqueConstraint('y', name='uq2')
        )

        Table(
            't', m2, Column('x', Integer), Column('y', Integer),
            Column('z', Integer),
            UniqueConstraint('x', 'z', name='uq1'),
            UniqueConstraint('y', 'z', name='uq2')
        )

        def include_object(object_, name, type_, reflected, compare_to):
            if type_ == 'index':
                return False
            return not (
                isinstance(object_, UniqueConstraint) and
                type_ == 'unique_constraint' and
                not reflected and name == 'uq1'
                and isinstance(compare_to, UniqueConstraint))

        diffs = self._fixture(m1, m2, object_filters=include_object)

        eq_(diffs[0][0], 'remove_constraint')
        eq_(diffs[0][1].name, 'uq2')
        eq_(diffs[1][0], 'add_constraint')
        eq_(diffs[1][1].name, 'uq2')
        eq_(len(diffs), 2)

Example 36

Project: alembic
Source File: _autogen_fixtures.py
View license
    @classmethod
    def _get_model_schema(cls):
        schema = cls.schema

        m = MetaData(schema=schema)

        Table('user', m,
              Column('id', Integer, primary_key=True),
              Column('name', String(50), nullable=False),
              Column('a1', Text, server_default="x")
              )

        Table('address', m,
              Column('id', Integer, primary_key=True),
              Column('email_address', String(100), nullable=False),
              Column('street', String(50)),
              UniqueConstraint('email_address', name="uq_email")
              )

        Table('order', m,
              Column('order_id', Integer, primary_key=True),
              Column('amount', Numeric(10, 2), nullable=True,
                     server_default=text("0")),
              Column('user_id', Integer, ForeignKey('user.id')),
              CheckConstraint('amount > -1', name='ck_order_amount'),
              )

        Table('item', m,
              Column('id', Integer, primary_key=True),
              Column('description', String(100)),
              Column('order_id', Integer, ForeignKey('order.order_id')),
              CheckConstraint('len(description) > 5')
              )
        return m

Example 37

Project: sqlalchemy
Source File: test_reflection.py
View license
    @testing.provide_metadata
    def test_reflection_with_unique_constraint(self):
        insp = inspect(testing.db)

        meta = self.metadata
        uc_table = Table('mysql_uc', meta,
                         Column('a', String(10)),
                         UniqueConstraint('a', name='uc_a'))

        uc_table.create()

        # MySQL converts unique constraints into unique indexes.
        # separately we get both
        indexes = dict((i['name'], i) for i in insp.get_indexes('mysql_uc'))
        constraints = set(i['name']
                          for i in insp.get_unique_constraints('mysql_uc'))

        self.assert_('uc_a' in indexes)
        self.assert_(indexes['uc_a']['unique'])
        self.assert_('uc_a' in constraints)

        # reflection here favors the unique index, as that's the
        # more "official" MySQL construct
        reflected = Table('mysql_uc', MetaData(testing.db), autoload=True)

        indexes = dict((i.name, i) for i in reflected.indexes)
        constraints = set(uc.name for uc in reflected.constraints)

        self.assert_('uc_a' in indexes)
        self.assert_(indexes['uc_a'].unique)
        self.assert_('uc_a' not in constraints)

Example 38

Project: sqlalchemy
Source File: test_reflection.py
View license
    @testing.provide_metadata
    @testing.only_on("postgresql >= 8.5")
    def test_reflection_with_unique_constraint(self):
        insp = inspect(testing.db)

        meta = self.metadata
        uc_table = Table('pgsql_uc', meta,
                         Column('a', String(10)),
                         UniqueConstraint('a', name='uc_a'))

        uc_table.create()

        # PostgreSQL will create an implicit index for a unique
        # constraint.   Separately we get both
        indexes = set(i['name'] for i in insp.get_indexes('pgsql_uc'))
        constraints = set(i['name']
                          for i in insp.get_unique_constraints('pgsql_uc'))

        self.assert_('uc_a' in indexes)
        self.assert_('uc_a' in constraints)

        # reflection corrects for the dupe
        reflected = Table('pgsql_uc', MetaData(testing.db), autoload=True)

        indexes = set(i.name for i in reflected.indexes)
        constraints = set(uc.name for uc in reflected.constraints)

        self.assert_('uc_a' not in indexes)
        self.assert_('uc_a' in constraints)

Example 39

Project: sqlalchemy
Source File: test_constraints.py
View license
    @testing.provide_metadata
    def test_unique_constraint_create(self):
        metadata = self.metadata

        Table('foo', metadata,
              Column('id', Integer, primary_key=True),
              Column('value', String(30), unique=True))
        Table('bar', metadata,
              Column('id', Integer, primary_key=True),
              Column('value', String(30)),
              Column('value2', String(30)),
              UniqueConstraint('value', 'value2', name='uix1')
              )

        self.assert_sql_execution(
            testing.db,
            lambda: metadata.create_all(checkfirst=False),
            AllOf(
                CompiledSQL('CREATE TABLE foo ('
                            'id INTEGER NOT NULL, '
                            'value VARCHAR(30), '
                            'PRIMARY KEY (id), '
                            'UNIQUE (value)'
                            ')'),
                CompiledSQL('CREATE TABLE bar ('
                            'id INTEGER NOT NULL, '
                            'value VARCHAR(30), '
                            'value2 VARCHAR(30), '
                            'PRIMARY KEY (id), '
                            'CONSTRAINT uix1 UNIQUE (value, value2)'
                            ')')
            )
        )

Example 40

Project: sqlalchemy
Source File: test_constraints.py
View license
    def test_deferrable_unique(self):
        factory = lambda **kw: UniqueConstraint('b', **kw)
        self._test_deferrable(factory)

Example 41

Project: snorkel
Source File: candidate.py
View license
def candidate_subclass(class_name, args, table_name=None):
    """
    Creates and returns a Candidate subclass with provided argument names, which are Context type.
    Creates the table in DB if does not exist yet.

    Import using:

    .. code-block:: python

        from snorkel.models import candidate_subclass

    :param class_name: The name of the class, should be "camel case" e.g. NewCandidateClass
    :param args: A list of names of consituent arguments, which refer to the Contexts--representing mentions--that
        comprise the candidate
    :param table_name: The name of the corresponding table in DB; if not provided, is converted from camel case
        by default, e.g. new_candidate_class
    """
    table_name = camel_to_under(class_name) if table_name is None else table_name
    class_attribs = {

        # Declares name for storage table
        '__tablename__' : table_name,
                
        # Connects ChemicalDisease records to generic Candidate records
        'id' : Column(Integer, ForeignKey('candidate.id'), primary_key=True),
                
        # Polymorphism information for SQLAlchemy
        '__mapper_args__' : {'polymorphic_identity': table_name},

        # Helper method to get argument names
        '__argnames__' : args
    }
        
    # Create named arguments
    unique_con_args = []
    for arg in args:
        class_attribs[arg + '_id'] = Column(Integer, ForeignKey('context.id'))
        class_attribs[arg]         = relationship('Context',
                                                  backref=backref(table_name + '_' + arg + 's', cascade_backrefs=False),
                                                  cascade_backrefs=False,
                                                  foreign_keys=class_attribs[arg + '_id'])
        unique_con_args.append(class_attribs[arg + '_id'])

    class_attribs['__table_args__'] = (UniqueConstraint(*unique_con_args),)

    # Create class
    C = type(class_name, (Candidate,), class_attribs)
        
    # Create table in DB
    if not snorkel_engine.dialect.has_table(snorkel_engine, table_name):
        C.__table__.create(bind=snorkel_engine)
    return C

Example 42

Project: DataGristle
Source File: metadata.py
View license
    def table_create(self):
        """ Creates the schema table
        """
        #                UniqueConstraint(columns=['schema_name']),
        self.schema   = Table('schema'          ,
                        self.metadata           ,
                        Column('schema_id'      ,
                               Integer          ,
                               nullable=False   ,
                               primary_key=True),
                        Column('schema_name'    ,
                               String(40)       ,
                               nullable=False)  ,
                        Column('schema_desc'    ,
                               String(255)      ,
                               nullable=False)  ,
                        UniqueConstraint('schema_name', name='schema_uk1'),
                        extend_existing=True    )
        self._table      = self.schema
        self._table_name = 'schema'
        self._unique_constraints = ['schema_name']

        return self.schema

Example 43

Project: DataGristle
Source File: metadata.py
View license
    def table_create(self):
        """ Creates the schema table
        """
        #                UniqueConstraint(columns=['schema_name']),
        self.schema   = Table('schema'          ,
                        self.metadata           ,
                        Column('schema_id'      ,
                               Integer          ,
                               nullable=False   ,
                               primary_key=True),
                        Column('schema_name'    ,
                               String(40)       ,
                               nullable=False)  ,
                        Column('schema_desc'    ,
                               String(255)      ,
                               nullable=False)  ,
                        UniqueConstraint('schema_name', name='schema_uk1'),
                        extend_existing=True    )
        self._table      = self.schema
        self._table_name = 'schema'
        self._unique_constraints = ['schema_name']

        return self.schema

Example 44

Project: DataGristle
Source File: metadata.py
View license
    def table_create(self):
        """ Handles creation of collection table.
        """

        self.collection = Table('collection',
              self.metadata,
              Column('collection_id'   , Integer       , nullable=False   ,
                     primary_key=True),
              Column('schema_id'       , Integer       , nullable=False  ),
              Column('collection_name' , String(40)    , nullable=False  ),
              Column('collection_desc' , String(256)   , nullable=False  ),
              UniqueConstraint('schema_id', 'collection_name',
                               name='collection_uk1'),
              ForeignKeyConstraint(columns=['schema_id'],
                                   refcolumns=['schema.schema_id'],
                                   name='collection_fk1',
                                   ondelete='CASCADE'),
              extend_existing=True)
        self._table      = self.collection
        self._table_name = 'collection'
        return self._table

Example 45

Project: DataGristle
Source File: metadata.py
View license
    def table_create(self):
        """ Handles creation of collection table.
        """

        self.collection = Table('collection',
              self.metadata,
              Column('collection_id'   , Integer       , nullable=False   ,
                     primary_key=True),
              Column('schema_id'       , Integer       , nullable=False  ),
              Column('collection_name' , String(40)    , nullable=False  ),
              Column('collection_desc' , String(256)   , nullable=False  ),
              UniqueConstraint('schema_id', 'collection_name',
                               name='collection_uk1'),
              ForeignKeyConstraint(columns=['schema_id'],
                                   refcolumns=['schema.schema_id'],
                                   name='collection_fk1',
                                   ondelete='CASCADE'),
              extend_existing=True)
        self._table      = self.collection
        self._table_name = 'collection'
        return self._table

Example 46

Project: DataGristle
Source File: metadata.py
View license
    def table_create(self):
        """ Creates the 'field' table.
        """

        self.field = Table('field',
            self.metadata,
            Column('field_id'        , Integer     , nullable=False   ,
                   primary_key=True),
            Column('collection_id'   , Integer     , nullable=False  ),
            Column('field_name'      , String(40)  , nullable=False  ),
            Column('field_desc'      , String(256) , nullable=True   ),
            Column('field_order'     , Integer     , nullable=True   ),
            Column('field_type'      , String(10)  , nullable=True   ),
            Column('field_len'       , Integer     , nullable=True   ),
            Column('element_name'    , String(60)  , nullable=True   ),
            UniqueConstraint('collection_id',
                   'field_name',
                   name='field_uk1'),
            ForeignKeyConstraint(columns=['collection_id'],
                   refcolumns=['collection.collection_id'],
                   name='field_fk1',
                   ondelete='CASCADE'),
            ForeignKeyConstraint(columns=['element_name'],
                   refcolumns=['element.element_name'],
                   name='field_fk2',
                   ondelete='RESTRICT'),
            CheckConstraint('field_len > 0',
                   name='field_len_ck1'),
            CheckConstraint("field_type in ('string','int','date','time','timestamp','float')",
                   name='field_len_ck2'),
            CheckConstraint("( (element_name IS NULL AND field_type IS NOT NULL) \
                   OR (element_name IS NOT NULL AND field_type IS NULL) ) ",
                   name='field_ck3') ,
            CheckConstraint("  (field_type IS NULL AND field_len IS NULL)   \
                   OR (field_type  = 'string' AND field_len IS NOT NULL)    \
                   OR (field_type <> 'string' AND field_len IS NULL)  ",
                   name='field_ck4') ,
            extend_existing=True )
        self._table      = self.field
        self._table_name = 'field'
        self.instance    = None # assigned in InstanceTools
        return self._table

Example 47

Project: DataGristle
Source File: metadata.py
View license
    def table_create(self):
        """ Creates the 'field' table.
        """

        self.field = Table('field',
            self.metadata,
            Column('field_id'        , Integer     , nullable=False   ,
                   primary_key=True),
            Column('collection_id'   , Integer     , nullable=False  ),
            Column('field_name'      , String(40)  , nullable=False  ),
            Column('field_desc'      , String(256) , nullable=True   ),
            Column('field_order'     , Integer     , nullable=True   ),
            Column('field_type'      , String(10)  , nullable=True   ),
            Column('field_len'       , Integer     , nullable=True   ),
            Column('element_name'    , String(60)  , nullable=True   ),
            UniqueConstraint('collection_id',
                   'field_name',
                   name='field_uk1'),
            ForeignKeyConstraint(columns=['collection_id'],
                   refcolumns=['collection.collection_id'],
                   name='field_fk1',
                   ondelete='CASCADE'),
            ForeignKeyConstraint(columns=['element_name'],
                   refcolumns=['element.element_name'],
                   name='field_fk2',
                   ondelete='RESTRICT'),
            CheckConstraint('field_len > 0',
                   name='field_len_ck1'),
            CheckConstraint("field_type in ('string','int','date','time','timestamp','float')",
                   name='field_len_ck2'),
            CheckConstraint("( (element_name IS NULL AND field_type IS NOT NULL) \
                   OR (element_name IS NOT NULL AND field_type IS NULL) ) ",
                   name='field_ck3') ,
            CheckConstraint("  (field_type IS NULL AND field_len IS NULL)   \
                   OR (field_type  = 'string' AND field_len IS NOT NULL)    \
                   OR (field_type <> 'string' AND field_len IS NULL)  ",
                   name='field_ck4') ,
            extend_existing=True )
        self._table      = self.field
        self._table_name = 'field'
        self.instance    = None # assigned in InstanceTools
        return self._table

Example 48

Project: DataGristle
Source File: metadata.py
View license
    def table_create(self):
        """ Creates the 'field_value' table.
        """

        self.field_value = Table('field_value',
            self.metadata,
            Column('field_id'        , Integer     , nullable=False  ),
            Column('fv_value'        , String(256) , nullable=False  ),
            Column('fv_desc'         , String(2048),                 ),
            Column('fv_issues'       , String(2048),                 ),
            UniqueConstraint('field_id',
                   'fv_value',
                   name='field_value_uk1'),
            ForeignKeyConstraint(columns=['field_id'],
                   refcolumns=['field.field_id'],
                   name='field_value_fk1',
                   ondelete='CASCADE'),
            extend_existing=True )
        self._table      = self.field_value
        self._table_name = 'field_value'
        return self._table

Example 49

Project: DataGristle
Source File: metadata.py
View license
    def table_create(self):
        """ Creates the 'field_value' table.
        """

        self.field_value = Table('field_value',
            self.metadata,
            Column('field_id'        , Integer     , nullable=False  ),
            Column('fv_value'        , String(256) , nullable=False  ),
            Column('fv_desc'         , String(2048),                 ),
            Column('fv_issues'       , String(2048),                 ),
            UniqueConstraint('field_id',
                   'fv_value',
                   name='field_value_uk1'),
            ForeignKeyConstraint(columns=['field_id'],
                   refcolumns=['field.field_id'],
                   name='field_value_fk1',
                   ondelete='CASCADE'),
            extend_existing=True )
        self._table      = self.field_value
        self._table_name = 'field_value'
        return self._table

Example 50

Project: DataGristle
Source File: metadata.py
View license
    def table_create(self):
        """ Creates the 'instance' table.
        """
        self.instance = Table('instance' ,
             self.metadata           ,
             Column('instance_id'    ,
                    Integer          ,
                    nullable=False   ,
                    primary_key=True),
             Column('schema_id'      ,
                    Integer          ,
                    nullable=False  ),
             Column('instance_name'  ,
                    String(255)      ,
                    nullable=False  ),
             UniqueConstraint('schema_id','instance_name', name='instance_uk1'),
             ForeignKeyConstraint(columns=['schema_id'],
                                  refcolumns=['schema.schema_id'],
                                  name='instance_fk1',
                                  ondelete='CASCADE'),
             extend_existing=True    )

        self._table      = self.instance
        self._table_name = 'instance'
        return self._table