Ejemplo n.º 1
0
 def test_nonreflected_fk_raises(self):
     """test that a NoReferencedColumnError is raised when reflecting
     a table with an FK to another table which has not included the target
     column in its reflection.
     
     """
     meta = MetaData(testing.db)
     a1 = Table('a', meta,
         Column('x', sa.Integer, primary_key=True),
         Column('z', sa.Integer),
         test_needs_fk=True
     )
     b1 = Table('b', meta,
         Column('y', sa.Integer, sa.ForeignKey('a.x')),
         test_needs_fk=True
     )
     meta.create_all()
     try:
         m2 = MetaData(testing.db)
         a2 = Table('a', m2, include_columns=['z'], autoload=True)
         b2 = Table('b', m2, autoload=True)
         
         self.assertRaises(tsa.exc.NoReferencedColumnError, a2.join, b2)
     finally:
         meta.drop_all()
Ejemplo n.º 2
0
    def test_use_existing(self):
        meta = MetaData(testing.db)
        users = Table('users', meta,
            Column('id', sa.Integer, primary_key=True),
            Column('name', sa.String(30)),
            test_needs_fk=True)
        addresses = Table('addresses', meta,
            Column('id', sa.Integer,primary_key=True),
            Column('user_id', sa.Integer, sa.ForeignKey('users.id')),
            Column('data', sa.String(100)),
            test_needs_fk=True)

        meta.create_all()
        try:
            meta2 = MetaData(testing.db)
            addresses = Table('addresses', meta2, Column('data', sa.Unicode), autoload=True)
            try:
                users = Table('users', meta2, Column('name', sa.Unicode), autoload=True)
                assert False
            except tsa.exc.InvalidRequestError, err:
                assert str(err) == "Table 'users' is already defined for this MetaData instance.  Specify 'useexisting=True' to redefine options and columns on an existing Table object."

            users = Table('users', meta2, Column('name', sa.Unicode), autoload=True, useexisting=True)
            assert isinstance(users.c.name.type, sa.Unicode)

            assert not users.quote

            users = Table('users', meta2, quote=True, autoload=True, useexisting=True)
            assert users.quote
Ejemplo n.º 3
0
    def test_use_existing(self):
        meta = MetaData(testing.db)
        users = Table('users', meta,
            Column('id', sa.Integer, primary_key=True),
            Column('name', sa.String(30)),
            test_needs_fk=True)
        addresses = Table('addresses', meta,
            Column('id', sa.Integer,primary_key=True),
            Column('user_id', sa.Integer, sa.ForeignKey('users.id')),
            Column('data', sa.String(100)),
            test_needs_fk=True)

        meta.create_all()
        try:
            meta2 = MetaData(testing.db)
            addresses = Table('addresses', meta2, Column('data', sa.Unicode), autoload=True)
            try:
                users = Table('users', meta2, Column('name', sa.Unicode), autoload=True)
                assert False
            except tsa.exc.InvalidRequestError, err:
                assert str(err) == "Table 'users' is already defined for this MetaData instance.  Specify 'useexisting=True' to redefine options and columns on an existing Table object."

            users = Table('users', meta2, Column('name', sa.Unicode), autoload=True, useexisting=True)
            assert isinstance(users.c.name.type, sa.Unicode)

            assert not users.quote

            users = Table('users', meta2, quote=True, autoload=True, useexisting=True)
            assert users.quote
Ejemplo n.º 4
0
    def test_index_reflection(self):
        m1 = MetaData(testing.db)
        t1 = Table('party', m1,
            Column('id', sa.Integer, nullable=False),
            Column('name', sa.String(20), index=True)
            )
        i1 = sa.Index('idx1', t1.c.id, unique=True)
        i2 = sa.Index('idx2', t1.c.name, t1.c.id, unique=False)
        m1.create_all()
        try:
            m2 = MetaData(testing.db)
            t2 = Table('party', m2, autoload=True)

            print len(t2.indexes), t2.indexes
            assert len(t2.indexes) == 3
            # Make sure indexes are in the order we expect them in
            tmp = [(idx.name, idx) for idx in t2.indexes]
            tmp.sort()
            r1, r2, r3 = [idx[1] for idx in tmp]

            assert r1.name == 'idx1'
            assert r2.name == 'idx2'
            assert r1.unique == True
            assert r2.unique == False
            assert r3.unique == False
            assert [t2.c.id] == r1.columns
            assert [t2.c.name, t2.c.id] == r2.columns
            assert [t2.c.name] == r3.columns
        finally:
            m1.drop_all()
Ejemplo n.º 5
0
    def test_override_keys(self):
        """test that columns can be overridden with a 'key', 
        and that ForeignKey targeting during reflection still works."""
        

        meta = MetaData(testing.db)
        a1 = Table('a', meta,
            Column('x', sa.Integer, primary_key=True),
            Column('z', sa.Integer),
            test_needs_fk=True
        )
        b1 = Table('b', meta,
            Column('y', sa.Integer, sa.ForeignKey('a.x')),
            test_needs_fk=True
        )
        meta.create_all()
        try:
            m2 = MetaData(testing.db)
            a2 = Table('a', m2, Column('x', sa.Integer, primary_key=True, key='x1'), autoload=True)
            b2 = Table('b', m2, autoload=True)
            
            assert a2.join(b2).onclause.compare(a2.c.x1==b2.c.y)
            assert b2.c.y.references(a2.c.x1)
        finally:
            meta.drop_all()
Ejemplo n.º 6
0
    def setUpAll(self):
        global cartitems, sometable, metadata
        metadata = MetaData(testing.db)
        cartitems = Table(
            "cartitems", metadata,
            Column("cart_id",
                   Integer,
                   Sequence('cart_id_seq'),
                   primary_key=True), Column("description", String(40)),
            Column("createdate", sa.DateTime()))
        sometable = Table(
            'Manager',
            metadata,
            Column(
                'obj_id',
                Integer,
                Sequence('obj_id_seq'),
            ),
            Column('name', String(128)),
            Column('id',
                   Integer,
                   Sequence('Manager_id_seq', optional=True),
                   primary_key=True),
        )

        metadata.create_all()
Ejemplo n.º 7
0
 def _test_get_foreign_keys(self, schema=None):
     meta = MetaData(testing.db)
     (users, addresses) = createTables(meta, schema)
     meta.create_all()
     insp = Inspector(meta.bind)
     try:
         expected_schema = schema
         if schema is None:
             try:
                 expected_schema = meta.bind.dialect.get_default_schema_name(
                                 meta.bind)
             except NotImplementedError:
                 expected_schema = None
         # users
         users_fkeys = insp.get_foreign_keys(users.name,
                                             schema=schema)
         fkey1 = users_fkeys[0]
         self.assert_(fkey1['name'] is not None)
         self.assertEqual(fkey1['referred_schema'], expected_schema)
         self.assertEqual(fkey1['referred_table'], users.name)
         self.assertEqual(fkey1['referred_columns'], ['user_id', ])
         self.assertEqual(fkey1['constrained_columns'], ['parent_user_id'])
         #addresses
         addr_fkeys = insp.get_foreign_keys(addresses.name,
                                            schema=schema)
         fkey1 = addr_fkeys[0]
         self.assert_(fkey1['name'] is not None)
         self.assertEqual(fkey1['referred_schema'], expected_schema)
         self.assertEqual(fkey1['referred_table'], users.name)
         self.assertEqual(fkey1['referred_columns'], ['user_id', ])
         self.assertEqual(fkey1['constrained_columns'], ['remote_user_id'])
     finally:
         addresses.drop()
         users.drop()
