From 71fc1f3a8d57e6a0425923c7af435ae209b93386 Mon Sep 17 00:00:00 2001 From: Denis Bykhov Date: Thu, 3 Apr 2025 19:15:55 +0500 Subject: [PATCH] Fix lookups from array (#8458) Signed-off-by: Denis Bykhov --- server/postgres/src/storage.ts | 41 +++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/server/postgres/src/storage.ts b/server/postgres/src/storage.ts index 6494ef451b..45c37bbd17 100644 --- a/server/postgres/src/storage.ts +++ b/server/postgres/src/storage.ts @@ -1012,6 +1012,13 @@ abstract class PostgresAdapterBase implements DbAdapter { return res } + private isArrayLookup (_class: Ref>, key: string): boolean { + const attr = this.hierarchy.findAttribute(_class, key) + if (attr === undefined) return false + if (attr.type._class === core.class.ArrOf) return true + return false + } + private buildJoinValue( clazz: Ref>, lookup: Lookup, @@ -1029,6 +1036,10 @@ abstract class PostgresAdapterBase implements DbAdapter { const _class = Array.isArray(value) ? value[0] : value const nested = Array.isArray(value) ? value[1] : undefined const domain = translateDomain(this.hierarchy.getDomain(_class)) + if (this.isArrayLookup(clazz, key)) { + this.getArrayLookup(baseDomain, key, _class, res, domain, parentKey) + continue + } const tkey = domain === DOMAIN_MODEL ? key : this.transformKey(baseDomain, clazz, key) const as = `lookup_${domain}_${parentKey !== undefined ? parentKey + '_lookup_' + key : key}`.toLowerCase() res.push({ @@ -1047,6 +1058,34 @@ abstract class PostgresAdapterBase implements DbAdapter { } } + private getArrayLookup ( + parentDomain: string, + key: string, + _class: Ref>, + result: JoinProps[], + domain: string, + parent?: string + ): void { + const desc = this.hierarchy + .getDescendants(this.hierarchy.getBaseClass(_class)) + .filter((it) => !this.hierarchy.isMixin(it)) + const as = `reverse_lookup_${domain}_${parent !== undefined ? parent + '_lookup_' + key : key}` + const from = isDataField(domain, key) + ? `ANY(SELECT jsonb_array_elements_text(${parentDomain}.data->'${key}'))` + : `ANY(${parentDomain}."${key}")` + result.push({ + isReverse: true, + table: domain, + toAlias: as, + toField: '_id', + classes: desc, + path: parent !== undefined ? `${parent}.${key}` : key, + fromAlias: '', + toClass: _class, + fromField: from + }) + } + private getReverseLookupValue ( parentDomain: string, lookup: ReverseLookups, @@ -1436,7 +1475,7 @@ abstract class PostgresAdapterBase implements DbAdapter { } } return [ - `(SELECT jsonb_agg(${join.toAlias}.*) FROM ${join.table} AS ${join.toAlias} WHERE ${join.fromAlias}.${join.fromField} = ${join.toAlias}."${join.toField}" ${classsesQuery}) AS ${join.toAlias}` + `(SELECT jsonb_agg(${join.toAlias}.*) FROM ${join.table} AS ${join.toAlias} WHERE ${join.toAlias}."${join.toField}" = ${join.fromAlias}${join.fromAlias !== '' ? '.' : ''}${join.fromField} ${classsesQuery}) AS ${join.toAlias}` ] }