From 9a904038ba5fc905d0dc2a017fa3ee9f9748be36 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Fri, 20 Nov 2026 19:54:16 -0600 Subject: [PATCH 1/6] feat: opt-in blob size limit; static foreign-key lookup; projected-name check in describe() - blob.max_decompressed_size (DJ_BLOB_MAX_DECOMPRESSED_SIZE): refuse a compressed blob whose recorded uncompressed size exceeds it, before decompressing. Unset by default, so nothing changes unless it is set. - resolve_foreign_key_reference looks each .name step up with inspect.getattr_static. - describe() checks each projected foreign-key attribute name it reads from the database. Refs #1717. --- src/datajoint/blob.py | 20 +++- src/datajoint/builtin_codecs/blob.py | 15 ++- src/datajoint/declare.py | 6 +- src/datajoint/settings.py | 19 ++++ src/datajoint/table.py | 10 +- .../test_definition_blob_follow_ups.py | 98 +++++++++++++++++++ tests/unit/test_blob_decompression.py | 97 +++++++++++++++++- tests/unit/test_foreign_key_reference.py | 35 +++++++ 8 files changed, 288 insertions(+), 12 deletions(-) create mode 100644 tests/integration/test_definition_blob_follow_ups.py diff --git a/src/datajoint/blob.py b/src/datajoint/blob.py index d8bf7a416..c80a17f7f 100644 --- a/src/datajoint/blob.py +++ b/src/datajoint/blob.py @@ -143,8 +143,9 @@ class Blob: Current serialization protocol (``b"mYm\\0"`` or ``b"dj0\\0"``). """ - def __init__(self, squeeze: bool = False) -> None: + def __init__(self, squeeze: bool = False, max_decompressed_size: int | None = None) -> None: self._squeeze = squeeze + self._max_decompressed_size = max_decompressed_size self._blob = None self._pos = 0 self.protocol = None @@ -186,8 +187,14 @@ def unpack(self, blob): pass # assume uncompressed but could be unrecognized compression else: self._pos += len(prefix) - blob_size = self.read_value() - self._blob = compression[prefix](self._blob[self._pos :], int(blob_size)) + blob_size = int(self.read_value()) + limit = self._max_decompressed_size + if limit is not None and blob_size > limit: + raise DataJointError( + f"Compressed blob declares {blob_size} bytes uncompressed, more than " + f"blob.max_decompressed_size ({limit}); it is not decompressed." + ) + self._blob = compression[prefix](self._blob[self._pos :], blob_size) self._pos = 0 blob_format = self.read_zero_terminated_string() if blob_format in ("mYm", "dj0"): @@ -633,7 +640,7 @@ def pack(obj, compress: bool = True) -> bytes: return Blob().pack(obj, compress=compress) -def unpack(blob: bytes, squeeze: bool = False): +def unpack(blob: bytes, squeeze: bool = False, max_decompressed_size: int | None = None): """ Deserialize a binary blob to a Python object. @@ -643,6 +650,9 @@ def unpack(blob: bytes, squeeze: bool = False): Binary data from ``pack()`` or MATLAB mYm serialization. squeeze : bool, optional If True, remove singleton dimensions from arrays. Default False. + max_decompressed_size : int, optional + Refuse a compressed blob whose recorded uncompressed size exceeds this + many bytes, before decompressing it. None (default): no limit. Returns ------- @@ -657,4 +667,4 @@ def unpack(blob: bytes, squeeze: bool = False): [1, 2, 3] """ if blob is not None: - return Blob(squeeze=squeeze).unpack(blob) + return Blob(squeeze=squeeze, max_decompressed_size=max_decompressed_size).unpack(blob) diff --git a/src/datajoint/builtin_codecs/blob.py b/src/datajoint/builtin_codecs/blob.py index ff65161f4..574ce892e 100644 --- a/src/datajoint/builtin_codecs/blob.py +++ b/src/datajoint/builtin_codecs/blob.py @@ -54,8 +54,17 @@ def encode(self, value: Any, *, key: dict | None = None, store_name: str | None return blob.pack(value, compress=True) - def decode(self, stored: bytes, *, key: dict | None = None) -> Any: - """Deserialize blob bytes back to a Python object.""" + def decode(self, stored: bytes, *, key: dict | None = None, context: dict | None = None) -> Any: + """ + Deserialize blob bytes back to a Python object. + + A compressed blob whose recorded uncompressed size exceeds + ``blob.max_decompressed_size`` is refused before it is decompressed. + """ from .. import blob - return blob.unpack(stored, squeeze=False) + config = self._codec_config(key, context) + if config is None: + from ..settings import config # type: ignore[assignment] + assert config is not None + return blob.unpack(stored, squeeze=False, max_decompressed_size=config["blob.max_decompressed_size"]) diff --git a/src/datajoint/declare.py b/src/datajoint/declare.py index 87cef4619..0c342c2f1 100644 --- a/src/datajoint/declare.py +++ b/src/datajoint/declare.py @@ -8,6 +8,7 @@ from __future__ import annotations import ast +import inspect import logging import re @@ -355,9 +356,10 @@ def is_table_class(obj): raise unresolved(f"{step[1]} is not defined in the declaration context") ref = context[step[1]] elif step[0] == "attr": + # Look the name up without running a property or a custom __getattr__ try: - ref = getattr(ref, step[1]) - except Exception: + ref = inspect.getattr_static(ref, step[1]) + except AttributeError: raise unresolved(f"no attribute {step[1]}") from None elif step[0] == "instance": if not is_table_class(ref): diff --git a/src/datajoint/settings.py b/src/datajoint/settings.py index 981bbc314..d38cce7a2 100644 --- a/src/datajoint/settings.py +++ b/src/datajoint/settings.py @@ -504,6 +504,24 @@ class JobsSettings(BaseSettings): ) +class BlobSettings(BaseSettings): + """Limits applied when blobs are read.""" + + model_config = SettingsConfigDict( + env_prefix="DJ_BLOB_", + case_sensitive=False, + extra="forbid", + validate_assignment=True, + ) + + max_decompressed_size: int | None = Field( + default=None, + ge=0, + description="Refuse a compressed blob whose recorded uncompressed size exceeds this many bytes, " + "before decompressing it. None (default): no limit. *New in 2.3.7.*", + ) + + class ProvenanceSettings(BaseSettings): """Extrinsic provenance capture at pipeline entry points.""" @@ -586,6 +604,7 @@ class Config(BaseSettings): display: DisplaySettings = Field(default_factory=DisplaySettings) jobs: JobsSettings = Field(default_factory=JobsSettings) provenance: ProvenanceSettings = Field(default_factory=ProvenanceSettings) + blob: BlobSettings = Field(default_factory=BlobSettings) # Unified stores configuration (replaces external and object_storage) # ``validation_alias`` redirects pydantic-settings' env source away from the diff --git a/src/datajoint/table.py b/src/datajoint/table.py index dd6e979f8..d41aa82ce 100644 --- a/src/datajoint/table.py +++ b/src/datajoint/table.py @@ -4,6 +4,7 @@ import inspect import itertools import json +import keyword import logging import re import uuid @@ -1413,7 +1414,14 @@ def describe(self, context=None, printout=False): class_name=_one_line(lookup_class_name(parent_name, context) or parent_name), ) else: - # projected foreign key + # projected foreign key; the new names are written as is, so they + # must be identifiers (the referenced names are quoted) + for new_name, ref in fk_props["attr_map"].items(): + if ref != new_name and not (new_name.isidentifier() and not keyword.iskeyword(new_name)): + raise DataJointError( + f"Cannot describe {self.full_table_name}: the foreign key attribute " + f"{new_name!r} read from the database is not a valid attribute name." + ) definition += "->{options} {class_name}.proj({proj_list})\n".format( options=options_str, class_name=_one_line(lookup_class_name(parent_name, context) or parent_name), diff --git a/tests/integration/test_definition_blob_follow_ups.py b/tests/integration/test_definition_blob_follow_ups.py new file mode 100644 index 000000000..a5e85920f --- /dev/null +++ b/tests/integration/test_definition_blob_follow_ups.py @@ -0,0 +1,98 @@ +""" +Definition and blob follow-ups (#1717), on both backends. + +- ``blob.max_decompressed_size`` refuses a compressed blob on fetch whose recorded + uncompressed size exceeds it. Unset, blobs are fetched as before. +- ``describe()`` refuses to write a projected foreign-key attribute name read from + the database that is not an identifier. +- A column comment and a referenced column name go through ``describe()`` and + ``alter()``. (Double quotes in comments on PostgreSQL are left to + https://github.com/datajoint/datajoint-python/issues/1729.) +""" + +import time + +import numpy as np +import pytest + +import datajoint as dj +from datajoint.errors import DataJointError + + +@pytest.fixture +def schema_fu(connection_by_backend, db_creds_by_backend): + name = f"djtest_def_blob_{db_creds_by_backend['backend']}_{str(int(time.time() * 1000))[-8:]}" + schema = dj.Schema(name, connection=connection_by_backend) + yield schema + schema.drop(prompt=False) + + +@pytest.fixture +def blob_table(schema_fu): + @schema_fu + class Signal(dj.Manual): + definition = """ + signal_id : int32 + --- + samples : + """ + + return Signal + + +def test_blob_size_limit_on_fetch(blob_table): + value = np.zeros(5_000_000, dtype=np.uint8) # about 5 kB compressed + blob_table.insert1({"signal_id": 1, "samples": value}) + np.testing.assert_array_equal((blob_table & {"signal_id": 1}).fetch1("samples"), value) + with dj.config.override(blob__max_decompressed_size=1_000_000): + with pytest.raises(DataJointError, match="max_decompressed_size"): + (blob_table & {"signal_id": 1}).fetch1("samples") + with dj.config.override(blob__max_decompressed_size=10_000_000): + np.testing.assert_array_equal((blob_table & {"signal_id": 1}).fetch1("samples"), value) + + +@pytest.fixture +def projected_tables(schema_fu): + class Parent(dj.Manual): + definition = """ + parent_id : int32 # the parent's id + """ + + class Child(dj.Manual): + definition = """ + child_id : int32 + --- + -> Parent.proj(parent_ref="parent_id") + note : varchar(64) # it's a note # with a hash + """ + + context = {"Parent": Parent, "Child": Child} + schema_fu(Parent, context=context) + schema_fu(Child, context=context) + return Parent, Child, context + + +def test_comment_and_referenced_name_through_describe_and_alter(projected_tables): + """alter() parses describe() of the current table, so both must survive the round trip.""" + _, Child, context = projected_tables + described = Child().describe(context=context) + assert '-> Parent.proj(parent_ref="parent_id")' in described + assert "# it's a note # with a hash" in described + Child.definition = Child.definition.rstrip() + "\n extra = null : int32 # added 'later' # also a hash\n" + Child().alter(prompt=False, context=context) + described = Child().describe(context=context) + assert '-> Parent.proj(parent_ref="parent_id")' in described + assert "# it's a note # with a hash" in described + assert "# added 'later' # also a hash" in described + assert Child().heading.attributes["parent_ref"].comment == "the parent's id" + Child().alter(prompt=False, context=context) # nothing left to alter + + +def test_describe_refuses_projected_name_that_is_not_an_identifier(projected_tables, connection_by_backend): + _, Child, _ = projected_tables + quote = connection_by_backend.adapter.quote_identifier + connection_by_backend.query(f"ALTER TABLE {Child.full_table_name} RENAME COLUMN {quote('parent_ref')} TO {quote('x=1')}") + connection_by_backend.dependencies.load() + table = dj.FreeTable(connection_by_backend, Child.full_table_name) + with pytest.raises(DataJointError, match="'x=1'.*not a valid attribute name"): + table.describe() diff --git a/tests/unit/test_blob_decompression.py b/tests/unit/test_blob_decompression.py index 9bca71928..2e2231c2b 100644 --- a/tests/unit/test_blob_decompression.py +++ b/tests/unit/test_blob_decompression.py @@ -6,8 +6,11 @@ import numpy as np import pytest -from datajoint.blob import len_u64, pack, unpack +import datajoint.blob as blob_module +from datajoint.blob import len_u64, pack, serialize_lookup, unpack +from datajoint.builtin_codecs.blob import BlobCodec from datajoint.errors import DataJointError +from datajoint.settings import Config PREFIX = b"ZL123\0" @@ -71,3 +74,95 @@ def test_corrupt_stream_is_rejected(): payload = pack(np.arange(1000), compress=False) with pytest.raises(DataJointError, match="Corrupt"): unpack(PREFIX + len_u64(payload) + b"not zlib data") + + +# --------------------------------------------------------------------------- # +# Opt-in cap on the recorded uncompressed size: blob.max_decompressed_size +# --------------------------------------------------------------------------- # +def high_ratio_blob(): + """A blob that records its true size: 50 MB of zeros, about 50 kB compressed.""" + value = np.zeros(50_000_000, dtype=np.uint8) + blob = pack(value) + assert blob.startswith(PREFIX) and len(blob) < 1_000_000 + return value, blob, int(np.frombuffer(blob[len(PREFIX) : len(PREFIX) + 8], dtype=np.uint64)[0]) + + +def test_true_size_high_ratio_blob_decodes_without_a_limit(): + value, blob, _ = high_ratio_blob() + np.testing.assert_array_equal(unpack(blob), value) + + +def test_limit_refuses_blob_before_decompressing_it(): + _, blob, size = high_ratio_blob() + tracemalloc.start() + try: + with pytest.raises(DataJointError, match="max_decompressed_size"): + unpack(blob, max_decompressed_size=size - 1) + _, peak = tracemalloc.get_traced_memory() + finally: + tracemalloc.stop() + assert peak < 5_000_000 + + +def test_limit_at_the_recorded_size_decodes(): + value, blob, size = high_ratio_blob() + np.testing.assert_array_equal(unpack(blob, max_decompressed_size=size), value) + + +def test_limit_does_not_apply_to_uncompressed_blob(): + blob = pack(np.arange(1000), compress=False) + np.testing.assert_array_equal(unpack(blob, max_decompressed_size=10), np.arange(1000)) + + +def test_setting_is_off_by_default(monkeypatch): + monkeypatch.delenv("DJ_BLOB_MAX_DECOMPRESSED_SIZE", raising=False) + assert Config().blob.max_decompressed_size is None + + +def test_setting_from_environment_and_validation(monkeypatch): + monkeypatch.setenv("DJ_BLOB_MAX_DECOMPRESSED_SIZE", "1000") + cfg = Config() + assert cfg["blob.max_decompressed_size"] == 1000 + with pytest.raises(ValueError): + cfg.blob.max_decompressed_size = -1 + + +def test_codec_applies_the_setting_from_its_config(): + value, blob, size = high_ratio_blob() + cfg = Config() + np.testing.assert_array_equal(BlobCodec().decode(blob, context={"config": cfg}), value) + cfg.blob.max_decompressed_size = size - 1 + with pytest.raises(DataJointError, match="max_decompressed_size"): + BlobCodec().decode(blob, context={"config": cfg}) + + +def _mym_double_array(values, dims_dtype): + """A MATLAB mYm blob holding a column of doubles, with dimensions of type ``dims_dtype``.""" + values = np.asarray(values, dtype=np.float64) + type_id = serialize_lookup[np.dtype("float64")]["type_id"] + return ( + b"mYm\0" + + b"A" + + np.array(2, dtype=dims_dtype).tobytes() # number of dimensions + + np.array([1, len(values)], dtype=dims_dtype).tobytes() # shape + + np.array([type_id, 0], dtype=np.uint32).tobytes() # type, not complex + + values.tobytes() + ) + + +@pytest.mark.parametrize("use_32bit_dims", [False, True], ids=["64bit", "32bit"]) +def test_matlab_blob_through_size_checks(monkeypatch, use_32bit_dims): + """mYm blobs from MATLAB: the recorded size is read with the configured width and checked.""" + dims_dtype = np.uint32 if use_32bit_dims else np.uint64 + monkeypatch.setattr(blob_module, "use_32bit_dims", use_32bit_dims) + values = np.arange(100_000, dtype=np.float64) % 7 + payload = _mym_double_array(values, dims_dtype) + blob = PREFIX + np.array(len(payload), dtype=dims_dtype).tobytes() + zlib.compress(payload) + np.testing.assert_array_equal(unpack(blob).ravel(), values) + np.testing.assert_array_equal(unpack(blob, max_decompressed_size=len(payload)).ravel(), values) + with pytest.raises(DataJointError, match="max_decompressed_size"): + unpack(blob, max_decompressed_size=len(payload) - 1) + for declared in (len(payload) - 1, len(payload) + 1): + wrong = PREFIX + np.array(declared, dtype=dims_dtype).tobytes() + zlib.compress(payload) + with pytest.raises(DataJointError, match="size mismatch"): + unpack(wrong) diff --git a/tests/unit/test_foreign_key_reference.py b/tests/unit/test_foreign_key_reference.py index 8d4656699..152ae389b 100644 --- a/tests/unit/test_foreign_key_reference.py +++ b/tests/unit/test_foreign_key_reference.py @@ -170,3 +170,38 @@ def test_describe_text_stays_on_one_line(): text = 'a "quoted" \\ value\nwith a line break' steps = parse_foreign_key_reference("Parent.proj(new={})".format(_quoted(text))) assert steps == [("name", "Parent"), ("proj", [], {"new": _one_line(text)})] + + +class _Lookups: + """An object whose attributes run code when read: a property and a custom __getattr__.""" + + def __init__(self, calls): + self._calls = calls + + @property + def Computed(self): + self._calls.append("property") + return Parent + + def __getattr__(self, name): + self._calls.append(f"__getattr__ {name}") + return Parent + + +@pytest.mark.parametrize("reference", ["lookups.Computed", "lookups.Anything", "lazy_module.Parent"]) +def test_attribute_lookup_runs_no_code(reference, context, calls): + """Each ``.name`` step only looks the name up; properties and __getattr__ are not run.""" + lazy_module = types.ModuleType("lazy_module") + lazy_module.__getattr__ = lambda name: calls.append(f"module __getattr__ {name}") or Parent + context.update(lookups=_Lookups(calls), lazy_module=lazy_module) + with pytest.raises(DataJointError, match="could not be resolved"): + resolve_foreign_key_reference(reference, context) + assert calls == [] + + +def test_attribute_lookup_finds_class_and_module_attributes(context): + real_module = types.ModuleType("real_module") + real_module.Parent = Parent + context["real_module"] = real_module + assert resolve_foreign_key_reference("real_module.Parent", context) is Parent + assert resolve_foreign_key_reference("real_module.Parent.Part", context) is Parent.Part From 8b76c50466f9032b6dacd64eb194c46269f54420 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Fri, 20 Nov 2026 21:05:47 -0600 Subject: [PATCH 2/6] fix(declare): fall back to getattr when the static lookup finds no value resolve_foreign_key_reference used inspect.getattr_static alone, so a reference through a module __getattr__ (a module that loads its tables lazily), a class __getattr__ or a property no longer resolved. The static lookup still runs first and resolves module attributes, table classes and part tables without running code. getattr runs only when the static lookup finds no attribute, or finds a descriptor such as a property. --- src/datajoint/declare.py | 42 +++++++++++++++--- tests/unit/test_foreign_key_reference.py | 54 ++++++++++++++++++++---- 2 files changed, 82 insertions(+), 14 deletions(-) diff --git a/src/datajoint/declare.py b/src/datajoint/declare.py index 0c342c2f1..1066d0fc6 100644 --- a/src/datajoint/declare.py +++ b/src/datajoint/declare.py @@ -307,14 +307,45 @@ def reference(): return steps +def _lookup_attribute(obj, name: str): + """ + Look up ``name`` on ``obj`` for a ``.name`` step of a foreign-key reference. + + The name is looked up statically first, with ``inspect.getattr_static``, + which runs no code of ``obj``. Module attributes, table classes and their + part tables are found this way. + + The dynamic ``getattr`` is the fallback. It runs only when the static + lookup finds no value: when ``obj`` has no such attribute (a module-level + or class ``__getattr__`` may supply it, as in a module that loads its + tables lazily), or when the attribute is a descriptor such as a property, + whose value only running it gives. References through these resolve as + they did with ``getattr`` alone. + + Raises + ------ + AttributeError + If neither lookup finds the attribute. + """ + try: + value = inspect.getattr_static(obj, name) + except AttributeError: + pass + else: + if not hasattr(type(value), "__get__"): + return value + return getattr(obj, name) + + def resolve_foreign_key_reference(ref_table: str, context: dict): """ Resolve the table reference of a foreign key line in a namespace. The reference is parsed by :func:`parse_foreign_key_reference`, never - evaluated: names are looked up in ``context`` attribute by attribute, a - table class may be instantiated with ``()``, and ``.proj(...)`` is called - with the parsed string arguments. + evaluated: names are looked up in ``context`` attribute by attribute + (statically first; see :func:`_lookup_attribute`), a table class may be + instantiated with ``()``, and ``.proj(...)`` is called with the parsed + string arguments. Parameters ---------- @@ -356,10 +387,9 @@ def is_table_class(obj): raise unresolved(f"{step[1]} is not defined in the declaration context") ref = context[step[1]] elif step[0] == "attr": - # Look the name up without running a property or a custom __getattr__ try: - ref = inspect.getattr_static(ref, step[1]) - except AttributeError: + ref = _lookup_attribute(ref, step[1]) + except Exception: raise unresolved(f"no attribute {step[1]}") from None elif step[0] == "instance": if not is_table_class(ref): diff --git a/tests/unit/test_foreign_key_reference.py b/tests/unit/test_foreign_key_reference.py index 152ae389b..b1cb41662 100644 --- a/tests/unit/test_foreign_key_reference.py +++ b/tests/unit/test_foreign_key_reference.py @@ -173,7 +173,9 @@ def test_describe_text_stays_on_one_line(): class _Lookups: - """An object whose attributes run code when read: a property and a custom __getattr__.""" + """An object whose attributes run code when read: a property, and a custom __getattr__ for other names.""" + + Static = Parent def __init__(self, calls): self._calls = calls @@ -185,20 +187,56 @@ def Computed(self): def __getattr__(self, name): self._calls.append(f"__getattr__ {name}") + if name == "Missing": + raise AttributeError(name) return Parent -@pytest.mark.parametrize("reference", ["lookups.Computed", "lookups.Anything", "lazy_module.Parent"]) -def test_attribute_lookup_runs_no_code(reference, context, calls): - """Each ``.name`` step only looks the name up; properties and __getattr__ are not run.""" +def _lazy_module(calls, **attributes): + """A module that supplies the names it does not hold through a module-level __getattr__ (PEP 562).""" lazy_module = types.ModuleType("lazy_module") - lazy_module.__getattr__ = lambda name: calls.append(f"module __getattr__ {name}") or Parent - context.update(lookups=_Lookups(calls), lazy_module=lazy_module) - with pytest.raises(DataJointError, match="could not be resolved"): - resolve_foreign_key_reference(reference, context) + vars(lazy_module).update(attributes) + + def __getattr__(name): + calls.append(f"module __getattr__ {name}") + if name == "Missing": + raise AttributeError(name) + return Parent + + lazy_module.__getattr__ = __getattr__ + return lazy_module + + +def test_static_lookup_runs_no_code(context, calls): + """A name the static lookup finds is resolved without running __getattr__, even when the object has one.""" + context.update(lookups=_Lookups(calls), lazy_module=_lazy_module(calls, Parent=Parent)) + assert resolve_foreign_key_reference("lookups.Static", context) is Parent + assert resolve_foreign_key_reference("lazy_module.Parent.Part", context) is Parent.Part assert calls == [] +@pytest.mark.parametrize( + "reference, call", + [ + ("lazy_module.Parent", "module __getattr__ Parent"), + ("lookups.Anything", "__getattr__ Anything"), + ("lookups.Computed", "property"), + ], +) +def test_dynamic_lookup_when_static_lookup_finds_no_value(reference, call, context, calls): + """A module or class __getattr__ and a property still resolve: getattr runs only for them.""" + context.update(lookups=_Lookups(calls), lazy_module=_lazy_module(calls)) + assert resolve_foreign_key_reference(reference, context) is Parent + assert calls == [call] + + +@pytest.mark.parametrize("reference", ["lazy_module.Missing", "lookups.Missing", "module.Missing"]) +def test_attribute_found_by_neither_lookup(reference, context, calls): + context.update(lookups=_Lookups(calls), lazy_module=_lazy_module(calls)) + with pytest.raises(DataJointError, match="could not be resolved: no attribute Missing"): + resolve_foreign_key_reference(reference, context) + + def test_attribute_lookup_finds_class_and_module_attributes(context): real_module = types.ModuleType("real_module") real_module.Parent = Parent From fa7fc89dfa320da5eded9fb1c89ae77e1772b562 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Sat, 21 Nov 2026 00:41:56 -0600 Subject: [PATCH 3/6] fix(table): describe() refuses only projected names that alter() cannot read back Python keywords such as `class` are valid attribute names, and parse_foreign_key_reference reads them back as .proj() keyword arguments. The identifier check refused them, so describe() failed for tables it described before. The check now writes the new name into a .proj() call and parses it back: a name read back as itself is written as before; one that is not (`x=1`, quotes, backslashes) raises. Add a test that tells the static-first lookup apart from getattr alone: an object whose __getattribute__ returns another table, or raises, for a name that is a table class attribute. --- src/datajoint/table.py | 25 +++++++-- .../test_definition_blob_follow_ups.py | 40 +++++++++++++-- tests/unit/test_foreign_key_reference.py | 51 ++++++++++++++++++- 3 files changed, 106 insertions(+), 10 deletions(-) diff --git a/src/datajoint/table.py b/src/datajoint/table.py index d41aa82ce..3d7f985ca 100644 --- a/src/datajoint/table.py +++ b/src/datajoint/table.py @@ -4,7 +4,6 @@ import inspect import itertools import json -import keyword import logging import re import uuid @@ -17,7 +16,7 @@ from . import provenance from .condition import make_condition -from .declare import alter, declare +from .declare import alter, declare, parse_foreign_key_reference from .dependencies import extract_master from .errors import ( AccessError, @@ -1414,10 +1413,10 @@ def describe(self, context=None, printout=False): class_name=_one_line(lookup_class_name(parent_name, context) or parent_name), ) else: - # projected foreign key; the new names are written as is, so they - # must be identifiers (the referenced names are quoted) + # projected foreign key; the new names are written as is (the + # referenced names are quoted), so each must be read back as itself for new_name, ref in fk_props["attr_map"].items(): - if ref != new_name and not (new_name.isidentifier() and not keyword.iskeyword(new_name)): + if ref != new_name and not _is_projection_name(new_name): raise DataJointError( f"Cannot describe {self.full_table_name}: the foreign key attribute " f"{new_name!r} read from the database is not a valid attribute name." @@ -1689,6 +1688,22 @@ def _quoted(text): return '"{}"'.format(_one_line(text).replace("\\", "\\\\").replace('"', '\\"')) +def _is_projection_name(name): + """ + Whether ``name``, written unquoted as a ``.proj()`` keyword argument, is parsed back as itself. + + ``describe()`` writes a projected foreign key as ``Parent.proj(new="old")`` and + ``alter()`` reads it back with :func:`~datajoint.declare.parse_foreign_key_reference`. + Any name that parser reads back unchanged is accepted, Python keywords such as + ``class`` included. + """ + try: + steps = parse_foreign_key_reference(f'Parent.proj({name}="")') + except (ValueError, SyntaxError): + return False + return steps == [("name", "Parent"), ("proj", [], {name: ""})] + + def lookup_class_name(name, context, depth=3): """ Find a table's class in the context given its full table name. diff --git a/tests/integration/test_definition_blob_follow_ups.py b/tests/integration/test_definition_blob_follow_ups.py index a5e85920f..6b1aece0c 100644 --- a/tests/integration/test_definition_blob_follow_ups.py +++ b/tests/integration/test_definition_blob_follow_ups.py @@ -4,7 +4,8 @@ - ``blob.max_decompressed_size`` refuses a compressed blob on fetch whose recorded uncompressed size exceeds it. Unset, blobs are fetched as before. - ``describe()`` refuses to write a projected foreign-key attribute name read from - the database that is not an identifier. + the database that ``alter()`` would not read back as itself. Names it reads back, + Python keywords such as ``class`` included, are written as before. - A column comment and a referenced column name go through ``describe()`` and ``alter()``. (Double quotes in comments on PostgreSQL are left to https://github.com/datajoint/datajoint-python/issues/1729.) @@ -88,11 +89,42 @@ def test_comment_and_referenced_name_through_describe_and_alter(projected_tables Child().alter(prompt=False, context=context) # nothing left to alter -def test_describe_refuses_projected_name_that_is_not_an_identifier(projected_tables, connection_by_backend): +@pytest.mark.parametrize("new_name", ["class", "from"]) +def test_projected_name_that_is_a_python_keyword(schema_fu, new_name): + """A Python keyword is a valid attribute name, and alter() reads it back from describe().""" + + class Parent(dj.Manual): + definition = """ + parent_id : int32 + """ + + class Child(dj.Manual): + definition = f""" + child_id : int32 + --- + -> Parent.proj({new_name}="parent_id") + """ + + context = {"Parent": Parent, "Child": Child} + schema_fu(Parent, context=context) + schema_fu(Child, context=context) + Parent.insert1({"parent_id": 1}) + Child.insert1({"child_id": 1, new_name: 1}) + assert f'-> Parent.proj({new_name}="parent_id")' in Child().describe(context=context) + Child().alter(prompt=False, context=context) # describe() is parsed back; nothing to alter + assert Child.fetch1(new_name) == 1 + + +@pytest.mark.parametrize("new_name", ["x=1", 'a"b', "a'b", "a\\b"]) +def test_describe_refuses_projected_name_not_read_back(projected_tables, connection_by_backend, new_name): _, Child, _ = projected_tables quote = connection_by_backend.adapter.quote_identifier - connection_by_backend.query(f"ALTER TABLE {Child.full_table_name} RENAME COLUMN {quote('parent_ref')} TO {quote('x=1')}") + q = quote("")[0] # the backend's identifier quote, doubled inside a quoted name + connection_by_backend.query( + f"ALTER TABLE {Child.full_table_name} RENAME COLUMN {quote('parent_ref')} TO {quote(new_name.replace(q, q + q))}" + ) connection_by_backend.dependencies.load() table = dj.FreeTable(connection_by_backend, Child.full_table_name) - with pytest.raises(DataJointError, match="'x=1'.*not a valid attribute name"): + with pytest.raises(DataJointError, match="not a valid attribute name") as error: table.describe() + assert repr(new_name) in str(error.value) diff --git a/tests/unit/test_foreign_key_reference.py b/tests/unit/test_foreign_key_reference.py index b1cb41662..66553fb47 100644 --- a/tests/unit/test_foreign_key_reference.py +++ b/tests/unit/test_foreign_key_reference.py @@ -15,7 +15,7 @@ from datajoint.adapters.mysql import MySQLAdapter from datajoint.declare import parse_foreign_key_reference, prepare_declare, resolve_foreign_key_reference from datajoint.errors import DataJointError -from datajoint.table import _one_line, _quoted +from datajoint.table import _is_projection_name, _one_line, _quoted class Parent(dj.Manual): @@ -96,6 +96,7 @@ def test_instantiation(context): ('Projectable().proj(a="b", c="d",)', (), {"a": "b", "c": "d"}), ("(Projectable).proj('x', a='b')", ("x",), {"a": "b"}), (r'Projectable.proj(a="say \"hi\"")', (), {"a": 'say "hi"'}), + ('Projectable.proj(class="projectable_id", from="b")', (), {"class": "projectable_id", "from": "b"}), ], ) def test_projection_arguments_are_string_literals(reference, args, kwargs, context): @@ -172,6 +173,22 @@ def test_describe_text_stays_on_one_line(): assert steps == [("name", "Parent"), ("proj", [], {"new": _one_line(text)})] +@pytest.mark.parametrize("name", ["parent_ref", "class", "from", "lambda", "_private", "Größe"]) +def test_projection_names_written_by_describe_are_read_back(name): + """describe() writes Parent.proj(new="old") with the new name unquoted; Python keywords are read back too.""" + assert _is_projection_name(name) + steps = parse_foreign_key_reference("Parent.proj({}={})".format(name, _quoted('old "quoted" \\ name'))) + assert steps == [("name", "Parent"), ("proj", [], {name: 'old "quoted" \\ name'})] + + +@pytest.mark.parametrize( + "name", + ["x=1", 'a"b', "a'b", "a\\b", 'a\\"b', "a b", "1a", "a#b", "a)", 'a="x",b', "a.b", "a\nb", ""], +) +def test_projection_names_not_read_back_are_refused(name): + assert not _is_projection_name(name) + + class _Lookups: """An object whose attributes run code when read: a property, and a custom __getattr__ for other names.""" @@ -215,6 +232,38 @@ def test_static_lookup_runs_no_code(context, calls): assert calls == [] +class _Intercepting: + """An object whose __getattribute__ runs for every attribute read: it returns another table, or raises.""" + + Static = Parent + + def __init__(self, calls, raises): + self._calls = calls + self._raises = raises + + def __getattribute__(self, name): + object.__getattribute__(self, "_calls").append(f"__getattribute__ {name}") + if object.__getattribute__(self, "_raises"): + raise AttributeError(name) + return Projectable + + +@pytest.mark.parametrize("raises", [False, True], ids=["returns another table", "raises"]) +def test_static_lookup_comes_before_getattr(raises, context, calls): + """getattr alone would run __getattribute__; the static lookup finds the class attribute without running it.""" + intercepting = _Intercepting(calls, raises) + context["intercepting"] = intercepting + assert resolve_foreign_key_reference("intercepting.Static", context) is Parent + assert calls == [] + # what getattr alone gives for the same name + if raises: + with pytest.raises(AttributeError): + getattr(intercepting, "Static") + else: + assert getattr(intercepting, "Static") is Projectable + assert calls == ["__getattribute__ Static"] + + @pytest.mark.parametrize( "reference, call", [ From ccf97f1685743c5cee361276770daa1293f9ed04 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Sat, 21 Nov 2026 01:33:18 -0600 Subject: [PATCH 4/6] fix: describe() writes projected names it cannot read back, with a warning; diagrams render such tables The foreign-key reference parser took a name only from \w characters, which miss characters that Python identifiers allow, such as combining marks and U+00B7. DataJoint 2.3.5 and earlier declared such names. The parser now takes every Python identifier as a name, so describe() writes them in a form that alter() reads back. For a projected foreign-key attribute whose new name is not an identifier (a column named by SQL, such as x=1 or a-b), no form of the reference holds the name. describe() no longer raises for it: it writes the name as is, as master does, and emits a warning. alter() raises for such a table instead of parsing that text. dj.Diagram gives a table whose describe() raises DataJointError a tooltip with only its name, and escapes double quotes in the attr_map edge attribute, which made the DOT source invalid for a column named a"b or a'b. One table no longer stops the diagram of its schema. --- src/datajoint/declare.py | 6 +- src/datajoint/diagram.py | 13 ++- src/datajoint/table.py | 56 ++++++++++--- .../test_definition_blob_follow_ups.py | 82 +++++++++++++++---- tests/unit/test_foreign_key_reference.py | 38 ++++++++- 5 files changed, 164 insertions(+), 31 deletions(-) diff --git a/src/datajoint/declare.py b/src/datajoint/declare.py index 1066d0fc6..93dce70ca 100644 --- a/src/datajoint/declare.py +++ b/src/datajoint/declare.py @@ -174,10 +174,14 @@ def build_attribute_parser() -> pp.ParserElement: foreign_key_parser = build_foreign_key_parser() attribute_parser = build_attribute_parser() +# A name token is a Python identifier, as checked with str.isidentifier() below. +# Python identifiers may contain non-ASCII characters that \w does not match, such +# as combining marks (the vowel sign in Hindi "कि") and U+00B7 MIDDLE DOT, so a name +# token also takes in every non-ASCII character other than white space. _REFERENCE_TOKEN = re.compile( r"""\s*(?: (?P\#.*) - | (?P[^\W\d]\w*) + | (?P(?:[^\W\d]|[^\x00-\x7f\s])(?:\w|[^\x00-\x7f\s])*) | (?P"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*') | (?P[.(),=]) )""", diff --git a/src/datajoint/diagram.py b/src/datajoint/diagram.py index 598d36d51..c57d50db1 100644 --- a/src/datajoint/diagram.py +++ b/src/datajoint/diagram.py @@ -1524,6 +1524,9 @@ def _encapsulate_edge_attributes(graph: nx.MultiDiGraph) -> None: """ Encapsulate edge attr_map in double quotes for pydot compatibility. + A double quote inside, from a column name such as ``a"b`` or ``a'b`` (whose + repr is double-quoted), is escaped, so the DOT source stays valid. + Modifies graph in place. See Also @@ -1532,7 +1535,7 @@ def _encapsulate_edge_attributes(graph: nx.MultiDiGraph) -> None: """ for u, v, k, edgedata in graph.edges(keys=True, data=True): if "attr_map" in edgedata: - graph.edges[u, v, k]["attr_map"] = '"{0}"'.format(edgedata["attr_map"]) + graph.edges[u, v, k]["attr_map"] = '"{0}"'.format(str(edgedata["attr_map"]).replace('"', '\\"')) @staticmethod def _encapsulate_node_names(graph: nx.MultiDiGraph) -> None: @@ -1734,7 +1737,13 @@ def _master_of(part_stripped): else: cls = self._resolve_class(name) if cls is not None: - description = cls().describe(context=self.context).split("\n") + try: + description = cls().describe(context=self.context).split("\n") + except DataJointError as error: + # one table that cannot be described must not stop the whole diagram: + # its tooltip shows only its name + logger.debug("No definition in the tooltip of %s: %s", name, error) + description = [name] description = ( ("-" * 30 if q.startswith("---") else (q.replace("->", "→") if "->" in q else q.split(":")[0])) for q in description diff --git a/src/datajoint/table.py b/src/datajoint/table.py index 3d7f985ca..9b690cbbe 100644 --- a/src/datajoint/table.py +++ b/src/datajoint/table.py @@ -337,7 +337,7 @@ def alter(self, prompt=True, context=None): frame = inspect.currentframe().f_back context = dict(frame.f_globals, **frame.f_locals) del frame - old_definition = self.describe(context=context) + old_definition = self._describe(context, strict=True) sql, _external_stores, pre_ddl, column_comments = alter( self.definition, old_definition, @@ -1363,11 +1363,35 @@ def describe(self, context=None, printout=False): ------- str The definition string for the table in DataJoint DDL format. + + Warns + ----- + UserWarning + If a projected foreign key attribute read from the database is not a + name a definition can hold, such as a column named ``a-b`` by SQL. The + name is written as is, and ``alter()`` refuses the table. """ if context is None: frame = inspect.currentframe().f_back context = dict(frame.f_globals, **frame.f_locals) del frame + definition = self._describe(context) + if printout: + logger.info("\n" + definition) + return definition + + def _describe(self, context, strict=False): + """ + Write the definition for :meth:`describe` and :meth:`alter`. + + A projected foreign key is written as ``Parent.proj(new="old")``: the old + names are quoted and the new names are not, since keyword names cannot be. + A new name that the foreign key parser does not read back as itself (a + column named ``a-b`` or ``x=1`` by SQL, for example) is written as is, + since no form of the reference holds it. ``alter()`` passes ``strict`` and + raises for such a name rather than parse a different definition; + ``describe()`` warns. + """ if self.full_table_name not in self.connection.dependencies: self.connection.dependencies.load() parents = self.parents(foreign_key_info=True) @@ -1376,6 +1400,7 @@ def describe(self, context=None, printout=False): definition = "# " + table_comment + "\n" if table_comment else "" attributes_thus_far = set() attributes_declared = set() + unreadable = [] # projected names written as is, which the parser does not read back indexes = self.heading.indexes.copy() if self.heading.indexes else {} for attr in self.heading.attributes.values(): if in_key and not attr.in_key: @@ -1414,13 +1439,12 @@ def describe(self, context=None, printout=False): ) else: # projected foreign key; the new names are written as is (the - # referenced names are quoted), so each must be read back as itself - for new_name, ref in fk_props["attr_map"].items(): - if ref != new_name and not _is_projection_name(new_name): - raise DataJointError( - f"Cannot describe {self.full_table_name}: the foreign key attribute " - f"{new_name!r} read from the database is not a valid attribute name." - ) + # referenced names are quoted); note those not read back as themselves + unreadable.extend( + new_name + for new_name, ref in fk_props["attr_map"].items() + if ref != new_name and not _is_projection_name(new_name) + ) definition += "->{options} {class_name}.proj({proj_list})\n".format( options=options_str, class_name=_one_line(lookup_class_name(parent_name, context) or parent_name), @@ -1447,8 +1471,20 @@ def describe(self, context=None, printout=False): definition += "{unique}INDEX ({attrs})\n".format( unique="UNIQUE " if v["unique"] else "", attrs=", ".join(_one_line(a) for a in k) ) - if printout: - logger.info("\n" + definition) + if unreadable: + names = ", ".join(repr(name) for name in unreadable) + if len(unreadable) == 1: + problem = f"the foreign key attribute {names} read from the database is not a name a definition can hold" + else: + problem = f"the foreign key attributes {names} read from the database are not names a definition can hold" + if strict: + raise DataJointError(f"Cannot alter {self.full_table_name}: {problem}.") + warnings.warn( + f"The definition of {self.full_table_name} cannot be read back: {problem}. " + "describe() writes such a name as is, and alter() refuses this table.", + UserWarning, + stacklevel=3, + ) return definition # --- private helper functions ---- diff --git a/tests/integration/test_definition_blob_follow_ups.py b/tests/integration/test_definition_blob_follow_ups.py index 6b1aece0c..1403985d6 100644 --- a/tests/integration/test_definition_blob_follow_ups.py +++ b/tests/integration/test_definition_blob_follow_ups.py @@ -3,9 +3,14 @@ - ``blob.max_decompressed_size`` refuses a compressed blob on fetch whose recorded uncompressed size exceeds it. Unset, blobs are fetched as before. -- ``describe()`` refuses to write a projected foreign-key attribute name read from - the database that ``alter()`` would not read back as itself. Names it reads back, - Python keywords such as ``class`` included, are written as before. +- A projected foreign-key attribute named with any Python identifier, a keyword + such as ``class`` or a name with characters that ``\\w`` does not match, is + declared, written by ``describe()`` and read back by ``alter()``. +- A projected foreign-key attribute named in the database with a name no definition + can hold (``x=1``, ``a-b``) is written as is by ``describe()``, with a warning; + ``alter()`` refuses the table, and ``dj.Diagram`` still renders the schema. +- ``dj.Diagram`` renders a table whose ``describe()`` raises, without its definition + in the tooltip. - A column comment and a referenced column name go through ``describe()`` and ``alter()``. (Double quotes in comments on PostgreSQL are left to https://github.com/datajoint/datajoint-python/issues/1729.) @@ -89,9 +94,13 @@ def test_comment_and_referenced_name_through_describe_and_alter(projected_tables Child().alter(prompt=False, context=context) # nothing left to alter -@pytest.mark.parametrize("new_name", ["class", "from"]) -def test_projected_name_that_is_a_python_keyword(schema_fu, new_name): - """A Python keyword is a valid attribute name, and alter() reads it back from describe().""" +@pytest.mark.parametrize("new_name", ["class", "from", "किताब_id", "x\u00b7y"]) +def test_projected_name_that_is_a_python_identifier(schema_fu, new_name): + """ + Every Python identifier is a valid projected name: a keyword, or a name with a + character that \\w does not match (a combining vowel sign, U+00B7). alter() reads + it back from describe(), and the diagram shows the table. + """ class Parent(dj.Manual): definition = """ @@ -113,18 +122,61 @@ class Child(dj.Manual): assert f'-> Parent.proj({new_name}="parent_id")' in Child().describe(context=context) Child().alter(prompt=False, context=context) # describe() is parsed back; nothing to alter assert Child.fetch1(new_name) == 1 + assert "Child" in dj.Diagram(schema_fu, context=context).make_svg().data -@pytest.mark.parametrize("new_name", ["x=1", 'a"b', "a'b", "a\\b"]) -def test_describe_refuses_projected_name_not_read_back(projected_tables, connection_by_backend, new_name): - _, Child, _ = projected_tables - quote = connection_by_backend.adapter.quote_identifier +# Column names that SQL accepts and that no definition can hold: the new name of a +# projected foreign key is written unquoted, as a keyword argument name, and the +# parser reads only a Python identifier there. +NAMES_NOT_READ_BACK = ["x=1", 'a"b', "a'b", "a\\b", "a-b", "a b", "1st_ref", "a$b"] + + +def _rename_foreign_key_column(connection, table, new_name): + quote = connection.adapter.quote_identifier q = quote("")[0] # the backend's identifier quote, doubled inside a quoted name - connection_by_backend.query( - f"ALTER TABLE {Child.full_table_name} RENAME COLUMN {quote('parent_ref')} TO {quote(new_name.replace(q, q + q))}" + connection.query( + f"ALTER TABLE {table.full_table_name} RENAME COLUMN {quote('parent_ref')} TO {quote(new_name.replace(q, q + q))}" ) - connection_by_backend.dependencies.load() + connection.dependencies.load() + + +@pytest.mark.parametrize("new_name", NAMES_NOT_READ_BACK) +def test_describe_writes_projected_name_not_read_back(projected_tables, connection_by_backend, new_name): + """describe() writes such a name as is and warns; alter() refuses the table instead of parsing that text.""" + _, Child, context = projected_tables + _rename_foreign_key_column(connection_by_backend, Child, new_name) table = dj.FreeTable(connection_by_backend, Child.full_table_name) - with pytest.raises(DataJointError, match="not a valid attribute name") as error: - table.describe() + with pytest.warns(UserWarning, match="cannot be read back") as record: + described = table.describe(context=context) + assert repr(new_name) in str(record[0].message) + assert f'.proj({new_name}="parent_id")' in described + assert "note" in described # the rest of the definition is written + with pytest.raises(DataJointError, match="Cannot alter") as error: + table.alter(prompt=False, context=context) assert repr(new_name) in str(error.value) + + +@pytest.mark.parametrize("new_name", NAMES_NOT_READ_BACK) +def test_diagram_of_schema_with_projected_name_not_read_back(projected_tables, connection_by_backend, new_name): + """One table whose definition cannot be read back does not stop the diagram of its schema.""" + _, Child, _ = projected_tables + _rename_foreign_key_column(connection_by_backend, Child, new_name) + module = dj.VirtualModule("module", Child.database, connection=connection_by_backend) + with pytest.warns(UserWarning, match="cannot be read back"): + svg = dj.Diagram(module.schema, context=vars(module)).make_svg().data + assert "Child" in svg and "Parent" in svg + + +def test_diagram_tooltip_without_definition(schema_fu, projected_tables, monkeypatch): + """A table whose describe() raises gets a tooltip without its definition; the other tables keep theirs.""" + _, Child, context = projected_tables + + def describe(self, context=None, printout=False): + raise DataJointError("cannot describe") + + monkeypatch.setattr(Child, "describe", describe) + diagram = dj.Diagram(schema_fu, context=context) + tooltips = {node.get_name().strip('"'): node.get("tooltip") for node in diagram.make_dot().get_nodes()} + assert tooltips["Child"].strip('"') == "Child" + assert "parent_id" in tooltips["Parent"] + assert "Child" in diagram.make_svg().data diff --git a/tests/unit/test_foreign_key_reference.py b/tests/unit/test_foreign_key_reference.py index 66553fb47..8caf02d19 100644 --- a/tests/unit/test_foreign_key_reference.py +++ b/tests/unit/test_foreign_key_reference.py @@ -173,17 +173,49 @@ def test_describe_text_stays_on_one_line(): assert steps == [("name", "Parent"), ("proj", [], {"new": _one_line(text)})] -@pytest.mark.parametrize("name", ["parent_ref", "class", "from", "lambda", "_private", "Größe"]) +@pytest.mark.parametrize( + "name", + ["parent_ref", "class", "from", "lambda", "_private", "Größe", "किताब_id", "x\u00b7y", "\u2118x", "x\u203fy", "__x"], +) def test_projection_names_written_by_describe_are_read_back(name): - """describe() writes Parent.proj(new="old") with the new name unquoted; Python keywords are read back too.""" + """ + describe() writes Parent.proj(new="old") with the new name unquoted. Every Python + identifier is read back: keywords, and names with characters that \\w does not + match (a combining vowel sign in किताब, U+00B7, U+2118, U+203F). + """ assert _is_projection_name(name) steps = parse_foreign_key_reference("Parent.proj({}={})".format(name, _quoted('old "quoted" \\ name'))) assert steps == [("name", "Parent"), ("proj", [], {name: 'old "quoted" \\ name'})] +@pytest.mark.parametrize("name", ["किताब", "x\u00b7y"]) +def test_identifiers_beyond_word_characters_resolve(name, context): + context[name] = Parent + assert resolve_foreign_key_reference(f"{name}.Part", context) is Parent.Part + + @pytest.mark.parametrize( "name", - ["x=1", 'a"b', "a'b", "a\\b", 'a\\"b', "a b", "1a", "a#b", "a)", 'a="x",b', "a.b", "a\nb", ""], + [ + "x=1", + 'a"b', + "a'b", + "a\\b", + 'a\\"b', + "a b", + "1a", + "a#b", + "a)", + 'a="x",b', + "a.b", + "a\nb", + "", + "a-b", + "a$b", + "a b", + "a\uff1db", + "\u0663a", + ], ) def test_projection_names_not_read_back_are_refused(name): assert not _is_projection_name(name) From 259b1b8b72fc224a2cfa6d98d87b67db3bf0fb14 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Sat, 21 Nov 2026 02:03:13 -0600 Subject: [PATCH 5/6] fix(diagram): escape backslashes in tooltips; ignore describe() warnings pydot quotes a tooltip and escapes its double quotes, but leaves its backslashes as they are. A referenced column named p\ by SQL escaped the closing quote of the renamed foreign key's edge tooltip, and the \" that describe() writes for a referenced column named p"id closed the child's node tooltip early: Graphviz rejected the DOT source. Both tooltips now double their backslashes, which Graphviz shows as one. The warning describe() emits for a projected name that alter() cannot read back is ignored while the diagram writes a tooltip, so it does not affect diagrams, also under -W error. --- src/datajoint/diagram.py | 14 ++++-- .../test_definition_blob_follow_ups.py | 49 ++++++++++++++++--- 2 files changed, 52 insertions(+), 11 deletions(-) diff --git a/src/datajoint/diagram.py b/src/datajoint/diagram.py index c57d50db1..8edee00ce 100644 --- a/src/datajoint/diagram.py +++ b/src/datajoint/diagram.py @@ -21,6 +21,7 @@ import io import logging import re +import warnings import networkx as nx @@ -1659,7 +1660,9 @@ def make_dot(self, theme=None): if child != parent ) if renames: - edata["tooltip"] = renames + # pydot quotes the value but leaves backslashes as they are: double + # them, so a column name ending in one does not escape the closing quote + edata["tooltip"] = renames.replace("\\", "\\\\") self._encapsulate_node_names(graph) self._encapsulate_edge_attributes(graph) @@ -1738,7 +1741,11 @@ def _master_of(part_stripped): cls = self._resolve_class(name) if cls is not None: try: - description = cls().describe(context=self.context).split("\n") + with warnings.catch_warnings(): + # describe() warns when alter() cannot read its text back; + # that does not concern the tooltip + warnings.simplefilter("ignore") + description = cls().describe(context=self.context).split("\n") except DataJointError as error: # one table that cannot be described must not stop the whole diagram: # its tooltip shows only its name @@ -1749,7 +1756,8 @@ def _master_of(part_stripped): for q in description if not q.startswith("#") ) - node.set_tooltip(" ".join(description)) + # backslashes doubled, as in the edge tooltip + node.set_tooltip(" ".join(description).replace("\\", "\\\\")) # Strip module prefix from label if it matches the cluster label display_name = name if name in part_names: diff --git a/tests/integration/test_definition_blob_follow_ups.py b/tests/integration/test_definition_blob_follow_ups.py index 1403985d6..312dbc270 100644 --- a/tests/integration/test_definition_blob_follow_ups.py +++ b/tests/integration/test_definition_blob_follow_ups.py @@ -8,15 +8,19 @@ declared, written by ``describe()`` and read back by ``alter()``. - A projected foreign-key attribute named in the database with a name no definition can hold (``x=1``, ``a-b``) is written as is by ``describe()``, with a warning; - ``alter()`` refuses the table, and ``dj.Diagram`` still renders the schema. + ``alter()`` refuses the table, and ``dj.Diagram`` still renders the schema, without + the warning. - ``dj.Diagram`` renders a table whose ``describe()`` raises, without its definition - in the tooltip. + in the tooltip, and a referenced column whose name has a double quote or ends in a + backslash. - A column comment and a referenced column name go through ``describe()`` and ``alter()``. (Double quotes in comments on PostgreSQL are left to https://github.com/datajoint/datajoint-python/issues/1729.) """ +import html import time +import warnings import numpy as np import pytest @@ -128,18 +132,29 @@ class Child(dj.Manual): # Column names that SQL accepts and that no definition can hold: the new name of a # projected foreign key is written unquoted, as a keyword argument name, and the # parser reads only a Python identifier there. -NAMES_NOT_READ_BACK = ["x=1", 'a"b', "a'b", "a\\b", "a-b", "a b", "1st_ref", "a$b"] +NAMES_NOT_READ_BACK = ["x=1", 'a"b', "a'b", "a\\b", 'a\\"b', "a-b", "a b", "1st_ref", "a$b"] -def _rename_foreign_key_column(connection, table, new_name): +def _rename_column(connection, table, old_name, new_name): quote = connection.adapter.quote_identifier q = quote("")[0] # the backend's identifier quote, doubled inside a quoted name connection.query( - f"ALTER TABLE {table.full_table_name} RENAME COLUMN {quote('parent_ref')} TO {quote(new_name.replace(q, q + q))}" + f"ALTER TABLE {table.full_table_name} RENAME COLUMN {quote(old_name)} TO {quote(new_name.replace(q, q + q))}" ) connection.dependencies.load() +def _rename_foreign_key_column(connection, table, new_name): + _rename_column(connection, table, "parent_ref", new_name) + + +def _make_svg_without_warnings(schema, context): + """Render the diagram with every warning raised as an error, as under ``python -W error``.""" + with warnings.catch_warnings(): + warnings.simplefilter("error") + return dj.Diagram(schema, context=context).make_svg().data + + @pytest.mark.parametrize("new_name", NAMES_NOT_READ_BACK) def test_describe_writes_projected_name_not_read_back(projected_tables, connection_by_backend, new_name): """describe() writes such a name as is and warns; alter() refuses the table instead of parsing that text.""" @@ -158,13 +173,31 @@ def test_describe_writes_projected_name_not_read_back(projected_tables, connecti @pytest.mark.parametrize("new_name", NAMES_NOT_READ_BACK) def test_diagram_of_schema_with_projected_name_not_read_back(projected_tables, connection_by_backend, new_name): - """One table whose definition cannot be read back does not stop the diagram of its schema.""" + """ + One table whose definition cannot be read back does not stop the diagram of its + schema, and the warning of describe() is not emitted for the tooltip. + """ _, Child, _ = projected_tables _rename_foreign_key_column(connection_by_backend, Child, new_name) module = dj.VirtualModule("module", Child.database, connection=connection_by_backend) - with pytest.warns(UserWarning, match="cannot be read back"): - svg = dj.Diagram(module.schema, context=vars(module)).make_svg().data + svg = _make_svg_without_warnings(module.schema, vars(module)) + assert "Child" in svg and "Parent" in svg + + +@pytest.mark.parametrize("referenced_name", ['p"id', "p\\"], ids=["double quote", "trailing backslash"]) +def test_diagram_with_referenced_column_renamed(projected_tables, connection_by_backend, referenced_name): + """ + A referenced column named by SQL with a double quote, or with a backslash at the + end, goes into the parent's tooltip and the renamed foreign key's edge tooltip. + Each is quoted in the DOT source, and the diagram renders. + """ + Parent, Child, _ = projected_tables + _rename_column(connection_by_backend, Parent, "parent_id", referenced_name) + module = dj.VirtualModule("module", Child.database, connection=connection_by_backend) + assert module.Child().parents(foreign_key_info=True)[0][1]["attr_map"] == {"parent_ref": referenced_name} + svg = _make_svg_without_warnings(module.schema, vars(module)) assert "Child" in svg and "Parent" in svg + assert html.escape(f"parent_ref \u2190 {referenced_name}") in svg # the edge tooltip def test_diagram_tooltip_without_definition(schema_fu, projected_tables, monkeypatch): From 2262563ad98a312a7edd458675ca0307886f4404 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Sat, 21 Nov 2026 02:16:28 -0600 Subject: [PATCH 6/6] test: raise only the describe() warning as an error in the diagram tests The diagram tests raised every warning as an error. With the minimum networkx version, to_pydot emits a DeprecationWarning of its own, which failed them. They now raise only the warning describe() emits for a name that alter() cannot read back, which the diagram must not let through. --- tests/integration/test_definition_blob_follow_ups.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/integration/test_definition_blob_follow_ups.py b/tests/integration/test_definition_blob_follow_ups.py index 312dbc270..1c320848a 100644 --- a/tests/integration/test_definition_blob_follow_ups.py +++ b/tests/integration/test_definition_blob_follow_ups.py @@ -148,10 +148,10 @@ def _rename_foreign_key_column(connection, table, new_name): _rename_column(connection, table, "parent_ref", new_name) -def _make_svg_without_warnings(schema, context): - """Render the diagram with every warning raised as an error, as under ``python -W error``.""" +def _make_svg_describe_warning_as_error(schema, context): + """Render the diagram with the warning of describe() raised as an error, as under ``python -W error``.""" with warnings.catch_warnings(): - warnings.simplefilter("error") + warnings.filterwarnings("error", message="The definition of .* cannot be read back", category=UserWarning) return dj.Diagram(schema, context=context).make_svg().data @@ -180,7 +180,7 @@ def test_diagram_of_schema_with_projected_name_not_read_back(projected_tables, c _, Child, _ = projected_tables _rename_foreign_key_column(connection_by_backend, Child, new_name) module = dj.VirtualModule("module", Child.database, connection=connection_by_backend) - svg = _make_svg_without_warnings(module.schema, vars(module)) + svg = _make_svg_describe_warning_as_error(module.schema, vars(module)) assert "Child" in svg and "Parent" in svg @@ -195,7 +195,7 @@ def test_diagram_with_referenced_column_renamed(projected_tables, connection_by_ _rename_column(connection_by_backend, Parent, "parent_id", referenced_name) module = dj.VirtualModule("module", Child.database, connection=connection_by_backend) assert module.Child().parents(foreign_key_info=True)[0][1]["attr_map"] == {"parent_ref": referenced_name} - svg = _make_svg_without_warnings(module.schema, vars(module)) + svg = _make_svg_describe_warning_as_error(module.schema, vars(module)) assert "Child" in svg and "Parent" in svg assert html.escape(f"parent_ref \u2190 {referenced_name}") in svg # the edge tooltip