Ejemplo n.º 8
0
 def _test_get_table_names(self, schema=None, table_type='table',
                           order_by=None):
     meta = MetaData(testing.db)
     (users, addresses) = createTables(meta, schema)
     meta.create_all()
     createViews(meta.bind, schema)
     try:
         insp = Inspector(meta.bind)
         if table_type == 'view':
             table_names = insp.get_view_names(schema)
             table_names.sort()
             answer = ['email_addresses_v', 'users_v']
         else:
             table_names = insp.get_table_names(schema,
                                                order_by=order_by)
             table_names.sort()
             if order_by == 'foreign_key':
                 answer = ['users', 'email_addresses']
             else:
                 answer = ['email_addresses', 'users']
         self.assertEqual(table_names, answer)
     finally:
         dropViews(meta.bind, schema)
         addresses.drop()
         users.drop()
Ejemplo n.º 9
0
    def test_unknown_types(self):
        meta = MetaData(testing.db)
        t = Table("test", meta,
            Column('foo', sa.DateTime))

        import sys
        dialect_module = sys.modules[testing.db.dialect.__module__]

        # we're relying on the presence of "ischema_names" in the
        # dialect module, else we can't test this.  we need to be able
        # to get the dialect to not be aware of some type so we temporarily
        # monkeypatch.  not sure what a better way for this could be,
        # except for an established dialect hook or dialect-specific tests
        if not hasattr(dialect_module, 'ischema_names'):
            return

        ischema_names = dialect_module.ischema_names
        t.create()
        dialect_module.ischema_names = {}
        try:
            m2 = MetaData(testing.db)
            self.assertRaises(tsa.exc.SAWarning, Table, "test", m2, autoload=True)

            @testing.emits_warning('Did not recognize type')
            def warns():
                m3 = MetaData(testing.db)
                t3 = Table("test", m3, autoload=True)
                assert t3.c.foo.type.__class__ == sa.types.NullType

        finally:
            dialect_module.ischema_names = ischema_names
            t.drop()
Ejemplo n.º 10
0
    def _test_get_indexes(self, schema=None):
        meta = MetaData(testing.db)
        (users, addresses) = createTables(meta, schema)
        meta.create_all()
        createIndexes(meta.bind, schema)
        try:
            # The database may decide to create indexes for foreign keys, etc.
            # so there may be more indexes than expected.
            insp = Inspector(meta.bind)
            indexes = insp.get_indexes('users', schema=schema)
            indexes.sort()
            if testing.against('oracle'):
                expected_indexes = [
                    {'unique': False,
                     'column_names': ['TEST1', 'TEST2'],
                     'name': 'USERS_T_IDX'}]
            else:
                expected_indexes = [
                    {'unique': False,
                     'column_names': ['test1', 'test2'],
                     'name': 'users_t_idx'}]
            index_names = [d['name'] for d in indexes]
            for e_index in expected_indexes:
                self.assertTrue(e_index['name'] in index_names)
                index = indexes[index_names.index(e_index['name'])]
                for key in e_index:
                    self.assertEqual(e_index[key], index[key])

        finally:
            addresses.drop()
            users.drop()
Ejemplo n.º 11
0
    def test_composite_fk(self):
        """test reflection of composite foreign keys"""

        meta = MetaData(testing.db)
        multi = Table(
            'multi', meta,
            Column('multi_id', sa.Integer, primary_key=True),
            Column('multi_rev', sa.Integer, primary_key=True),
            Column('multi_hoho', sa.Integer, primary_key=True),
            Column('name', sa.String(50), nullable=False),
            Column('val', sa.String(100)),
            test_needs_fk=True,
        )
        multi2 = Table('multi2', meta,
            Column('id', sa.Integer, primary_key=True),
            Column('foo', sa.Integer),
            Column('bar', sa.Integer),
            Column('lala', sa.Integer),
            Column('data', sa.String(50)),
            sa.ForeignKeyConstraint(['foo', 'bar', 'lala'], ['multi.multi_id', 'multi.multi_rev', 'multi.multi_hoho']),
            test_needs_fk=True,
        )
        meta.create_all()

        try:
            meta2 = MetaData()
            table = Table('multi', meta2, autoload=True, autoload_with=testing.db)
            table2 = Table('multi2', meta2, autoload=True, autoload_with=testing.db)
            self.assert_tables_equal(multi, table)
            self.assert_tables_equal(multi2, table2)
            j = sa.join(table, table2)
            self.assert_(sa.and_(table.c.multi_id==table2.c.foo, table.c.multi_rev==table2.c.bar, table.c.multi_hoho==table2.c.lala).compare(j.onclause))
        finally:
            meta.drop_all()
Ejemplo n.º 12
0
    def test_include_columns(self):
        meta = MetaData(testing.db)
        foo = Table('foo', meta, *[Column(n, sa.String(30))
                                   for n in ['a', 'b', 'c', 'd', 'e', 'f']])
        meta.create_all()
        try:
            meta2 = MetaData(testing.db)
            foo = Table('foo', meta2, autoload=True,
                        include_columns=['b', 'f', 'e'])
            # test that cols come back in original order
            self.assertEquals([c.name for c in foo.c], ['b', 'e', 'f'])
            for c in ('b', 'f', 'e'):
                assert c in foo.c
            for c in ('a', 'c', 'd'):
                assert c not in foo.c

            # test against a table which is already reflected
            meta3 = MetaData(testing.db)
            foo = Table('foo', meta3, autoload=True)
            foo = Table('foo', meta3, include_columns=['b', 'f', 'e'],
                        useexisting=True)
            self.assertEquals([c.name for c in foo.c], ['b', 'e', 'f'])
            for c in ('b', 'f', 'e'):
                assert c in foo.c
            for c in ('a', 'c', 'd'):
                assert c not in foo.c
        finally:
            meta.drop_all()
Ejemplo n.º 13
0
    def test_basic(self):
        try:
            # the 'convert_unicode' should not get in the way of the reflection
            # process.  reflecttable for oracle, postgres (others?) expect non-unicode
            # strings in result sets/bind params
            bind = engines.utf8_engine(options={'convert_unicode':True})
            metadata = MetaData(bind)

            if testing.against('sybase', 'maxdb', 'oracle', 'mssql'):
                names = set(['plain'])
            else:
                names = set([u'plain', u'Unit\u00e9ble', u'\u6e2c\u8a66'])

            for name in names:
                Table(name, metadata, Column('id', sa.Integer, sa.Sequence(name + "_id_seq"), primary_key=True))
            metadata.create_all()

            reflected = set(bind.table_names())
            if not names.issubset(reflected):
                # Python source files in the utf-8 coding seem to normalize
                # literals as NFC (and the above are explicitly NFC).  Maybe
                # this database normalizes NFD on reflection.
                nfc = set([unicodedata.normalize('NFC', n) for n in names])
                self.assert_(nfc == names)
                # Yep.  But still ensure that bulk reflection and create/drop
                # work with either normalization.

            r = MetaData(bind, reflect=True)
            r.drop_all()
            r.create_all()
        finally:
            metadata.drop_all()
            bind.dispose()
