Skip to content

Commit d6fc514

Browse files
authored
[aiohttp] - use batch updates (#9932)
1 parent a1ca18a commit d6fc514

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

frameworks/Python/aiohttp/app/views.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ def json_response(payload):
2727
READ_SELECT_ORM = select(World.randomnumber).where(World.id == bindparam("id"))
2828
READ_FORTUNES_ORM = select(Fortune.id, Fortune.message)
2929
WRITE_ROW_SQL = 'UPDATE "world" SET "randomnumber"=$2 WHERE id=$1'
30+
WRITE_ROW_BATCH_SQL = 'UPDATE "world" w SET "randomnumber"=u.new_val FROM (SELECT unnest($1::int[]) as id, unnest($2::int[]) as new_val) u WHERE w.id = u.id'
3031

3132
template_path = Path(__file__).parent / 'templates' / 'fortune.jinja'
3233
template = jinja2.Template(template_path.read_text())
@@ -155,15 +156,20 @@ async def updates_raw(request):
155156
num_queries = get_num_queries(request)
156157
update_ids = sample(range(1, 10001), num_queries)
157158
update_ids.sort()
158-
fetch_params = tuple((i, ) for i in update_ids)
159-
updates = tuple(zip(update_ids, sample(range(1, 10001), num_queries)))
160-
worlds = [{'id': row_id, 'randomNumber': number} for row_id, number in updates]
159+
160+
numbers = sample(range(1, 10001), num_queries)
161+
fetch_params = [(i,) for i in update_ids]
162+
row_updates = [*zip(update_ids, numbers)]
161163

162164
async with request.app['pg'].acquire() as conn:
163165
# the result of this is the int previous random number which we don't actually use
164166
await conn.executemany(READ_ROW_SQL, fetch_params)
165-
await conn.executemany(WRITE_ROW_SQL, updates)
167+
if num_queries <= 5:
168+
await conn.executemany(WRITE_ROW_SQL, row_updates)
169+
else:
170+
await conn.execute(WRITE_ROW_BATCH_SQL, update_ids, numbers)
166171

172+
worlds = [{'id': row_id, 'randomNumber': number} for row_id, number in row_updates]
167173
return json_response(worlds)
168174

169175

0 commit comments

Comments
 (0)