Bug #121864 JSON unsigned integers >= 2^63 become negative when converted to DECIMAL (CAST, JSON_VALUE, JSON_TABLE, columns)

Submitted: 22 Nov 22:48
Reporter: Ke Han Email Updates:
Status: Open Impact on me:
None 
Category:MySQL Server: JSON Severity:S3 (Non-critical)
Version:26.10.0 (trunk 06bcb0eb0ad), 8.4.13 OS:Any
Assigned to: CPU Architecture:Any

[22 Nov 22:48] Ke Han
Description:
MySQL stores a JSON integer between 2^63 and 2^64-1 as the JSON type
UNSIGNED INTEGER (64-bit counters, byte totals, hashes, unsigned ids). When
such a value is converted to DECIMAL it comes out as value - 2^64:
9223372036854775808 becomes -9223372036854775808, 12345678901234567890
becomes -6101065172474983726 and 18446744073709551615 becomes -1. This
happens for every JSON-to-DECIMAL conversion:

- CAST(doc->'$.x' AS DECIMAL(p,s))
- JSON_VALUE(doc, '$.x' RETURNING DECIMAL(p,s))
- JSON_TABLE columns of type DECIMAL
- storing doc->'$.x' in a DECIMAL column: INSERT ... SELECT, UPDATE ... SET,
  STORED and VIRTUAL generated columns
- multi-valued indexes on CAST(doc->'$.a' AS DECIMAL(p,0) ARRAY)

There is no error or warning, also in strict mode (SHOW COUNT(*) WARNINGS
gives 0 after the INSERT and after the INSERT ... SELECT below). The same
values converted through their text form (CAST(doc->>'$.x' AS DECIMAL)) or
with CAST(doc->'$.x' AS UNSIGNED) are correct.

The negative numbers are stored: in the example the generated column and a
copy made with INSERT ... SELECT hold -1 for 18446744073709551615,
ORDER BY bytes DESC LIMIT 1 returns id 2 instead of id 5 (the largest
counter), and DELETE ... WHERE bytes < 0 deletes three of five rows although none of the
documents holds a negative number. In the multi-valued index the entry of
18446744073709551615 is -1, so a JSON_CONTAINS(..., -1) lookup through the
index matches a document that does not contain -1 and a DELETE using it
removes that document.

Bug #101945 reports these JSON values for a BIGINT UNSIGNED column, where
the assignment fails with ERROR 1264 (Out of range value); that is the
integer coercion and a loud error. The DECIMAL coercion is another function
(below) and silently stores a different number.

How to repeat:
-- run with: mysql -uroot --table < file
CREATE DATABASE m211;
USE m211;
CREATE TABLE metrics (id INT PRIMARY KEY, doc JSON,
  bytes DECIMAL(20,0) AS (doc->'$.bytes') STORED);
INSERT INTO metrics (id, doc) VALUES
  (1, '{"dev": "a", "bytes": 1000}'),
  (2, '{"dev": "b", "bytes": 9223372036854775807}'),
  (3, '{"dev": "c", "bytes": 9223372036854775808}'),
  (4, '{"dev": "d", "bytes": 12345678901234567890}'),
  (5, '{"dev": "e", "bytes": 18446744073709551615}');
SHOW COUNT(*) WARNINGS;

SELECT id, JSON_TYPE(doc->'$.bytes') AS type,
       CAST(doc->>'$.bytes' AS DECIMAL(20,0)) AS from_text,
       CAST(doc->'$.bytes' AS UNSIGNED) AS as_unsigned,
       CAST(doc->'$.bytes' AS DECIMAL(20,0)) AS as_decimal,
       JSON_VALUE(doc, '$.bytes' RETURNING DECIMAL(20,0)) AS json_value,
       bytes AS stored_column
FROM metrics ORDER BY id;
SELECT m.id, jt.b FROM metrics m,
  JSON_TABLE(m.doc, '$' COLUMNS (b DECIMAL(20,0) PATH '$.bytes')) jt ORDER BY m.id;

CREATE TABLE usage_copy (id INT PRIMARY KEY, bytes DECIMAL(20,0));
INSERT INTO usage_copy SELECT id, doc->'$.bytes' FROM metrics;
SHOW COUNT(*) WARNINGS;
SELECT * FROM usage_copy ORDER BY id;

SELECT id FROM metrics ORDER BY bytes DESC LIMIT 1;
DELETE FROM metrics WHERE bytes < 0;
SELECT id, doc FROM metrics ORDER BY id;

CREATE TABLE batches (id INT PRIMARY KEY, doc JSON,
  KEY mvi ((CAST(doc->'$.counters' AS DECIMAL(20,0) ARRAY))));