Ejemplo n.º 14
0
    def test_with_inheritance(self):
        metadata = MetaData(testing.db)

        table1 = Table("mytable", metadata,
            Column('col1', Integer, primary_key=True),
            Column('col2', String(30))
            )

        table2 = Table("mytable2", metadata,
            Column('col1', Integer, ForeignKey('mytable.col1'),
                   primary_key=True),
            Column('col3', String(30)),
            )

        @profile_memory
        def go():
            class A(_base.ComparableEntity):
                pass
            class B(A):
                pass

            mapper(A, table1,
                   polymorphic_on=table1.c.col2,
                   polymorphic_identity='a')
            mapper(B, table2,
                   inherits=A,
                   polymorphic_identity='b')

            sess = create_session()
            a1 = A()
            a2 = A()
            b1 = B(col3='b1')
            b2 = B(col3='b2')
            for x in [a1,a2,b1, b2]:
                sess.add(x)
            sess.flush()
            sess.clear()

            alist = sess.query(A).order_by(A.col1).all()
            self.assertEquals(
                [
                    A(), A(), B(col3='b1'), B(col3='b2')
                ],
                alist)

            for a in alist:
                sess.delete(a)
            sess.flush()

            # dont need to clear_mappers()
            del B
            del A

        metadata.create_all()
        try:
            go()
        finally:
            metadata.drop_all()
        assert_no_mappers()
Ejemplo n.º 15
0
 def setUpAll(self):
     global users, metadata
     metadata = MetaData(testing.db)
     users = Table('users', metadata,
         Column('user_id', INT, primary_key = True),
         Column('user_name', VARCHAR(20)),
     )
     metadata.create_all()
Ejemplo n.º 16
0
 def setUpAll(self):
     global metadata, foo
     metadata = MetaData(testing.db)
     foo = Table('foo', metadata, Column('id', Integer, primary_key=True),
                 Column('data', String(100)))
     metadata.create_all()
     testing.db.execute(
         "create function insert_foo(varchar) returns integer as 'insert into foo(data) values ($1);select 1;' language sql"
     )
Ejemplo n.º 17
0
 def setUpAll(self):
     global users, metadata
     metadata = MetaData(testing.db)
     users = Table(
         'users',
         metadata,
         Column('user_id', INT, primary_key=True),
         Column('user_name', VARCHAR(20)),
     )
     metadata.create_all()
Ejemplo n.º 18
0
    def test_override_nonexistent_fk(self):
        """test that you can override columns and create new foreign keys to other reflected tables
        which have no foreign keys.  this is common with MySQL MyISAM tables."""

        meta = MetaData(testing.db)
        users = Table('users', meta,
            Column('id', sa.Integer, primary_key=True),
            Column('name', sa.String(30)))
        addresses = Table('addresses', meta,
            Column('id', sa.Integer, primary_key=True),
            Column('street', sa.String(30)),
            Column('user_id', sa.Integer))

        meta.create_all()
        try:
            meta2 = MetaData(testing.db)
            a2 = Table('addresses', meta2,
                Column('user_id', sa.Integer, sa.ForeignKey('users.id')),
                autoload=True)
            u2 = Table('users', meta2, autoload=True)

            assert len(a2.c.user_id.foreign_keys) == 1
            assert len(a2.foreign_keys) == 1
            assert [c.parent for c in a2.foreign_keys] == [a2.c.user_id]
            assert [c.parent for c in a2.c.user_id.foreign_keys] == [a2.c.user_id]
            assert list(a2.c.user_id.foreign_keys)[0].parent is a2.c.user_id
            assert u2.join(a2).onclause == u2.c.id==a2.c.user_id

            meta3 = MetaData(testing.db)
            u3 = Table('users', meta3, autoload=True)
            a3 = Table('addresses', meta3,
                Column('user_id', sa.Integer, sa.ForeignKey('users.id')),
                autoload=True)

            assert u3.join(a3).onclause == u3.c.id==a3.c.user_id

            meta4 = MetaData(testing.db)
            u4 = Table('users', meta4,
                       Column('id', sa.Integer, key='u_id', primary_key=True),
                       autoload=True)
            a4 = Table('addresses', meta4,
                       Column('id', sa.Integer, key='street', primary_key=True),
                       Column('street', sa.String(30), key='user_id'),
                       Column('user_id', sa.Integer, sa.ForeignKey('users.u_id'),
                              key='id'),
                       autoload=True)

            assert u4.join(a4).onclause.compare(u4.c.u_id==a4.c.id)
            assert list(u4.primary_key) == [u4.c.u_id]
            assert len(u4.columns) == 2
            assert len(u4.constraints) == 1
            assert len(a4.columns) == 3
            assert len(a4.constraints) == 2
        finally:
            meta.drop_all()
Ejemplo n.º 19
0
    def test_mapper_reset(self):
        metadata = MetaData(testing.db)

        table1 = Table("mytable", metadata,
            Column('col1', Integer, primary_key=True),
            Column('col2', String(30)))

        table2 = Table("mytable2", metadata,
            Column('col1', Integer, primary_key=True),
            Column('col2', String(30)),
            Column('col3', Integer, ForeignKey("mytable.col1")))

        @profile_memory
        def go():
            m1 = mapper(A, table1, properties={
                "bs":relation(B, order_by=table2.c.col1)
            })
            m2 = mapper(B, table2)

            m3 = mapper(A, table1, non_primary=True)

            sess = create_session()
            a1 = A(col2="a1")
            a2 = A(col2="a2")
            a3 = A(col2="a3")
            a1.bs.append(B(col2="b1"))
            a1.bs.append(B(col2="b2"))
            a3.bs.append(B(col2="b3"))
            for x in [a1,a2,a3]:
                sess.add(x)
            sess.flush()
            sess.clear()

            alist = sess.query(A).order_by(A.col1).all()
            self.assertEquals(
                [
                    A(col2="a1", bs=[B(col2="b1"), B(col2="b2")]),
                    A(col2="a2", bs=[]),
                    A(col2="a3", bs=[B(col2="b3")])
                ],
                alist)

            for a in alist:
                sess.delete(a)
            sess.flush()
            sess.close()
            clear_mappers()

        metadata.create_all()
        try:
            go()
        finally:
            metadata.drop_all()
        assert_no_mappers()
Ejemplo n.º 20
0
 def setUp(self):
     global meta, table, engine
     engine = engines.reconnecting_engine()
     meta = MetaData(engine)
     table = Table('sometable', meta,
         Column('id', Integer, primary_key=True),
         Column('name', String(50)))
     meta.create_all()
     table.insert().execute(
         [{'id':i, 'name':'row %d' % i} for i in range(1, 100)]
     )
Ejemplo n.º 21
0
 def test_empty_insert(self):
     metadata = MetaData(testing.db)
     t1 = Table('t1', metadata,
             Column('is_true', Boolean, server_default=('1')))
     metadata.create_all()
     
     try:
         result = t1.insert().execute()
         self.assertEquals(1, select([func.count(text('*'))], from_obj=t1).scalar())
         self.assertEquals(True, t1.select().scalar())
     finally:
         metadata.drop_all()
Ejemplo n.º 22
0
    def test_override_existing_fk(self):
        """test that you can override columns and specify new foreign keys to other reflected tables,
        on columns which *do* already have that foreign key, and that the FK is not duped.
        """

        meta = MetaData(testing.db)
        users = Table('users', meta,
            Column('id', sa.Integer, primary_key=True),
            Column('name', sa.String(30)),
            test_needs_fk=True)
        addresses = Table('addresses', meta,
            Column('id', sa.Integer, primary_key=True),
            Column('user_id', sa.Integer, sa.ForeignKey('users.id')),
            test_needs_fk=True)

        meta.create_all()
        try:
            meta2 = MetaData(testing.db)
            a2 = Table('addresses', meta2,
                Column('user_id', sa.Integer, sa.ForeignKey('users.id')),
                autoload=True)
            u2 = Table('users', meta2, autoload=True)

            s = sa.select([a2])
            assert s.c.user_id
            assert len(a2.foreign_keys) == 1
            assert len(a2.c.user_id.foreign_keys) == 1
            assert len(a2.constraints) == 2
            assert [c.parent for c in a2.foreign_keys] == [a2.c.user_id]
            assert [c.parent for c in a2.c.user_id.foreign_keys] == [a2.c.user_id]
            assert list(a2.c.user_id.foreign_keys)[0].parent is a2.c.user_id
            assert u2.join(a2).onclause == u2.c.id==a2.c.user_id

            meta2 = MetaData(testing.db)
            u2 = Table('users', meta2,
                Column('id', sa.Integer, primary_key=True),
                autoload=True)
            a2 = Table('addresses', meta2,
                Column('id', sa.Integer, primary_key=True),
                Column('user_id', sa.Integer, sa.ForeignKey('users.id')),
                autoload=True)

            s = sa.select([a2])
            assert s.c.user_id
            assert len(a2.foreign_keys) == 1
            assert len(a2.c.user_id.foreign_keys) == 1
            assert len(a2.constraints) == 2
            assert [c.parent for c in a2.foreign_keys] == [a2.c.user_id]
            assert [c.parent for c in a2.c.user_id.foreign_keys] == [a2.c.user_id]
            assert list(a2.c.user_id.foreign_keys)[0].parent is a2.c.user_id
            assert u2.join(a2).onclause == u2.c.id==a2.c.user_id
        finally:
            meta.drop_all()
Ejemplo n.º 23
0
 def _test_get_table_oid(self, table_name, schema=None):
     if testing.against('postgres'):
         meta = MetaData(testing.db)
         (users, addresses) = createTables(meta, schema)
         meta.create_all()
         try:
             insp = create_inspector(meta.bind)
             oid = insp.get_table_oid(table_name, schema)
             self.assert_(isinstance(oid, int))
         finally:
             addresses.drop()
             users.drop()
Ejemplo n.º 24
0
 def setUp(self):
     global meta, table, engine
     engine = engines.reconnecting_engine()
     meta = MetaData(engine)
     table = Table('sometable', meta, Column('id',
                                             Integer,
                                             primary_key=True),
                   Column('name', String(50)))
     meta.create_all()
     table.insert().execute([{
         'id': i,
         'name': 'row %d' % i
     } for i in range(1, 100)])
Ejemplo n.º 25
0
    def test_override_nonexistent_fk(self):
        """test that you can override columns and create new foreign keys to other reflected tables
        which have no foreign keys.  this is common with MySQL MyISAM tables."""

        meta = MetaData(testing.db)
        users = Table('users', meta,
            Column('id', sa.Integer, primary_key=True),
            Column('name', sa.String(30)))
        addresses = Table('addresses', meta,
            Column('id', sa.Integer, primary_key=True),
            Column('street', sa.String(30)),
            Column('user_id', sa.Integer))

        meta.create_all()
        try:
            meta2 = MetaData(testing.db)
            a2 = Table('addresses', meta2,
                Column('user_id', sa.Integer, sa.ForeignKey('users.id')),
                autoload=True)
            u2 = Table('users', meta2, autoload=True)

            assert len(a2.c.user_id.foreign_keys) == 1
            assert len(a2.foreign_keys) == 1
            assert [c.parent for c in a2.foreign_keys] == [a2.c.user_id]
            assert [c.parent for c in a2.c.user_id.foreign_keys] == [a2.c.user_id]
            assert list(a2.c.user_id.foreign_keys)[0].parent is a2.c.user_id
            assert u2.join(a2).onclause == u2.c.id==a2.c.user_id

            meta3 = MetaData(testing.db)
            u3 = Table('users', meta3, autoload=True)
            a3 = Table('addresses', meta3,
                Column('user_id', sa.Integer, sa.ForeignKey('users.id')),
                autoload=True)

            assert u3.join(a3).onclause == u3.c.id==a3.c.user_id

            meta4 = MetaData(testing.db)
            u4 = Table('users', meta4,
                       Column('id', sa.Integer, key='u_id', primary_key=True),
                       autoload=True)
            a4 = Table('addresses', meta4,
                       Column('id', sa.Integer, key='street', primary_key=True),
                       Column('street', sa.String(30), key='user_id'),
                       Column('user_id', sa.Integer, sa.ForeignKey('users.u_id'),
                              key='id'),
                       autoload=True)

            assert u4.join(a4).onclause.compare(u4.c.u_id==a4.c.id)
            assert list(u4.primary_key) == [u4.c.u_id]
            assert len(u4.columns) == 2
            assert len(u4.constraints) == 1
            assert len(a4.columns) == 3
            assert len(a4.constraints) == 2
        finally:
            meta.drop_all()
Ejemplo n.º 26
0
    def test_include_columns(self):
        meta = MetaData(testing.db)
        foo = Table('foo', meta, *[Column(n, sa.String(30))
                                   for n in ['a', 'b', 'c', 'd', 'e', 'f']])
        meta.create_all()
        try:
            meta2 = MetaData(testing.db)
            foo = Table('foo', meta2, autoload=True,
                        include_columns=['b', 'f', 'e'])
            # test that cols come back in original order
            self.assertEquals([c.name for c in foo.c], ['b', 'e', 'f'])
            for c in ('b', 'f', 'e'):
                assert c in foo.c
            for c in ('a', 'c', 'd'):
                assert c not in foo.c

            # test against a table which is already reflected
            meta3 = MetaData(testing.db)
            foo = Table('foo', meta3, autoload=True)
            foo = Table('foo', meta3, include_columns=['b', 'f', 'e'],
                        useexisting=True)
            self.assertEquals([c.name for c in foo.c], ['b', 'e', 'f'])
            for c in ('b', 'f', 'e'):
                assert c in foo.c
            for c in ('a', 'c', 'd'):
                assert c not in foo.c
        finally:
            meta.drop_all()
Ejemplo n.º 27
0
 def setUpAll(self):
     global metadata, users
     metadata = MetaData()
     users = Table('users', metadata,
                   Column('user_id', sa.Integer, sa.Sequence('user_id_seq'), primary_key=True),
                   Column('user_name', sa.String(40)),
                   )
Ejemplo n.º 28
0
    def _test_get_primary_keys(self, schema=None):
        meta = MetaData(testing.db)
        (users, addresses) = createTables(meta, schema)
        meta.create_all()
        insp = Inspector(meta.bind)
        try:
            users_pkeys = insp.get_primary_keys(users.name,
                                                schema=schema)
            self.assertEqual(users_pkeys,  ['user_id'])
            addr_pkeys = insp.get_primary_keys(addresses.name,
                                               schema=schema)
            self.assertEqual(addr_pkeys,  ['address_id'])

        finally:
            addresses.drop()
            users.drop()
Ejemplo n.º 29
0
    def test_tokens(self):
        m = MetaData()
        bind = self.mock_engine()
        sane_alone = Table('t', m, Column('id', Integer))
        sane_schema = Table('t', m, Column('id', Integer), schema='s')
        insane_alone = Table('t t', m, Column('id', Integer))
        insane_schema = Table('t t', m, Column('id', Integer), schema='s s')

        ddl = DDL('%(schema)s-%(table)s-%(fullname)s')

        self.assertEquals(ddl._expand(sane_alone, bind), '-t-t')
        self.assertEquals(ddl._expand(sane_schema, bind), 's-t-s.t')
        self.assertEquals(ddl._expand(insane_alone, bind), '-"t t"-"t t"')
        self.assertEquals(ddl._expand(insane_schema, bind),
                          '"s s"-"t t"-"s s"."t t"')

        # overrides are used piece-meal and verbatim.
        ddl = DDL('%(schema)s-%(table)s-%(fullname)s-%(bonus)s',
                  context={
                      'schema': 'S S',
                      'table': 'T T',
                      'bonus': 'b'
                  })
        self.assertEquals(ddl._expand(sane_alone, bind), 'S S-T T-t-b')
        self.assertEquals(ddl._expand(sane_schema, bind), 'S S-T T-s.t-b')
        self.assertEquals(ddl._expand(insane_alone, bind), 'S S-T T-"t t"-b')
        self.assertEquals(ddl._expand(insane_schema, bind),
                          'S S-T T-"s s"."t t"-b')
Ejemplo n.º 30
0
    def test_passive_override(self):
        """
        Primarily for postgres, tests that when we get a primary key column
        back from reflecting a table which has a default value on it, we
        pre-execute that DefaultClause upon insert, even though DefaultClause
        says "let the database execute this", because in postgres we must have
        all the primary key values in memory before insert; otherwise we can't
        locate the just inserted row.

        """
        # TODO: move this to dialect/postgres
        try:
            meta = MetaData(testing.db)
            testing.db.execute(
                """
             CREATE TABLE speedy_users
             (
                 speedy_user_id   SERIAL     PRIMARY KEY,

                 user_name        VARCHAR    NOT NULL,
                 user_password    VARCHAR    NOT NULL
             );
            """, None)

            t = Table("speedy_users", meta, autoload=True)
            t.insert().execute(user_name='user', user_password='******')
            l = t.select().execute().fetchall()
            eq_(l, [(1, 'user', 'lala')])
        finally:
            testing.db.execute("drop table speedy_users", None)
Ejemplo n.º 31
0
    def setUpAll(self):
        global metadata, users
        metadata = MetaData()
        users = Table('users', metadata,
                      Column('user_id', sa.Integer, sa.Sequence('user_id_seq', optional=True), primary_key=True),
                      Column('user_name', sa.String(40)),
                      )

        addresses = Table('email_addresses', metadata,
            Column('address_id', sa.Integer, sa.Sequence('address_id_seq', optional=True), primary_key = True),
            Column('user_id', sa.Integer, sa.ForeignKey(users.c.user_id)),
            Column('email_address', sa.String(40)),
        )

        orders = Table('orders', metadata,
            Column('order_id', sa.Integer, sa.Sequence('order_id_seq', optional=True), primary_key = True),
            Column('user_id', sa.Integer, sa.ForeignKey(users.c.user_id)),
            Column('description', sa.String(50)),
            Column('isopen', sa.Integer),
        )

        orderitems = Table('items', metadata,
            Column('item_id', sa.INT, sa.Sequence('items_id_seq', optional=True), primary_key = True),
            Column('order_id', sa.INT, sa.ForeignKey("orders")),
            Column('item_name', sa.VARCHAR(50)),
        )
Ejemplo n.º 32
0
 def test_iteration(self):
     metadata = MetaData()
     table1 = Table('table1', metadata,
         Column('col1', sa.Integer, primary_key=True),
         schema='someschema')
     table2 = Table('table2', metadata,
         Column('col1', sa.Integer, primary_key=True),
         Column('col2', sa.Integer, sa.ForeignKey('someschema.table1.col1')),
         schema='someschema')
     # ensure this doesnt crash
     print [t for t in metadata.sorted_tables]
     buf = StringIO.StringIO()
     def foo(s, p=None):
         buf.write(s)
     gen = sa.create_engine(testing.db.name + "://", strategy="mock", executor=foo)
     gen = gen.dialect.schemagenerator(gen.dialect, gen)
     gen.traverse(table1)
     gen.traverse(table2)
     buf = buf.getvalue()
     print buf
     if testing.db.dialect.preparer(testing.db.dialect).omit_schema:
         assert buf.index("CREATE TABLE table1") > -1
         assert buf.index("CREATE TABLE table2") > -1
     else:
         assert buf.index("CREATE TABLE someschema.table1") > -1
         assert buf.index("CREATE TABLE someschema.table2") > -1
Ejemplo n.º 33
0
    def test_compileonattr_rel_backref_a(self):
        m = MetaData()
        t1 = Table('t1', m, Column('id', Integer, primary_key=True),
                   Column('x', Integer))
        t2 = Table('t2', m, Column('id', Integer, primary_key=True),
                   Column('t1_id', Integer, ForeignKey('t1.id')))

        class Base(object):
            def __init__(self, *args, **kwargs):
                pass

        for base in object, Base:

            class A(base):
                pass

            class B(base):
                pass

            mapper(A, t1, properties=dict(bs=relation(B, backref='a')))
            mapper(B, t2)

            b = B()
            assert b.a is None
            a = A()
            b.a = a

            session = create_session()
            session.add(b)
            assert a in session, "base is %s" % base
Ejemplo n.º 34
0
    def test_rekey(self):
        meta = MetaData(testing.db)

        class User(Base, ComparableEntity):
            __tablename__ = 'users'
            __autoload__ = True
            nom = Column('name', String(50), key='nom')
            addresses = relation("Address", backref="user")

        class Address(Base, ComparableEntity):
            __tablename__ = 'addresses'
            __autoload__ = True

        u1 = User(nom='u1', addresses=[
            Address(email='one'),
            Address(email='two'),
            ])
        sess = create_session()
        sess.add(u1)
        sess.flush()
        sess.clear()

        eq_(sess.query(User).all(), [User(nom='u1', addresses=[
            Address(email='one'),
            Address(email='two'),
            ])])

        a1 = sess.query(Address).filter(Address.email == 'two').one()
        eq_(a1, Address(email='two'))
        eq_(a1.user, User(nom='u1'))

        self.assertRaises(TypeError, User, name='u3')
