From e545a60bf41bf6efe1e9d7730cc474bda9d3fc62 Mon Sep 17 00:00:00 2001
From: Alexey Botchkov <holyfoot@askmonty.org>
Date: Tue, 28 Apr 2020 16:08:18 +0400
Subject: [PATCH] MDEV-22236 JSON_ARRAYAGG query leads to SIGSEGV in
 Charset::swap on optimized builds.

The json_arrayagg::val_str should handle NULL result.
---
 mysql-test/main/func_json.result |  8 ++++++++
 mysql-test/main/func_json.test   |  8 ++++++++
 sql/item_jsonfunc.cc             | 15 ++++++++-------
 3 files changed, 24 insertions(+), 7 deletions(-)

diff --git a/mysql-test/main/func_json.result b/mysql-test/main/func_json.result
index be6ea1a7b61..716ae78a35c 100644
--- a/mysql-test/main/func_json.result
+++ b/mysql-test/main/func_json.result
@@ -1213,3 +1213,11 @@ DROP TABLE t1;
 #
 # End of 10.4 tests
 #
+#
+# MDEV-16620 JSON_ARRAYAGG
+#
+CREATE TABLE t1 (a INT);
+SELECT JSON_ARRAYAGG(a) FROM t1;
+JSON_ARRAYAGG(a)
+NULL
+DROP TABLE t1;
diff --git a/mysql-test/main/func_json.test b/mysql-test/main/func_json.test
index fea33b899b2..2c5dbfbd42c 100644
--- a/mysql-test/main/func_json.test
+++ b/mysql-test/main/func_json.test
@@ -732,3 +732,11 @@ DROP TABLE t1;
 --echo #
 --echo # End of 10.4 tests
 --echo #
+
+-- echo #
+-- echo # MDEV-16620 JSON_ARRAYAGG
+-- echo #
+
+CREATE TABLE t1 (a INT);
+SELECT JSON_ARRAYAGG(a) FROM t1;
+DROP TABLE t1;
diff --git a/sql/item_jsonfunc.cc b/sql/item_jsonfunc.cc
index a3b5d3b7fac..134c2573ea7 100644
--- a/sql/item_jsonfunc.cc
+++ b/sql/item_jsonfunc.cc
@@ -3632,13 +3632,14 @@ String* Item_func_json_arrayagg::convert_to_json(Item *item, String *res)
 
 String* Item_func_json_arrayagg::val_str(String *str)
 {
-  str= Item_func_group_concat::val_str(str);
-  String s;
-  s.append('[');
-  s.swap(*str);
-  str->append(s);
-  str->append(']');
-
+  if ((str= Item_func_group_concat::val_str(str)))
+  {
+    String s;
+    s.append('[');
+    s.swap(*str);
+    str->append(s);
+    str->append(']');
+  }
   return str;
 }
 
-- 
2.30.9