Skip to content

fix(json): make JSON path annotations and value comparisons portable - #1607

Open
dimitri-yatsenko wants to merge 6 commits into
masterfrom
fix/json-path-portability
Open

dimitri-yatsenko wants to merge 6 commits into
masterfrom
fix/json-path-portability

Conversation

@dimitri-yatsenko

@dimitri-yatsenko dimitri-yatsenko commented Oct 17, 2026 •

Copy link
Copy Markdown
Member

Summary

The same JSON path query could give different results on MySQL and PostgreSQL. This PR makes JSON path type annotations and value restrictions behave the same on both.

Type annotations (#1563). Doc.proj(n="data.n:int") worked on PostgreSQL but was a syntax error on MySQL, and so were int4, int8, numeric, text, varchar, timestamp and most other PostgreSQL spellings. Some MySQL spellings failed on PostgreSQL in turn (tinyint, signed int, year, binary), and some gave wrong values there (char cut 'Acme' to 'A'). Precision and range differed as well: float was single precision on MySQL and double precision on PostgreSQL, real the reverse, and int or smallint failed the whole query on PostgreSQL for a value that MySQL returned. Now every type name that an annotation accepts is mapped onto a type of each backend, or raises a DataJointError that lists the portable types. Each integer and floating-point annotation except unsigned has the same range on both backends, and each has the same precision (MySQL returns single-precision values with 6 significant digits, and MySQL 8.0.21 compares them in double precision; see "Results that still differ between the backends"). A type given more arguments than it takes, such as float(10,2), raises a DataJointError too: only decimal, numeric and dec take two. No annotation reaches the server as a syntax error. An argument outside a backend's range, such as time(7) on MySQL, is still reported by the server.

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 coerced the text to a number, so True missed JSON true and False matched almost everything. Bools and numbers are now compared as JSON values, with the same result on both backends.

Changes

Type annotations:

  • adapters/base.py adds parse_json_type(), which splits an annotation into its name, arguments, time zone qualifier, character set and collation. The _JSON_TYPE_PATTERN check in condition.py (from 2.3.6) still runs first and is unchanged.
  • parse_json_type() also checks the number of arguments. decimal, numeric and dec take two, the precision and scale. The integer types (a display width), float, the string types, binary, varbinary, bit and the time types except date take one. The other types take none. Too many arguments raise a DataJointError on both backends, and so does float(p) with p outside 1 to 53 (MySQL took float(0), PostgreSQL did not).
  • Each adapter maps every accepted name:
Accepted names MySQL RETURNING PostgreSQL cast
int, integer, int2, int4, int8, tinyint, smallint, mediumint, bigint, year signed bigint
signed, signed int, signed integer signed bigint
unsigned, unsigned int, unsigned integer unsigned bigint
bool, boolean signed as written
float, float8, double, double precision, float(p) with p from 25 to 53 double double precision
real, float4, float(p) with p from 1 to 24 float real
decimal(p,s), numeric(p,s), dec(p,s) decimal(p,s) as written
decimal, numeric, dec without precision decimal(65,30) as written
char, character, nchar, text char text
varchar, char varying, character varying char as written
any of the string names with a length (n) char(n) varchar(n)
binary(n) binary(n) bytea
binary, varbinary, varbinary(n), bytea binary bytea
json, jsonb json the JSON value (jsonb_extract_path), cast to json or jsonb
date date date
time(n), datetime(n), timestamp(n), optionally without time zone time(n), datetime(n) time(n), timestamp(n)
bit DataJointError bit varying
timetz, timestamptz, the with time zone forms, interval, bit(n), uuid DataJointError as written
  • Floating-point precision follows PostgreSQL and standard SQL: float alone is double precision, real single. MySQL's own spellings disagree: its REAL is DOUBLE, and RETURNING FLOAT is single precision whatever the precision argument (float(30) returned 1234567.89 as 1234570.0). So float(p) maps by its precision, and neither MySQL spelling is passed on as written.
  • Every integer annotation except unsigned is a 64-bit signed integer on both backends. unsigned is 64-bit on both but unsigned only on MySQL, since PostgreSQL has no unsigned type (see "Results that still differ between the backends"). MySQL's RETURNING has only SIGNED and UNSIGNED, both 64-bit, so it cannot check the range of int or smallint. PostgreSQL now casts every integer name to bigint rather than fail the whole query on a value beyond the narrower type's range.
  • Integer display widths (int(11)) are dropped on both backends. A character set (char(20) character set utf8mb4) is kept on MySQL and dropped on PostgreSQL. A collation applies to the returned string: json_value(... returning char(20)) collate utf8mb4_bin on MySQL, since RETURNING takes no COLLATE clause, and ::varchar(20) collate ucs_basic on PostgreSQL.
  • 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.

Why decimal(65,30) for a decimal without precision: on PostgreSQL, numeric without precision keeps the exact value with any number of digits and returns a Python Decimal. MySQL's bare DECIMAL is DECIMAL(10,0), which rounds 2.5 to 3. DECIMAL(65,30) is MySQL's widest decimal: it is exact for up to 35 integer digits and 30 decimal places, and it also returns a Decimal. Beyond 30 decimal places it rounds (1e-40 becomes 0), and from 1e35 in magnitude it returns NULL. double would return a float, would not hold 0.1 exactly, and would give a different Python type than PostgreSQL.

Value comparisons:

  • Bools and numbers (numpy scalars and Decimal included) are compared as JSON values: json_extract(...) = cast('64' as json) on MySQL, jsonb_extract_path(...) = '64'::jsonb on PostgreSQL. The JSON literal is quoted through the backend adapter, like every other restriction value.
  • Strings still compare as text, so {"s.ch": "64"} and {"s.cal": "true"} work as before. 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.

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.
  • 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). One odd row would break the whole query.
  • JSON equality compares numbers by value on both servers (64 = 64.0, and integers from -2^63 to 2^64 - 1 stay exact; see "Results that still differ" for numbers beyond that). It matches a boolean only to a JSON boolean. A value of another JSON type is unequal rather than an error.

Behavior change

Restrictions by a bool or a number on a JSON path, without an annotation:

Restriction Before, MySQL Before, PostgreSQL After, both
{"s.x": True} matched 1 and "1", not JSON true error JSON true only
{"s.x": False} matched JSON false and true, 0, "0", and any string that does not read as a number, such as "Acme" error JSON false only
{"s.x": 1} matched 1 and "1" error 1 and 1.0
{"s.x": 0} matched the same rows as False error 0 and 0.0
{"s.x": 64} matched 64, 64.0, "64" and "64abc" error 64 and 64.0
{"s.x": Decimal("2.50")} compared as text: no match for a stored 2.5 same as MySQL matches 2.5
T - {"s.x": 64} left out rows that hold JSON null at the path error includes them; a missing key is still left out of both

Type annotations:

  • MySQL, decimal or dec without precision: before, DECIMAL(10,0), which rounded to a whole number (2.5 became 3) and held at most 10 digits. After, the exact value, returned with 30 decimal places (Decimal('2.500000000000000000000000000000'), equal to Decimal('2.5')).
  • MySQL, float without precision and float(p) with p from 25 to 53: before, single precision whatever p, so 1234567.89 came back as 1234570.0. After, double, as on PostgreSQL.
  • MySQL, real: before, MySQL's REAL, which is DOUBLE. After, float, single precision as on PostgreSQL.
  • Both backends, float(0) and float(p) above 53: before, float(0) was single precision on MySQL and a server error on PostgreSQL, and above 53 a server error on both. After, a DataJointError.
  • MySQL, nchar: before, utf8mb3, with a deprecation warning from the server. After, char in the default utf8mb4.
  • MySQL, year: before, RETURNING YEAR, a syntax error before MySQL 8.0.22 and limited to the years 1901 to 2155 after it. After, signed.
  • MySQL, uuid, interval, bit, timetz, timestamptz and the with time zone forms: before, a server syntax error. After, a DataJointError that lists the portable types.
  • Both backends, a type with more arguments than it takes, such as float(10,2), char(10,2), time(3,2), date(3) or json(3): before, a server syntax error. After, a DataJointError.
  • PostgreSQL, signed and unsigned: before, cast to integer, so a value beyond 2,147,483,647 failed the whole query with "out of range". After, bigint, which is 64-bit like MySQL's.
  • PostgreSQL, int, integer, int4, smallint and int2: before, 32- or 16-bit, so a larger value failed the whole query with "out of range". After, bigint, 64-bit like MySQL's signed.
  • PostgreSQL, char, character and nchar without a length: before, char(1), which cut 'Acme' to 'A'. After, text.
  • PostgreSQL, char(n), character(n) and nchar(n): before, padded with blanks to n ('Acme '). After, varchar(n), without padding. Restrictions match the same rows, since PostgreSQL ignored the padding when comparing.
  • PostgreSQL, json and jsonb: before, the text was cast, so a JSON string at the path failed the whole query with "invalid input syntax for type json". After, the JSON value is cast.
  • PostgreSQL, bit without a length: before, bit(1), which kept only the first bit ('101' became '1'). After, bit varying, which keeps every bit.

Indexes on an annotated JSON path. An index declaration uses the same mapping as a query, and an existing index keeps the expression it was created with. For the annotations below, queries now produce a different expression than an index declared before this change, so they no longer use that index. Re-create such an index to use it again:

  • MySQL: decimal and dec without precision (decimal becomes decimal(65,30)); nchar(n) (becomes char(n) in utf8mb4); year (becomes signed; RETURNING YEAR needs MySQL 8.0.22 or later); float and float(p) with p from 25 to 53 (float becomes double); real (real, which is double, becomes float).
  • PostgreSQL: signed, unsigned, int, integer, int4, smallint and int2 (integer or smallint becomes bigint); char, character and nchar without a length (char(1) becomes text); char(n), character(n) and nchar(n) (char(n) becomes varchar(n)); jsonb (the cast of the extracted text becomes the cast of the JSON value); bit without a length (bit(1) becomes bit varying).

json, and nchar without a length on MySQL, change as well, but neither server can index them. Every other annotation that worked before casts to the same type as before, and both servers match an index by type rather than by spelling: an index on ::float serves ::double precision on PostgreSQL, and one on returning float8 serves returning double on MySQL. An annotation that was a server error before could not have been used in an index.

Results that still differ between the backends:

  • A single-precision annotation (real, float4, float(p) with p up to 24) returns 6 significant digits on MySQL (1234567.89 becomes 1234570.0) and the shortest decimal that reads back as the same single-precision value on PostgreSQL (1234567.9). MySQL 8.0.21 also compares it in double precision, so {"s.x:real": 0.1} matches a stored 0.1 there; PostgreSQL, MySQL 8.0.46 and MySQL 8.4 compare the single-precision value, and it matches on none of them. float and double return the same value on both.
  • unsigned is MySQL's 64-bit UNSIGNED and PostgreSQL's bigint, since PostgreSQL has no unsigned type. A negative value is NULL on MySQL and returned as is on PostgreSQL. A value from 2^63 to 2^64 - 1 is returned on MySQL and fails the query on PostgreSQL ("out of range").
  • A boolean annotation returns 1/0 on MySQL and True/False on PostgreSQL.
  • A json or jsonb annotation returns the JSON text as a string on MySQL ('{"a": 1}', '"Acme"', '64') and the decoded value on PostgreSQL ({'a': 1}, 'Acme', 64). A projected attribute carries no type that would tell the fetch to decode the MySQL text, so this is left as is.
  • A value that the annotated type cannot hold, such as "abc" under :int or :date, or an integer outside -2^63 to 2^63 - 1 under an integer annotation other than unsigned, is NULL on MySQL and fails the whole query on PostgreSQL ("invalid input syntax" or "out of range"). An integer annotation on a number with a fraction rounds it on MySQL (2.7 becomes 3, 2.5 becomes 2) and fails the query on PostgreSQL. Checked on MySQL 8.0 and PostgreSQL 15.
  • A string longer than n in char(n) is NULL on MySQL and cut to n characters on PostgreSQL.
  • time, datetime and timestamp without (n) drop the fraction of a second on MySQL (03:04:05.567 becomes 03:04:05) and keep microseconds on PostgreSQL; write (6) to get the same value on both. A time outside 00:00:00 to 24:00:00, such as 25:00:00 or a negative time, is returned on MySQL and fails the query on PostgreSQL.
  • A decimal without precision is exact on PostgreSQL with any number of digits. On MySQL it rounds beyond 30 decimal places and is NULL from 1e35 in magnitude, and MySQL stores a JSON number that has a fraction as a 64-bit float.
  • MySQL holds a JSON integer outside -2^63 to 2^64 - 1, and every JSON number with a fraction or an exponent, as a 64-bit float, which keeps 15 to 17 significant digits. PostgreSQL keeps the exact number. A value restriction therefore compares rounded values on MySQL and exact values on PostgreSQL, and numbers that differ only beyond the 15th significant digit can match different rows: {"s.x": 2**70} also matches a stored 2**70 + 1 on MySQL, and {"s.x": Decimal("0.10000000000000000001")} matches a stored 0.1. Integers within that range, and numbers with up to 15 significant digits, match the same rows on both.

Tests

  • tests/integration/test_json_path.py runs on MySQL and PostgreSQL: 140 cases per backend. 140 of the 280 fail on master. They cover:
    • restrictions by bool, int, float, numpy scalars, Decimal and string, against stored floats, non-numeric strings, missing keys and JSON null;
    • every type name the annotation accepts (test_every_annotation), with the expected value where both backends agree, and the DataJointError on MySQL for the PostgreSQL-only types;
    • a decimal without precision keeping 1234567890123.25 and 0.1 exactly;
    • 1234567.89 under each float spelling: exact under the double-precision names, rounded to single precision under real, float4, float(1) and float(24), on both backends;
    • every signed integer name on 2**40, -5 and -2**63, and unsigned on a negative value and on 2**64 - 1, with each backend's result;
    • restrictions by integers at the 64-bit limits, which match exactly on both, and beyond them, where MySQL compares rounded values;
    • string annotations with and without a length, a character set, and a collation;
    • a bare bit keeping every bit on PostgreSQL;
    • a DataJointError for too many type arguments.
  • Unit tests in tests/unit/test_adapters.py check each backend's mapping and the rejected types. tests/unit/test_condition.py checks that every type name accepted by _JSON_TYPE_PATTERN maps onto both backends or raises a DataJointError, that too many type arguments and float(p) outside 1 to 53 raise a DataJointError in projections and index declarations, and the JSON literal rendering.
  • The full test suite passes on both backends with the latest master merged in. tests/integration/test_json_path.py also passes against MySQL 8.4, the second MySQL image in CI.

Documentation: datajoint-docs PR 318 updates the JSON path section of the type-system spec and merges after this PR.

Merge conflict with PR 1735

PR 1735 also appends tests at the end of tests/unit/test_condition.py, and the two conflict there. Whichever merges second keeps both blocks: the tests from this PR (WRONG_ARGUMENTS_JSON_TYPES, test_json_type_with_wrong_arguments, test_json_float_precision_out_of_range and TestJsonLiteral), then the uuid and JSON object tests from PR 1735. src/datajoint/condition.py merges without a conflict. With both blocks kept, tests/unit/test_condition.py passes.

Fixes #1563
Fixes #1564

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.
@dimitri-yatsenko dimitri-yatsenko added this to the v2.4 milestone Oct 17, 2026
@dimitri-yatsenko dimitri-yatsenko added the bug Indicates an unexpected problem or unintended behavior label Oct 17, 2026
@dimitri-yatsenko
dimitri-yatsenko marked this pull request as draft October 21, 2026 16:46
@dimitri-yatsenko dimitri-yatsenko modified the milestones: v2.4, v2.3.7 Nov 6, 2026
Master now quotes JSON path segments with the adapter's string quoting,
validates the return type after `:` against a list of known type names,
and renders mapping-restriction values through one quoting function.
All of that is kept; this branch's changes sit on top of it.

- adapters/mysql.py: imports keep both re and ssl. json_path_expr keeps
  master's quoted path and maps the return type through
  _json_return_type. json_path_equals quotes the path and the JSON
  literal with quote_string as well, which renders the same SQL for
  every literal it receives.
- adapters/postgres.py: _json_path_args quotes each segment with
  quote_string (now an instance method); json_path_expr keeps this
  branch's datetime-to-timestamp mapping; json_path_equals quotes the
  JSON literal with quote_string.
- condition.py: imports keep both math and numbers. The JSON value
  comparison for bools and numbers runs before master's uuid check,
  which no longer tests key_match for None because master rejects an
  invalid key earlier.
- tests/unit/test_condition.py: kept master's mapping-restriction tests
  and moved TestJsonLiteral after them, using the imports that section
  already makes.
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.
…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.
…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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Indicates an unexpected problem or unintended behavior

Projects

None yet

1 participant