Ejemplo n.º 35
0
    def setUpAll(self):
        global cartitems, sometable, metadata
        metadata = MetaData(testing.db)
        cartitems = Table("cartitems", metadata,
            Column("cart_id", Integer, Sequence('cart_id_seq'), primary_key=True),
            Column("description", String(40)),
            Column("createdate", sa.DateTime())
        )
        sometable = Table( 'Manager', metadata,
               Column('obj_id', Integer, Sequence('obj_id_seq'), ),
               Column('name', String(128)),
               Column('id', Integer, Sequence('Manager_id_seq', optional=True),
                      primary_key=True),
           )

        metadata.create_all()
Ejemplo n.º 36
0
    def test_basic(self):
        meta = MetaData(testing.db)

        class User(Base, ComparableEntity):
            __tablename__ = 'users'
            __autoload__ = True
            addresses = relation("Address", backref="user")

        class Address(Base, ComparableEntity):
            __tablename__ = 'addresses'
            __autoload__ = True

        u1 = User(name='u1', addresses=[
            Address(email='one'),
            Address(email='two'),
            ])
        sess = create_session()
        sess.add(u1)
        sess.flush()
        sess.clear()

        eq_(sess.query(User).all(), [User(name='u1', addresses=[
            Address(email='one'),
            Address(email='two'),
            ])])

        a1 = sess.query(Address).filter(Address.email == 'two').one()
        eq_(a1, Address(email='two'))
        eq_(a1.user, User(name='u1'))
Ejemplo n.º 37
0
    def test_supplied_fk(self):
        meta = MetaData(testing.db)

        class IMHandle(Base, ComparableEntity):
            __tablename__ = 'imhandles'
            __autoload__ = True

            user_id = Column('user_id', Integer,
                             ForeignKey('users.id'))
        class User(Base, ComparableEntity):
            __tablename__ = 'users'
            __autoload__ = True
            handles = relation("IMHandle", backref="user")

        u1 = User(name='u1', handles=[
            IMHandle(network='blabber', handle='foo'),
            IMHandle(network='lol', handle='zomg')
            ])
        sess = create_session()
        sess.add(u1)
        sess.flush()
        sess.clear()

        eq_(sess.query(User).all(), [User(name='u1', handles=[
            IMHandle(network='blabber', handle='foo'),
            IMHandle(network='lol', handle='zomg')
            ])])

        a1 = sess.query(IMHandle).filter(IMHandle.handle == 'zomg').one()
        eq_(a1, IMHandle(network='lol', handle='zomg'))
        eq_(a1.user, User(name='u1'))
Ejemplo n.º 38
0
    def test_compileonattr_rel_backref_b(self):
        m = MetaData()
        t1 = Table('t1', m, Column('id', Integer, primary_key=True),
                   Column('x', Integer))
        t2 = Table('t2', m, Column('id', Integer, primary_key=True),
                   Column('t1_id', Integer, ForeignKey('t1.id')))

        class Base(object):
            def __init__(self):
                pass

        class Base_AKW(object):
            def __init__(self, *args, **kwargs):
                pass

        for base in object, Base, Base_AKW:

            class A(base):
                pass

            class B(base):
                pass

            mapper(A, t1)
            mapper(B, t2, properties=dict(a=relation(A, backref='bs')))

            a = A()
            b = B()
            b.a = a

            session = create_session()
            session.add(a)
            assert b in session, 'base: %s' % base
Ejemplo n.º 39
0
    def test_mutable_identity(self):
        metadata = MetaData(testing.db)

        table1 = Table("mytable", metadata,
            Column('col1', Integer, primary_key=True),
            Column('col2', PickleType(comparator=operator.eq))
            )
        
        class Foo(object):
            def __init__(self, col2):
                self.col2 = col2
        
        mapper(Foo, table1)
        metadata.create_all()
        
        session = sessionmaker()()
        
        def go():
            obj = [
                Foo({'a':1}),
                Foo({'b':1}),
                Foo({'c':1}),
                Foo({'d':1}),
                Foo({'e':1}),
                Foo({'f':1}),
                Foo({'g':1}),
                Foo({'h':1}),
                Foo({'i':1}),
                Foo({'j':1}),
                Foo({'k':1}),
                Foo({'l':1}),
            ]
            
            session.add_all(obj)
            session.commit()
            
            testing.eq_(len(session.identity_map._mutable_attrs), 12)
            testing.eq_(len(session.identity_map), 12)
            obj = None
            gc.collect()
            testing.eq_(len(session.identity_map._mutable_attrs), 0)
            testing.eq_(len(session.identity_map), 0)
            
        try:
            go()
        finally:
            metadata.drop_all()
Ejemplo n.º 40
0
 def _test_get_view_definition(self, schema=None):
     meta = MetaData(testing.db)
     (users, addresses) = createTables(meta, schema)
     meta.create_all()
     createViews(meta.bind, schema)
     view_name1 = 'users_v'
     view_name2 = 'email_addresses_v'
     try:
         insp = Inspector(meta.bind)
         v1 = insp.get_view_definition(view_name1, schema=schema)
         self.assert_(v1)
         v2 = insp.get_view_definition(view_name2, schema=schema)
         self.assert_(v2)
     finally:
         dropViews(meta.bind, schema)
         addresses.drop()
         users.drop()
Ejemplo n.º 41
0
 def test_implicit_sequence_exec(self):
     s = Sequence("my_sequence", metadata=MetaData(testing.db))
     s.create()
     try:
         x = s.execute()
         eq_(x, 1)
     finally:
         s.drop()
Ejemplo n.º 42
0
    def test_mapped_managerattr(self):
        t = Table('t', MetaData(), Column('id', Integer, primary_key=True),
                  Column(attributes.ClassManager.MANAGER_ATTR, Integer))

        class T(object):
            pass

        self.assertRaises(KeyError, mapper, T, t)
Ejemplo n.º 43
0
 def test_nonreflected_fk_raises(self):
     """test that a NoReferencedColumnError is raised when reflecting
     a table with an FK to another table which has not included the target
     column in its reflection.
     
     """
     meta = MetaData(testing.db)
     a1 = Table('a', meta,
         Column('x', sa.Integer, primary_key=True),
         Column('z', sa.Integer),
         test_needs_fk=True
     )
     b1 = Table('b', meta,
         Column('y', sa.Integer, sa.ForeignKey('a.x')),
         test_needs_fk=True
     )
     meta.create_all()
     try:
         m2 = MetaData(testing.db)
         a2 = Table('a', m2, include_columns=['z'], autoload=True)
         b2 = Table('b', m2, autoload=True)
         
         self.assertRaises(tsa.exc.NoReferencedColumnError, a2.join, b2)
     finally:
         meta.drop_all()
