Repository navigation
fix(json): make JSON path annotations and value comparisons portable - #1607
Open
dimitri-yatsenko wants to merge 6 commits into
Open
dimitri-yatsenko wants to merge 6 commits into
dimitri-yatsenko wants to merge 6 commits into
Conversation
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
requested review from
MilagrosMarin,
lum-agilyti and
ttngu207
October 17, 2026 22:02
dimitri-yatsenko
marked this pull request as draft
October 21, 2026 16:46
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.
dimitri-yatsenko
marked this pull request as ready for review
November 21, 2026 01:22
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 wereint4,int8,numeric,text,varchar,timestampand most other PostgreSQL spellings. Some MySQL spellings failed on PostgreSQL in turn (tinyint,signed int,year,binary), and some gave wrong values there (charcut'Acme'to'A'). Precision and range differed as well:floatwas single precision on MySQL and double precision on PostgreSQL,realthe reverse, andintorsmallintfailed 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 aDataJointErrorthat lists the portable types. Each integer and floating-point annotation exceptunsignedhas 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 asfloat(10,2), raises aDataJointErrortoo: onlydecimal,numericanddectake two. No annotation reaches the server as a syntax error. An argument outside a backend's range, such astime(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, soTruemissed JSONtrueandFalsematched almost everything. Bools and numbers are now compared as JSON values, with the same result on both backends.Changes
Type annotations:
adapters/base.pyaddsparse_json_type(), which splits an annotation into its name, arguments, time zone qualifier, character set and collation. The_JSON_TYPE_PATTERNcheck incondition.py(from 2.3.6) still runs first and is unchanged.parse_json_type()also checks the number of arguments.decimal,numericanddectake two, the precision and scale. The integer types (a display width),float, the string types,binary,varbinary,bitand the time types exceptdatetake one. The other types take none. Too many arguments raise aDataJointErroron both backends, and so doesfloat(p)withpoutside 1 to 53 (MySQL tookfloat(0), PostgreSQL did not).RETURNINGint,integer,int2,int4,int8,tinyint,smallint,mediumint,bigint,yearsignedbigintsigned,signed int,signed integersignedbigintunsigned,unsigned int,unsigned integerunsignedbigintbool,booleansignedfloat,float8,double,double precision,float(p)withpfrom 25 to 53doubledouble precisionreal,float4,float(p)withpfrom 1 to 24floatrealdecimal(p,s),numeric(p,s),dec(p,s)decimal(p,s)decimal,numeric,decwithout precisiondecimal(65,30)char,character,nchar,textchartextvarchar,char varying,character varyingchar(n)char(n)varchar(n)binary(n)binary(n)byteabinary,varbinary,varbinary(n),byteabinarybyteajson,jsonbjsonjsonb_extract_path), cast tojsonorjsonbdatedatedatetime(n),datetime(n),timestamp(n), optionallywithout time zonetime(n),datetime(n)time(n),timestamp(n)bitDataJointErrorbit varyingtimetz,timestamptz, thewith time zoneforms,interval,bit(n),uuidDataJointErrorfloatalone is double precision,realsingle. MySQL's own spellings disagree: itsREALisDOUBLE, andRETURNING FLOATis single precision whatever the precision argument (float(30)returned1234567.89as1234570.0). Sofloat(p)maps by its precision, and neither MySQL spelling is passed on as written.unsignedis a 64-bit signed integer on both backends.unsignedis 64-bit on both but unsigned only on MySQL, since PostgreSQL has no unsigned type (see "Results that still differ between the backends"). MySQL'sRETURNINGhas onlySIGNEDandUNSIGNED, both 64-bit, so it cannot check the range ofintorsmallint. PostgreSQL now casts every integer name tobigintrather than fail the whole query on a value beyond the narrower type's range.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_binon MySQL, sinceRETURNINGtakes noCOLLATEclause, and::varchar(20) collate ucs_basicon PostgreSQL.DataJointErroron both backends.Why
decimal(65,30)for a decimal without precision: on PostgreSQL,numericwithout precision keeps the exact value with any number of digits and returns a PythonDecimal. MySQL's bareDECIMALisDECIMAL(10,0), which rounds2.5to3.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 aDecimal. Beyond 30 decimal places it rounds (1e-40becomes0), and from1e35in magnitude it returnsNULL.doublewould return afloat, would not hold0.1exactly, and would give a different Python type than PostgreSQL.Value comparisons:
Decimalincluded) are compared as JSON values:json_extract(...) = cast('64' as json)on MySQL,jsonb_extract_path(...) = '64'::jsonbon PostgreSQL. The JSON literal is quoted through the backend adapter, like every other restriction value.{"s.ch": "64"}and{"s.cal": "true"}work as before. An annotated key such as{"s.n:int": 7}still compares the cast value.DataJointError, since JSON cannot represent them.Why compare JSON values rather than use either approach suggested in the issue:
64against a stored64.0, and64.0against a stored64, because the texts differ.'abc'::numeric). One odd row would break the whole query.Behavior change
Restrictions by a bool or a number on a JSON path, without an annotation:
{"s.x": True}1and"1", not JSONtruetrueonly{"s.x": False}falseandtrue,0,"0", and any string that does not read as a number, such as"Acme"falseonly{"s.x": 1}1and"1"1and1.0{"s.x": 0}False0and0.0{"s.x": 64}64,64.0,"64"and"64abc"64and64.0{"s.x": Decimal("2.50")}2.52.5T - {"s.x": 64}nullat the pathType annotations:
decimalordecwithout precision: before,DECIMAL(10,0), which rounded to a whole number (2.5became3) and held at most 10 digits. After, the exact value, returned with 30 decimal places (Decimal('2.500000000000000000000000000000'), equal toDecimal('2.5')).floatwithout precision andfloat(p)withpfrom 25 to 53: before, single precision whateverp, so1234567.89came back as1234570.0. After,double, as on PostgreSQL.real: before, MySQL'sREAL, which isDOUBLE. After,float, single precision as on PostgreSQL.float(0)andfloat(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, aDataJointError.nchar: before,utf8mb3, with a deprecation warning from the server. After,charin the defaultutf8mb4.year: before,RETURNING YEAR, a syntax error before MySQL 8.0.22 and limited to the years 1901 to 2155 after it. After,signed.uuid,interval,bit,timetz,timestamptzand thewith time zoneforms: before, a server syntax error. After, aDataJointErrorthat lists the portable types.float(10,2),char(10,2),time(3,2),date(3)orjson(3): before, a server syntax error. After, aDataJointError.signedandunsigned: before, cast tointeger, 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.int,integer,int4,smallintandint2: before, 32- or 16-bit, so a larger value failed the whole query with "out of range". After,bigint, 64-bit like MySQL'ssigned.char,characterandncharwithout a length: before,char(1), which cut'Acme'to'A'. After,text.char(n),character(n)andnchar(n): before, padded with blanks ton('Acme '). After,varchar(n), without padding. Restrictions match the same rows, since PostgreSQL ignored the padding when comparing.jsonandjsonb: 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.bitwithout 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:
decimalanddecwithout precision (decimalbecomesdecimal(65,30));nchar(n)(becomeschar(n)inutf8mb4);year(becomessigned;RETURNING YEARneeds MySQL 8.0.22 or later);floatandfloat(p)withpfrom 25 to 53 (floatbecomesdouble);real(real, which isdouble, becomesfloat).signed,unsigned,int,integer,int4,smallintandint2(integerorsmallintbecomesbigint);char,characterandncharwithout a length (char(1)becomestext);char(n),character(n)andnchar(n)(char(n)becomesvarchar(n));jsonb(the cast of the extracted text becomes the cast of the JSON value);bitwithout a length (bit(1)becomesbit varying).json, andncharwithout 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::floatserves::double precisionon PostgreSQL, and one onreturning float8servesreturning doubleon MySQL. An annotation that was a server error before could not have been used in an index.Results that still differ between the backends:
real,float4,float(p)withpup to 24) returns 6 significant digits on MySQL (1234567.89becomes1234570.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 stored0.1there; PostgreSQL, MySQL 8.0.46 and MySQL 8.4 compare the single-precision value, and it matches on none of them.floatanddoublereturn the same value on both.unsignedis MySQL's 64-bitUNSIGNEDand PostgreSQL'sbigint, since PostgreSQL has no unsigned type. A negative value isNULLon 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").1/0on MySQL andTrue/Falseon PostgreSQL.jsonorjsonbannotation 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."abc"under:intor:date, or an integer outside -2^63 to 2^63 - 1 under an integer annotation other thanunsigned, isNULLon 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.7becomes3,2.5becomes2) and fails the query on PostgreSQL. Checked on MySQL 8.0 and PostgreSQL 15.ninchar(n)isNULLon MySQL and cut toncharacters on PostgreSQL.time,datetimeandtimestampwithout(n)drop the fraction of a second on MySQL (03:04:05.567becomes03:04:05) and keep microseconds on PostgreSQL; write(6)to get the same value on both. Atimeoutside 00:00:00 to 24:00:00, such as25:00:00or a negative time, is returned on MySQL and fails the query on PostgreSQL.NULLfrom1e35in magnitude, and MySQL stores a JSON number that has a fraction as a 64-bit float.{"s.x": 2**70}also matches a stored2**70 + 1on MySQL, and{"s.x": Decimal("0.10000000000000000001")}matches a stored0.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.pyruns on MySQL and PostgreSQL: 140 cases per backend. 140 of the 280 fail onmaster. They cover:Decimaland string, against stored floats, non-numeric strings, missing keys and JSONnull;test_every_annotation), with the expected value where both backends agree, and theDataJointErroron MySQL for the PostgreSQL-only types;1234567890123.25and0.1exactly;1234567.89under each float spelling: exact under the double-precision names, rounded to single precision underreal,float4,float(1)andfloat(24), on both backends;2**40,-5and-2**63, andunsignedon a negative value and on2**64 - 1, with each backend's result;bitkeeping every bit on PostgreSQL;DataJointErrorfor too many type arguments.tests/unit/test_adapters.pycheck each backend's mapping and the rejected types.tests/unit/test_condition.pychecks that every type name accepted by_JSON_TYPE_PATTERNmaps onto both backends or raises aDataJointError, that too many type arguments andfloat(p)outside 1 to 53 raise aDataJointErrorin projections and index declarations, and the JSON literal rendering.mastermerged in.tests/integration/test_json_path.pyalso 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_rangeandTestJsonLiteral), then the uuid and JSON object tests from PR 1735.src/datajoint/condition.pymerges without a conflict. With both blocks kept,tests/unit/test_condition.pypasses.Fixes #1563
Fixes #1564