Skip to content
2 changes: 1 addition & 1 deletion src/Database/Adapter/Postgres.php
Original file line number Diff line number Diff line change
Expand Up @@ -1047,7 +1047,7 @@ private function getIndexName(string $collection, string $id, int|string|null $t
private function getCollectionCreators(string $collection): array
{
$statement = $this->prepareStatement(
'SELECT '.$this->quote(Storage::TENANT).' FROM '.$this->getTable(Database::METADATA).' WHERE '.$this->collateDocumentId($this->quote(Storage::UID)).' = ? ORDER BY '.$this->quote(Storage::SEQUENCE).' ASC LIMIT 1',
'SELECT '.$this->quote(Storage::TENANT).' FROM '.$this->getTable(Database::METADATA).' WHERE '.$this->quote(Storage::UID).' = ? ORDER BY '.$this->quote(Storage::SEQUENCE).' ASC LIMIT 1',
Comment thread
appwrite[bot] marked this conversation as resolved.
Resolved
Event::IndexRename,
);
$statement->bindValue(1, $collection);
Expand Down
125 changes: 125 additions & 0 deletions src/Database/Builder/CollatesDocumentIds.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
<?php

namespace Utopia\Database\Builder;

use Utopia\Query\Builder\JoinBuilder;
use Utopia\Query\Method;
use Utopia\Query\Query;

/**
* Document ids are unique in the collation of their unique indexes, and an engine only uses an index for a
* comparison made in the index's collation, so equality on an id column, and a join ON an id column, compares in
* that collation. The using builder names the collation in COLLATION and decides which columns, and which joins,
* are collated.
*/
trait CollatesDocumentIds
{
abstract private function isCollated(string $column): bool;

abstract private function collatesJoin(string $left, string $right): bool;

#[\Override]
public function compileJoin(Query $query): string
{
return $this->collateJoin(parent::compileJoin($query), $this->onComparisons($query->getJoinOnQueries()));
}

#[\Override]
protected function compileJoinWithBuilder(Query $query, JoinBuilder $joinBuilder): string
{
$comparisons = [];
foreach ($joinBuilder->ons as $on) {
$comparisons[] = [$on->left, $on->operator, $on->right];
}

return $this->collateJoin(parent::compileJoinWithBuilder($query, $joinBuilder), $comparisons);
}

/**
* @param array<mixed> $values
*/
#[\Override]
protected function compileIn(string $attribute, array $values, ?string $column = null): string
{
return parent::compileIn($this->collate($attribute, $column), $values, $column);
}

/**
* @param array<mixed> $values
*/
#[\Override]
protected function compileNotIn(string $attribute, array $values, ?string $column = null): string
{
return parent::compileNotIn($this->collate($attribute, $column), $values, $column);
}

private function collate(string $attribute, ?string $column): string
{
return $column !== null && $this->isCollated($column) ? $attribute.' COLLATE '.self::COLLATION : $attribute;
}

/**
* @param list<array{string, string, string}> $comparisons
*/
private function collateJoin(string $sql, array $comparisons): string
{
foreach ($comparisons as [$left, $operator, $right]) {
if (! \in_array($operator, ['=', '!=', '<>'], true) || ! $this->collatesJoin($left, $right)) {
continue;
}

$comparison = ' '.$operator.' '.$this->resolveAndWrap($right);
$wrappedLeft = $this->resolveAndWrap($left);
$sql = \str_replace($wrappedLeft.$comparison, $wrappedLeft.' COLLATE '.self::COLLATION.$comparison, $sql);
}

return $sql;
}

/**
* The last segment of a column, after the attribute hooks resolve it.
*/
private function columnName(string $column): string
{
$resolved = $this->resolveAttribute($column);
$separator = \strrpos($resolved, '.');

return $separator === false ? $resolved : \substr($resolved, $separator + 1);
}

/**
* @param array<mixed> $queries
* @return list<array{string, string, string}>
*/
private function onComparisons(array $queries): array
{
$comparisons = [];
foreach ($queries as $query) {
if (! $query instanceof Query) {
continue;
}

$comparisons = match ($query->getMethod()) {
Method::On => [...$comparisons, ...$this->comparison($query->getValues())],
Method::And, Method::Or => [...$comparisons, ...$this->onComparisons($query->getValues())],
default => $comparisons,
};
}

return $comparisons;
}

/**
* @param array<mixed> $values
* @return list<array{string, string, string}>
*/
private function comparison(array $values): array
{
[$left, $operator, $right] = [$values[0] ?? null, $values[1] ?? null, $values[2] ?? null];
if (! \is_string($left) || ! \is_string($operator) || ! \is_string($right) || $left === '' || $right === '') {
return [];
}

return [[$left, $operator, $right]];
}
}
109 changes: 19 additions & 90 deletions src/Database/Builder/Postgres.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
*/
class Postgres extends Base implements Filtering, Scoping
{
use CollatesDocumentIds;
use CompilesFilters;
use MatchesContainsAllPatterns;
use PreparesSearchTerms;
Expand All @@ -34,10 +35,6 @@ class Postgres extends Base implements Filtering, Scoping

public const string COLLATION = 'utf8_ci_ai';

private const string COLLATE = ' COLLATE '.self::COLLATION;

private const array EQUALITY_OPERATORS = ['=', '!=', '<>'];

/**
* @param bool $sharedTables Whether the `_perms` unique index is the shared-tables one, built without the collation
*/
Expand Down Expand Up @@ -85,92 +82,6 @@ public function compileFilter(Query $query): string
return parent::compileFilter($query);
}

#[\Override]
public function compileJoin(Query $query): string
{
$sql = parent::compileJoin($query);

foreach ($this->onComparisons($query->getJoinOnQueries()) as [$left, $operator, $right]) {
if (! \in_array($operator, self::EQUALITY_OPERATORS, true) || ! $this->isCollated($left) || ! $this->isCollated($right)) {
continue;
}

$comparison = ' '.$operator.' '.$this->resolveAndWrap($right);
$wrappedLeft = $this->resolveAndWrap($left);
$sql = \str_replace($wrappedLeft.$comparison, $wrappedLeft.self::COLLATE.$comparison, $sql);
}

return $sql;
}

/**
* @param array<mixed> $values
*/
#[\Override]
protected function compileIn(string $attribute, array $values, ?string $column = null): string
{
return parent::compileIn($this->collate($attribute, $column), $values, $column);
}

/**
* @param array<mixed> $values
*/
#[\Override]
protected function compileNotIn(string $attribute, array $values, ?string $column = null): string
{
return parent::compileNotIn($this->collate($attribute, $column), $values, $column);
}

private function collate(string $attribute, ?string $column): string
{
return $column !== null && $this->isCollated($column) ? $attribute.self::COLLATE : $attribute;
}

private function isCollated(string $column): bool
{
$resolved = $this->resolveAttribute($column);
$separator = \strrpos($resolved, '.');
$name = $separator === false ? $resolved : \substr($resolved, $separator + 1);

return $name === Storage::UID || ($name === Storage::PERMISSIONS_DOCUMENT && ! $this->sharedTables);
}

/**
* @param array<mixed> $queries
* @return list<array{string, string, string}>
*/
private function onComparisons(array $queries): array
{
$comparisons = [];
foreach ($queries as $query) {
if (! $query instanceof Query) {
continue;
}

$comparisons = match ($query->getMethod()) {
Method::On => [...$comparisons, ...$this->comparison($query->getValues())],
Method::And, Method::Or => [...$comparisons, ...$this->onComparisons($query->getValues())],
default => $comparisons,
};
}

return $comparisons;
}

/**
* @param array<mixed> $values
* @return list<array{string, string, string}>
*/
private function comparison(array $values): array
{
[$left, $operator, $right] = [$values[0] ?? null, $values[1] ?? null, $values[2] ?? null];
if (! \is_string($left) || ! \is_string($operator) || ! \is_string($right) || $left === '' || $right === '') {
return [];
}

return [[$left, $operator, $right]];
}

/**
* ST_Distance() cannot be served by the GIST index, so distanceLessThan() leads with a predicate that can: ST_DWithin()
* on the geometry, or, for a distance in meters from a point to a point column, a degree box around the point. The
Expand Down Expand Up @@ -250,4 +161,22 @@ private static function degreesWithinMeters(string|array $point, float $meters):

return [$longitudeDegrees, $latitudeDegrees];
}

#[\Override]
private function isCollated(string $column): bool
{
$name = $this->columnName($column);

return $name === Storage::UID || ($name === Storage::PERMISSIONS_DOCUMENT && ! $this->sharedTables);
}

/**
* Only a join between two id columns: a plain column such as a relationship key has an index in the default
* collation, which a collated comparison could not use.
*/
#[\Override]
private function collatesJoin(string $left, string $right): bool
{
return $this->isCollated($left) && $this->isCollated($right);
}
}
Loading
Loading