From 7688a1b06823ad1fcc090e9c07c18184d58d8edd Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ivan=20Milinovi=C4=87?=
 <44698587+imilinovic@users.noreply.github.com>
Date: Tue, 13 Feb 2024 01:10:03 +0100
Subject: [PATCH] Fix unbound variable causing crash inside subquery (#1710)

---
 src/query/frontend/semantic/symbol_generator.cpp   | 11 +++++++++--
 .../tests/memgraph_V1/features/subqueries.feature  | 14 ++++++++++++++
 2 files changed, 23 insertions(+), 2 deletions(-)

diff --git a/src/query/frontend/semantic/symbol_generator.cpp b/src/query/frontend/semantic/symbol_generator.cpp
index a3e855301..e8ef3cba5 100644
--- a/src/query/frontend/semantic/symbol_generator.cpp
+++ b/src/query/frontend/semantic/symbol_generator.cpp
@@ -1,4 +1,4 @@
-// Copyright 2023 Memgraph Ltd.
+// Copyright 2024 Memgraph Ltd.
 //
 // Use of this software is governed by the Business Source License
 // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source
@@ -394,9 +394,16 @@ SymbolGenerator::ReturnType SymbolGenerator::Visit(Identifier &ident) {
     // can reference symbols bound later in the same MATCH. We collect them
     // here, so that they can be checked after visiting Match.
     scope.identifiers_in_match.emplace_back(&ident);
+  } else if (scope.in_call_subquery && !scope.in_with) {
+    if (!scope.symbols.contains(ident.name_) && !ConsumePredefinedIdentifier(ident.name_)) {
+      throw UnboundVariableError(ident.name_);
+    }
+    symbol = GetOrCreateSymbol(ident.name_, ident.user_declared_, Symbol::Type::ANY);
   } else {
     // Everything else references a bound symbol.
-    if (!HasSymbol(ident.name_) && !ConsumePredefinedIdentifier(ident.name_)) throw UnboundVariableError(ident.name_);
+    if (!HasSymbol(ident.name_) && !ConsumePredefinedIdentifier(ident.name_)) {
+      throw UnboundVariableError(ident.name_);
+    }
     symbol = GetOrCreateSymbol(ident.name_, ident.user_declared_, Symbol::Type::ANY);
   }
   ident.MapTo(symbol);
diff --git a/tests/gql_behave/tests/memgraph_V1/features/subqueries.feature b/tests/gql_behave/tests/memgraph_V1/features/subqueries.feature
index 17b3b22e3..e2ae72d51 100644
--- a/tests/gql_behave/tests/memgraph_V1/features/subqueries.feature
+++ b/tests/gql_behave/tests/memgraph_V1/features/subqueries.feature
@@ -185,6 +185,20 @@ Feature: Subqueries
             """
         Then an error should be raised
 
+    Scenario: Subquery with an unbound variable
+        Given an empty graph
+        When executing query:
+        """
+        MATCH (node1)
+        CALL {
+            MATCH (node2)
+            WHERE node1.property > 0
+            return 1 as state
+        }
+        return 1
+        """
+        Then an error should be raised
+
     Scenario: Subquery returning primitive but not aliased
         Given an empty graph
         And having executed