Fix lookups from array (#8458)

Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com>
This commit is contained in:
Denis Bykhov 2025-04-03 19:15:55 +05:00 committed by GitHub
parent 6c052f290b
commit 71fc1f3a8d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1012,6 +1012,13 @@ abstract class PostgresAdapterBase implements DbAdapter {
return res
}
private isArrayLookup (_class: Ref<Class<Doc>>, 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<T extends Doc>(
clazz: Ref<Class<T>>,
lookup: Lookup<T>,
@ -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<Class<Doc>>,
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}`
]
}