INSERT INTO batches VALUES (1, '{"counters": [18446744073709551615, 7]}'), (2, '{"counters": [-1, 8]}');
SELECT id FROM batches WHERE JSON_CONTAINS(doc->'$.counters', CAST(-1 AS JSON)) ORDER BY id;
SELECT id FROM batches IGNORE INDEX (mvi) WHERE JSON_CONTAINS(doc->'$.counters', CAST(-1 AS JSON)) ORDER BY id;
DELETE FROM batches WHERE JSON_CONTAINS(doc->'$.counters', CAST(-1 AS JSON));
SELECT COUNT(*) AS batches_left FROM batches;

Result on 26.10.0 (8.4.13 gives the same):
  warnings after the INSERT: 0
  +----+------------------+----------------------+----------------------+----------------------+----------------------+----------------------+
  | id | type             | from_text            | as_unsigned          | as_decimal           | json_value           | stored_column        |
  +----+------------------+----------------------+----------------------+----------------------+----------------------+----------------------+
  |  1 | INTEGER          |                 1000 |                 1000 |                 1000 |                 1000 |                 1000 |
  |  2 | UNSIGNED INTEGER |  9223372036854775807 |  9223372036854775807 |  9223372036854775807 |  9223372036854775807 |  9223372036854775807 |
  |  3 | UNSIGNED INTEGER |  9223372036854775808 |  9223372036854775808 | -9223372036854775808 | -9223372036854775808 | -9223372036854775808 |
  |  4 | UNSIGNED INTEGER | 12345678901234567890 | 12345678901234567890 | -6101065172474983726 | -6101065172474983726 | -6101065172474983726 |
  |  5 | UNSIGNED INTEGER | 18446744073709551615 | 18446744073709551615 |                   -1 |                   -1 |                   -1 |
  +----+------------------+----------------------+----------------------+----------------------+----------------------+----------------------+
  JSON_TABLE b:   1000, 9223372036854775807, -9223372036854775808, -6101065172474983726, -1
  usage_copy:     the same five values; warnings after the INSERT ... SELECT: 0
  ORDER BY bytes DESC LIMIT 1:  id 2              <- id 5 holds the largest counter
  DELETE FROM metrics WHERE bytes < 0: deletes ids 3, 4, 5; rows left: 1, 2
  batches, JSON_CONTAINS(..., -1) through the index:  1, 2    <- batch 1 does not contain -1
           with IGNORE INDEX (mvi):                 2
  batches_left after the DELETE: 0                  <- batch 1 deleted

Expected: the DECIMAL conversions return the JSON value (from_text /
as_unsigned), the stored column and usage_copy hold the original numbers,
the DELETE removes nothing, ORDER BY ... DESC returns id 5, the index lookup
returns only batch 2 and the DELETE leaves batch 1. The manual's JSON
conversion rules ("Converting between JSON and non-JSON values") say that
CAST(JSON AS other type) "Succeeds if the JSON document consists of a
single scalar value of the target type and that scalar value can be cast to
the target type. Otherwise, returns NULL and produces a warning."
DECIMAL(20,0) holds all these values, and a silent sign change is neither.

Suggested fix:
Json_wrapper::coerce_decimal() converts a JSON UNSIGNED INTEGER with
longlong2decimal(), which takes a signed longlong, so the ulonglong from
get_uint() is converted to int64 first:
https://github.com/mysql/mysql-server/blob/06bcb0eb0ad281e08dd2b4d81b99ad25491433e7/sql-co...
  case enum_json_type::J_UINT:
    if (longlong2decimal(get_uint(), decimal_value)) {
ulonglong2decimal() (include/decimal.h, line 72) is the function for an
unsigned value (or int2my_decimal(..., true /* unsigned */, ...), as the
J_BOOLEAN case below uses):
https://github.com/mysql/mysql-server/blob/06bcb0eb0ad281e08dd2b4d81b99ad25491433e7/includ...
The other coercions handle J_UINT correctly: coerce_int() sets
unsigned_flag (line 2863) and coerce_real() uses
static_cast<double>(get_uint()) (line 2968). coerce_decimal() is what
val_decimal_from_json() (CAST and assignments of JSON functions to DECIMAL
columns), save_json_to_field() (JSON_TABLE DECIMAL columns) and
Item_func_json_value::extract_decimal_value() (JSON_VALUE ... RETURNING
DECIMAL) call, which is why all of them return the same wrong value:
https://github.com/mysql/mysql-server/blob/06bcb0eb0ad281e08dd2b4d81b99ad25491433e7/sql/it...
https://github.com/mysql/mysql-server/blob/06bcb0eb0ad281e08dd2b4d81b99ad25491433e7/sql/it...
https://github.com/mysql/mysql-server/blob/06bcb0eb0ad281e08dd2b4d81b99ad25491433e7/sql/it...

Workaround: convert through the text form, CAST(doc->>'$.x' AS
DECIMAL(20,0)), or through CAST(doc->'$.x' AS UNSIGNED).

Portions of this website are copyright © 2001, 2002 The PHP Group

Page generated in 0.040 sec. using MySQL 8.4.7-u6-cloud

Timestamp references displayed by the system are UTC.
Content reproduced on this site is the property of the respective copyright holders.
It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.