From 43726447a03aab461019f424672e8f08f24a07cb Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Tue, 13 Oct 2026 15:42:05 -0500 Subject: [PATCH 1/5] fix(json): make JSON path annotations and value comparisons portable The same JSON path query could give different results on MySQL and PostgreSQL in two ways. Type annotations (#1563). `Doc.proj(n="data.n:int")` worked on PostgreSQL but was a syntax error on MySQL, because the MySQL adapter passed the annotation straight into `JSON_VALUE ... RETURNING`, which accepts only its own short list of types. The MySQL adapter now maps the common PostgreSQL spellings onto that list: `int`, `integer`, `smallint`, `bigint`, `bool` and `boolean` to `signed`; `numeric(p,s)` to `decimal(p,s)`; `varchar(n)` and `text` to `char(n)` and `char`; `double precision` to `double`; `timestamp` to `datetime`. In the other direction, the PostgreSQL adapter now maps `datetime` to `timestamp`, the one RETURNING type it rejected. Spellings that already worked pass through unchanged, so nothing that ran before changes. Value comparisons (#1564). In a mapping restriction such as `{"s.cal": True}` or `{"s.ch": 64}`, the extracted JSON value is text. PostgreSQL refused to compare text with a bool or a number. MySQL compared `'true'` with `1` and silently matched nothing. Bools and numbers (numpy scalars and Decimal included) are now compared as JSON values: `json_extract(...) = cast('64' as json)` on MySQL, `jsonb_extract_path(...) = '64'::jsonb` on PostgreSQL. Why compare JSON values rather than use either approach suggested in the issue: - Rendering the value as text breaks `64` against a stored `64.0`, and `64.0` against a stored `64`, because the texts differ. It would also have broken those matches on MySQL, where numeric coercion makes them work today. - Casting the extracted text to the value's type raises on PostgreSQL for any row that holds a non-numeric string at that path (`'abc'::numeric`), so one odd row would break the whole query. - JSON equality compares numbers numerically on both servers (64 = 64.0, and large integers stay exact). It matches a boolean only to a JSON boolean, and a value of another JSON type is unequal rather than an error. One behavior change: on MySQL, a number no longer matches a JSON string holding the same digits (`{"s.ch": 64}` against `"64"`), which it used to do through text coercion. PostgreSQL never matched this case; it raised. Strings still compare as text, so `{"s.ch": "64"}` and `{"s.cal": "true"}` work as before, and an annotated key such as `{"s.n:int": 7}` still compares the cast value. NaN and infinity raise a DataJointError, since JSON cannot represent them. The new integration tests run on both backends. They cover restrictions by bool, int, float, numpy scalars, Decimal and string, including against stored floats, non-numeric strings and missing keys, and restrictions and projections with each annotation spelling. 42 of the 90 cases fail on the previous code. Closes #1563. Closes #1564. --- src/datajoint/adapters/base.py | 37 ++++++- src/datajoint/adapters/mysql.py | 68 +++++++++++- src/datajoint/adapters/postgres.py | 56 +++++++--- src/datajoint/condition.py | 40 +++++++ tests/integration/test_json_path.py | 161 ++++++++++++++++++++++++++++ tests/unit/test_adapters.py | 65 +++++++++++ tests/unit/test_condition.py | 37 ++++++- 7 files changed, 447 insertions(+), 17 deletions(-) create mode 100644 tests/integration/test_json_path.py diff --git a/src/datajoint/adapters/base.py b/src/datajoint/adapters/base.py index 5b4a7ab72..be28e5b16 100644 --- a/src/datajoint/adapters/base.py +++ b/src/datajoint/adapters/base.py @@ -1138,7 +1138,12 @@ def json_path_expr(self, column: str, path: str, return_type: str | None = None) path : str JSON path (e.g., 'field' or 'nested.field'). return_type : str, optional - Return type specification (MySQL-specific). + Type to cast the extracted value to. Every backend accepts MySQL's + ``JSON_VALUE ... RETURNING`` spellings (``signed``, ``unsigned``, + ``decimal(p,s)``, ``char(n)``, ``double``, ``datetime``, ...) and the + common PostgreSQL spellings (``int``, ``integer``, ``bigint``, + ``numeric(p,s)``, ``varchar(n)``, ``text``, ``boolean``, + ``timestamp``, ...). Returns ------- @@ -1152,6 +1157,36 @@ def json_path_expr(self, column: str, path: str, return_type: str | None = None) """ ... + @abstractmethod + def json_path_equals(self, column: str, path: str, value: str) -> str: + """ + Generate a condition comparing the JSON value at a path with a JSON literal. + + The comparison is between JSON values, not text: numbers compare + numerically (``64`` equals ``64.0``), booleans match only JSON booleans, + and a value of another JSON type (e.g. a string) is simply unequal. + + Parameters + ---------- + column : str + Column name containing JSON data. + path : str + JSON path (e.g., 'field' or 'nested.field'). + value : str + JSON literal (e.g., '64', '2.5', 'true'). + + Returns + ------- + str + Database-specific SQL condition. + + Examples + -------- + MySQL: json_extract(`column`, _utf8mb4'$.path') = cast('64' as json) + PostgreSQL: jsonb_extract_path("column", 'path') = '64'::jsonb + """ + ... + def translate_expression(self, expr: str) -> str: """ Translate SQL expression for backend compatibility. diff --git a/src/datajoint/adapters/mysql.py b/src/datajoint/adapters/mysql.py index 2ef9baf84..40cfa3d8f 100644 --- a/src/datajoint/adapters/mysql.py +++ b/src/datajoint/adapters/mysql.py @@ -7,6 +7,7 @@ from __future__ import annotations +import re from typing import Any import pymysql as client @@ -44,6 +45,25 @@ "date": "date", } +# JSON path type annotations (``attr.path:type``) that PostgreSQL accepts but +# MySQL's ``JSON_VALUE ... RETURNING`` does not, mapped onto the RETURNING +# vocabulary so the same annotation works on both backends. Annotations not +# listed here are passed through unchanged. +JSON_RETURN_TYPE_MAP = { + "int": "signed", + "integer": "signed", + "smallint": "signed", + "bigint": "signed", + "bool": "signed", + "boolean": "signed", + "numeric": "decimal", + "double precision": "double", + "varchar": "char", + "text": "char", + "timestamp": "datetime", +} +_JSON_RETURN_TYPE_PATTERN = re.compile(r"\s*(?P[a-z]+(?:\s+[a-z]+)?)\s*(?P\(.*\))?\s*") + class MySQLAdapter(DatabaseAdapter): """MySQL database adapter implementation.""" @@ -856,7 +876,9 @@ def json_path_expr(self, column: str, path: str, return_type: str | None = None) path : str JSON path (e.g., 'field' or 'nested.field'). return_type : str, optional - Return type specification (e.g., 'decimal(10,2)'). + Return type specification (e.g., 'decimal(10,2)'). PostgreSQL + spellings such as 'int' or 'numeric(10,2)' are mapped onto the + RETURNING vocabulary (see ``JSON_RETURN_TYPE_MAP``). Returns ------- @@ -869,11 +891,53 @@ def json_path_expr(self, column: str, path: str, return_type: str | None = None) "json_value(`data`, _utf8mb4'$.field')" >>> adapter.json_path_expr('data', 'value', 'decimal(10,2)') "json_value(`data`, _utf8mb4'$.value' returning decimal(10,2))" + >>> adapter.json_path_expr('data', 'n', 'int') + "json_value(`data`, _utf8mb4'$.n' returning signed)" """ quoted_col = self.quote_identifier(column) - return_clause = f" returning {return_type}" if return_type else "" + return_clause = f" returning {self._json_return_type(return_type)}" if return_type else "" return f"json_value({quoted_col}, _utf8mb4'$.{path}'{return_clause})" + @staticmethod + def _json_return_type(return_type: str) -> str: + """Map a JSON path type annotation onto MySQL's RETURNING vocabulary.""" + match = _JSON_RETURN_TYPE_PATTERN.fullmatch(return_type.lower()) + if match is None: + return return_type + name = " ".join(match["name"].split()) + if name not in JSON_RETURN_TYPE_MAP: + return return_type + mysql_type = JSON_RETURN_TYPE_MAP[name] + # Integer display widths (e.g. int(11)) have no RETURNING equivalent; other + # arguments (precision, scale, length) carry over. + return mysql_type if mysql_type == "signed" else mysql_type + (match["args"] or "") + + def json_path_equals(self, column: str, path: str, value: str) -> str: + """ + Generate a condition comparing the JSON value at a path with a JSON literal. + + Parameters + ---------- + column : str + Column name containing JSON data. + path : str + JSON path (e.g., 'field' or 'nested.field'). + value : str + JSON literal (e.g., '64', '2.5', 'true'). + + Returns + ------- + str + MySQL condition comparing two JSON values. + + Examples + -------- + >>> adapter.json_path_equals('data', 'n', '64') + "json_extract(`data`, _utf8mb4'$.n') = cast('64' as json)" + """ + quoted_col = self.quote_identifier(column) + return f"json_extract({quoted_col}, _utf8mb4'$.{path}') = cast('{value}' as json)" + def translate_expression(self, expr: str) -> str: """ Translate SQL expression for MySQL compatibility. diff --git a/src/datajoint/adapters/postgres.py b/src/datajoint/adapters/postgres.py index 3a55d8eb8..938ab7259 100644 --- a/src/datajoint/adapters/postgres.py +++ b/src/datajoint/adapters/postgres.py @@ -1103,6 +1103,23 @@ def json_path_expr(self, column: str, path: str, return_type: str | None = None) 'jsonb_extract_path_text("data", \\'value\\')::float' """ quoted_col = self.quote_identifier(column) + expr = f"jsonb_extract_path_text({quoted_col}, {self._json_path_args(path)})" + # Add cast if return type specified + if return_type: + # Map DataJoint types to PostgreSQL types + pg_type = return_type.lower() + if pg_type in ("unsigned", "signed"): + pg_type = "integer" + elif pg_type == "double": + pg_type = "double precision" + elif pg_type.startswith("datetime"): + pg_type = "timestamp" + pg_type[len("datetime") :] + expr = f"({expr})::{pg_type}" + return expr + + @staticmethod + def _json_path_args(path: str) -> str: + """Split a JSON path into quoted jsonb_extract_path() arguments.""" # Split path by '.' for nested access, handling array notation path_parts = [] for part in path.split("."): @@ -1115,18 +1132,33 @@ def json_path_expr(self, column: str, path: str, return_type: str | None = None) path_parts.extend(indices) else: path_parts.append(part) - path_args = ", ".join(f"'{part}'" for part in path_parts) - expr = f"jsonb_extract_path_text({quoted_col}, {path_args})" - # Add cast if return type specified - if return_type: - # Map DataJoint types to PostgreSQL types - pg_type = return_type.lower() - if pg_type in ("unsigned", "signed"): - pg_type = "integer" - elif pg_type == "double": - pg_type = "double precision" - expr = f"({expr})::{pg_type}" - return expr + return ", ".join(f"'{part}'" for part in path_parts) + + def json_path_equals(self, column: str, path: str, value: str) -> str: + """ + Generate a condition comparing the JSON value at a path with a JSON literal. + + Parameters + ---------- + column : str + Column name containing JSON data. + path : str + JSON path (e.g., 'field' or 'nested.field'). + value : str + JSON literal (e.g., '64', '2.5', 'true'). + + Returns + ------- + str + PostgreSQL condition comparing two jsonb values. + + Examples + -------- + >>> adapter.json_path_equals('data', 'n', '64') + 'jsonb_extract_path("data", \\'n\\') = \\'64\\'::jsonb' + """ + quoted_col = self.quote_identifier(column) + return f"jsonb_extract_path({quoted_col}, {self._json_path_args(path)}) = '{value}'::jsonb" def translate_expression(self, expr: str) -> str: """ diff --git a/src/datajoint/condition.py b/src/datajoint/condition.py index f5789348a..5f74e7b68 100644 --- a/src/datajoint/condition.py +++ b/src/datajoint/condition.py @@ -13,6 +13,7 @@ import inspect import json import logging +import math import re import uuid from dataclasses import dataclass @@ -66,6 +67,40 @@ def translate_attribute(key: str, adapter=None) -> tuple[dict | None, str]: ) +# Python values that a JSON path restriction compares as JSON values, not as text +_JSON_SCALAR_TYPES = (bool, numpy.bool_, int, numpy.integer, float, numpy.floating, decimal.Decimal) + + +def _json_literal(value: Any) -> str: + """ + Render a bool or number as a JSON literal for a JSON path comparison. + + Parameters + ---------- + value : bool, int, float, or decimal.Decimal + Value to render (numpy scalars included). + + Returns + ------- + str + JSON literal, e.g. ``'true'``, ``'64'``, ``'2.5'``. + + Raises + ------ + DataJointError + If the value is NaN or infinite, which JSON cannot represent. + """ + if isinstance(value, (bool, numpy.bool_)): + return "true" if value else "false" + if isinstance(value, (int, numpy.integer)): + return str(int(value)) + if isinstance(value, decimal.Decimal) and value.is_finite(): + return str(value) + if isinstance(value, (float, numpy.floating)) and math.isfinite(value): + return json.dumps(float(value)) + raise DataJointError(f"Cannot restrict a JSON path by the non-finite number {value}.") + + class PromiscuousOperand: """ Wrapper to bypass join compatibility checking. @@ -344,6 +379,11 @@ def prep_value(k, v): return f"{k}='{json.dumps(v)}'" if v is None: return f"{k} IS NULL" + if is_json_path and not key_match["type"] and isinstance(v, _JSON_SCALAR_TYPES): + # The extracted value is text: PostgreSQL refuses to compare it with a + # bool or number, and MySQL matches no bool. Compare JSON values instead, + # which gives the same result on both (64 matches 64.0, true only true). + return adapter.json_path_equals(key_match["attr"], key_match["path"], _json_literal(v)) if key_match is not None and query_expression.heading[key_match["attr"]].uuid: if not isinstance(v, uuid.UUID): try: diff --git a/tests/integration/test_json_path.py b/tests/integration/test_json_path.py new file mode 100644 index 000000000..edc41d982 --- /dev/null +++ b/tests/integration/test_json_path.py @@ -0,0 +1,161 @@ +""" +JSON path restrictions and type annotations give the same result on MySQL and +PostgreSQL. + +- A mapping restriction on a JSON path compares bool and number values as JSON + values, so ``True`` and ``64`` work on both backends and ``64`` matches a + stored ``64.0`` (#1564). +- A ``attr.path:type`` annotation accepts the same type spellings on both + backends (#1563). +""" + +import datetime +import decimal + +import numpy as np +import pytest + +import datajoint as dj + + +@pytest.fixture +def Device(connection_by_backend, backend, prefix): + schema = dj.Schema(f"{prefix}_json_path_{backend}", connection=connection_by_backend) + + @schema + class Device(dj.Manual): + definition = """ + name : varchar(32) + --- + s : json + """ + + Device.insert( + [ + dict( + name="a", + s=dict(vendor="Acme", ch=64, gain=2.5, cal=True, n=7, made="2024-01-02 03:04:05", pos=[1, 2]), + ), + dict( + name="b", + s=dict(vendor="Other", ch=16.0, gain=0.1, cal=False, n=3, made="2025-06-07 08:09:10", pos=[3, 4]), + ), + # Strings where the other rows hold numbers + dict(name="c", s=dict(vendor="64", ch="sixty-four")), + ], + skip_duplicates=True, + ) + yield Device + schema.drop() + + +def names(query): + return sorted(query.to_arrays("name")) + + +@pytest.mark.parametrize( + "restriction, expected", + [ + # strings compare as text, as before + ({"s.vendor": "Acme"}, ["a"]), + ({"s.ch": "64"}, ["a"]), + ({"s.cal": "true"}, ["a"]), + # bool + ({"s.cal": True}, ["a"]), + ({"s.cal": False}, ["b"]), + ({"s.cal": np.bool_(True)}, ["a"]), + # int, including against a stored float and a stored non-numeric string + ({"s.ch": 64}, ["a"]), + ({"s.ch": 16}, ["b"]), + ({"s.ch": np.int64(64)}, ["a"]), + ({"s.n": 7}, ["a"]), + # float, including against a stored int + ({"s.ch": 64.0}, ["a"]), + ({"s.gain": 2.5}, ["a"]), + ({"s.gain": 0.1}, ["b"]), + ({"s.gain": np.float64(2.5)}, ["a"]), + ({"s.gain": decimal.Decimal("2.50")}, ["a"]), + # a number or bool never matches a JSON string, a missing key never matches + ({"s.vendor": 64}, []), + ({"s.vendor": True}, []), + ({"s.missing": 1}, []), + # array element + ({"s.pos[1]": 4}, ["b"]), + # combined with a regular attribute + ({"name": "a", "s.cal": True, "s.ch": 64}, ["a"]), + ({"name": "b", "s.cal": True}, []), + ], +) +def test_restrict_by_value(Device, restriction, expected): + assert names(Device & restriction) == expected + + +def test_anti_restrict(Device): + # Row c holds a string at s.ch, which is unequal to 64 rather than an error + assert names(Device - {"s.ch": 64}) == ["b", "c"] + # Row c has no s.cal, so it matches neither the restriction nor its complement + assert names(Device - {"s.cal": True}) == ["b"] + + +@pytest.mark.parametrize( + "restriction, expected", + [ + ({"s.n:int": 7}, ["a"]), + ({"s.n:signed": 3}, ["b"]), + ({"s.n:unsigned": 7}, ["a"]), + ({"s.cal:boolean": True}, ["a"]), + ({"s.cal:bool": False}, ["b"]), + ({"s.made:datetime": datetime.datetime(2024, 1, 2, 3, 4, 5)}, ["a"]), + ({"s.made:timestamp": datetime.datetime(2025, 6, 7, 8, 9, 10)}, ["b"]), + ], +) +def test_restrict_by_annotated_path(Device, restriction, expected): + assert names(Device & restriction) == expected + + +@pytest.mark.parametrize( + "annotation, expected", + [ + ("int", [7, 3]), + ("integer", [7, 3]), + ("bigint", [7, 3]), + ("smallint", [7, 3]), + ("signed", [7, 3]), + ("unsigned", [7, 3]), + ], +) +def test_project_integer_annotation(Device, annotation, expected): + rows = (Device & "name in ('a', 'b')").proj(n=f"s.n:{annotation}").to_dicts(order_by="name") + assert [row["n"] for row in rows] == expected + assert all(isinstance(row["n"], (int, np.integer)) for row in rows) + + +@pytest.mark.parametrize("annotation", ["decimal(4,1)", "numeric(4,1)"]) +def test_project_decimal_annotation(Device, annotation): + rows = Device.proj(g=f"s.gain:{annotation}").to_dicts(order_by="name") + assert [row["g"] for row in rows[:2]] == [decimal.Decimal("2.5"), decimal.Decimal("0.1")] + + +@pytest.mark.parametrize("annotation", ["double", "double precision"]) +def test_project_double_annotation(Device, annotation): + rows = (Device & "name in ('a', 'b')").proj(g=f"s.gain:{annotation}").to_dicts(order_by="name") + assert [row["g"] for row in rows] == [2.5, 0.1] + + +@pytest.mark.parametrize("annotation", ["varchar(16)", "text"]) +def test_project_string_annotation(Device, annotation): + rows = Device.proj(v=f"s.vendor:{annotation}").to_dicts(order_by="name") + assert [row["v"] for row in rows] == ["Acme", "Other", "64"] + + +@pytest.mark.parametrize("annotation", ["bool", "boolean"]) +def test_project_boolean_annotation(Device, annotation): + rows = (Device & "name in ('a', 'b')").proj(c=f"s.cal:{annotation}").to_dicts(order_by="name") + # PostgreSQL returns True/False, MySQL 1/0 + assert [row["c"] for row in rows] == [True, False] + + +@pytest.mark.parametrize("annotation", ["datetime", "timestamp"]) +def test_project_datetime_annotation(Device, annotation): + rows = (Device & "name in ('a', 'b')").proj(m=f"s.made:{annotation}").to_dicts(order_by="name") + assert [row["m"] for row in rows] == [datetime.datetime(2024, 1, 2, 3, 4, 5), datetime.datetime(2025, 6, 7, 8, 9, 10)] diff --git a/tests/unit/test_adapters.py b/tests/unit/test_adapters.py index bd0afa9e0..d0eccbbce 100644 --- a/tests/unit/test_adapters.py +++ b/tests/unit/test_adapters.py @@ -181,6 +181,46 @@ def test_json_path_expr_with_return_type(self, adapter): result = adapter.json_path_expr("data", "value", "decimal(10,2)") assert result == "json_value(`data`, _utf8mb4'$.value' returning decimal(10,2))" + @pytest.mark.parametrize( + "annotation, returning", + [ + # PostgreSQL spellings are mapped onto the RETURNING vocabulary + ("int", "signed"), + ("INTEGER", "signed"), + ("bigint", "signed"), + ("smallint", "signed"), + ("int(11)", "signed"), + ("bool", "signed"), + ("boolean", "signed"), + ("numeric", "decimal"), + ("numeric(5,1)", "decimal(5,1)"), + ("double precision", "double"), + ("varchar(16)", "char(16)"), + ("text", "char"), + ("timestamp", "datetime"), + # RETURNING spellings pass through unchanged + ("signed", "signed"), + ("unsigned", "unsigned"), + ("decimal(4, 1)", "decimal(4, 1)"), + ("char(20)", "char(20)"), + ("float", "float"), + ("double", "double"), + ("datetime", "datetime"), + ], + ) + def test_json_path_expr_maps_return_type(self, adapter, annotation, returning): + """PostgreSQL type spellings in a JSON path annotation are valid on MySQL (#1563).""" + result = adapter.json_path_expr("data", "n", annotation) + assert result == f"json_value(`data`, _utf8mb4'$.n' returning {returning})" + + def test_json_path_equals(self, adapter): + """Test JSON path comparison with a JSON literal.""" + assert adapter.json_path_equals("data", "n", "64") == "json_extract(`data`, _utf8mb4'$.n') = cast('64' as json)" + assert ( + adapter.json_path_equals("data", "a[0].b", "true") + == "json_extract(`data`, _utf8mb4'$.a[0].b') = cast('true' as json)" + ) + def test_transaction_sql(self, adapter): """Test transaction statements.""" assert "START TRANSACTION" in adapter.start_transaction_sql() @@ -326,6 +366,30 @@ def test_json_path_expr_nested(self, adapter): result = adapter.json_path_expr("data", "nested.field") assert result == "jsonb_extract_path_text(\"data\", 'nested', 'field')" + @pytest.mark.parametrize( + "annotation, cast", + [ + ("signed", "integer"), + ("unsigned", "integer"), + ("double", "double precision"), + ("datetime", "timestamp"), + ("datetime(3)", "timestamp(3)"), + ("int", "int"), + ("decimal(5,1)", "decimal(5,1)"), + ], + ) + def test_json_path_expr_maps_return_type(self, adapter, annotation, cast): + """MySQL RETURNING spellings in a JSON path annotation are valid on PostgreSQL.""" + result = adapter.json_path_expr("data", "n", annotation) + assert result == f"(jsonb_extract_path_text(\"data\", 'n'))::{cast}" + + def test_json_path_equals(self, adapter): + """Test JSON path comparison with a JSON literal.""" + assert adapter.json_path_equals("data", "n", "64") == "jsonb_extract_path(\"data\", 'n') = '64'::jsonb" + assert ( + adapter.json_path_equals("data", "a[0].b", "true") == "jsonb_extract_path(\"data\", 'a', '0', 'b') = 'true'::jsonb" + ) + def test_transaction_sql(self, adapter): """Test transaction statements.""" assert adapter.start_transaction_sql() == "BEGIN" @@ -405,6 +469,7 @@ def test_adapter_implements_interface(self, backend): "current_timestamp_expr", "interval_expr", "json_path_expr", + "json_path_equals", "format_column_definition", "table_options_clause", "table_comment_ddl", diff --git a/tests/unit/test_condition.py b/tests/unit/test_condition.py index 3200e34c4..89ea6e066 100644 --- a/tests/unit/test_condition.py +++ b/tests/unit/test_condition.py @@ -1,7 +1,12 @@ -"""Unit tests for condition.py - Top class and merge logic.""" +"""Unit tests for condition.py - Top class and merge logic, JSON path literals.""" +import decimal + +import numpy as np import pytest -from datajoint.condition import Top + +from datajoint.condition import Top, _json_literal +from datajoint.errors import DataJointError class TestTopMerge: @@ -93,3 +98,31 @@ def test_invalid_offset_type_raises(self): """Non-integer offset raises TypeError.""" with pytest.raises(TypeError): Top(offset="1") + + +class TestJsonLiteral: + """Tests for rendering restriction values as JSON literals (#1564).""" + + @pytest.mark.parametrize( + "value, literal", + [ + (True, "true"), + (False, "false"), + (np.bool_(True), "true"), + (64, "64"), + (np.int64(-3), "-3"), + (2**70, str(2**70)), + (64.0, "64.0"), + (0.1, "0.1"), + (np.float32(2.5), "2.5"), + (1e-7, "1e-07"), + (decimal.Decimal("20.50"), "20.50"), + ], + ) + def test_literal(self, value, literal): + assert _json_literal(value) == literal + + @pytest.mark.parametrize("value", [float("nan"), float("inf"), np.float64("-inf"), decimal.Decimal("NaN")]) + def test_non_finite_raises(self, value): + with pytest.raises(DataJointError): + _json_literal(value) From 6f09fd692296526b1813af0f4eaa6bb5326e246e Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Fri, 20 Nov 2026 21:05:59 -0600 Subject: [PATCH 2/5] fix(json): map every accepted JSON path type on both backends Each type name that a JSON path annotation accepts is now mapped onto a type of each backend, or rejected with a DataJointError naming the portable types, so no annotation reaches the server as a syntax error. - MySQL: every integer spelling (int4, int8, tinyint, mediumint, ...) maps to signed or unsigned; varchar, character varying, text and nchar map to char; bytea and varbinary to binary; jsonb to json; year to signed. A decimal or numeric without precision maps to decimal(65,30), which keeps the value exactly, instead of DECIMAL(10,0), which rounds it. A collation applies to the returned string, since RETURNING takes no COLLATE clause. uuid, interval, bit, timetz, timestamptz and the with-time-zone forms have no MySQL equivalent and raise a DataJointError. - PostgreSQL: signed and unsigned (with or without int/integer) cast to bigint, as MySQL's are 64-bit; tinyint, mediumint and year to smallint or integer; binary and varbinary to bytea; integer display widths are dropped. char, character and nchar without a length cast to text instead of char(1), which truncated the string; with a length they cast to varchar(n) instead of blank-padded char(n). json and jsonb cast the JSON value instead of its text, so JSON strings no longer fail the cast. A MySQL character set is dropped. - A time zone qualifier on a non-time type, or a character set or collation on a non-string type, raises a DataJointError on both backends. --- src/datajoint/adapters/base.py | 107 ++++++++++++++++++++-- src/datajoint/adapters/mysql.py | 97 ++++++++++++-------- src/datajoint/adapters/postgres.py | 71 ++++++++++---- tests/integration/test_json_path.py | 104 ++++++++++++++++++++- tests/unit/test_adapters.py | 137 ++++++++++++++++++++++++---- tests/unit/test_condition.py | 52 ++++++++++- 6 files changed, 481 insertions(+), 87 deletions(-) diff --git a/src/datajoint/adapters/base.py b/src/datajoint/adapters/base.py index 0bd0bec5b..1c976145a 100644 --- a/src/datajoint/adapters/base.py +++ b/src/datajoint/adapters/base.py @@ -7,8 +7,96 @@ from __future__ import annotations +import re from abc import ABC, abstractmethod -from typing import Any +from typing import Any, NamedTuple + +from ..errors import DataJointError + +# Parts of a JSON path type annotation (``attr.path:type``). The annotation has +# already passed ``condition._JSON_TYPE_PATTERN``; this only splits it. +_JSON_TYPE_PARTS = re.compile( + r"\s*(?P(?:un)?signed(?:\s+int(?:eger)?)?|double(?:\s+precision)?|char(?:acter)?(?:\s+varying)?|[a-z]+\d?)" + r"(?:\s*\((?P\s*\d+\s*(?:,\s*\d+\s*)?)\))?" + r"(?:\s+(?Pwith|without)\s+time\s+zone)?" + r"(?:\s+(?:character\s+set|charset)\s+(?P\w+))?" + r"(?:\s+collate\s+(?P\w+))?\s*", + re.IGNORECASE, +) + +# Type names accepted in a JSON path annotation, grouped by the kind of value they name. +# Each adapter maps every name onto its own types, or rejects it with a DataJointError. +JSON_INTEGER_TYPES = frozenset( + "signed, signed int, signed integer, unsigned, unsigned int, unsigned integer, " + "int, int2, int4, int8, integer, tinyint, smallint, mediumint, bigint, year".split(", ") +) +JSON_FLOAT_TYPES = frozenset("real, float, float4, float8, double, double precision".split(", ")) +JSON_DECIMAL_TYPES = frozenset(("decimal", "numeric", "dec")) +JSON_BOOLEAN_TYPES = frozenset(("bool", "boolean")) +JSON_STRING_TYPES = frozenset("char, character, nchar, varchar, char varying, character varying, text".split(", ")) +JSON_BINARY_TYPES = frozenset(("binary", "varbinary", "bytea")) +JSON_JSON_TYPES = frozenset(("json", "jsonb")) +JSON_TIME_TYPES = frozenset(("date", "time", "timetz", "datetime", "timestamp", "timestamptz", "interval")) +JSON_OTHER_TYPES = frozenset(("bit", "uuid")) +_JSON_TYPE_NAMES = ( + JSON_INTEGER_TYPES + | JSON_FLOAT_TYPES + | JSON_DECIMAL_TYPES + | JSON_BOOLEAN_TYPES + | JSON_STRING_TYPES + | JSON_BINARY_TYPES + | JSON_JSON_TYPES + | JSON_TIME_TYPES + | JSON_OTHER_TYPES +) + +# Annotations that work on every backend, for error messages +JSON_PORTABLE_TYPES = ( + "signed, unsigned, int, integer, smallint, bigint, decimal(p,s), numeric(p,s), float, double, " + "bool, boolean, char(n), varchar(n), text, date, time, datetime, timestamp, json" +) + + +class JsonType(NamedTuple): + """A JSON path type annotation split into its parts (see ``parse_json_type``).""" + + name: str # lower case with single spaces, e.g. 'int', 'double precision' + args: str # '' or the argument list as written, e.g. '(10, 2)' + zone: str | None # 'with' or 'without' (time zone), or None + charset: str | None + collate: str | None + + +def parse_json_type(annotation: str) -> JsonType: + """ + Split a JSON path type annotation into its parts. + + Parameters + ---------- + annotation : str + Type annotation from an ``attr.path:type`` key, e.g. ``'decimal(10, 2)'``. + + Returns + ------- + JsonType + Name, arguments, time zone qualifier, character set, and collation. + + Raises + ------ + DataJointError + If the annotation is not a known type name, or combines a qualifier with a + type that does not take it (e.g. ``int with time zone``). + """ + match = _JSON_TYPE_PARTS.fullmatch(annotation) + name = " ".join(match["name"].lower().split()) if match else None + if match is None or name not in _JSON_TYPE_NAMES: + raise DataJointError(f"Unsupported JSON path type `{annotation}`. Portable types: {JSON_PORTABLE_TYPES}.") + if match["zone"] and name not in ("time", "datetime", "timestamp"): + raise DataJointError(f"JSON path type `{annotation}`: only time and timestamp types take a time zone qualifier.") + if (match["charset"] or match["collate"]) and name not in JSON_STRING_TYPES: + raise DataJointError(f"JSON path type `{annotation}`: only string types take a character set or collation.") + args = f"({match['args']})" if match["args"] else "" + return JsonType(name, args, match["zone"] and match["zone"].lower(), match["charset"], match["collate"]) class DatabaseAdapter(ABC): @@ -1160,18 +1248,23 @@ def json_path_expr(self, column: str, path: str, return_type: str | None = None) path : str JSON path (e.g., 'field' or 'nested.field'). return_type : str, optional - Type to cast the extracted value to. Every backend accepts MySQL's - ``JSON_VALUE ... RETURNING`` spellings (``signed``, ``unsigned``, - ``decimal(p,s)``, ``char(n)``, ``double``, ``datetime``, ...) and the - common PostgreSQL spellings (``int``, ``integer``, ``bigint``, - ``numeric(p,s)``, ``varchar(n)``, ``text``, ``boolean``, - ``timestamp``, ...). + Type to cast the extracted value to: a MySQL ``JSON_VALUE ... RETURNING`` + spelling (``signed``, ``unsigned``, ``decimal(p,s)``, ``char(n)``, + ``double``, ``datetime``, ...) or a PostgreSQL spelling (``int``, + ``integer``, ``bigint``, ``numeric(p,s)``, ``varchar(n)``, ``text``, + ``boolean``, ``timestamp``, ...). Each backend maps the name onto its + own type (see ``parse_json_type`` for the accepted names). Returns ------- str Database-specific JSON extraction SQL expression. + Raises + ------ + DataJointError + If the backend has no equivalent of the type (e.g. ``uuid`` on MySQL). + Examples -------- MySQL: json_value(`column`, _utf8mb4'$.path' returning type) diff --git a/src/datajoint/adapters/mysql.py b/src/datajoint/adapters/mysql.py index e8fabb481..a8ff16a8e 100644 --- a/src/datajoint/adapters/mysql.py +++ b/src/datajoint/adapters/mysql.py @@ -15,7 +15,19 @@ from pymysql.constants import CLIENT, CR from .. import errors -from .base import DatabaseAdapter +from .base import ( + JSON_BINARY_TYPES, + JSON_BOOLEAN_TYPES, + JSON_DECIMAL_TYPES, + JSON_FLOAT_TYPES, + JSON_INTEGER_TYPES, + JSON_JSON_TYPES, + JSON_PORTABLE_TYPES, + JSON_STRING_TYPES, + DatabaseAdapter, + JsonType, + parse_json_type, +) # Core type mapping: DataJoint core types → MySQL types CORE_TYPE_MAP = { @@ -47,25 +59,6 @@ "date": "date", } -# JSON path type annotations (``attr.path:type``) that PostgreSQL accepts but -# MySQL's ``JSON_VALUE ... RETURNING`` does not, mapped onto the RETURNING -# vocabulary so the same annotation works on both backends. Annotations not -# listed here are passed through unchanged. -JSON_RETURN_TYPE_MAP = { - "int": "signed", - "integer": "signed", - "smallint": "signed", - "bigint": "signed", - "bool": "signed", - "boolean": "signed", - "numeric": "decimal", - "double precision": "double", - "varchar": "char", - "text": "char", - "timestamp": "datetime", -} -_JSON_RETURN_TYPE_PATTERN = re.compile(r"\s*(?P[a-z]+(?:\s+[a-z]+)?)\s*(?P\(.*\))?\s*") - class _TLSUnavailableError(client.err.OperationalError): """TLS is required but the server does not offer it.""" @@ -311,7 +304,6 @@ def quote_string(self, value: str) -> str: def get_master_table_name(self, part_table: str) -> str | None: """Extract master table name from part table (MySQL backtick format).""" - import re # MySQL format: `schema`.`master__part` match = re.match(r"(?P`\w+`.`#?\w+)__\w+`", part_table) @@ -805,7 +797,6 @@ def get_constraint_info_sql(self, constraint_name: str, schema_name: str, table_ def parse_foreign_key_error(self, error_message: str) -> dict[str, str | list[str] | None] | None: """Parse MySQL foreign key violation error message.""" - import re # MySQL FK error pattern with backticks pattern = re.compile( @@ -962,15 +953,19 @@ def json_path_expr(self, column: str, path: str, return_type: str | None = None) path : str JSON path (e.g., 'field' or 'nested.field'). return_type : str, optional - Return type specification (e.g., 'decimal(10,2)'). PostgreSQL - spellings such as 'int' or 'numeric(10,2)' are mapped onto the - RETURNING vocabulary (see ``JSON_RETURN_TYPE_MAP``). + Type annotation (e.g., 'decimal(10,2)'). PostgreSQL spellings such as + 'int', 'numeric(10,2)' or 'text' are mapped onto the RETURNING types. Returns ------- str MySQL json_value() expression. + Raises + ------ + DataJointError + If the annotation names a type that MySQL cannot return (e.g. 'uuid'). + Examples -------- >>> adapter.json_path_expr('data', 'field') @@ -981,22 +976,45 @@ def json_path_expr(self, column: str, path: str, return_type: str | None = None) "json_value(`data`, _utf8mb4'$.n' returning signed)" """ quoted_col = self.quote_identifier(column) - return_clause = f" returning {self._json_return_type(return_type)}" if return_type else "" - return f"json_value({quoted_col}, _utf8mb4{self.quote_string('$.' + path)}{return_clause})" + expr = f"json_value({quoted_col}, _utf8mb4{self.quote_string('$.' + path)}" + if not return_type: + return expr + ")" + json_type = parse_json_type(return_type) + expr += f" returning {self._json_returning_type(json_type, return_type)})" + # RETURNING takes no COLLATE clause; collate the returned string instead + return expr + (f" collate {json_type.collate}" if json_type.collate else "") @staticmethod - def _json_return_type(return_type: str) -> str: - """Map a JSON path type annotation onto MySQL's RETURNING vocabulary.""" - match = _JSON_RETURN_TYPE_PATTERN.fullmatch(return_type.lower()) - if match is None: - return return_type - name = " ".join(match["name"].split()) - if name not in JSON_RETURN_TYPE_MAP: - return return_type - mysql_type = JSON_RETURN_TYPE_MAP[name] - # Integer display widths (e.g. int(11)) have no RETURNING equivalent; other - # arguments (precision, scale, length) carry over. - return mysql_type if mysql_type == "signed" else mysql_type + (match["args"] or "") + def _json_returning_type(json_type: JsonType, annotation: str) -> str: + """Map a parsed JSON path type annotation onto a ``JSON_VALUE ... RETURNING`` type.""" + name, args = json_type.name, json_type.args + if name in JSON_INTEGER_TYPES: + # Integer display widths such as int(11) have no RETURNING equivalent + return "unsigned" if name.startswith("unsigned") else "signed" + if name in JSON_BOOLEAN_TYPES: + return "signed" + if name in JSON_FLOAT_TYPES: + # RETURNING takes every float spelling; only float(p) takes an argument + return name + (args if name == "float" else "") + if name in JSON_DECIMAL_TYPES: + # A bare DECIMAL is DECIMAL(10,0) on MySQL and would round the value. + # DECIMAL(65,30) is the widest MySQL decimal, closest to PostgreSQL's + # unconstrained numeric: exact, and returned as a Python Decimal. + return "decimal" + (args or "(65,30)") + if name in JSON_STRING_TYPES: + # CHAR without a length is unlimited in RETURNING, like PostgreSQL text + charset = f" character set {json_type.charset}" if json_type.charset else "" + return "char" + args + charset + if name in JSON_BINARY_TYPES: + return "binary" + (args if name == "binary" else "") + if name in JSON_JSON_TYPES: + return "json" + if name in ("date", "time", "datetime", "timestamp") and json_type.zone != "with": + return {"timestamp": "datetime"}.get(name, name) + (args if name != "date" else "") + raise errors.DataJointError( + f"JSON path type `{annotation}` has no MySQL equivalent. Types that work on both " + f"MySQL and PostgreSQL: {JSON_PORTABLE_TYPES}." + ) def json_path_equals(self, column: str, path: str, value: str) -> str: """ @@ -1043,7 +1061,6 @@ def translate_expression(self, expr: str) -> str: str Translated expression for MySQL. """ - import re # STRING_AGG(col, 'sep') → GROUP_CONCAT(col SEPARATOR 'sep') def replace_string_agg(match): diff --git a/src/datajoint/adapters/postgres.py b/src/datajoint/adapters/postgres.py index c7b19bad3..1c4fe74e6 100644 --- a/src/datajoint/adapters/postgres.py +++ b/src/datajoint/adapters/postgres.py @@ -19,7 +19,22 @@ sql = None # type: ignore from .. import errors -from .base import DatabaseAdapter +from .base import ( + JSON_BINARY_TYPES, + JSON_DECIMAL_TYPES, + JSON_FLOAT_TYPES, + JSON_INTEGER_TYPES, + JSON_JSON_TYPES, + JSON_STRING_TYPES, + DatabaseAdapter, + JsonType, + parse_json_type, +) + +# Integer type names PostgreSQL knows, and casts for the MySQL-only ones. MySQL's +# SIGNED and UNSIGNED are 64-bit, so they and their variants cast to bigint. +_PG_INTEGER_TYPES = frozenset(("int", "int2", "int4", "int8", "integer", "smallint", "bigint")) +_PG_INTEGER_CASTS = {"tinyint": "smallint", "mediumint": "integer", "year": "integer"} logger = logging.getLogger(__name__.split(".")[0]) @@ -1175,7 +1190,9 @@ def json_path_expr(self, column: str, path: str, return_type: str | None = None) path : str JSON path (e.g., 'field' or 'nested.field'). return_type : str, optional - Return type specification for casting (e.g., 'float', 'decimal(10,2)'). + Type annotation to cast to (e.g., 'float', 'decimal(10,2)'). MySQL + RETURNING spellings such as 'signed', 'double' or 'datetime' are + mapped onto PostgreSQL types. Returns ------- @@ -1189,22 +1206,44 @@ def json_path_expr(self, column: str, path: str, return_type: str | None = None) >>> adapter.json_path_expr('data', 'nested.field') 'jsonb_extract_path_text("data", \\'nested\\', \\'field\\')' >>> adapter.json_path_expr('data', 'value', 'float') - 'jsonb_extract_path_text("data", \\'value\\')::float' + '(jsonb_extract_path_text("data", \\'value\\'))::float' """ quoted_col = self.quote_identifier(column) - expr = f"jsonb_extract_path_text({quoted_col}, {self._json_path_args(path)})" - # Add cast if return type specified - if return_type: - # Map DataJoint types to PostgreSQL types - pg_type = return_type.lower() - if pg_type in ("unsigned", "signed"): - pg_type = "integer" - elif pg_type == "double": - pg_type = "double precision" - elif pg_type.startswith("datetime"): - pg_type = "timestamp" + pg_type[len("datetime") :] - expr = f"({expr})::{pg_type}" - return expr + path_args = self._json_path_args(path) + if not return_type: + return f"jsonb_extract_path_text({quoted_col}, {path_args})" + json_type = parse_json_type(return_type) + if json_type.name in JSON_JSON_TYPES: + # Cast the JSON value itself: the text of a JSON string is not valid JSON + return f"(jsonb_extract_path({quoted_col}, {path_args}))::{json_type.name}" + expr = f"(jsonb_extract_path_text({quoted_col}, {path_args}))::{self._json_cast_type(json_type)}" + return expr + (f" collate {json_type.collate}" if json_type.collate else "") + + @staticmethod + def _json_cast_type(json_type: JsonType) -> str: + """Map a parsed JSON path type annotation onto a PostgreSQL type to cast to.""" + name, args = json_type.name, json_type.args + if name in JSON_INTEGER_TYPES: + # Display widths such as int(11) have no PostgreSQL equivalent + return name if name in _PG_INTEGER_TYPES else _PG_INTEGER_CASTS.get(name, "bigint") + if name in JSON_FLOAT_TYPES: + return "double precision" if name.startswith("double") else name + (args if name == "float" else "") + if name in JSON_DECIMAL_TYPES: + return name + args + if name in JSON_STRING_TYPES: + # char(n) would pad with blanks and char alone means char(1), which + # truncates; varchar(n) and text return the string as MySQL does. + # A MySQL character set has no PostgreSQL equivalent and is dropped. + if args: + return "varchar" + args + return name if "varying" in name or name == "varchar" else "text" + if name in JSON_BINARY_TYPES: + return "bytea" + if name in ("bool", "boolean", "date", "uuid"): + return name + # time, timetz, datetime, timestamp, timestamptz, interval, bit + zone = f" {json_type.zone} time zone" if json_type.zone else "" + return {"datetime": "timestamp"}.get(name, name) + args + zone def _json_path_args(self, path: str) -> str: """Split a JSON path into quoted jsonb_extract_path() arguments.""" diff --git a/tests/integration/test_json_path.py b/tests/integration/test_json_path.py index edc41d982..d76bda5b8 100644 --- a/tests/integration/test_json_path.py +++ b/tests/integration/test_json_path.py @@ -6,7 +6,7 @@ values, so ``True`` and ``64`` work on both backends and ``64`` matches a stored ``64.0`` (#1564). - A ``attr.path:type`` annotation accepts the same type spellings on both - backends (#1563). + backends, or raises a DataJointError for a type one backend lacks (#1563). """ import datetime @@ -34,7 +34,22 @@ class Device(dj.Manual): [ dict( name="a", - s=dict(vendor="Acme", ch=64, gain=2.5, cal=True, n=7, made="2024-01-02 03:04:05", pos=[1, 2]), + s=dict( + vendor="Acme", + ch=64, + gain=2.5, + cal=True, + n=7, + made="2024-01-02 03:04:05", + pos=[1, 2], + price=1234567890123.25, + day="2024-01-02", + at="03:04:05", + year=2024, + id="6ba7b810-9dad-11d1-80b4-00c04fd430c8", + span="1 day", + flag="1", + ), ), dict( name="b", @@ -95,6 +110,9 @@ def test_anti_restrict(Device): assert names(Device - {"s.ch": 64}) == ["b", "c"] # Row c has no s.cal, so it matches neither the restriction nor its complement assert names(Device - {"s.cal": True}) == ["b"] + # A JSON null is a value unequal to 64, unlike a missing key + Device.insert1(dict(name="d", s=dict(ch=None))) + assert names(Device - {"s.ch": 64}) == ["b", "c", "d"] @pytest.mark.parametrize( @@ -130,24 +148,58 @@ def test_project_integer_annotation(Device, annotation, expected): assert all(isinstance(row["n"], (int, np.integer)) for row in rows) -@pytest.mark.parametrize("annotation", ["decimal(4,1)", "numeric(4,1)"]) +@pytest.mark.parametrize("annotation", ["decimal(4,1)", "numeric(4,1)", "numeric", "decimal", "dec"]) def test_project_decimal_annotation(Device, annotation): rows = Device.proj(g=f"s.gain:{annotation}").to_dicts(order_by="name") assert [row["g"] for row in rows[:2]] == [decimal.Decimal("2.5"), decimal.Decimal("0.1")] +@pytest.mark.parametrize("annotation", ["numeric", "decimal", "dec"]) +def test_decimal_without_precision_keeps_value(Device, annotation): + """A bare decimal annotation neither rounds (MySQL DECIMAL is DECIMAL(10,0)) nor overflows.""" + price = (Device & {"name": "a"}).proj(p=f"s.price:{annotation}").fetch1("p") + assert price == decimal.Decimal("1234567890123.25") + assert names(Device & {f"s.gain:{annotation}": decimal.Decimal("0.1")}) == ["b"] + + @pytest.mark.parametrize("annotation", ["double", "double precision"]) def test_project_double_annotation(Device, annotation): rows = (Device & "name in ('a', 'b')").proj(g=f"s.gain:{annotation}").to_dicts(order_by="name") assert [row["g"] for row in rows] == [2.5, 0.1] -@pytest.mark.parametrize("annotation", ["varchar(16)", "text"]) +@pytest.mark.parametrize( + "annotation", + [ + "varchar(16)", + "text", + # char alone is char(1) on PostgreSQL and char(16) pads with blanks + "char", + "character", + "nchar", + "char(16)", + "nchar(16)", + "varchar", + "character varying", + "char(16) character set utf8mb4", + ], +) def test_project_string_annotation(Device, annotation): rows = Device.proj(v=f"s.vendor:{annotation}").to_dicts(order_by="name") assert [row["v"] for row in rows] == ["Acme", "Other", "64"] +def test_restrict_by_string_annotation(Device): + assert names(Device & {"s.vendor:char": "Acme"}) == ["a"] + assert names(Device & {"s.vendor:char(16)": "Acme"}) == ["a"] + + +def test_string_annotation_collation(Device, backend): + collation = "utf8mb4_0900_ai_ci" if backend == "mysql" else "ucs_basic" + rows = Device.proj(v=f"s.vendor:char(16) collate {collation}").to_dicts(order_by="name") + assert [row["v"] for row in rows] == ["Acme", "Other", "64"] + + @pytest.mark.parametrize("annotation", ["bool", "boolean"]) def test_project_boolean_annotation(Device, annotation): rows = (Device & "name in ('a', 'b')").proj(c=f"s.cal:{annotation}").to_dicts(order_by="name") @@ -159,3 +211,47 @@ def test_project_boolean_annotation(Device, annotation): def test_project_datetime_annotation(Device, annotation): rows = (Device & "name in ('a', 'b')").proj(m=f"s.made:{annotation}").to_dicts(order_by="name") assert [row["m"] for row in rows] == [datetime.datetime(2024, 1, 2, 3, 4, 5), datetime.datetime(2025, 6, 7, 8, 9, 10)] + + +# Every type name a JSON path annotation accepts, the JSON field of row "a" it reads, +# and the value it gives on both backends (None: any value) +ANNOTATIONS = { + **dict.fromkeys( + "signed, unsigned, signed int, signed integer, unsigned int, unsigned integer, int, int2, int4, " + "int8, integer, tinyint, smallint, mediumint, bigint".split(", "), + ("n", 7), + ), + "year": ("year", 2024), + **dict.fromkeys("real, float, float4, float8, double, double precision".split(", "), ("gain", 2.5)), + **dict.fromkeys(("decimal", "numeric", "dec"), ("gain", decimal.Decimal("2.5"))), + **dict.fromkeys(("bool", "boolean"), ("cal", True)), + **dict.fromkeys("char, character, char varying, character varying, varchar, nchar, text".split(", "), ("vendor", "Acme")), + **dict.fromkeys(("binary", "varbinary", "bytea"), ("vendor", None)), + **dict.fromkeys(("json", "jsonb"), ("n", None)), + "date": ("day", datetime.date(2024, 1, 2)), + "datetime": ("made", datetime.datetime(2024, 1, 2, 3, 4, 5)), + "timestamp": ("made", datetime.datetime(2024, 1, 2, 3, 4, 5)), + "time": ("at", None), + # PostgreSQL types with no MySQL equivalent + "timetz": ("at", None), + "timestamptz": ("made", None), + "uuid": ("id", None), + "interval": ("span", None), + "bit": ("flag", None), +} +POSTGRESQL_ONLY = {"timetz", "timestamptz", "uuid", "interval", "bit"} + + +@pytest.mark.parametrize("annotation", ANNOTATIONS) +def test_every_annotation(Device, backend, annotation): + """Each accepted annotation works on both backends, or raises a DataJointError (#1563).""" + field, expected = ANNOTATIONS[annotation] + row = Device & {"name": "a"} + if backend == "mysql" and annotation in POSTGRESQL_ONLY: + with pytest.raises(dj.DataJointError, match="has no MySQL equivalent"): + row.proj(v=f"s.{field}:{annotation}") + return + value = row.proj(v=f"s.{field}:{annotation}").fetch1("v") + assert value is not None + if expected is not None: + assert value == expected diff --git a/tests/unit/test_adapters.py b/tests/unit/test_adapters.py index 0020abd97..c9be73968 100644 --- a/tests/unit/test_adapters.py +++ b/tests/unit/test_adapters.py @@ -191,28 +191,63 @@ def test_json_path_expr_with_return_type(self, adapter): @pytest.mark.parametrize( "annotation, returning", [ - # PostgreSQL spellings are mapped onto the RETURNING vocabulary + # integer spellings, display widths dropped ("int", "signed"), ("INTEGER", "signed"), - ("bigint", "signed"), + ("int2", "signed"), + ("int4", "signed"), + ("int8", "signed"), + ("tinyint", "signed"), ("smallint", "signed"), + ("mediumint", "signed"), + ("bigint", "signed"), ("int(11)", "signed"), + ("signed integer", "signed"), + ("unsigned int", "unsigned"), + ("year", "signed"), ("bool", "signed"), ("boolean", "signed"), - ("numeric", "decimal"), + # a decimal without precision keeps the value instead of rounding it + ("numeric", "decimal(65,30)"), + ("decimal", "decimal(65,30)"), + ("dec", "decimal(65,30)"), ("numeric(5,1)", "decimal(5,1)"), - ("double precision", "double"), - ("varchar(16)", "char(16)"), - ("text", "char"), - ("timestamp", "datetime"), - # RETURNING spellings pass through unchanged - ("signed", "signed"), - ("unsigned", "unsigned"), ("decimal(4, 1)", "decimal(4, 1)"), - ("char(20)", "char(20)"), - ("float", "float"), + ("dec(7)", "decimal(7)"), + # floats + ("double precision", "double precision"), ("double", "double"), + ("float", "float"), + ("float(30)", "float(30)"), + ("float4", "float4"), + ("float8", "float8"), + ("real", "real"), + # strings: CHAR without a length is unlimited in RETURNING + ("char", "char"), + ("character", "char"), + ("nchar", "char"), + ("text", "char"), + ("varchar", "char"), + ("character varying", "char"), + ("char(20)", "char(20)"), + ("varchar(16)", "char(16)"), + ("char varying(16)", "char(16)"), + ("char(20) character set utf8mb4", "char(20) character set utf8mb4"), + ("char(20) charset utf8mb4", "char(20) character set utf8mb4"), + # binary and JSON + ("binary(4)", "binary(4)"), + ("varbinary(4)", "binary"), + ("bytea", "binary"), + ("json", "json"), + ("jsonb", "json"), + # dates and times + ("date", "date"), + ("time", "time"), + ("time(3)", "time(3)"), ("datetime", "datetime"), + ("datetime(6)", "datetime(6)"), + ("timestamp", "datetime"), + ("timestamp(3) without time zone", "datetime(3)"), ], ) def test_json_path_expr_maps_return_type(self, adapter, annotation, returning): @@ -220,6 +255,23 @@ def test_json_path_expr_maps_return_type(self, adapter, annotation, returning): result = adapter.json_path_expr("data", "n", annotation) assert result == f"json_value(`data`, _utf8mb4'$.n' returning {returning})" + def test_json_path_expr_collation(self, adapter): + """RETURNING takes no COLLATE clause, so the returned string is collated.""" + assert adapter.json_path_expr("data", "s", "char(20) character set utf8mb4 collate utf8mb4_bin") == ( + "json_value(`data`, _utf8mb4'$.s' returning char(20) character set utf8mb4) collate utf8mb4_bin" + ) + + @pytest.mark.parametrize( + "annotation", + ["uuid", "interval", "bit", "bit(3)", "timetz", "timestamptz", "time with time zone", "timestamp with time zone"], + ) + def test_json_path_expr_rejects_type_without_equivalent(self, adapter, annotation): + """A type MySQL cannot return raises a DataJointError instead of a SQL syntax error.""" + from datajoint.errors import DataJointError + + with pytest.raises(DataJointError, match="has no MySQL equivalent"): + adapter.json_path_expr("data", "n", annotation) + def test_json_path_equals(self, adapter): """Test JSON path comparison with a JSON literal.""" assert adapter.json_path_equals("data", "n", "64") == "json_extract(`data`, _utf8mb4'$.n') = cast('64' as json)" @@ -381,13 +433,55 @@ def test_json_path_expr_nested(self, adapter): @pytest.mark.parametrize( "annotation, cast", [ - ("signed", "integer"), - ("unsigned", "integer"), + # MySQL integer spellings; SIGNED and UNSIGNED are 64-bit + ("signed", "bigint"), + ("unsigned", "bigint"), + ("signed integer", "bigint"), + ("UNSIGNED INT", "bigint"), + ("tinyint", "smallint"), + ("mediumint", "integer"), + ("year", "integer"), + ("int(11)", "int"), + ("int", "int"), + ("int8", "int8"), + ("bigint", "bigint"), + # floats and decimals ("double", "double precision"), + ("double precision", "double precision"), + ("float", "float"), + ("float(10)", "float(10)"), + ("real", "real"), + ("decimal(5,1)", "decimal(5,1)"), + ("numeric", "numeric"), + ("dec", "dec"), + ("bool", "bool"), + # strings: char alone is char(1) and char(n) pads, so both become varchar or text + ("char", "text"), + ("character", "text"), + ("nchar", "text"), + ("text", "text"), + ("char(20)", "varchar(20)"), + ("nchar(20)", "varchar(20)"), + ("varchar", "varchar"), + ("varchar(16)", "varchar(16)"), + ("character varying", "character varying"), + ("char(20) character set utf8mb4", "varchar(20)"), + # binary and other types + ("binary", "bytea"), + ("varbinary(4)", "bytea"), + ("bytea", "bytea"), + ("uuid", "uuid"), + ("bit(3)", "bit(3)"), + ("interval", "interval"), + # dates and times + ("date", "date"), ("datetime", "timestamp"), ("datetime(3)", "timestamp(3)"), - ("int", "int"), - ("decimal(5,1)", "decimal(5,1)"), + ("timestamp", "timestamp"), + ("timestamptz", "timestamptz"), + ("timestamp(3) with time zone", "timestamp(3) with time zone"), + ("time", "time"), + ("timetz", "timetz"), ], ) def test_json_path_expr_maps_return_type(self, adapter, annotation, cast): @@ -395,6 +489,17 @@ def test_json_path_expr_maps_return_type(self, adapter, annotation, cast): result = adapter.json_path_expr("data", "n", annotation) assert result == f"(jsonb_extract_path_text(\"data\", 'n'))::{cast}" + @pytest.mark.parametrize("annotation", ["json", "jsonb"]) + def test_json_path_expr_json_type(self, adapter, annotation): + """A JSON annotation casts the JSON value, since the text of a JSON string is not JSON.""" + result = adapter.json_path_expr("data", "n", annotation) + assert result == f"(jsonb_extract_path(\"data\", 'n'))::{annotation}" + + def test_json_path_expr_collation(self, adapter): + assert adapter.json_path_expr("data", "s", "text collate ucs_basic") == ( + "(jsonb_extract_path_text(\"data\", 's'))::text collate ucs_basic" + ) + def test_json_path_equals(self, adapter): """Test JSON path comparison with a JSON literal.""" assert adapter.json_path_equals("data", "n", "64") == "jsonb_extract_path(\"data\", 'n') = '64'::jsonb" diff --git a/tests/unit/test_condition.py b/tests/unit/test_condition.py index 3aad216c2..b249f19bc 100644 --- a/tests/unit/test_condition.py +++ b/tests/unit/test_condition.py @@ -186,12 +186,21 @@ def test_invalid_offset_type_raises(self): "bool", "jsonb", "timestamp", - "timestamptz", - "timestamp with time zone", "timestamp(3) without time zone", - "uuid", ] +# PostgreSQL types with no MySQL equivalent: a DataJointError on MySQL +POSTGRESQL_ONLY_JSON_TYPES = ["timestamptz", "timestamp with time zone", "uuid", "interval", "bit", "timetz"] + +# Every type name that _JSON_TYPE_PATTERN accepts +ACCEPTED_JSON_TYPE_NAMES = ( + "signed, unsigned, signed int, signed integer, unsigned int, unsigned integer, int, int2, int4, int8, " + "integer, tinyint, smallint, mediumint, bigint, real, float, float4, float8, double, double precision, " + "decimal, numeric, dec, bool, boolean, bit, char, character, char varying, character varying, varchar, " + "nchar, text, binary, varbinary, bytea, json, jsonb, uuid, date, datetime, year, time, timetz, timestamp, " + "timestamptz, interval" +).split(", ") + def _fake_expression(backend, names=("name", "car", "uid")): """Stand-in for a query expression: an adapter and a heading.""" @@ -323,6 +332,14 @@ def test_valid_json_type_accepted(self, backend, type_spec): cond = _condition(backend, {f"car.length:{type_spec}": 1}) assert cond.endswith("=1)") + @pytest.mark.parametrize("type_spec", POSTGRESQL_ONLY_JSON_TYPES) + def test_postgresql_only_json_type(self, backend, type_spec): + if backend == "mysql": + with pytest.raises(DataJointError, match="has no MySQL equivalent"): + _condition(backend, {f"car.length:{type_spec}": 1}) + else: + assert _condition(backend, {f"car.length:{type_spec}": 1}).endswith("=1)") + @pytest.mark.parametrize("value", [float("nan"), float("inf"), -float("inf"), np.float64("nan"), np.float32("inf")]) def test_non_finite_number_rejected(self, backend, value): with pytest.raises(DataJointError, match="non-finite"): @@ -418,12 +435,39 @@ def test_json_type_in_projection_and_index(backend, type_spec): adapter = get_adapter(backend) expr = translate_attribute(f"car.length:{type_spec}", adapter)[1] - assert expr.startswith("json_value(" if backend == "mysql" else "(jsonb_extract_path_text(") + assert expr.startswith("json_value(" if backend == "mysql" else "(jsonb_extract_path") index_sql = [] compile_index(f"index(car.length:{type_spec})", index_sql, adapter) assert index_sql == [f"index (({expr}))"] +# Types that MySQL's JSON_VALUE ... RETURNING accepts, and types that PostgreSQL lacks +MYSQL_RETURNING_TYPES = {"signed", "unsigned", "float", "float4", "float8", "real", "double", "double precision"} +MYSQL_RETURNING_TYPES |= {"decimal(65,30)", "char", "binary", "json", "date", "time", "datetime"} +NOT_POSTGRESQL_TYPES = {"signed", "unsigned", "tinyint", "mediumint", "double", "datetime", "year", "binary", "varbinary"} + + +@pytest.mark.parametrize("name", ACCEPTED_JSON_TYPE_NAMES) +def test_every_accepted_json_type_name_is_mapped(name): + """ + Each type name that a JSON path annotation accepts is mapped onto a type of each + backend, or rejected with a DataJointError; it never reaches the server as is (#1563). + """ + from datajoint.condition import _JSON_TYPE_PATTERN + + assert _JSON_TYPE_PATTERN.fullmatch(name) + if name in POSTGRESQL_ONLY_JSON_TYPES: + with pytest.raises(DataJointError, match="has no MySQL equivalent"): + translate_attribute(f"car.length:{name}", get_adapter("mysql")) + else: + mysql_expr = translate_attribute(f"car.length:{name}", get_adapter("mysql"))[1] + assert mysql_expr.split(" returning ")[1].removesuffix(")") in MYSQL_RETURNING_TYPES + postgres_expr = translate_attribute(f"car.length:{name}", get_adapter("postgresql"))[1] + cast = postgres_expr.split(")::")[1] + # char, character and nchar alone mean char(1), which truncates the string + assert cast not in NOT_POSTGRESQL_TYPES | {"char", "character", "nchar"} + + @pytest.mark.parametrize("backend", BACKENDS) @pytest.mark.parametrize("type_spec", ["unsigned) OR (1", "nonsense"]) def test_invalid_json_type_in_projection_and_index(backend, type_spec): From bc2f75b584ac381f9de69968ae04318ea72d0088 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Sat, 21 Nov 2026 00:42:41 -0600 Subject: [PATCH 3/5] fix(json): reject extra type arguments; cast bare bit to bit varying on PostgreSQL Only decimal, numeric and dec take two arguments. A second argument on any other type (float(10,2), char(10,2), time(3,2)), or an argument on a type that takes none (date(3), json(3), bool(1)), raised a server syntax error; it now raises a DataJointError on both backends. On PostgreSQL, bit alone means bit(1) and kept only the first bit of the string. A bare bit annotation now casts to bit varying. --- src/datajoint/adapters/base.py | 24 +++++++++++++-- src/datajoint/adapters/postgres.py | 5 +++- tests/integration/test_json_path.py | 12 ++++++-- tests/unit/test_adapters.py | 2 ++ tests/unit/test_condition.py | 45 +++++++++++++++++++++++++++-- 5 files changed, 81 insertions(+), 7 deletions(-) diff --git a/src/datajoint/adapters/base.py b/src/datajoint/adapters/base.py index 1c976145a..cf4275cb6 100644 --- a/src/datajoint/adapters/base.py +++ b/src/datajoint/adapters/base.py @@ -50,6 +50,19 @@ | JSON_OTHER_TYPES ) +# How many arguments a type takes: precision and scale for a decimal; a length, a float +# precision, or fractional seconds; or an integer display width, which is dropped. +# Every other type takes none. +_JSON_TYPE_MAX_ARGS = { + **dict.fromkeys(JSON_DECIMAL_TYPES, 2), + **dict.fromkeys( + JSON_INTEGER_TYPES + | JSON_STRING_TYPES + | {"float", "binary", "varbinary", "bit", "time", "timetz", "datetime", "timestamp", "timestamptz", "interval"}, + 1, + ), +} + # Annotations that work on every backend, for error messages JSON_PORTABLE_TYPES = ( "signed, unsigned, int, integer, smallint, bigint, decimal(p,s), numeric(p,s), float, double, " @@ -84,13 +97,20 @@ def parse_json_type(annotation: str) -> JsonType: Raises ------ DataJointError - If the annotation is not a known type name, or combines a qualifier with a - type that does not take it (e.g. ``int with time zone``). + If the annotation is not a known type name, gives a type more arguments than + it takes (e.g. ``float(10,2)``), or combines a qualifier with a type that does + not take it (e.g. ``int with time zone``). """ match = _JSON_TYPE_PARTS.fullmatch(annotation) name = " ".join(match["name"].lower().split()) if match else None if match is None or name not in _JSON_TYPE_NAMES: raise DataJointError(f"Unsupported JSON path type `{annotation}`. Portable types: {JSON_PORTABLE_TYPES}.") + max_args = _JSON_TYPE_MAX_ARGS.get(name, 0) + if match["args"] and match["args"].count(",") + 1 > max_args: + raise DataJointError( + f"JSON path type `{annotation}`: {name} takes " + + ("no arguments." if max_args == 0 else "one argument. Only decimal and numeric take precision and scale.") + ) if match["zone"] and name not in ("time", "datetime", "timestamp"): raise DataJointError(f"JSON path type `{annotation}`: only time and timestamp types take a time zone qualifier.") if (match["charset"] or match["collate"]) and name not in JSON_STRING_TYPES: diff --git a/src/datajoint/adapters/postgres.py b/src/datajoint/adapters/postgres.py index 1c4fe74e6..9827f7db3 100644 --- a/src/datajoint/adapters/postgres.py +++ b/src/datajoint/adapters/postgres.py @@ -1241,7 +1241,10 @@ def _json_cast_type(json_type: JsonType) -> str: return "bytea" if name in ("bool", "boolean", "date", "uuid"): return name - # time, timetz, datetime, timestamp, timestamptz, interval, bit + if name == "bit": + # bit alone means bit(1), which keeps only the first bit of the string + return "bit" + args if args else "bit varying" + # time, timetz, datetime, timestamp, timestamptz, interval zone = f" {json_type.zone} time zone" if json_type.zone else "" return {"datetime": "timestamp"}.get(name, name) + args + zone diff --git a/tests/integration/test_json_path.py b/tests/integration/test_json_path.py index d76bda5b8..2d7292747 100644 --- a/tests/integration/test_json_path.py +++ b/tests/integration/test_json_path.py @@ -48,7 +48,7 @@ class Device(dj.Manual): year=2024, id="6ba7b810-9dad-11d1-80b4-00c04fd430c8", span="1 day", - flag="1", + bits="101", ), ), dict( @@ -200,6 +200,13 @@ def test_string_annotation_collation(Device, backend): assert [row["v"] for row in rows] == ["Acme", "Other", "64"] +@pytest.mark.parametrize("annotation", ["float(10,2)", "char(16,2)", "datetime(3,2)", "date(3)", "json(3)"]) +def test_annotation_with_wrong_arguments(Device, annotation): + """Only a decimal takes two arguments; a server syntax error becomes a DataJointError.""" + with pytest.raises(dj.DataJointError, match="takes (no arguments|one argument)"): + Device.proj(v=f"s.gain:{annotation}") + + @pytest.mark.parametrize("annotation", ["bool", "boolean"]) def test_project_boolean_annotation(Device, annotation): rows = (Device & "name in ('a', 'b')").proj(c=f"s.cal:{annotation}").to_dicts(order_by="name") @@ -237,7 +244,8 @@ def test_project_datetime_annotation(Device, annotation): "timestamptz": ("made", None), "uuid": ("id", None), "interval": ("span", None), - "bit": ("flag", None), + # bit alone would be bit(1) on PostgreSQL and keep only the first bit + "bit": ("bits", "101"), } POSTGRESQL_ONLY = {"timetz", "timestamptz", "uuid", "interval", "bit"} diff --git a/tests/unit/test_adapters.py b/tests/unit/test_adapters.py index c9be73968..8558b46de 100644 --- a/tests/unit/test_adapters.py +++ b/tests/unit/test_adapters.py @@ -471,6 +471,8 @@ def test_json_path_expr_nested(self, adapter): ("varbinary(4)", "bytea"), ("bytea", "bytea"), ("uuid", "uuid"), + # bit alone means bit(1), which keeps only the first bit + ("bit", "bit varying"), ("bit(3)", "bit(3)"), ("interval", "interval"), # dates and times diff --git a/tests/unit/test_condition.py b/tests/unit/test_condition.py index b249f19bc..eb49ba773 100644 --- a/tests/unit/test_condition.py +++ b/tests/unit/test_condition.py @@ -464,8 +464,9 @@ def test_every_accepted_json_type_name_is_mapped(name): assert mysql_expr.split(" returning ")[1].removesuffix(")") in MYSQL_RETURNING_TYPES postgres_expr = translate_attribute(f"car.length:{name}", get_adapter("postgresql"))[1] cast = postgres_expr.split(")::")[1] - # char, character and nchar alone mean char(1), which truncates the string - assert cast not in NOT_POSTGRESQL_TYPES | {"char", "character", "nchar"} + # char, character and nchar alone mean char(1), which truncates the string, + # and bit alone means bit(1), which keeps only the first bit + assert cast not in NOT_POSTGRESQL_TYPES | {"char", "character", "nchar", "bit"} @pytest.mark.parametrize("backend", BACKENDS) @@ -480,6 +481,46 @@ def test_invalid_json_type_in_projection_and_index(backend, type_spec): compile_index(f"index(car.length:{type_spec})", [], adapter) +# Accepted by _JSON_TYPE_PATTERN, but with more arguments than the type takes: only a +# decimal takes two (precision and scale), and a float, date, bool or JSON type takes none +WRONG_ARGUMENTS_JSON_TYPES = [ + "float(10,2)", + "double(10,2)", + "double precision(10)", + "real(5)", + "float8(5)", + "int(10,2)", + "signed(10,2)", + "char(10,2)", + "varchar(16,2)", + "text(10,2)", + "binary(4,2)", + "bytea(4)", + "time(3,2)", + "timestamp(3,2) without time zone", + "bit(3,2)", + "date(3)", + "bool(1)", + "json(3)", + "uuid(3)", +] + + +@pytest.mark.parametrize("backend", BACKENDS) +@pytest.mark.parametrize("type_spec", WRONG_ARGUMENTS_JSON_TYPES) +def test_json_type_with_wrong_arguments(backend, type_spec): + """Too many type arguments raise a DataJointError on both backends, not a server syntax error.""" + from datajoint.condition import _JSON_TYPE_PATTERN + from datajoint.declare import compile_index + + assert _JSON_TYPE_PATTERN.fullmatch(type_spec) + adapter = get_adapter(backend) + with pytest.raises(DataJointError, match="takes (no arguments|one argument)"): + translate_attribute(f"car.length:{type_spec}", adapter) + with pytest.raises(DataJointError, match="takes (no arguments|one argument)"): + compile_index(f"index(car.length:{type_spec})", [], adapter) + + class TestJsonLiteral: """Tests for rendering restriction values as JSON literals (#1564).""" From 98aa5b55b005aa2fc9be28f7b4c69b7615a459cf Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Sat, 21 Nov 2026 01:29:52 -0600 Subject: [PATCH 4/5] fix(json): give float and integer annotations the same precision and range on both backends - float without a precision, float8, double and float(p) with p from 25 to 53 are double precision on both backends. On MySQL, RETURNING FLOAT is single precision for every p, so these now return DOUBLE. - real, float4 and float(p) with p up to 24 are single precision on both: FLOAT on MySQL, where REAL is DOUBLE, and real on PostgreSQL. - float(p) outside 1 to 53 raises a DataJointError on both backends. - Every integer annotation casts to bigint on PostgreSQL, 64-bit like MySQL's RETURNING SIGNED, so a value beyond the range of int or smallint no longer fails the query. - The portable types in the error message add real and float(p). - Tests check the values on both backends: 1234567.89 under each float spelling, integers beyond 32 bits and at the 64-bit limits, unsigned outside 0 to 2**63 - 1, and restrictions by integers beyond 64 bits, which MySQL compares as 64-bit floats. --- src/datajoint/adapters/base.py | 26 ++++++++-- src/datajoint/adapters/mysql.py | 5 +- src/datajoint/adapters/postgres.py | 15 +++--- tests/integration/test_json_path.py | 77 +++++++++++++++++++++++++++++ tests/unit/test_adapters.py | 44 +++++++++++------ tests/unit/test_condition.py | 12 ++++- 6 files changed, 146 insertions(+), 33 deletions(-) diff --git a/src/datajoint/adapters/base.py b/src/datajoint/adapters/base.py index cf4275cb6..fe5502ffb 100644 --- a/src/datajoint/adapters/base.py +++ b/src/datajoint/adapters/base.py @@ -65,8 +65,8 @@ # Annotations that work on every backend, for error messages JSON_PORTABLE_TYPES = ( - "signed, unsigned, int, integer, smallint, bigint, decimal(p,s), numeric(p,s), float, double, " - "bool, boolean, char(n), varchar(n), text, date, time, datetime, timestamp, json" + "signed, unsigned, int, integer, smallint, bigint, decimal(p,s), numeric(p,s), real, float, float(p), " + "double, bool, boolean, char(n), varchar(n), text, date, time, datetime, timestamp, json" ) @@ -79,6 +79,17 @@ class JsonType(NamedTuple): charset: str | None collate: str | None + @property + def single_precision(self) -> bool: + """ + Whether a floating-point type is single precision. + + As in PostgreSQL, ``real``, ``float4`` and ``float(p)`` with ``p`` up to 24 are + single precision; ``float``, ``float8``, ``double``, ``double precision`` and + ``float(p)`` with ``p`` from 25 to 53 are double precision. + """ + return self.name in ("real", "float4") or (self.name == "float" and bool(self.args) and int(self.args[1:-1]) <= 24) + def parse_json_type(annotation: str) -> JsonType: """ @@ -98,8 +109,9 @@ def parse_json_type(annotation: str) -> JsonType: ------ DataJointError If the annotation is not a known type name, gives a type more arguments than - it takes (e.g. ``float(10,2)``), or combines a qualifier with a type that does - not take it (e.g. ``int with time zone``). + it takes (e.g. ``float(10,2)``), gives ``float`` a precision outside 1 to 53, + or combines a qualifier with a type that does not take it (e.g. ``int with + time zone``). """ match = _JSON_TYPE_PARTS.fullmatch(annotation) name = " ".join(match["name"].lower().split()) if match else None @@ -111,6 +123,9 @@ def parse_json_type(annotation: str) -> JsonType: f"JSON path type `{annotation}`: {name} takes " + ("no arguments." if max_args == 0 else "one argument. Only decimal and numeric take precision and scale.") ) + if name == "float" and match["args"] and not 1 <= int(match["args"]) <= 53: + # MySQL would take float(0) and PostgreSQL would not; neither takes more than 53 + raise DataJointError(f"JSON path type `{annotation}`: float takes a precision from 1 to 53.") if match["zone"] and name not in ("time", "datetime", "timestamp"): raise DataJointError(f"JSON path type `{annotation}`: only time and timestamp types take a time zone qualifier.") if (match["charset"] or match["collate"]) and name not in JSON_STRING_TYPES: @@ -1300,6 +1315,9 @@ def json_path_equals(self, column: str, path: str, value: str) -> str: The comparison is between JSON values, not text: numbers compare numerically (``64`` equals ``64.0``), booleans match only JSON booleans, and a value of another JSON type (e.g. a string) is simply unequal. + PostgreSQL compares numbers exactly. MySQL holds a JSON integer outside + the range -2**63 to 2**64 - 1, and any number with a fraction or an + exponent, as a 64-bit float, and compares the rounded values. Parameters ---------- diff --git a/src/datajoint/adapters/mysql.py b/src/datajoint/adapters/mysql.py index a8ff16a8e..66dc7798e 100644 --- a/src/datajoint/adapters/mysql.py +++ b/src/datajoint/adapters/mysql.py @@ -994,8 +994,9 @@ def _json_returning_type(json_type: JsonType, annotation: str) -> str: if name in JSON_BOOLEAN_TYPES: return "signed" if name in JSON_FLOAT_TYPES: - # RETURNING takes every float spelling; only float(p) takes an argument - return name + (args if name == "float" else "") + # Precision as on PostgreSQL. MySQL's REAL is DOUBLE, and RETURNING FLOAT + # is single precision with or without a precision, so neither is passed on. + return "float" if json_type.single_precision else "double" if name in JSON_DECIMAL_TYPES: # A bare DECIMAL is DECIMAL(10,0) on MySQL and would round the value. # DECIMAL(65,30) is the widest MySQL decimal, closest to PostgreSQL's diff --git a/src/datajoint/adapters/postgres.py b/src/datajoint/adapters/postgres.py index 9827f7db3..a2d8f5365 100644 --- a/src/datajoint/adapters/postgres.py +++ b/src/datajoint/adapters/postgres.py @@ -31,11 +31,6 @@ parse_json_type, ) -# Integer type names PostgreSQL knows, and casts for the MySQL-only ones. MySQL's -# SIGNED and UNSIGNED are 64-bit, so they and their variants cast to bigint. -_PG_INTEGER_TYPES = frozenset(("int", "int2", "int4", "int8", "integer", "smallint", "bigint")) -_PG_INTEGER_CASTS = {"tinyint": "smallint", "mediumint": "integer", "year": "integer"} - logger = logging.getLogger(__name__.split(".")[0]) # use_tls dict keys (PyMySQL ssl names, as for MySQL) → libpq connection parameters @@ -1206,7 +1201,7 @@ def json_path_expr(self, column: str, path: str, return_type: str | None = None) >>> adapter.json_path_expr('data', 'nested.field') 'jsonb_extract_path_text("data", \\'nested\\', \\'field\\')' >>> adapter.json_path_expr('data', 'value', 'float') - '(jsonb_extract_path_text("data", \\'value\\'))::float' + '(jsonb_extract_path_text("data", \\'value\\'))::double precision' """ quoted_col = self.quote_identifier(column) path_args = self._json_path_args(path) @@ -1224,10 +1219,12 @@ def _json_cast_type(json_type: JsonType) -> str: """Map a parsed JSON path type annotation onto a PostgreSQL type to cast to.""" name, args = json_type.name, json_type.args if name in JSON_INTEGER_TYPES: - # Display widths such as int(11) have no PostgreSQL equivalent - return name if name in _PG_INTEGER_TYPES else _PG_INTEGER_CASTS.get(name, "bigint") + # 64-bit, like MySQL's RETURNING SIGNED, which takes no size: a narrower type + # would fail the whole query on a value out of its range. Display widths + # such as int(11) are dropped. + return "bigint" if name in JSON_FLOAT_TYPES: - return "double precision" if name.startswith("double") else name + (args if name == "float" else "") + return "real" if json_type.single_precision else "double precision" if name in JSON_DECIMAL_TYPES: return name + args if name in JSON_STRING_TYPES: diff --git a/tests/integration/test_json_path.py b/tests/integration/test_json_path.py index 2d7292747..13d8b92d3 100644 --- a/tests/integration/test_json_path.py +++ b/tests/integration/test_json_path.py @@ -49,6 +49,14 @@ class Device(dj.Manual): id="6ba7b810-9dad-11d1-80b4-00c04fd430c8", span="1 day", bits="101", + # more digits than single precision holds + x=1234567.89, + # beyond 32 bits, the 64-bit limits, and beyond 64 bits + big=2**40, + neg=-5, + i64=-(2**63), + u64=2**64 - 1, + huge=2**70, ), ), dict( @@ -105,6 +113,19 @@ def test_restrict_by_value(Device, restriction, expected): assert names(Device & restriction) == expected +def test_restrict_by_large_integer(Device, backend): + """Integers from -2**63 to 2**64 - 1 compare exactly on both backends.""" + assert names(Device & {"s.u64": 2**64 - 1}) == ["a"] + assert names(Device & {"s.u64": 2**64 - 2}) == [] + assert names(Device & {"s.i64": -(2**63)}) == ["a"] + assert names(Device & {"s.i64": -(2**63) + 1}) == [] + assert names(Device & {"s.huge": 2**70}) == ["a"] + # MySQL holds a JSON integer beyond that range, and a number with a fraction, as a + # 64-bit float and compares the rounded values; PostgreSQL compares exact values + assert names(Device & {"s.huge": 2**70 + 1}) == (["a"] if backend == "mysql" else []) + assert names(Device & {"s.gain": decimal.Decimal("0.10000000000000000001")}) == (["b"] if backend == "mysql" else []) + + def test_anti_restrict(Device): # Row c holds a string at s.ch, which is unequal to 64 rather than an error assert names(Device - {"s.ch": 64}) == ["b", "c"] @@ -148,6 +169,62 @@ def test_project_integer_annotation(Device, annotation, expected): assert all(isinstance(row["n"], (int, np.integer)) for row in rows) +# Integer annotations other than unsigned: 64-bit signed on both backends +SIGNED_ANNOTATIONS = ["int", "integer", "int2", "int4", "int8", "tinyint", "smallint", "mediumint", "bigint"] +SIGNED_ANNOTATIONS += ["signed", "signed int", "year"] + + +@pytest.mark.parametrize("annotation", SIGNED_ANNOTATIONS) +def test_integer_annotation_is_64_bit(Device, annotation): + """No integer annotation checks a narrower range, so a value beyond 32 bits works on both backends.""" + row = Device & {"name": "a"} + assert row.proj(v=f"s.big:{annotation}").fetch1("v") == 2**40 + assert row.proj(v=f"s.neg:{annotation}").fetch1("v") == -5 + assert row.proj(v=f"s.i64:{annotation}").fetch1("v") == -(2**63) + assert names(Device & {f"s.big:{annotation}": 2**40}) == ["a"] + + +@pytest.mark.parametrize("annotation", ["unsigned", "unsigned int", "unsigned integer"]) +def test_unsigned_annotation(Device, backend, annotation): + """unsigned is MySQL's 64-bit UNSIGNED and PostgreSQL's bigint: they differ outside 0 to 2**63 - 1.""" + row = Device & {"name": "a"} + assert row.proj(v=f"s.big:{annotation}").fetch1("v") == 2**40 + if backend == "mysql": + assert row.proj(v=f"s.neg:{annotation}").fetch1("v") is None + assert row.proj(v=f"s.u64:{annotation}").fetch1("v") == 2**64 - 1 + else: + import psycopg2.errors + + assert row.proj(v=f"s.neg:{annotation}").fetch1("v") == -5 + with pytest.raises(psycopg2.errors.NumericValueOutOfRange): + row.proj(v=f"s.u64:{annotation}").fetch1("v") + + +# Floating-point annotations by precision, the same on both backends +DOUBLE_PRECISION = ["float", "float(25)", "float(53)", "float8", "double", "double precision"] +SINGLE_PRECISION = ["real", "float4", "float(1)", "float(24)"] + + +@pytest.mark.parametrize("annotation", DOUBLE_PRECISION) +def test_double_precision_annotation(Device, annotation): + """float, float8 and float(p) from p = 25 are double precision on both backends.""" + assert (Device & {"name": "a"}).proj(v=f"s.x:{annotation}").fetch1("v") == 1234567.89 + assert names(Device & {f"s.x:{annotation}": 1234567.89}) == ["a"] + assert names(Device & {f"s.gain:{annotation}": 0.1}) == ["b"] + + +@pytest.mark.parametrize("annotation", SINGLE_PRECISION) +def test_single_precision_annotation(Device, annotation): + """real, float4 and float(p) up to p = 24 are single precision on both backends.""" + value = (Device & {"name": "a"}).proj(v=f"s.x:{annotation}").fetch1("v") + # MySQL returns 6 significant digits (1234570.0), PostgreSQL the shortest + # decimal that reads back as the same single-precision value (1234567.9) + assert value != 1234567.89 + assert value == pytest.approx(1234567.89, rel=1e-5) + # A value that single precision holds exactly matches on both + assert names(Device & {f"s.gain:{annotation}": 2.5}) == ["a"] + + @pytest.mark.parametrize("annotation", ["decimal(4,1)", "numeric(4,1)", "numeric", "decimal", "dec"]) def test_project_decimal_annotation(Device, annotation): rows = Device.proj(g=f"s.gain:{annotation}").to_dicts(order_by="name") diff --git a/tests/unit/test_adapters.py b/tests/unit/test_adapters.py index 8558b46de..8d8157181 100644 --- a/tests/unit/test_adapters.py +++ b/tests/unit/test_adapters.py @@ -214,14 +214,18 @@ def test_json_path_expr_with_return_type(self, adapter): ("numeric(5,1)", "decimal(5,1)"), ("decimal(4, 1)", "decimal(4, 1)"), ("dec(7)", "decimal(7)"), - # floats - ("double precision", "double precision"), + # floats: precision as on PostgreSQL, where float is double precision and + # real is single; RETURNING FLOAT is single precision for every float(p) + ("double precision", "double"), ("double", "double"), - ("float", "float"), - ("float(30)", "float(30)"), - ("float4", "float4"), - ("float8", "float8"), - ("real", "real"), + ("float", "double"), + ("float8", "double"), + ("float(25)", "double"), + ("float(53)", "double"), + ("real", "float"), + ("float4", "float"), + ("float(1)", "float"), + ("float(24)", "float"), # strings: CHAR without a length is unlimited in RETURNING ("char", "char"), ("character", "char"), @@ -433,23 +437,31 @@ def test_json_path_expr_nested(self, adapter): @pytest.mark.parametrize( "annotation, cast", [ - # MySQL integer spellings; SIGNED and UNSIGNED are 64-bit + # every integer is 64-bit, like MySQL's SIGNED and UNSIGNED ("signed", "bigint"), ("unsigned", "bigint"), ("signed integer", "bigint"), ("UNSIGNED INT", "bigint"), - ("tinyint", "smallint"), - ("mediumint", "integer"), - ("year", "integer"), - ("int(11)", "int"), - ("int", "int"), - ("int8", "int8"), + ("tinyint", "bigint"), + ("smallint", "bigint"), + ("int2", "bigint"), + ("mediumint", "bigint"), + ("year", "bigint"), + ("int(11)", "bigint"), + ("int", "bigint"), + ("integer", "bigint"), + ("int4", "bigint"), + ("int8", "bigint"), ("bigint", "bigint"), # floats and decimals ("double", "double precision"), ("double precision", "double precision"), - ("float", "float"), - ("float(10)", "float(10)"), + ("float", "double precision"), + ("float8", "double precision"), + ("float(53)", "double precision"), + ("float(10)", "real"), + ("float(24)", "real"), + ("float4", "real"), ("real", "real"), ("decimal(5,1)", "decimal(5,1)"), ("numeric", "numeric"), diff --git a/tests/unit/test_condition.py b/tests/unit/test_condition.py index eb49ba773..0382741a1 100644 --- a/tests/unit/test_condition.py +++ b/tests/unit/test_condition.py @@ -442,8 +442,8 @@ def test_json_type_in_projection_and_index(backend, type_spec): # Types that MySQL's JSON_VALUE ... RETURNING accepts, and types that PostgreSQL lacks -MYSQL_RETURNING_TYPES = {"signed", "unsigned", "float", "float4", "float8", "real", "double", "double precision"} -MYSQL_RETURNING_TYPES |= {"decimal(65,30)", "char", "binary", "json", "date", "time", "datetime"} +MYSQL_RETURNING_TYPES = {"signed", "unsigned", "float", "double", "decimal(65,30)", "char", "binary", "json"} +MYSQL_RETURNING_TYPES |= {"date", "time", "datetime"} NOT_POSTGRESQL_TYPES = {"signed", "unsigned", "tinyint", "mediumint", "double", "datetime", "year", "binary", "varbinary"} @@ -521,6 +521,14 @@ def test_json_type_with_wrong_arguments(backend, type_spec): compile_index(f"index(car.length:{type_spec})", [], adapter) +@pytest.mark.parametrize("backend", BACKENDS) +@pytest.mark.parametrize("type_spec", ["float(0)", "float(54)", "float( 99 )"]) +def test_json_float_precision_out_of_range(backend, type_spec): + """float(p) takes 1 to 53 on both backends; MySQL would otherwise take float(0).""" + with pytest.raises(DataJointError, match="float takes a precision from 1 to 53"): + translate_attribute(f"car.length:{type_spec}", get_adapter(backend)) + + class TestJsonLiteral: """Tests for rendering restriction values as JSON literals (#1564).""" From 7520c0b74fa8d404ee76131ffc0bf951414e2c86 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Tue, 24 Nov 2026 15:29:16 -0600 Subject: [PATCH 5/5] Run the JSON-path index declaration test on PostgreSQL Indexes on JSON paths are now created on PostgreSQL, so the test no longer needs to skip that backend. --- tests/integration/test_restriction_values.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/tests/integration/test_restriction_values.py b/tests/integration/test_restriction_values.py index 94c793209..967f48082 100644 --- a/tests/integration/test_restriction_values.py +++ b/tests/integration/test_restriction_values.py @@ -177,8 +177,6 @@ def test_json_types_in_restriction_and_projection(item, backend): def test_json_type_in_index_declaration(connection_by_backend, backend, prefix): - if backend == "postgresql": - pytest.skip("Indexes on JSON paths are not created on PostgreSQL (index name is derived from the expression)") schema = dj.Schema(f"{prefix}_restriction_values_index_{backend}", connection=connection_by_backend) numeric, text = NUMERIC_JSON_TYPES[backend][0], TEXT_JSON_TYPES[backend][0] try: