aio-libs / aiomysql

aiomysql is a library for accessing a MySQL database from the asyncio
https://aiomysql.rtfd.io
MIT License
1.76k stars 257 forks source link

sqlalchemy example doesn't save rows #247

Open BlinkyStitt opened 6 years ago

BlinkyStitt commented 6 years ago

I was following https://github.com/aio-libs/aiomysql/blob/master/docs/sa.rst and I noticed that running the example multiple times did not work as expected.

The example:

import asyncio
import sqlalchemy as sa

from aiomysql.sa import create_engine

metadata = sa.MetaData()

tbl = sa.Table('tbl', metadata,
               sa.Column('id', sa.Integer, primary_key=True),
               sa.Column('val', sa.String(255)))

@asyncio.coroutine
def go():
    engine = yield from create_engine(user='root',
                                      db='dabbot',
                                      host='db',
                                      password='dabbot')

    with (yield from engine) as conn:
        yield from conn.execute(tbl.insert().values(val='abc'))

        res = yield from conn.execute(tbl.select())
        for row in res:
            print(row.id, row.val)

asyncio.get_event_loop().run_until_complete(go())
bash-4.4$ python /app/simple.py 
1 abc
bash-4.4$ python /app/simple.py 
2 abc
bash-4.4$ python /app/simple.py 
3 abc
bash-4.4$ python /app/simple.py 
4 abc
bash-4.4$ python /app/simple.py 
5 abc

Then I opened up adminer and added 6 def

bash-4.4$ python /app/simple.py 
6 def
7 abc
bash-4.4$ python /app/simple.py 
6 def
8 abc

I think the example is missing conn.execute('commit').

The example at https://github.com/aio-libs/aiomysql/blob/master/examples/example_simple_sa.py has the same issue. I removed the "drop" statement and it doesn't persist rows like I expect.

bash-4.4$ python /app/simple.py 
1 abc
2 xyz
bash-4.4$ python /app/simple.py 
3 abc
4 xyz
bash-4.4$ python /app/simple.py 
5 abc
6 xyz
BlinkyStitt commented 6 years ago

https://github.com/aio-libs/aiomysql/issues/224 looks like the same issue. The examples should probably make a note about autocommit.

jettify commented 6 years ago

Good point. Would you like to make PR?

BlinkyStitt commented 6 years ago

Hey! I’ve been really busy, but now I have free time. Will write up a PR now.

On Feb 19, 2018, at 6:48 PM, Nikolay Novik notifications@github.com wrote:

Good point. Would you like to make PR?

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/aio-libs/aiomysql/issues/247#issuecomment-366852333, or mute the thread https://github.com/notifications/unsubscribe-auth/AAmGXep4FpXshZgr8Op5BYHoloJxKCAyks5tWjJ5gaJpZM4R0-tm.