Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 21 additions & 6 deletions src/Database/Adapter/SQL.php
Original file line number Diff line number Diff line change
Expand Up @@ -1914,6 +1914,9 @@ protected function getSQLIndexType(string $type): string
/**
* Get SQL condition for permissions
*
* Uses correlated EXISTS so the planner can short-circuit at the first matching
* _perms row per outer document, instead of materializing IN (subquery).
*
* @param string $collection
* @param array<string> $roles
* @param string $alias
Expand All @@ -1931,15 +1934,27 @@ protected function getSQLPermissionsCondition(
throw new DatabaseException('Unknown permission type: ' . $type);
}

if (empty($roles)) {
return '1 = 0';
}

$roles = \array_map(fn ($role) => $this->getPDO()->quote($role), $roles);
$roles = \implode(', ', $roles);

return "{$this->quote($alias)}.{$this->quote('_uid')} IN (
SELECT _document
FROM {$this->getSQLTable($collection . '_perms')}
WHERE _permission IN ({$roles})
AND _type = '{$type}'
{$this->getTenantQuery($collection)}
$outerAlias = $this->quote($alias);
$permsTable = $this->getSQLTable($collection . '_perms');
// Leading-underscore sentinel to avoid collisions with caller-provided aliases
$innerAlias = '_perms_inner';
$innerAliasQuoted = $this->quote($innerAlias);
$tenantClause = $this->getTenantQuery($collection, $innerAlias);

return "EXISTS (
SELECT 1
FROM {$permsTable} AS {$innerAliasQuoted}
WHERE {$innerAliasQuoted}._document = {$outerAlias}._uid
AND {$innerAliasQuoted}._permission IN ({$roles})
AND {$innerAliasQuoted}._type = '{$type}'
{$tenantClause}
)";
}

Expand Down
Loading