From ea7c46232f5c20d20b8b812d25ab1c68a30c1434 Mon Sep 17 00:00:00 2001 From: Daniele Varrazzo Date: Fri, 23 Jul 2021 22:59:44 +0200 Subject: [PATCH] Don't register any TypeInfo on oid 0 Someone may conceivably register info of an array only. Let's not clobber INVALID_OID, I wouldn't know the side effects... --- psycopg/psycopg/_typeinfo.py | 3 ++- tests/test_typeinfo.py | 37 ++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/psycopg/psycopg/_typeinfo.py b/psycopg/psycopg/_typeinfo.py index fa9103229..b8db91757 100644 --- a/psycopg/psycopg/_typeinfo.py +++ b/psycopg/psycopg/_typeinfo.py @@ -259,7 +259,8 @@ class TypesRegistry: def add(self, info: TypeInfo) -> None: self._ensure_own_state() - self._by_oid[info.oid] = info + if info.oid: + self._by_oid[info.oid] = info if info.array_oid: self._by_oid[info.array_oid] = info self._by_name[info.name] = info diff --git a/tests/test_typeinfo.py b/tests/test_typeinfo.py index ed792c372..8a209d128 100644 --- a/tests/test_typeinfo.py +++ b/tests/test_typeinfo.py @@ -104,3 +104,40 @@ def test_registry_by_builtin_name(conn, name): info = psycopg.adapters.types[name] assert info.name == "text" assert info.oid == 25 + + +def test_registry_empty(): + r = psycopg.types.TypesRegistry() + assert r.get("text") is None + with pytest.raises(KeyError): + r["text"] + + +@pytest.mark.parametrize("oid, aoid", [(1, 2), (1, 0), (0, 2), (0, 0)]) +def test_registry_invalid_oid(oid, aoid): + r = psycopg.types.TypesRegistry() + ti = psycopg.types.TypeInfo("test", oid, aoid) + r.add(ti) + assert r["test"] is ti + if oid: + assert r[oid] is ti + if aoid: + assert r[aoid] is ti + with pytest.raises(KeyError): + r[0] + + +def test_registry_copy(): + r = psycopg.types.TypesRegistry(psycopg.postgres.types) + assert r.get("text") is r["text"] is r[25] + assert r["text"].oid == 25 + + +def test_registry_isolated(): + orig = psycopg.postgres.types + tinfo = orig["text"] + r = psycopg.types.TypesRegistry(orig) + tdummy = psycopg.types.TypeInfo("dummy", tinfo.oid, tinfo.array_oid) + r.add(tdummy) + assert r[25] is r["dummy"] is tdummy + assert orig[25] is r["text"] is tinfo -- 2.47.3