From: Daniele Varrazzo Date: Sun, 5 Apr 2020 02:07:04 +0000 (+1200) Subject: Check that arrays contain consistent objects. X-Git-Tag: 3.0.dev0~606 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=6369deb2d21894ccfadbd7d63b799b6e67feef52;p=thirdparty%2Fpsycopg.git Check that arrays contain consistent objects. --- diff --git a/psycopg3/types/array.py b/psycopg3/types/array.py index 43a5a4408..6d0d937a0 100644 --- a/psycopg3/types/array.py +++ b/psycopg3/types/array.py @@ -106,6 +106,12 @@ class ListAdapter(BaseListAdapter): if isinstance(ad, tuple): if oid == 0: oid = ad[1] + got_type = type(item) + elif oid != ad[1]: + raise e.DataError( + f"array contains different types," + f" at least {got_type} and {type(item)}" + ) ad = ad[0] tokens.append(escape_item(ad)) @@ -148,6 +154,12 @@ class BinaryListAdapter(BaseListAdapter): if isinstance(ad, tuple): if head[2] == 0: head[2] = ad[1] + got_type = type(item) + elif head[2] != ad[1]: + raise e.DataError( + f"array contains different types," + f" at least {got_type} and {type(item)}" + ) ad = ad[0] if ad is None: head[1] = 1 diff --git a/tests/types/test_array.py b/tests/types/test_array.py index b6e79a8d4..26721bf4b 100644 --- a/tests/types/test_array.py +++ b/tests/types/test_array.py @@ -1,6 +1,7 @@ import pytest +import psycopg3 from psycopg3.types import builtins -from psycopg3.adapt import TypeCaster, UnknownCaster, Format +from psycopg3.adapt import TypeCaster, UnknownCaster, Format, Transformer from psycopg3.types.array import UnknownArrayCaster, ArrayCaster @@ -72,6 +73,16 @@ def test_adapt_list_int(conn, obj, want): assert cur.fetchone()[0] +@pytest.mark.parametrize( + "input", + [[["a"], ["b", "c"]], [["a"], []], [[]], [[["a"]], ["b"]], [True, b"a"]], +) +def test_bad_binary_array(input): + tx = Transformer() + with pytest.raises(psycopg3.DataError): + tx.adapt(input, Format.BINARY) + + @pytest.mark.parametrize("fmt_out", [Format.TEXT, Format.BINARY]) @pytest.mark.parametrize("want, obj", tests_int) def test_cast_list_int(conn, obj, want, fmt_out):