AsyncPG PostgreSQL COPY Binary Load
Bulk load millions of rows into PostgreSQL with asyncpg COPY, streaming records from an async generator with a single protocol message.
Code
import asyncio
import asyncpg
async def generate_rows(n: int):
for i in range(n):
# 生产环境中这里通常是异步分页读取外部数据源
yield (i, f'user-{i}', i % 2 == 0 and 'active' or 'inactive')
async def bulk_copy(dsn: str, rows, batch_size: int = 10_000) -> int:
conn = await asyncpg.connect(dsn)
loaded = 0
try:
async with conn.transaction():
await conn.execute(
'CREATE TEMP TABLE staging_users '
'(id bigint PRIMARY KEY, name text, status text)'
)
await conn.copy_to_table(
'staging_users',
source=rows,
)
loaded = await conn.fetchval('SELECT count(*) FROM staging_users')
finally:
await conn.close()
return loaded
async def main() -> None:
rows = generate_rows(25_000)
total = await bulk_copy(
'postgresql://user:pass@localhost/app',
rows,
)
print('rows staged:', total)
asyncio.run(main())How it works
AsyncPG PostgreSQL COPY Binary Load is built around the functions generate_rows, bulk_copy and main.
The cycling part of this snippet is for i in range(n). Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed.
Points of care
- Plan for an install step:
asyncioandasyncpgare a real dependency, resolved by the package manager.
Using it
The primary signature is def generate_rows(n: int)
The demo output is labeled (rows staged:), so every printed line maps back to its originating operation.
Import generate_rows from the file and call it — the rest of the code is implementation detail.
Key statements
async def main() -> None:
rows = generate_rows(25_000)
total = await bulk_copy(
'postgresql://user:pass@localhost/app',
rows,
)
print('rows staged:', total)
async def generate_rows(n: int):
for i in range(n):
# 生产环境中这里通常是异步分页读取外部数据源
yield (i, f'user-{i}', i % 2 == 0 and 'active' or 'inactive')
async with conn.transaction():
await conn.execute(
'CREATE TEMP TABLE staging_users '
'(id bigint PRIMARY KEY, name text, status text)'
)
await conn.copy_to_table(
'staging_users',
source=rows,
)
loaded = await conn.fetchval('SELECT count(*) FROM staging_users')
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Binary Text ConverterConvert UTF-8 text to 8-bit binary groups and decode binary back to text with strict validation.Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.
FAQ
- Which packages must be installed first?
- Yes. The imports resolve to `asyncio` and `asyncpg`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.