diff --git a/src/datajoint/adapters/base.py b/src/datajoint/adapters/base.py index 215200892..83863bc50 100644 --- a/src/datajoint/adapters/base.py +++ b/src/datajoint/adapters/base.py @@ -10,7 +10,129 @@ import hashlib 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 +) + +# 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), real, float, float(p), " + "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 + + @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: + """ + 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, gives a type more arguments than + 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 + 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 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: + 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): @@ -1171,13 +1293,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 - Return type specification (MySQL-specific). + 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) @@ -1185,6 +1317,39 @@ 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. + 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 + ---------- + 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 e55425254..66dc7798e 100644 --- a/src/datajoint/adapters/mysql.py +++ b/src/datajoint/adapters/mysql.py @@ -7,6 +7,7 @@ from __future__ import annotations +import re import ssl from typing import Any @@ -14,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 = { @@ -291,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) @@ -785,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( @@ -942,23 +953,96 @@ 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)'). + 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') "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) + 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_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: + # 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 + # 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: + """ + 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_clause = f" returning {return_type}" if return_type else "" - return f"json_value({quoted_col}, _utf8mb4{self.quote_string('$.' + path)}{return_clause})" + quoted_path = self.quote_string("$." + path) + return f"json_extract({quoted_col}, _utf8mb4{quoted_path}) = cast({self.quote_string(value)} as json)" def translate_expression(self, expr: str) -> str: """ @@ -978,7 +1062,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 52686763f..a2d8f5365 100644 --- a/src/datajoint/adapters/postgres.py +++ b/src/datajoint/adapters/postgres.py @@ -19,7 +19,17 @@ 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, +) logger = logging.getLogger(__name__.split(".")[0]) @@ -1175,7 +1185,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,9 +1201,52 @@ 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) + 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: + # 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 "real" if json_type.single_precision else "double precision" + 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 + 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 + + def _json_path_args(self, 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("."): @@ -1204,18 +1259,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(self.quote_string(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(self.quote_string(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)}) = {self.quote_string(value)}::jsonb" def translate_expression(self, expr: str) -> str: """ diff --git a/src/datajoint/condition.py b/src/datajoint/condition.py index e9b6cdbfe..17da05a85 100644 --- a/src/datajoint/condition.py +++ b/src/datajoint/condition.py @@ -13,6 +13,7 @@ import inspect import json import logging +import math import numbers import re import uuid @@ -86,6 +87,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. @@ -371,6 +406,11 @@ def prep_value(k, v): return f"{k}={literal(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 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..13d8b92d3 --- /dev/null +++ b/tests/integration/test_json_path.py @@ -0,0 +1,342 @@ +""" +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, or raises a DataJointError for a type one backend lacks (#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], + price=1234567890123.25, + day="2024-01-02", + at="03:04:05", + year=2024, + 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( + 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_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"] + # 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( + "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) + + +# 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") + 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", + # 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", ["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") + # 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)] + + +# 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 alone would be bit(1) on PostgreSQL and keep only the first bit + "bit": ("bits", "101"), +} +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/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: diff --git a/tests/unit/test_adapters.py b/tests/unit/test_adapters.py index bcfe6a612..8d8157181 100644 --- a/tests/unit/test_adapters.py +++ b/tests/unit/test_adapters.py @@ -188,6 +188,102 @@ 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", + [ + # integer spellings, display widths dropped + ("int", "signed"), + ("INTEGER", "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"), + # 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)"), + ("decimal(4, 1)", "decimal(4, 1)"), + ("dec(7)", "decimal(7)"), + # 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", "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"), + ("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): + """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_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)" + 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() @@ -338,6 +434,93 @@ 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", + [ + # every integer is 64-bit, like MySQL's SIGNED and UNSIGNED + ("signed", "bigint"), + ("unsigned", "bigint"), + ("signed integer", "bigint"), + ("UNSIGNED INT", "bigint"), + ("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", "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"), + ("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 alone means bit(1), which keeps only the first bit + ("bit", "bit varying"), + ("bit(3)", "bit(3)"), + ("interval", "interval"), + # dates and times + ("date", "date"), + ("datetime", "timestamp"), + ("datetime(3)", "timestamp(3)"), + ("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): + """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}" + + @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" + 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" @@ -430,6 +613,7 @@ def test_adapter_implements_interface(self, backend): "statement_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 6e6be5ecc..0382741a1 100644 --- a/tests/unit/test_condition.py +++ b/tests/unit/test_condition.py @@ -1,7 +1,8 @@ -"""Unit tests for condition.py - Top class and merge logic.""" +"""Unit tests for condition.py - Top class and merge logic, JSON path literals.""" import pytest -from datajoint.condition import Top + +from datajoint.condition import Top, _json_literal class TestTopMerge: @@ -185,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.""" @@ -322,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"): @@ -417,12 +435,40 @@ 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", "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"} + + +@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, + # 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) @pytest.mark.parametrize("type_spec", ["unsigned) OR (1", "nonsense"]) def test_invalid_json_type_in_projection_and_index(backend, type_spec): @@ -433,3 +479,79 @@ def test_invalid_json_type_in_projection_and_index(backend, type_spec): translate_attribute(f"car.length:{type_spec}", adapter) with pytest.raises(DataJointError): 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) + + +@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).""" + + @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) diff --git a/tests/unit/test_declare_index.py b/tests/unit/test_declare_index.py index 4789616b4..49ebd86b7 100644 --- a/tests/unit/test_declare_index.py +++ b/tests/unit/test_declare_index.py @@ -23,7 +23,7 @@ def index_ddl(): def test_json_path_index_keeps_the_expression(index_ddl): assert index_ddl[0].startswith('CREATE INDEX "idx_indexed_jsonb_extract_path_text_') - assert index_ddl[0].endswith(""" ON "s"."indexed" (((jsonb_extract_path_text("data", 'size'))::integer))""") + assert index_ddl[0].endswith(""" ON "s"."indexed" (((jsonb_extract_path_text("data", 'size'))::bigint))""") def test_index_mixing_columns_and_json_paths(index_ddl):