Python sqlalchemy.testing.schema.Table() Examples

The following are 30 code examples for showing how to use sqlalchemy.testing.schema.Table(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module sqlalchemy.testing.schema , or try the search function .

Example 1
Project: sqlalchemy   Author: sqlalchemy   File: test_execute.py    License: MIT License 6 votes vote down vote up
def test_not_an_executable(self):
        for obj in (
            Table("foo", MetaData(), Column("x", Integer)),
            Column("x", Integer),
            tsa.and_(True),
            tsa.and_(True).compile(),
            column("foo"),
            column("foo").compile(),
            MetaData(),
            Integer(),
            tsa.Index(name="foo"),
            tsa.UniqueConstraint("x"),
        ):
            with testing.db.connect() as conn:
                assert_raises_message(
                    tsa.exc.ObjectNotExecutableError,
                    "Not an executable object",
                    conn.execute,
                    obj,
                ) 
Example 2
Project: sqlalchemy   Author: sqlalchemy   File: test_execute.py    License: MIT License 6 votes vote down vote up
def test_sequence_not_duped(self):
        engine, buf = self._engine_fixture()
        metadata = MetaData()
        t = Table(
            "testtable",
            metadata,
            Column(
                "pk", Integer, Sequence("testtable_pk_seq"), primary_key=True,
            ),
        )

        t.create(engine)
        t.drop(engine)

        eq_(re.findall(r"CREATE (\w+)", buf.getvalue()), ["SEQUENCE", "TABLE"])

        eq_(re.findall(r"DROP (\w+)", buf.getvalue()), ["TABLE", "SEQUENCE"]) 
Example 3
Project: sqlalchemy   Author: sqlalchemy   File: test_execute.py    License: MIT License 6 votes vote down vote up
def define_tables(cls, metadata):
        Table(
            "users",
            metadata,
            Column("user_id", INT, primary_key=True, autoincrement=False),
            Column("user_name", VARCHAR(20)),
            test_needs_acid=True,
        )
        Table(
            "users_autoinc",
            metadata,
            Column(
                "user_id", INT, primary_key=True, test_needs_autoincrement=True
            ),
            Column("user_name", VARCHAR(20)),
            test_needs_acid=True,
        ) 
Example 4
Project: sqlalchemy   Author: sqlalchemy   File: test_bind.py    License: MIT License 6 votes vote down vote up
def test_create_drop_constructor_bound(self):
        for bind in (testing.db, testing.db.connect()):
            try:
                for args in (([bind], {}), ([], {"bind": bind})):
                    metadata = MetaData(*args[0], **args[1])
                    table = Table(
                        "test_table", metadata, Column("foo", Integer)
                    )
                    assert metadata.bind is table.bind is bind
                    metadata.create_all()
                    is_true(inspect(bind).has_table(table.name))
                    metadata.drop_all()
                    table.create()
                    table.drop()
                    is_false(inspect(bind).has_table(table.name))
            finally:
                if isinstance(bind, engine.Connection):
                    bind.close() 
Example 5
Project: sqlalchemy   Author: sqlalchemy   File: test_reflection.py    License: MIT License 6 votes vote down vote up
def test_include_columns_indexes(self):
        m = self.metadata

        t1 = Table("t1", m, Column("a", sa.Integer), Column("b", sa.Integer))
        sa.Index("foobar", t1.c.a, t1.c.b)
        sa.Index("bat", t1.c.a)
        m.create_all()
        m2 = MetaData(testing.db)
        t2 = Table("t1", m2, autoload=True)
        assert len(t2.indexes) == 2

        m2 = MetaData(testing.db)
        t2 = Table("t1", m2, autoload=True, include_columns=["a"])
        assert len(t2.indexes) == 1

        m2 = MetaData(testing.db)
        t2 = Table("t1", m2, autoload=True, include_columns=["a", "b"])
        assert len(t2.indexes) == 2 
Example 6
Project: sqlalchemy   Author: sqlalchemy   File: test_reflection.py    License: MIT License 6 votes vote down vote up
def test_unknown_types(self):
        """Test the handling of unknown types for the given dialect.

        sqlite is skipped because it has special rules for unknown types using
        'affinity types' - this feature is tested in that dialect's test spec.
        """
        meta = self.metadata
        t = Table("test", meta, Column("foo", sa.DateTime))

        ischema_names = testing.db.dialect.ischema_names
        t.create()
        testing.db.dialect.ischema_names = {}
        try:
            m2 = MetaData(testing.db)

            with testing.expect_warnings("Did not recognize type"):
                t3 = Table("test", m2, autoload_with=testing.db)
                is_(t3.c.foo.type.__class__, sa.types.NullType)

        finally:
            testing.db.dialect.ischema_names = ischema_names 
Example 7
Project: sqlalchemy   Author: sqlalchemy   File: test_reflection.py    License: MIT License 6 votes vote down vote up
def test_basic_override(self):
        meta = self.metadata
        table = Table(
            "override_test",
            meta,
            Column("col1", sa.Integer, primary_key=True),
            Column("col2", sa.String(20)),
            Column("col3", sa.Numeric),
        )
        table.create()

        meta2 = MetaData(testing.db)
        table = Table(
            "override_test",
            meta2,
            Column("col2", sa.Unicode()),
            Column("col4", sa.String(30)),
            autoload=True,
        )

        self.assert_(isinstance(table.c.col1.type, sa.Integer))
        self.assert_(isinstance(table.c.col2.type, sa.Unicode))
        self.assert_(isinstance(table.c.col4.type, sa.String)) 
Example 8
Project: sqlalchemy   Author: sqlalchemy   File: test_reflection.py    License: MIT License 6 votes vote down vote up
def test_override_upgrade_pk_flag(self):
        meta = self.metadata
        table = Table(
            "override_test",
            meta,
            Column("col1", sa.Integer),
            Column("col2", sa.String(20)),
            Column("col3", sa.Numeric),
        )
        table.create()

        meta2 = MetaData(testing.db)
        table = Table(
            "override_test",
            meta2,
            Column("col1", sa.Integer, primary_key=True),
            autoload=True,
        )

        eq_(list(table.primary_key), [table.c.col1])
        eq_(table.c.col1.primary_key, True) 
Example 9
Project: sqlalchemy   Author: sqlalchemy   File: test_reflection.py    License: MIT License 6 votes vote down vote up
def test_pks_not_uniques(self):
        """test that primary key reflection not tripped up by unique
        indexes"""

        with testing.db.begin() as conn:
            conn.exec_driver_sql(
                """
                CREATE TABLE book (
                    id INTEGER NOT NULL,
                    title VARCHAR(100) NOT NULL,
                    series INTEGER,
                    series_id INTEGER,
                    UNIQUE(series, series_id),
                    PRIMARY KEY(id)
                )"""
            )

        book = Table("book", self.metadata, autoload_with=testing.db)
        assert book.primary_key.contains_column(book.c.id)
        assert not book.primary_key.contains_column(book.c.series)
        eq_(len(book.primary_key), 1) 
Example 10
Project: sqlalchemy   Author: sqlalchemy   File: test_reflection.py    License: MIT License 6 votes vote down vote up
def test_composite_pks(self):
        """test reflection of a composite primary key"""

        with testing.db.begin() as conn:
            conn.exec_driver_sql(
                """
                CREATE TABLE book (
                    id INTEGER NOT NULL,
                    isbn VARCHAR(50) NOT NULL,
                    title VARCHAR(100) NOT NULL,
                    series INTEGER NOT NULL,
                    series_id INTEGER NOT NULL,
                    UNIQUE(series, series_id),
                    PRIMARY KEY(id, isbn)
                )"""
            )
        book = Table("book", self.metadata, autoload_with=testing.db)
        assert book.primary_key.contains_column(book.c.id)
        assert book.primary_key.contains_column(book.c.isbn)
        assert not book.primary_key.contains_column(book.c.series)
        eq_(len(book.primary_key), 2) 
Example 11
Project: jbox   Author: jpush   File: test_reflection.py    License: MIT License 5 votes vote down vote up
def define_tables(cls, metadata):
        Table('test_table', metadata,
              Column('id', Integer, primary_key=True),
              Column('data', String(50))
              ) 
Example 12
Project: jbox   Author: jpush   File: test_reflection.py    License: MIT License 5 votes vote down vote up
def define_temp_tables(cls, metadata):
        # cheat a bit, we should fix this with some dialect-level
        # temp table fixture
        if testing.against("oracle"):
            kw = {
                'prefixes': ["GLOBAL TEMPORARY"],
                'oracle_on_commit': 'PRESERVE ROWS'
            }
        else:
            kw = {
                'prefixes': ["TEMPORARY"],
            }

        user_tmp = Table(
            "user_tmp", metadata,
            Column("id", sa.INT, primary_key=True),
            Column('name', sa.VARCHAR(50)),
            Column('foo', sa.INT),
            sa.UniqueConstraint('name', name='user_tmp_uq'),
            sa.Index("user_tmp_ix", "foo"),
            **kw
        )
        if testing.requires.view_reflection.enabled and \
                testing.requires.temporary_views.enabled:
            event.listen(
                user_tmp, "after_create",
                DDL("create temporary view user_tmp_v as "
                    "select * from user_tmp")
            )
            event.listen(
                user_tmp, "before_drop",
                DDL("drop view user_tmp_v")
            ) 
Example 13
Project: jbox   Author: jpush   File: test_reflection.py    License: MIT License 5 votes vote down vote up
def _type_round_trip(self, *types):
        t = Table('t', self.metadata,
                  *[
                      Column('t%d' % i, type_)
                      for i, type_ in enumerate(types)
                  ]
                  )
        t.create()

        return [
            c['type'] for c in
            inspect(self.metadata.bind).get_columns('t')
        ] 
Example 14
Project: jbox   Author: jpush   File: test_reflection.py    License: MIT License 5 votes vote down vote up
def test_nullable_reflection(self):
        t = Table('t', self.metadata,
                  Column('a', Integer, nullable=True),
                  Column('b', Integer, nullable=False))
        t.create()
        eq_(
            dict(
                (col['name'], col['nullable'])
                for col in inspect(self.metadata.bind).get_columns('t')
            ),
            {"a": True, "b": False}
        ) 
Example 15
Project: Fluid-Designer   Author: Microvellum   File: test_reflection.py    License: GNU General Public License v3.0 5 votes vote down vote up
def define_tables(cls, metadata):
        Table('test_table', metadata,
              Column('id', Integer, primary_key=True),
              Column('data', String(50))
              ) 
Example 16
Project: Fluid-Designer   Author: Microvellum   File: test_reflection.py    License: GNU General Public License v3.0 5 votes vote down vote up
def define_temp_tables(cls, metadata):
        # cheat a bit, we should fix this with some dialect-level
        # temp table fixture
        if testing.against("oracle"):
            kw = {
                'prefixes': ["GLOBAL TEMPORARY"],
                'oracle_on_commit': 'PRESERVE ROWS'
            }
        else:
            kw = {
                'prefixes': ["TEMPORARY"],
            }

        user_tmp = Table(
            "user_tmp", metadata,
            Column("id", sa.INT, primary_key=True),
            Column('name', sa.VARCHAR(50)),
            Column('foo', sa.INT),
            sa.UniqueConstraint('name', name='user_tmp_uq'),
            sa.Index("user_tmp_ix", "foo"),
            **kw
        )
        if testing.requires.view_reflection.enabled and \
                testing.requires.temporary_views.enabled:
            event.listen(
                user_tmp, "after_create",
                DDL("create temporary view user_tmp_v as "
                    "select * from user_tmp")
            )
            event.listen(
                user_tmp, "before_drop",
                DDL("drop view user_tmp_v")
            ) 
Example 17
Project: Fluid-Designer   Author: Microvellum   File: test_reflection.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _type_round_trip(self, *types):
        t = Table('t', self.metadata,
                  *[
                      Column('t%d' % i, type_)
                      for i, type_ in enumerate(types)
                  ]
                  )
        t.create()

        return [
            c['type'] for c in
            inspect(self.metadata.bind).get_columns('t')
        ] 
Example 18
Project: Fluid-Designer   Author: Microvellum   File: test_reflection.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_nullable_reflection(self):
        t = Table('t', self.metadata,
                  Column('a', Integer, nullable=True),
                  Column('b', Integer, nullable=False))
        t.create()
        eq_(
            dict(
                (col['name'], col['nullable'])
                for col in inspect(self.metadata.bind).get_columns('t')
            ),
            {"a": True, "b": False}
        ) 
Example 19
Project: planespotter   Author: yfauser   File: test_reflection.py    License: MIT License 5 votes vote down vote up
def define_tables(cls, metadata):
        Table('test_table', metadata,
              Column('id', Integer, primary_key=True),
              Column('data', String(50))
              ) 
Example 20
Project: planespotter   Author: yfauser   File: test_reflection.py    License: MIT License 5 votes vote down vote up
def define_temp_tables(cls, metadata):
        # cheat a bit, we should fix this with some dialect-level
        # temp table fixture
        if testing.against("oracle"):
            kw = {
                'prefixes': ["GLOBAL TEMPORARY"],
                'oracle_on_commit': 'PRESERVE ROWS'
            }
        else:
            kw = {
                'prefixes': ["TEMPORARY"],
            }

        user_tmp = Table(
            "user_tmp", metadata,
            Column("id", sa.INT, primary_key=True),
            Column('name', sa.VARCHAR(50)),
            Column('foo', sa.INT),
            sa.UniqueConstraint('name', name='user_tmp_uq'),
            sa.Index("user_tmp_ix", "foo"),
            **kw
        )
        if testing.requires.view_reflection.enabled and \
                testing.requires.temporary_views.enabled:
            event.listen(
                user_tmp, "after_create",
                DDL("create temporary view user_tmp_v as "
                    "select * from user_tmp")
            )
            event.listen(
                user_tmp, "before_drop",
                DDL("drop view user_tmp_v")
            ) 
Example 21
Project: planespotter   Author: yfauser   File: test_reflection.py    License: MIT License 5 votes vote down vote up
def _type_round_trip(self, *types):
        t = Table('t', self.metadata,
                  *[
                      Column('t%d' % i, type_)
                      for i, type_ in enumerate(types)
                  ]
                  )
        t.create()

        return [
            c['type'] for c in
            inspect(self.metadata.bind).get_columns('t')
        ] 
Example 22
Project: planespotter   Author: yfauser   File: test_reflection.py    License: MIT License 5 votes vote down vote up
def test_nullable_reflection(self):
        t = Table('t', self.metadata,
                  Column('a', Integer, nullable=True),
                  Column('b', Integer, nullable=False))
        t.create()
        eq_(
            dict(
                (col['name'], col['nullable'])
                for col in inspect(self.metadata.bind).get_columns('t')
            ),
            {"a": True, "b": False}
        ) 
Example 23
Project: planespotter   Author: yfauser   File: test_reflection.py    License: MIT License 5 votes vote down vote up
def _test_get_check_constraints(self, schema=None):
        orig_meta = self.metadata
        Table(
            'sa_cc', orig_meta,
            Column('a', Integer()),
            sa.CheckConstraint('a > 1 AND a < 5', name='cc1'),
            sa.CheckConstraint('a = 1 OR (a > 2 AND a < 5)', name='cc2'),
            schema=schema
        )

        orig_meta.create_all()

        inspector = inspect(orig_meta.bind)
        reflected = sorted(
            inspector.get_check_constraints('sa_cc', schema=schema),
            key=operator.itemgetter('name')
        )

        reflected = [
            {"name": item["name"],
             # trying to minimize effect of quoting, parenthesis, etc.
             # may need to add more to this as new dialects get CHECK
             # constraint reflection support
             "sqltext": re.sub(r"[`'\(\)]", '', item["sqltext"].lower())}
            for item in reflected
        ]
        eq_(
            reflected,
            [
                {'name': 'cc1', 'sqltext': 'a > 1 and a < 5'},
                {'name': 'cc2', 'sqltext': 'a = 1 or a > 2 and a < 5'}
            ]
        ) 
Example 24
Project: planespotter   Author: yfauser   File: test_reflection.py    License: MIT License 5 votes vote down vote up
def define_tables(cls, metadata):
        Table(
            quoted_name('t1', quote=True), metadata,
            Column('id', Integer, primary_key=True),
        )
        Table(
            quoted_name('t2', quote=True), metadata,
            Column('id', Integer, primary_key=True),
            Column('t1id', ForeignKey('t1.id'))
        ) 
Example 25
Project: planespotter   Author: yfauser   File: test_reflection.py    License: MIT License 5 votes vote down vote up
def test_reflect_lowercase_forced_tables(self):

        m2 = MetaData(testing.db)
        t2_ref = Table(quoted_name('t2', quote=True), m2, autoload=True)
        t1_ref = m2.tables['t1']
        assert t2_ref.c.t1id.references(t1_ref.c.id)

        m3 = MetaData(testing.db)
        m3.reflect(only=lambda name, m: name.lower() in ('t1', 't2'))
        assert m3.tables['t2'].c.t1id.references(m3.tables['t1'].c.id) 
Example 26
Project: pyRevit   Author: eirannejad   File: test_reflection.py    License: GNU General Public License v3.0 5 votes vote down vote up
def define_tables(cls, metadata):
        Table('test_table', metadata,
              Column('id', Integer, primary_key=True),
              Column('data', String(50))
              ) 
Example 27
Project: pyRevit   Author: eirannejad   File: test_reflection.py    License: GNU General Public License v3.0 5 votes vote down vote up
def define_temp_tables(cls, metadata):
        # cheat a bit, we should fix this with some dialect-level
        # temp table fixture
        if testing.against("oracle"):
            kw = {
                'prefixes': ["GLOBAL TEMPORARY"],
                'oracle_on_commit': 'PRESERVE ROWS'
            }
        else:
            kw = {
                'prefixes': ["TEMPORARY"],
            }

        user_tmp = Table(
            "user_tmp", metadata,
            Column("id", sa.INT, primary_key=True),
            Column('name', sa.VARCHAR(50)),
            Column('foo', sa.INT),
            sa.UniqueConstraint('name', name='user_tmp_uq'),
            sa.Index("user_tmp_ix", "foo"),
            **kw
        )
        if testing.requires.view_reflection.enabled and \
                testing.requires.temporary_views.enabled:
            event.listen(
                user_tmp, "after_create",
                DDL("create temporary view user_tmp_v as "
                    "select * from user_tmp")
            )
            event.listen(
                user_tmp, "before_drop",
                DDL("drop view user_tmp_v")
            ) 
Example 28
Project: pyRevit   Author: eirannejad   File: test_reflection.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _type_round_trip(self, *types):
        t = Table('t', self.metadata,
                  *[
                      Column('t%d' % i, type_)
                      for i, type_ in enumerate(types)
                  ]
                  )
        t.create()

        return [
            c['type'] for c in
            inspect(self.metadata.bind).get_columns('t')
        ] 
Example 29
Project: pyRevit   Author: eirannejad   File: test_reflection.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_nullable_reflection(self):
        t = Table('t', self.metadata,
                  Column('a', Integer, nullable=True),
                  Column('b', Integer, nullable=False))
        t.create()
        eq_(
            dict(
                (col['name'], col['nullable'])
                for col in inspect(self.metadata.bind).get_columns('t')
            ),
            {"a": True, "b": False}
        ) 
Example 30
Project: pyRevit   Author: eirannejad   File: test_reflection.py    License: GNU General Public License v3.0 5 votes vote down vote up
def define_tables(cls, metadata):
        Table(
            quoted_name('t1', quote=True), metadata,
            Column('id', Integer, primary_key=True),
        )
        Table(
            quoted_name('t2', quote=True), metadata,
            Column('id', Integer, primary_key=True),
            Column('t1id', ForeignKey('t1.id'))
        )