Ejemplo n.º 44
0
    def test_composite_fk(self):
        """test reflection of composite foreign keys"""

        meta = MetaData(testing.db)
        multi = Table(
            'multi', meta,
            Column('multi_id', sa.Integer, primary_key=True),
            Column('multi_rev', sa.Integer, primary_key=True),
            Column('multi_hoho', sa.Integer, primary_key=True),
            Column('name', sa.String(50), nullable=False),
            Column('val', sa.String(100)),
            test_needs_fk=True,
        )
        multi2 = Table('multi2', meta,
            Column('id', sa.Integer, primary_key=True),
            Column('foo', sa.Integer),
            Column('bar', sa.Integer),
            Column('lala', sa.Integer),
            Column('data', sa.String(50)),
            sa.ForeignKeyConstraint(['foo', 'bar', 'lala'], ['multi.multi_id', 'multi.multi_rev', 'multi.multi_hoho']),
            test_needs_fk=True,
        )
        meta.create_all()

        try:
            meta2 = MetaData()
            table = Table('multi', meta2, autoload=True, autoload_with=testing.db)
            table2 = Table('multi2', meta2, autoload=True, autoload_with=testing.db)
            self.assert_tables_equal(multi, table)
            self.assert_tables_equal(multi2, table2)
            j = sa.join(table, table2)
            self.assert_(sa.and_(table.c.multi_id==table2.c.foo, table.c.multi_rev==table2.c.bar, table.c.multi_hoho==table2.c.lala).compare(j.onclause))
        finally:
            meta.drop_all()
Ejemplo n.º 45
0
    def test_index_reflection(self):
        m1 = MetaData(testing.db)
        t1 = Table('party', m1,
            Column('id', sa.Integer, nullable=False),
            Column('name', sa.String(20), index=True)
            )
        i1 = sa.Index('idx1', t1.c.id, unique=True)
        i2 = sa.Index('idx2', t1.c.name, t1.c.id, unique=False)
        m1.create_all()
        try:
            m2 = MetaData(testing.db)
            t2 = Table('party', m2, autoload=True)

            print len(t2.indexes), t2.indexes
            assert len(t2.indexes) == 3
            # Make sure indexes are in the order we expect them in
            tmp = [(idx.name, idx) for idx in t2.indexes]
            tmp.sort()
            r1, r2, r3 = [idx[1] for idx in tmp]

            assert r1.name == 'idx1'
            assert r2.name == 'idx2'
            assert r1.unique == True
            assert r2.unique == False
            assert r3.unique == False
            assert [t2.c.id] == r1.columns
            assert [t2.c.name, t2.c.id] == r2.columns
            assert [t2.c.name] == r3.columns
        finally:
            m1.drop_all()
Ejemplo n.º 46
0
    def test_override_keys(self):
        """test that columns can be overridden with a 'key', 
        and that ForeignKey targeting during reflection still works."""
        

        meta = MetaData(testing.db)
        a1 = Table('a', meta,
            Column('x', sa.Integer, primary_key=True),
            Column('z', sa.Integer),
            test_needs_fk=True
        )
        b1 = Table('b', meta,
            Column('y', sa.Integer, sa.ForeignKey('a.x')),
            test_needs_fk=True
        )
        meta.create_all()
        try:
            m2 = MetaData(testing.db)
            a2 = Table('a', m2, Column('x', sa.Integer, primary_key=True, key='x1'), autoload=True)
            b2 = Table('b', m2, autoload=True)
            
            assert a2.join(b2).onclause.compare(a2.c.x1==b2.c.y)
            assert b2.c.y.references(a2.c.x1)
        finally:
            meta.drop_all()
Ejemplo n.º 47
0
 def test_fk_error(self):
     metadata = MetaData(testing.db)
     slots_table = Table('slots', metadata,
         Column('slot_id', sa.Integer, primary_key=True),
         Column('pkg_id', sa.Integer, sa.ForeignKey('pkgs.pkg_id')),
         Column('slot', sa.String(128)),
         )
         
     self.assertRaisesMessage(tsa.exc.InvalidRequestError, "Could not find table 'pkgs' with which to generate a foreign key", metadata.create_all)
Ejemplo n.º 48
0
 def setUp(self):
     self.engine = engines.mock_engine()
     self.metadata = MetaData(self.engine)
     self.users = Table(
         'users',
         self.metadata,
         Column('user_id', Integer, primary_key=True),
         Column('user_name', String(40)),
     )
Ejemplo n.º 49
0
    def test_with_explicit_autoloaded(self):
        meta = MetaData(testing.db)
        t1 = Table('t1', meta,
                   Column('id', String(50), primary_key=True),
                   Column('data', String(50)))
        meta.create_all()
        try:
            class MyObj(Base):
                __table__ = Table('t1', Base.metadata, autoload=True)

            sess = create_session()
            m = MyObj(id="someid", data="somedata")
            sess.add(m)
            sess.flush()

            eq_(t1.select().execute().fetchall(), [('someid', 'somedata')])
        finally:
            meta.drop_all()
Ejemplo n.º 50
0
 def _test_get_columns(self, schema=None, table_type='table'):
     meta = MetaData(testing.db)
     (users, addresses) = createTables(meta, schema)
     table_names = ['users', 'email_addresses']
     meta.create_all()
     if table_type == 'view':
         createViews(meta.bind, schema)
         table_names = ['users_v', 'email_addresses_v']
     try:
         insp = Inspector(meta.bind)
         for (table_name, table) in zip(table_names, (users, addresses)):
             schema_name = schema
             if schema and testing.against('oracle'):
                 schema_name = schema.upper()
             cols = insp.get_columns(table_name, schema=schema_name)
             self.assert_(len(cols) > 0, len(cols))
             # should be in order
             for (i, col) in enumerate(table.columns):
                 self.assertEqual(col.name, cols[i]['name'])
                 # coltype is tricky
                 # It may not inherit from col.type while they share
                 # the same base.
                 ctype = cols[i]['type'].__class__
                 ctype_def = col.type
                 if isinstance(ctype_def, sa.types.TypeEngine):
                     ctype_def = ctype_def.__class__
                 # Oracle returns Date for DateTime.
                 if testing.against('oracle') \
                     and ctype_def in (sql_types.Date, sql_types.DateTime):
                         ctype_def = sql_types.Date
                 self.assert_(
                     issubclass(ctype, ctype_def) or \
                     len(
                         set(
                             ctype.__bases__
                         ).intersection(ctype_def.__bases__)) > 0
                 ,("%s(%s), %s(%s)" % (col.name, col.type, cols[i]['name'],
                                       ctype)))
     finally:
         if table_type == 'view':
             dropViews(meta.bind, schema)
         addresses.drop()
         users.drop()
Ejemplo n.º 51
0
 def setUpAll(self):
     global users, metadata
     metadata = MetaData()
     users = Table(
         'query_users',
         metadata,
         Column('user_id', INT, primary_key=True),
         Column('user_name', VARCHAR(20)),
         test_needs_acid=True,
     )
     users.create(testing.db)
Ejemplo n.º 52
0
 def setUpAll(self):
     global counters, metadata
     metadata = MetaData()
     counters = Table(
         'forupdate_counters',
         metadata,
         Column('counter_id', INT, primary_key=True),
         Column('counter_value', INT),
         test_needs_acid=True,
     )
     counters.create(testing.db)
Ejemplo n.º 53
0
    def test_compileonattr(self):
        t = Table('t', MetaData(), Column('id', Integer, primary_key=True),
                  Column('x', Integer))

        class A(object):
            pass

        mapper(A, t)

        a = A()
        assert a.id is None
