Created
January 28, 2025 15:00
-
-
Save aliwo/ee680c79b86ae3e46187612740e3af0e to your computer and use it in GitHub Desktop.
SERIALIZABLE and bulk insert postgres
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import asyncio | |
| from datetime import date | |
| from uuid import uuid4 | |
| import asyncpg | |
| async def get_connection(): | |
| return await asyncpg.connect( | |
| user='postgres', | |
| password='1234', | |
| database='postgres', | |
| host='127.0.0.1', | |
| port='5432' | |
| ) | |
| async def bulk() -> None: | |
| """ | |
| CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; | |
| CREATE TABLE IF NOT EXISTS participants ( | |
| id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), | |
| name VARCHAR(255) NOT NULL | |
| ); | |
| CREATE TABLE IF NOT EXISTS participant_dates ( | |
| id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), | |
| participant_id UUID REFERENCES participants(id), | |
| date DATE | |
| ); | |
| """ | |
| conn = await get_connection() | |
| try: | |
| async with conn.transaction(isolation="serializable"): | |
| id_ = await conn.fetchval( | |
| f""" | |
| INSERT INTO participants (name) VALUES ('test_{str(uuid4())}') RETURNING id; | |
| """ | |
| ) | |
| await conn.executemany( | |
| """ | |
| INSERT INTO participant_dates (participant_id, date) VALUES ( | |
| $1, | |
| $2 | |
| ); | |
| """, | |
| [ | |
| (id_, date(2025, 1, 1)), | |
| (id_, date(2025, 1, 2)), | |
| (id_, date(2025, 1, 3)), | |
| (id_, date(2025, 1, 4)), | |
| (id_, date(2025, 1, 5)), | |
| (id_, date(2025, 1, 6)), | |
| (id_, date(2025, 1, 7)), | |
| (id_, date(2025, 1, 8)), | |
| (id_, date(2025, 1, 9)), | |
| (id_, date(2025, 1, 10)), | |
| (id_, date(2025, 1, 11)), | |
| (id_, date(2025, 1, 12)), | |
| (id_, date(2025, 1, 13)), | |
| (id_, date(2025, 1, 14)), | |
| (id_, date(2025, 1, 15)), | |
| (id_, date(2025, 1, 16)), | |
| (id_, date(2025, 1, 17)), | |
| (id_, date(2025, 1, 18)), | |
| (id_, date(2025, 1, 19)), | |
| (id_, date(2025, 1, 20)), | |
| ] | |
| ) | |
| except Exception as e: | |
| print(e) | |
| async def main() -> None: | |
| # 50 concurrent call | |
| await asyncio.gather( | |
| bulk(), bulk(), bulk(), bulk(), bulk(), bulk(), bulk(), bulk(), bulk(), bulk(), | |
| bulk(), bulk(), bulk(), bulk(), bulk(), bulk(), bulk(), bulk(), bulk(), bulk(), | |
| bulk(), bulk(), bulk(), bulk(), bulk(), bulk(), bulk(), bulk(), bulk(), bulk(), | |
| bulk(), bulk(), bulk(), bulk(), bulk(), bulk(), bulk(), bulk(), bulk(), bulk(), | |
| bulk(), bulk(), bulk(), bulk(), bulk(), bulk(), bulk(), bulk(), bulk(), bulk(), | |
| ) | |
| asyncio.run(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment