Skip to content

Commit 5c4f50a

Browse files
committed
Add executemany() in prepared statement
1 parent 4997888 commit 5c4f50a

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

asyncpg/prepared_stmt.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,25 @@ async def fetchrow(self, *args, timeout=None):
196196
return None
197197
return data[0]
198198

199+
@connresource.guarded
200+
async def executemany(self, args, *, timeout: float=None):
201+
"""Execute the statement for each sequence of arguments in *args*.
202+
203+
:param args: An (async) iterable containing sequences of arguments.
204+
:param float timeout: Optional timeout value in seconds.
205+
:return None: This method discards the results of the operations.
206+
207+
.. versionadded:: 0.16.0
208+
"""
209+
protocol = self._connection._protocol
210+
try:
211+
return await protocol.bind_execute_many(
212+
self._state, args, '', timeout)
213+
except exceptions.OutdatedSchemaCacheError:
214+
await self._connection.reload_schema_state()
215+
self._state.mark_closed()
216+
raise
217+
199218
async def __bind_execute(self, args, limit, timeout):
200219
protocol = self._connection._protocol
201220
try:

tests/test_prepare.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -600,3 +600,38 @@ async def test_prepare_does_not_use_cache(self):
600600
# prepare with disabled cache
601601
await self.con.prepare('select 1')
602602
self.assertEqual(len(cache), 0)
603+
604+
async def test_prepare_executemany(self):
605+
await self.con.execute('CREATE TEMP TABLE exmany (a text, b int)')
606+
607+
try:
608+
stmt = await self.con.prepare('''
609+
INSERT INTO exmany VALUES($1, $2)
610+
''')
611+
612+
result = await stmt.executemany([
613+
('a', 1), ('b', 2), ('c', 3), ('d', 4)
614+
])
615+
616+
self.assertIsNone(result)
617+
618+
result = await self.con.fetch('''
619+
SELECT * FROM exmany
620+
''')
621+
622+
self.assertEqual(result, [
623+
('a', 1), ('b', 2), ('c', 3), ('d', 4)
624+
])
625+
626+
# Empty set
627+
await stmt.executemany(())
628+
629+
result = await self.con.fetch('''
630+
SELECT * FROM exmany
631+
''')
632+
633+
self.assertEqual(result, [
634+
('a', 1), ('b', 2), ('c', 3), ('d', 4)
635+
])
636+
finally:
637+
await self.con.execute('DROP TABLE exmany')

0 commit comments

Comments
 (0)