2

I have a table with data we've collected from various sources. It's got the item name, the source and the source's value.

The table looks like the following:

id name source value
1 abc web 1
2 abc print 2
3 xyz print 8
4 xyz web 9

Using the JSON_OBJECTAGG() function, I can group the sources together based on the name:

SELECT name, JSON_OBJECTAGG(source, value) AS data FROM testStuff GROUP BY name 

This correctly gives:

name data
abc {"web":1, "print": 2}
xyz {"print":8, "web": 9}

Now, I want to run that query, but with a filter on the price/source, so I ran the following query:

SELECT name, JSON_OBJECTAGG(source, value) AS data FROM testStuff GROUP BY name HAVING JSON_CONTAINS(data, 2, '$.print') 

This seems to work, but there's a slight issue:

name data
abc {"web":1, "print": 2}}

Why is there suddenly an extra } at the end of the JSON data? The HAVING clause is correctly filtering the rows, but why does it modify the result data?

Online demo: https://sqlfiddle.com/mariadb/online-compiler?id=ccf1041c-3ada-4fc9-bd77-2b0fe1428392

I'm not sure what version of MariaDB that site uses, but testing this on my local computer using MariaDB 10.11.9 gives the same results.

EDIT: It seems I can fix this by using:

SELECT name, JSON_OBJECTAGG(source, value) AS data FROM testStuff GROUP BY name HAVING JSON_CONTAINS(JSON_OBJECTAGG(source, value), 2, '$.print') 

I just was trying to avoid writing the JSON_OBJECTAGG() multiple times. Also, while this fixes the issue, I still am curious as to why this was an issue in the first place.

EDIT 2: Another "fix" is to replace JSON_OBJECTAGG() with GROUP_CONCAT().

The following returns the correct data:

SELECT name, REPLACE(GROUP_CONCAT(JSON_OBJECT(source, value)), '},{', ',') AS data FROM testStuff GROUP BY name HAVING JSON_CONTAINS(data, 2, '$.print') 
3
  • 1
    This seems like a bug in MariaDB. A JSON function should never return invalid JSON. If you can, please open a bug report on the MariaDB Jira: jira.mariadb.org/browse/MDEV Commented Oct 17, 2024 at 5:56
  • @markusjm I didn't think to check their Jira! I looked and this bug has already been reported: jira.mariadb.org/browse/MDEV-23068 Commented Oct 17, 2024 at 13:09
  • 1
    Perhaps you can answer your own question since you're the one who found the answer: it's a bug in MariaDB. Including the link as the answer also makes it more visible and hopefully gets it fixed faster. Commented Oct 18, 2024 at 5:01

1 Answer 1

0

The SQL in this query is correct, the issue here is a bug in MariaDB itself. (Link: https://jira.mariadb.org/browse/MDEV-23068)

I didn't open this bug report, it was created July 2020!

Hopefully this bug gets addressed in a future release of MariaDB.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.