Ejemplo n.º 54
0
    def test_basic_reflection(self):
        meta = MetaData(testing.db)

        users = Table('engine_users', meta,
            Column('user_id', sa.INT, primary_key=True),
            Column('user_name', sa.VARCHAR(20), nullable=False),
            Column('test1', sa.CHAR(5), nullable=False),
            Column('test2', sa.Float(5), nullable=False),
            Column('test3', sa.Text),
            Column('test4', sa.Numeric, nullable = False),
            Column('test5', sa.DateTime),
            Column('parent_user_id', sa.Integer,
                   sa.ForeignKey('engine_users.user_id')),
            Column('test6', sa.DateTime, nullable=False),
            Column('test7', sa.Text),
            Column('test8', sa.Binary),
            Column('test_passivedefault2', sa.Integer, server_default='5'),
            Column('test9', sa.Binary(100)),
            Column('test_numeric', sa.Numeric()),
            test_needs_fk=True,
        )

        addresses = Table('engine_email_addresses', meta,
            Column('address_id', sa.Integer, primary_key = True),
            Column('remote_user_id', sa.Integer, sa.ForeignKey(users.c.user_id)),
            Column('email_address', sa.String(20)),
            test_needs_fk=True,
        )
        meta.create_all()

        try:
            meta2 = MetaData()
            reflected_users = Table('engine_users', meta2, autoload=True,
                                    autoload_with=testing.db)
            reflected_addresses = Table('engine_email_addresses', meta2,
                                        autoload=True, autoload_with=testing.db)
            self.assert_tables_equal(users, reflected_users)
            self.assert_tables_equal(addresses, reflected_addresses)
        finally:
            addresses.drop()
            users.drop()
Ejemplo n.º 55
0
    def test_reserved(self):
        # check a table that uses an SQL reserved name doesn't cause an error
        meta = MetaData(testing.db)
        table_a = Table('select', meta,
                       Column('not', sa.Integer, primary_key=True),
                       Column('from', sa.String(12), nullable=False),
                       sa.UniqueConstraint('from', name='when'))
        sa.Index('where', table_a.c['from'])

        # There's currently no way to calculate identifier case normalization
        # in isolation, so...
        if testing.against('firebird', 'oracle', 'maxdb'):
            check_col = 'TRUE'
        else:
            check_col = 'true'
        quoter = meta.bind.dialect.identifier_preparer.quote_identifier

        table_b = Table('false', meta,
                        Column('create', sa.Integer, primary_key=True),
                        Column('true', sa.Integer, sa.ForeignKey('select.not')),
                        sa.CheckConstraint('%s <> 1' % quoter(check_col),
                                        name='limit'))

        table_c = Table('is', meta,
                        Column('or', sa.Integer, nullable=False, primary_key=True),
                        Column('join', sa.Integer, nullable=False, primary_key=True),
                        sa.PrimaryKeyConstraint('or', 'join', name='to'))

        index_c = sa.Index('else', table_c.c.join)

        meta.create_all()

        index_c.drop()

        meta2 = MetaData(testing.db)
        try:
            table_a2 = Table('select', meta2, autoload=True)
            table_b2 = Table('false', meta2, autoload=True)
            table_c2 = Table('is', meta2, autoload=True)
        finally:
            meta.drop_all()
Ejemplo n.º 56
0
    def setUpAll(self):
        global reflection_metadata
        reflection_metadata = MetaData(testing.db)

        Table('users', reflection_metadata,
              Column('id', Integer, primary_key=True),
              Column('name', String(50)),
              test_needs_fk=True)
        Table('addresses', reflection_metadata,
              Column('id', Integer, primary_key=True),
              Column('email', String(50)),
              Column('user_id', Integer, ForeignKey('users.id')),
              test_needs_fk=True)
        Table('imhandles', reflection_metadata,
              Column('id', Integer, primary_key=True),
              Column('user_id', Integer),
              Column('network', String(50)),
              Column('handle', String(50)),
              test_needs_fk=True)

        reflection_metadata.create_all()
Ejemplo n.º 57
0
    def test_override_pkfk(self):
        """test that you can override columns which contain foreign keys to other reflected tables,
        where the foreign key column is also a primary key column"""

        meta = MetaData(testing.db)
        users = Table('users', meta,
            Column('id', sa.Integer, primary_key=True),
            Column('name', sa.String(30)))
        addresses = Table('addresses', meta,
            Column('id', sa.Integer, primary_key=True),
            Column('street', sa.String(30)))


        meta.create_all()
        try:
            meta2 = MetaData(testing.db)
            a2 = Table('addresses', meta2,
                Column('id', sa.Integer,
                       sa.ForeignKey('users.id'), primary_key=True),
                autoload=True)
            u2 = Table('users', meta2, autoload=True)

            assert list(a2.primary_key) == [a2.c.id]
            assert list(u2.primary_key) == [u2.c.id]
            assert u2.join(a2).onclause == u2.c.id==a2.c.id

            meta3 = MetaData(testing.db)
            u3 = Table('users', meta3, autoload=True)
            a3 = Table('addresses', meta3,
                Column('id', sa.Integer, sa.ForeignKey('users.id'),
                       primary_key=True),
                autoload=True)

            assert list(a3.primary_key) == [a3.c.id]
            assert list(u3.primary_key) == [u3.c.id]
            assert u3.join(a3).onclause == u3.c.id==a3.c.id

        finally:
            meta.drop_all()
Ejemplo n.º 58
0
    def test_join_cache(self):
        metadata = MetaData(testing.db)

        table1 = Table("table1", metadata,
            Column('id', Integer, primary_key=True),
            Column('data', String(30))
            )

        table2 = Table("table2", metadata,
            Column('id', Integer, primary_key=True),
            Column('data', String(30)),
            Column('t1id', Integer, ForeignKey('table1.id'))
            )
        
        class Foo(object):
            pass
            
        class Bar(object):
            pass
            
        mapper(Foo, table1, properties={
            'bars':relation(mapper(Bar, table2))
        })
        metadata.create_all()

        session = sessionmaker()
        
        @profile_memory
        def go():
            s = table2.select()
            sess = session()
            sess.query(Foo).join((s, Foo.bars)).all()
            sess.rollback()
        try:
            go()
        finally:
            metadata.drop_all()
Ejemplo n.º 59
0
    def test_explicit_default_schema(self):
        engine = testing.db

        if testing.against('mysql+mysqldb'):
            schema = testing.db.url.database
        elif testing.against('postgres'):
            schema = 'public'
        elif testing.against('sqlite'):
            # Works for CREATE TABLE main.foo, SELECT FROM main.foo, etc.,
            # but fails on:
            #   FOREIGN KEY(col2) REFERENCES main.table1 (col1)
            schema = 'main'
        else:
            schema = engine.dialect.get_default_schema_name(engine.connect())

        metadata = MetaData(engine)
        table1 = Table('table1', metadata,
                       Column('col1', sa.Integer, primary_key=True),
                       test_needs_fk=True,
                       schema=schema)
        table2 = Table('table2', metadata,
                       Column('col1', sa.Integer, primary_key=True),
                       Column('col2', sa.Integer,
                              sa.ForeignKey('%s.table1.col1' % schema)),
                       test_needs_fk=True,
                       schema=schema)
        try:
            metadata.create_all()
            metadata.create_all(checkfirst=True)
            assert len(metadata.tables) == 2
            metadata.clear()

            table1 = Table('table1', metadata, autoload=True, schema=schema)
            table2 = Table('table2', metadata, autoload=True, schema=schema)
            assert len(metadata.tables) == 2
        finally:
            metadata.drop_all()