본문 바로가기
C.W.K.
Stream
Lesson 03 of 10 · published

Async cursor, iteration, transaction

~12 min · aiosqlite, transactions, iteration

Level 0Scout
0 XP0/80 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

같은 패턴에 async만 입혔어

aiosqlite의 cursor는 async context manager야. 순회는 async for로 하고, transaction은 connection에 async with를 걸거나 BEGIN과 COMMIT을 직접 쓰면 돼. semantic은 sync와 똑같고 await만 붙는 셈이야.

Tip: async with conn:은 sync sqlite3의 with conn:과 똑같이 움직여. 들어갈 때 BEGIN하고, 잘 끝나면 COMMIT하고, 예외가 나면 ROLLBACK해. async 코드에서 transaction을 다루는 일상 패턴이야.

Code

Cursor + iteration + transaction·python
import aiosqlite

async def write_chunk(conn, rows):
    async with conn:                        # BEGIN/COMMIT/ROLLBACK context
        await conn.executemany(
            'INSERT INTO notes(body) VALUES (?)',
            rows,
        )

async def stream_all(conn):
    async with conn.execute('SELECT id, body FROM notes ORDER BY id') as cur:
        async for row in cur:
            yield row

async def main():
    async with aiosqlite.connect('demo.db') as conn:
        conn.row_factory = aiosqlite.Row
        await write_chunk(conn, [(f'note{i}',) for i in range(1000)])
        async for row in stream_all(conn):
            print(dict(row))

External links

Exercise

aiosqlite에 executemany와 transaction을 얹어서 row 10만 개를 밀어넣는 async 함수를 써봐. 시간을 재고. 그다음 중간에 일부러 예외를 던져서 transaction이 되돌려지는지 확인해. 그 뒤의 row가 하나도 안 보여야 맞아.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.