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-flavored

aiosqlite 의 cursor 는 async context manager. Iteration 은 async for. Transaction 은 connection 위 async with 또는 명시적 BEGIN/COMMIT — sync 와 같은 semantic, await 만.

Tip: async with conn: 가 sync sqlite3 의 with conn: 처럼 동작 — entry 시 implicit BEGIN, 성공 시 COMMIT, exception 시 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 으로 100k row bulk import 하는 async 함수. 시간 측정. 그 다음 중간에 일부러 exception, transaction 롤백 확인 (이후 row 안 보임).

Progress

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

댓글 0

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

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