Exemplo n.º 1
0
 def mydefault_using_connection(ctx):
     conn = ctx.connection
     try:
         return conn.execute(sa.select([sa.text('12')])).scalar()
     finally:
         # ensure a "close()" on this connection does nothing,
         # since its a "branched" connection
         conn.close()
Exemplo n.º 2
0
 def mydefault_using_connection(ctx):
     conn = ctx.connection
     try:
         return conn.execute(sa.select([sa.text('12')])).scalar()
     finally:
         # ensure a "close()" on this connection does nothing,
         # since its a "branched" connection
         conn.close()
Exemplo n.º 3
0
    def test_autoincrement_single_col(self):
        single = Table('single', self.metadata,
                       Column('id', Integer, primary_key=True))
        single.create()

        r = single.insert().execute()
        id_ = r.last_inserted_ids()[0]
        assert id_ is not None
        eq_(1, sa.select([func.count(sa.text('*'))], from_obj=single).scalar())
Exemplo n.º 4
0
    def test_autoincrement_single_col(self):
        single = Table('single', self.metadata,
                       Column('id', Integer, primary_key=True))
        single.create()

        r = single.insert().execute()
        id_ = r.last_inserted_ids()[0]
        assert id_ is not None
        eq_(1, sa.select([func.count(sa.text('*'))], from_obj=single).scalar())
Exemplo n.º 5
0
    def test_implicit_text(self):
        conn1 = testing.db.connect()
        conn2 = testing.db.connect()

        conn1.execute(text("insert into foo (data) values ('implicitdata')"))
        assert conn2.execute(select([foo.c.data])).fetchall() == [('implicitdata',)]

        conn1.close()
        conn2.close()
Exemplo n.º 6
0
    def test_explicit_text(self):
        conn1 = testing.db.connect()
        conn2 = testing.db.connect()

        conn1.execute(text("select insert_foo('moredata')", autocommit=True))
        assert conn2.execute(select([foo.c.data])).fetchall() == [('moredata',)]

        conn1.close()
        conn2.close()
Exemplo n.º 7
0
    def test_implicit_text(self):
        conn1 = testing.db.connect()
        conn2 = testing.db.connect()

        conn1.execute(text("insert into foo (data) values ('implicitdata')"))
        assert conn2.execute(select([foo.c.data
                                     ])).fetchall() == [('implicitdata', )]

        conn1.close()
        conn2.close()
Exemplo n.º 8
0
    def test_explicit_text(self):
        conn1 = testing.db.connect()
        conn2 = testing.db.connect()

        conn1.execute(text("select insert_foo('moredata')", autocommit=True))
        assert conn2.execute(select([foo.c.data
                                     ])).fetchall() == [('moredata', )]

        conn1.close()
        conn2.close()
Exemplo n.º 9
0
    def test_control(self):
        # test that not using autocommit does not commit
        conn1 = testing.db.connect()
        conn2 = testing.db.connect()

        conn1.execute(select([func.insert_foo('data1')]))
        assert conn2.execute(select([foo.c.data])).fetchall() == []

        conn1.execute(text("select insert_foo('moredata')"))
        assert conn2.execute(select([foo.c.data])).fetchall() == []

        trans = conn1.begin()
        trans.commit()

        assert conn2.execute(select([foo.c.data])).fetchall() == [('data1',), ('moredata',)]

        conn1.close()
        conn2.close()
Exemplo n.º 10
0
    def test_control(self):
        # test that not using autocommit does not commit
        conn1 = testing.db.connect()
        conn2 = testing.db.connect()

        conn1.execute(select([func.insert_foo('data1')]))
        assert conn2.execute(select([foo.c.data])).fetchall() == []

        conn1.execute(text("select insert_foo('moredata')"))
        assert conn2.execute(select([foo.c.data])).fetchall() == []

        trans = conn1.begin()
        trans.commit()

        assert conn2.execute(select([foo.c.data
                                     ])).fetchall() == [('data1', ),
                                                        ('moredata', )]

        conn1.close()
        conn2.close()
Exemplo n.º 11
0
    def test_clauseelement(self):
        metadata = MetaData()
        table = Table('test_table', metadata,
            Column('foo', Integer))
        metadata.create_all(bind=testing.db)
        try:
            for elem in [
                table.select,
                lambda **kwargs: sa.func.current_timestamp(**kwargs).select(),
#                func.current_timestamp().select,
                lambda **kwargs:text("select * from test_table", **kwargs)
            ]:
                for bind in (
                    testing.db,
                    testing.db.connect()
                ):
                    try:
                        e = elem(bind=bind)
                        assert e.bind is bind
                        e.execute()
                    finally:
                        if isinstance(bind, engine.Connection):
                            bind.close()

                try:
                    e = elem()
                    assert e.bind is None
                    e.execute()
                    assert False
                except exc.UnboundExecutionError, e:
                    assert str(e).endswith(
                        'is not bound and does not support direct '
                        'execution. Supply this statement to a Connection or '
                        'Engine for execution. Or, assign a bind to the '
                        'statement or the Metadata of its underlying tables to '
                        'enable implicit execution via this method.')
        finally:
            if isinstance(bind, engine.Connection):
                bind.close()
            metadata.drop_all(bind=testing.db)
