From 0d51a20a02d9edab03d946e3ebd70d78f8ba5d76 Mon Sep 17 00:00:00 2001
From: DavIvek <david.ivekovic@memgraph.io>
Date: Mon, 9 Oct 2023 15:25:25 +0200
Subject: [PATCH] Fix a crash caused by declaring a path with only one node in
 OPTIONAL MATCH clause (#1318)

---
 src/query/plan/rule_based_planner.hpp               |  4 ++++
 .../features/OptionalMatchAcceptance.feature        | 13 +++++++++++++
 2 files changed, 17 insertions(+)

diff --git a/src/query/plan/rule_based_planner.hpp b/src/query/plan/rule_based_planner.hpp
index 055d47d2c..2ecf54ee2 100644
--- a/src/query/plan/rule_based_planner.hpp
+++ b/src/query/plan/rule_based_planner.hpp
@@ -488,6 +488,10 @@ class RuleBasedPlanner {
         last_op = std::make_unique<ScanAll>(std::move(last_op), node1_symbol, view);
         new_symbols.emplace_back(node1_symbol);
 
+        last_op = GenFilters(std::move(last_op), bound_symbols, filters, storage, symbol_table);
+        last_op = impl::GenNamedPaths(std::move(last_op), bound_symbols, named_paths);
+        last_op = GenFilters(std::move(last_op), bound_symbols, filters, storage, symbol_table);
+      } else if (named_paths.size() == 1U) {
         last_op = GenFilters(std::move(last_op), bound_symbols, filters, storage, symbol_table);
         last_op = impl::GenNamedPaths(std::move(last_op), bound_symbols, named_paths);
         last_op = GenFilters(std::move(last_op), bound_symbols, filters, storage, symbol_table);
diff --git a/tests/gql_behave/tests/openCypher_M09/features/OptionalMatchAcceptance.feature b/tests/gql_behave/tests/openCypher_M09/features/OptionalMatchAcceptance.feature
index 391afe337..b2d680d72 100644
--- a/tests/gql_behave/tests/openCypher_M09/features/OptionalMatchAcceptance.feature
+++ b/tests/gql_behave/tests/openCypher_M09/features/OptionalMatchAcceptance.feature
@@ -323,3 +323,16 @@ Feature: OptionalMatchAcceptance
       | a  | b            |
       | [] | [42, 43, 44] |
     And no side effects
+
+  Scenario: Declaring a path with only one node in OPTIONAL MATCH after MATCH in which that node is already used
+    When executing query:
+      """
+      MATCH (n1) OPTIONAL MATCH p=(n1) RETURN p;
+      """
+    Then the result should be:
+      | p                 |
+      | <(:Single)>       |
+      | <(:A {prop: 42})> |
+      | <(:B {prop: 46})> |
+      | <(:C)>            |
+    And no side effects