From ffba8d3ae195df81bb127ed0ae34a88635fe8e32 Mon Sep 17 00:00:00 2001
From: Leonardo <leomilho@gmail.com>
Date: Wed, 19 Feb 2025 17:39:51 +0100
Subject: [PATCH] fix: count query error empty entities

---
 .../cypher/converter/queryConverter.test.ts   | 33 +++++++++++++++++++
 src/utils/cypher/converter/queryConverter.ts  |  3 +-
 2 files changed, 35 insertions(+), 1 deletion(-)

diff --git a/src/utils/cypher/converter/queryConverter.test.ts b/src/utils/cypher/converter/queryConverter.test.ts
index eb561d3..c981a89 100644
--- a/src/utils/cypher/converter/queryConverter.test.ts
+++ b/src/utils/cypher/converter/queryConverter.test.ts
@@ -630,4 +630,37 @@ describe('query2Cypher', () => {
 
     expect(fixCypherSpaces(cypher.query)).toEqual(fixCypherSpaces(expectedCypher));
   });
+
+  it('should return correctly on a query with count', () => {
+    const query: BackendQueryFormat = {
+      saveStateID: 'b1873956-e51b-46db-9c33-ab8bfbd177ef',
+      query: [
+        {
+          id: 'path_0',
+          node: {
+            relation: {
+              id: 'id_1739982191754',
+              label: 'HAS',
+              depth: {
+                max: 1,
+                min: 1,
+              },
+              direction: 'BOTH',
+              node: {},
+            },
+          },
+        },
+      ],
+      limit: 555,
+      return: ['*'],
+      cached: false,
+    };
+
+    const cypher = query2Cypher(query);
+    const expectedCypher = 'MATCH path_0 = (()-[id_1739982191754:HAS*1..1]-()) RETURN * LIMIT 555';
+    expect(fixCypherSpaces(cypher.query)).toEqual(fixCypherSpaces(expectedCypher));
+    const expectedCypherCount =
+      'MATCH path_0 = (()-[id_1739982191754:HAS*1..1]-()) RETURN COUNT(DISTINCT id_1739982191754) as id_1739982191754_count';
+    expect(fixCypherSpaces(cypher.countQuery)).toEqual(fixCypherSpaces(expectedCypherCount));
+  });
 });
diff --git a/src/utils/cypher/converter/queryConverter.ts b/src/utils/cypher/converter/queryConverter.ts
index d46071b..b4b2634 100644
--- a/src/utils/cypher/converter/queryConverter.ts
+++ b/src/utils/cypher/converter/queryConverter.ts
@@ -95,7 +95,8 @@ export function query2Cypher(JSONQuery: BackendQueryFormat): QueryCypher {
   countQuery += Object.values(cacheData.entities)
     .map(e => `COUNT(DISTINCT ${e.id}) as ${e.id}_count`)
     .join(', ');
-  countQuery += Object.values(cacheData.relations).length > 0 ? ', ' : '';
+
+  countQuery += Object.values(cacheData.entities).length > 0 && Object.values(cacheData.relations).length > 0 ? ', ' : '';
   countQuery += Object.values(cacheData.relations)
     .map(r => `COUNT(DISTINCT ${r.id}) as ${r.id}_count`)
     .join(', ');
-- 
GitLab