From 331af1cbf6075ba0849733e70e216106568e25c1 Mon Sep 17 00:00:00 2001
From: Denis Bykhov <bykhov.denis@gmail.com>
Date: Thu, 12 Dec 2024 14:39:19 +0500
Subject: [PATCH] Fix cached error (#7439)

Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com>
---
 server/middleware/src/queryJoin.ts | 21 ++++++++++++---------
 server/postgres/src/storage.ts     | 17 ++++++++++-------
 2 files changed, 22 insertions(+), 16 deletions(-)

diff --git a/server/middleware/src/queryJoin.ts b/server/middleware/src/queryJoin.ts
index 35fa53f3cc..6cc71787cc 100644
--- a/server/middleware/src/queryJoin.ts
+++ b/server/middleware/src/queryJoin.ts
@@ -49,17 +49,20 @@ export class QueryJoiner {
   ): Promise<FindResult<T>> {
     // Will find a query or add + 1 to callbacks
     const q = this.findQuery(_class, query, options) ?? this.createQuery(_class, query, options)
-    if (q.result === undefined) {
-      q.result = this._findAll(ctx, _class, query, options)
-    }
-    if (q.result instanceof Promise) {
-      q.result = await q.result
-    }
-    q.callbacks--
+    try {
+      if (q.result === undefined) {
+        q.result = this._findAll(ctx, _class, query, options)
+      }
+      if (q.result instanceof Promise) {
+        q.result = await q.result
+      }
 
-    this.removeFromQueue(q)
+      return q.result as FindResult<T>
+    } finally {
+      q.callbacks--
 
-    return q.result as FindResult<T>
+      this.removeFromQueue(q)
+    }
   }
 
   private findQuery<T extends Doc>(
diff --git a/server/postgres/src/storage.ts b/server/postgres/src/storage.ts
index 2b4ecb8272..5ac4aac0d7 100644
--- a/server/postgres/src/storage.ts
+++ b/server/postgres/src/storage.ts
@@ -576,21 +576,24 @@ abstract class PostgresAdapterBase implements DbAdapter {
           }
           sqlChunks.push(`WHERE ${this.buildQuery(_class, domain, query, joins, options)}`)
 
+          const totalSqlChunks = [...sqlChunks]
+
+          if (options?.sort !== undefined) {
+            sqlChunks.push(this.buildOrder(_class, domain, options.sort, joins))
+          }
+          if (options?.limit !== undefined) {
+            sqlChunks.push(`LIMIT ${options.limit}`)
+          }
+
           return (await this.mgr.read(ctx.id, async (connection) => {
             let total = options?.total === true ? 0 : -1
             if (options?.total === true) {
               const totalReq = `SELECT COUNT(${domain}._id) as count FROM ${domain}`
-              const totalSql = [totalReq, ...sqlChunks].join(' ')
+              const totalSql = [totalReq, ...totalSqlChunks].join(' ')
               const totalResult = await connection.unsafe(totalSql)
               const parsed = Number.parseInt(totalResult[0].count)
               total = Number.isNaN(parsed) ? 0 : parsed
             }
-            if (options?.sort !== undefined) {
-              sqlChunks.push(this.buildOrder(_class, domain, options.sort, joins))
-            }
-            if (options?.limit !== undefined) {
-              sqlChunks.push(`LIMIT ${options.limit}`)
-            }
 
             const finalSql: string = [select, ...sqlChunks].join(' ')
             fquery = finalSql