From 48a01919bc8e09ce0a6ba610daacd167b3d2fcd4 Mon Sep 17 00:00:00 2001 From: Jake Barnby Date: Thu, 2 Apr 2026 04:17:23 +1300 Subject: [PATCH] (fix): add static cache for related collection lookups The findOne query per relationship attribute ran on every getDatabasesDB call. Static cache keyed by database+internal name caches results across requests within the same Swoole worker process. Co-Authored-By: Claude Opus 4.6 (1M context) --- app/init/resources.php | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/app/init/resources.php b/app/init/resources.php index ca5d26a3e5..b2d9b30644 100644 --- a/app/init/resources.php +++ b/app/init/resources.php @@ -785,6 +785,8 @@ Http::setResource('getDatabasesDB', function (Group $pools, Database $dbForProje } // Also register related collections from relationship attributes + // Use static cache to avoid repeated queries across requests + static $relatedCache = []; $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attr) { if ($attr->getAttribute('type') !== \Utopia\Query\Schema\ColumnType::Relationship->value) { @@ -796,6 +798,14 @@ Http::setResource('getDatabasesDB', function (Group $pools, Database $dbForProje if ($relatedInternalName === null) { continue; } + // Check static cache first + $cacheKey = $dbPrefix . ':' . $relatedInternalName; + if (isset($relatedCache[$cacheKey])) { + [$relKey, $fullKey, $externalId] = $relatedCache[$cacheKey]; + $metadata->setCollectionId($relKey, $externalId); + $metadata->setCollectionId($fullKey, $externalId); + continue; + } // Extract sequence from internal name (e.g., 'collection_16' → '16') $parts = \explode('_', $relatedInternalName); $relSeq = \end($parts); @@ -813,8 +823,11 @@ Http::setResource('getDatabasesDB', function (Group $pools, Database $dbForProje ) ); if ($relatedCol !== null && !$relatedCol->isEmpty()) { - $metadata->setCollectionId('collection_' . $relSeq, $relatedCol->getId()); - $metadata->setCollectionId($dbPrefix . '_collection_' . $relSeq, $relatedCol->getId()); + $relKey = 'collection_' . $relSeq; + $fullKey = $dbPrefix . '_collection_' . $relSeq; + $metadata->setCollectionId($relKey, $relatedCol->getId()); + $metadata->setCollectionId($fullKey, $relatedCol->getId()); + $relatedCache[$cacheKey] = [$relKey, $fullKey, $relatedCol->getId()]; } } catch (\Throwable) { // Skip — related collection may not exist yet