Skip to content
20 changes: 15 additions & 5 deletions src/datajoint/blob.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"):
Expand Down Expand Up @@ -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.

Expand All @@ -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
-------
Expand All @@ -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)
15 changes: 12 additions & 3 deletions src/datajoint/builtin_codecs/blob.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"])
46 changes: 41 additions & 5 deletions src/datajoint/declare.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from __future__ import annotations

import ast
import inspect
import logging
import re

Expand Down Expand Up @@ -173,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<comment>\#.*)
| (?P<name>[^\W\d]\w*)
| (?P<name>(?:[^\W\d]|[^\x00-\x7f\s])(?:\w|[^\x00-\x7f\s])*)
| (?P<string>"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*')
| (?P<punct>[.(),=])
)""",
Expand Down Expand Up @@ -306,14 +311,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
----------
Expand Down Expand Up @@ -356,7 +392,7 @@ def is_table_class(obj):
ref = context[step[1]]
elif step[0] == "attr":
try:
ref = getattr(ref, step[1])
ref = _lookup_attribute(ref, step[1])
except Exception:
raise unresolved(f"no attribute {step[1]}") from None
elif step[0] == "instance":
Expand Down
25 changes: 21 additions & 4 deletions src/datajoint/diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import io
import logging
import re
import warnings

import networkx as nx

Expand Down Expand Up @@ -1524,6 +1525,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
Expand All @@ -1532,7 +1536,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:
Expand Down Expand Up @@ -1656,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)
Expand Down Expand Up @@ -1734,13 +1740,24 @@ 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:
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
logger.debug("No definition in the tooltip of %s: %s", name, error)
description = [name]
description = (
("-" * 30 if q.startswith("---") else (q.replace("->", "&#8594;") if "->" in q else q.split(":")[0]))
for q in description
if not q.startswith("#")
)
node.set_tooltip("&#13;".join(description))
# backslashes doubled, as in the edge tooltip
node.set_tooltip("&#13;".join(description).replace("\\", "\\\\"))
# Strip module prefix from label if it matches the cluster label
display_name = name
if name in part_names:
Expand Down
19 changes: 19 additions & 0 deletions src/datajoint/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""

Expand Down Expand Up @@ -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
Expand Down
69 changes: 64 additions & 5 deletions src/datajoint/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand All @@ -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:
Expand Down Expand Up @@ -1413,7 +1438,13 @@ 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 (the
# 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),
Expand All @@ -1440,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 ----
Expand Down Expand Up @@ -1681,6 +1724,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.
Expand Down
Loading