From 95bc8d96bda92d378b107b5a262e6947a7055816 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Rito?= <16895040+ritojoao@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:17:28 -0300 Subject: [PATCH] Keep COPY OUT data received before a NoticeResponse --- asyncpg/protocol/coreproto.pyx | 11 ++++++++++- tests/test_copy.py | 25 +++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/asyncpg/protocol/coreproto.pyx b/asyncpg/protocol/coreproto.pyx index d5936c7a..10c5fe01 100644 --- a/asyncpg/protocol/coreproto.pyx +++ b/asyncpg/protocol/coreproto.pyx @@ -444,7 +444,16 @@ cdef class CoreProtocol: cdef: ReadBuffer buf = self.buffer - self.result = buf.consume_messages(b'd') + data = buf.consume_messages(b'd') + + # A non-CopyData message (e.g. NoticeResponse) may have been + # interleaved with CopyData, in which case the data consumed so + # far has not been pushed out yet. Keep it instead of + # overwriting it. + if self.result is None: + self.result = data + elif data is not None: + self.result += data # By this point we have consumed all CopyData messages # in the inbound buffer. If there are no messages left diff --git a/tests/test_copy.py b/tests/test_copy.py index 724b23a1..69458e98 100644 --- a/tests/test_copy.py +++ b/tests/test_copy.py @@ -143,6 +143,31 @@ async def test_copy_from_query_basics(self): ] ) + async def test_copy_from_query_with_notices(self): + # NoticeResponse messages interleaved with CopyData must not + # make the already received data disappear. + await self.con.execute(''' + CREATE OR REPLACE FUNCTION pg_temp.copy_noisy(i int) + RETURNS int LANGUAGE plpgsql AS $$ + BEGIN + RAISE NOTICE 'noise %', i; + RETURN i; + END + $$ + ''') + + f = io.BytesIO() + res = await self.con.copy_from_query(''' + SELECT pg_temp.copy_noisy(i) AS a, i + 1 AS b + FROM generate_series(1, 3) AS i + ''', output=f, format='csv', header=True) + + self.assertEqual(res, 'COPY 3') + self.assertEqual( + f.getvalue().decode().split('\n'), + ['a,b', '1,2', '2,3', '3,4', ''] + ) + async def test_copy_from_query_with_args(self): f = io.BytesIO()