Exemplo n.º 12
0
    def test_clauseelement(self):
        metadata = MetaData()
        table = Table('test_table', metadata, Column('foo', Integer))
        metadata.create_all(bind=testing.db)
        try:
            for elem in [
                    table.select,
                    lambda **kwargs: sa.func.current_timestamp(**kwargs).
                    select(),
                    #                func.current_timestamp().select,
                    lambda **kwargs: text("select * from test_table", **kwargs)
            ]:
                for bind in (testing.db, testing.db.connect()):
                    try:
                        e = elem(bind=bind)
                        assert e.bind is bind
                        e.execute()
                    finally:
                        if isinstance(bind, engine.Connection):
                            bind.close()

                try:
                    e = elem()
                    assert e.bind is None
                    e.execute()
                    assert False
                except exc.UnboundExecutionError, e:
                    assert str(e).endswith(
                        'is not bound and does not support direct '
                        'execution. Supply this statement to a Connection or '
                        'Engine for execution. Or, assign a bind to the '
                        'statement or the Metadata of its underlying tables to '
                        'enable implicit execution via this method.')
        finally:
            if isinstance(bind, engine.Connection):
                bind.close()
            metadata.drop_all(bind=testing.db)
Exemplo n.º 13
0
 def myupdate_with_ctx(ctx):
     conn = ctx.connection
     return conn.execute(sa.select([sa.text('13')])).scalar()
Exemplo n.º 14
0
    def setUpAll(self):
        global t, f, f2, ts, currenttime, metadata, default_generator

        db = testing.db
        metadata = MetaData(db)
        default_generator = {'x': 50}

        def mydefault():
            default_generator['x'] += 1
            return default_generator['x']

        def myupdate_with_ctx(ctx):
            conn = ctx.connection
            return conn.execute(sa.select([sa.text('13')])).scalar()

        def mydefault_using_connection(ctx):
            conn = ctx.connection
            try:
                return conn.execute(sa.select([sa.text('12')])).scalar()
            finally:
                # ensure a "close()" on this connection does nothing,
                # since its a "branched" connection
                conn.close()

        use_function_defaults = testing.against('postgres', 'mssql', 'maxdb')
        is_oracle = testing.against('oracle')

        # select "count(1)" returns different results on different DBs also
        # correct for "current_date" compatible as column default, value
        # differences
        currenttime = func.current_date(type_=sa.Date, bind=db)
        if is_oracle:
            ts = db.scalar(
                sa.select([
                    func.trunc(func.sysdate(),
                               sa.literal_column("'DAY'"),
                               type_=sa.Date).label('today')
                ]))
            assert isinstance(
                ts, datetime.date) and not isinstance(ts, datetime.datetime)
            f = sa.select([func.length('abcdef')], bind=db).scalar()
            f2 = sa.select([func.length('abcdefghijk')], bind=db).scalar()
            # TODO: engine propigation across nested functions not working
            currenttime = func.trunc(currenttime,
                                     sa.literal_column("'DAY'"),
                                     bind=db,
                                     type_=sa.Date)
            def1 = currenttime
            def2 = func.trunc(sa.text("sysdate"),
                              sa.literal_column("'DAY'"),
                              type_=sa.Date)

            deftype = sa.Date
        elif use_function_defaults:
            f = sa.select([func.length('abcdef')], bind=db).scalar()
            f2 = sa.select([func.length('abcdefghijk')], bind=db).scalar()
            def1 = currenttime
            deftype = sa.Date
            if testing.against('maxdb'):
                def2 = sa.text("curdate")
            elif testing.against('mssql'):
                def2 = sa.text("getdate()")
            else:
                def2 = sa.text("current_date")
            ts = db.func.current_date().scalar()
        else:
            f = len('abcdef')
            f2 = len('abcdefghijk')
            def1 = def2 = "3"
            ts = 3
            deftype = Integer

        t = Table(
            'default_test1',
            metadata,
            # python function
            Column('col1', Integer, primary_key=True, default=mydefault),

            # python literal
            Column('col2',
                   String(20),
                   default="imthedefault",
                   onupdate="im the update"),

            # preexecute expression
            Column('col3',
                   Integer,
                   default=func.length('abcdef'),
                   onupdate=func.length('abcdefghijk')),

            # SQL-side default from sql expression
            Column('col4', deftype, server_default=def1),

            # SQL-side default from literal expression
            Column('col5', deftype, server_default=def2),

            # preexecute + update timestamp
            Column('col6', sa.Date, default=currenttime, onupdate=currenttime),
            Column('boolcol1', sa.Boolean, default=True),
            Column('boolcol2', sa.Boolean, default=False),

            # python function which uses ExecutionContext
            Column('col7',
                   Integer,
                   default=mydefault_using_connection,
                   onupdate=myupdate_with_ctx),

            # python builtin
            Column('col8',
                   sa.Date,
                   default=datetime.date.today,
                   onupdate=datetime.date.today),
            # combo
            Column('col9', String(20), default='py', server_default='ddl'))
        t.create()
