From 4f85d27efdf443cccf18ba29a3221f524904cce2 Mon Sep 17 00:00:00 2001
From: Mergen Imeev <imeevma@tarantool.org>
Date: Tue, 7 Nov 2023 12:52:18 +0300
Subject: [PATCH] sql: fix segmentation fault when JOIN uses USING

Before this patch, nameInUsingClause() expected old_col to be non-NULL,
but this may not be the case. This patch fixes this feature accordingly.

Follow-up #4467

NO_DOC=bugfix
NO_CHANGELOG=feature was not released yet
---
 src/box/sql/resolve.c                         | 20 ++++++++++---------
 ...67_sql_id_backwards_compatibility_test.lua |  9 +++++++++
 2 files changed, 20 insertions(+), 9 deletions(-)

diff --git a/src/box/sql/resolve.c b/src/box/sql/resolve.c
index 71de5a0fe9..48906542eb 100644
--- a/src/box/sql/resolve.c
+++ b/src/box/sql/resolve.c
@@ -137,15 +137,17 @@ resolveAlias(struct ExprList *pEList, int iCol, struct Expr *pExpr,
 static bool
 nameInUsingClause(struct IdList *pUsing, const char *zCol, const char *old_col)
 {
-	if (pUsing) {
-		for (int k = 0; k < pUsing->nId; k++) {
-			if (strcmp(pUsing->a[k].zName, zCol) == 0)
-				return true;
-		}
-		for (int i = 0; i < pUsing->nId; i++) {
-			if (strcmp(pUsing->a[i].zName, old_col) == 0)
-				return true;
-		}
+	if (pUsing == NULL)
+		return false;
+	for (int k = 0; k < pUsing->nId; k++) {
+		if (strcmp(pUsing->a[k].zName, zCol) == 0)
+			return true;
+	}
+	if (old_col == NULL)
+		return false;
+	for (int i = 0; i < pUsing->nId; i++) {
+		if (strcmp(pUsing->a[i].zName, old_col) == 0)
+			return true;
 	}
 	return false;
 }
diff --git a/test/sql-luatest/gh_4467_sql_id_backwards_compatibility_test.lua b/test/sql-luatest/gh_4467_sql_id_backwards_compatibility_test.lua
index 47db22cd55..f17147cb81 100644
--- a/test/sql-luatest/gh_4467_sql_id_backwards_compatibility_test.lua
+++ b/test/sql-luatest/gh_4467_sql_id_backwards_compatibility_test.lua
@@ -661,3 +661,12 @@ g.test_drop_constraint = function()
         box.func.check_ASD_THREE:drop()
     end)
 end
+
+-- Make sure USING in JOIN does not cause segfault.
+g.test_using_in_join = function()
+    g.server:exec(function()
+        box.execute([[CREATE TABLE T(I INT PRIMARY KEY, A INT);]])
+        box.execute([[SELECT * FROM T LEFT JOIN T USING(A);]])
+        box.execute([[DROP TABLE T;]])
+    end)
+end
-- 
GitLab