Exemplo n.º 15
0
 def myupdate_with_ctx(ctx):
     conn = ctx.connection
     return conn.execute(sa.select([sa.text('13')])).scalar()
Exemplo n.º 16
0
    def setUpAll(self):
        global t, f, f2, ts, currenttime, metadata, default_generator

        db = testing.db
        metadata = MetaData(db)
        default_generator = {'x':50}

        def mydefault():
            default_generator['x'] += 1
            return default_generator['x']

        def myupdate_with_ctx(ctx):
            conn = ctx.connection
            return conn.execute(sa.select([sa.text('13')])).scalar()

        def mydefault_using_connection(ctx):
            conn = ctx.connection
            try:
                return conn.execute(sa.select([sa.text('12')])).scalar()
            finally:
                # ensure a "close()" on this connection does nothing,
                # since its a "branched" connection
                conn.close()

        use_function_defaults = testing.against('postgres', 'mssql', 'maxdb')
        is_oracle = testing.against('oracle')

        # select "count(1)" returns different results on different DBs also
        # correct for "current_date" compatible as column default, value
        # differences
        currenttime = func.current_date(type_=sa.Date, bind=db)
        if is_oracle:
            ts = db.scalar(sa.select([func.trunc(func.sysdate(), sa.literal_column("'DAY'"), type_=sa.Date).label('today')]))
            assert isinstance(ts, datetime.date) and not isinstance(ts, datetime.datetime)
            f = sa.select([func.length('abcdef')], bind=db).scalar()
            f2 = sa.select([func.length('abcdefghijk')], bind=db).scalar()
            # TODO: engine propigation across nested functions not working
            currenttime = func.trunc(currenttime, sa.literal_column("'DAY'"), bind=db, type_=sa.Date)
            def1 = currenttime
            def2 = func.trunc(sa.text("sysdate"), sa.literal_column("'DAY'"), type_=sa.Date)

            deftype = sa.Date
        elif use_function_defaults:
            f = sa.select([func.length('abcdef')], bind=db).scalar()
            f2 = sa.select([func.length('abcdefghijk')], bind=db).scalar()
            def1 = currenttime
            deftype = sa.Date
            if testing.against('maxdb'):
                def2 = sa.text("curdate")
            elif testing.against('mssql'):
                def2 = sa.text("getdate()")
            else:
                def2 = sa.text("current_date")
            ts = db.func.current_date().scalar()
        else:
            f = len('abcdef')
            f2 = len('abcdefghijk')
            def1 = def2 = "3"
            ts = 3
            deftype = Integer

        t = Table('default_test1', metadata,
            # python function
            Column('col1', Integer, primary_key=True,
                   default=mydefault),

            # python literal
            Column('col2', String(20),
                   default="imthedefault",
                   onupdate="im the update"),

            # preexecute expression
            Column('col3', Integer,
                   default=func.length('abcdef'),
                   onupdate=func.length('abcdefghijk')),

            # SQL-side default from sql expression
            Column('col4', deftype,
                   server_default=def1),

            # SQL-side default from literal expression
            Column('col5', deftype,
                   server_default=def2),

            # preexecute + update timestamp
            Column('col6', sa.Date,
                   default=currenttime,
                   onupdate=currenttime),

            Column('boolcol1', sa.Boolean, default=True),
            Column('boolcol2', sa.Boolean, default=False),

            # python function which uses ExecutionContext
            Column('col7', Integer,
                   default=mydefault_using_connection,
                   onupdate=myupdate_with_ctx),

            # python builtin
            Column('col8', sa.Date,
                   default=datetime.date.today,
                   onupdate=datetime.date.today),
            # combo
            Column('col9', String(20),
                   default='py',
                   server_default='ddl'))
        t.create()