diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index c831384f6..81e749670 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -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', Event::IndexRename, ); $statement->bindValue(1, $collection); diff --git a/src/Database/Builder/CollatesDocumentIds.php b/src/Database/Builder/CollatesDocumentIds.php new file mode 100644 index 000000000..6f29a5c52 --- /dev/null +++ b/src/Database/Builder/CollatesDocumentIds.php @@ -0,0 +1,125 @@ +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 $values + */ + #[\Override] + protected function compileIn(string $attribute, array $values, ?string $column = null): string + { + return parent::compileIn($this->collate($attribute, $column), $values, $column); + } + + /** + * @param array $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 $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 $queries + * @return list + */ + 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 $values + * @return list + */ + 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]]; + } +} diff --git a/src/Database/Builder/Postgres.php b/src/Database/Builder/Postgres.php index e4d9859a1..ca40a4dbf 100644 --- a/src/Database/Builder/Postgres.php +++ b/src/Database/Builder/Postgres.php @@ -23,6 +23,7 @@ */ class Postgres extends Base implements Filtering, Scoping { + use CollatesDocumentIds; use CompilesFilters; use MatchesContainsAllPatterns; use PreparesSearchTerms; @@ -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 */ @@ -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 $values - */ - #[\Override] - protected function compileIn(string $attribute, array $values, ?string $column = null): string - { - return parent::compileIn($this->collate($attribute, $column), $values, $column); - } - - /** - * @param array $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 $queries - * @return list - */ - 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 $values - * @return list - */ - 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 @@ -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); + } } diff --git a/src/Database/Builder/SQLite.php b/src/Database/Builder/SQLite.php index eed4b08c8..16d89317e 100644 --- a/src/Database/Builder/SQLite.php +++ b/src/Database/Builder/SQLite.php @@ -21,57 +21,18 @@ */ class SQLite extends Base implements Filtering, Scoping { + use CollatesDocumentIds; use CompilesFilters; use ScopesCollections; public const string COLLATION = 'NOCASE'; - private const string COLLATE = ' COLLATE '.self::COLLATION; - private const array COLLATED_COLUMNS = [Storage::UID, Storage::PERMISSIONS_DOCUMENT]; - private const array EQUALITY_OPERATORS = ['=', '!=', '<>']; - private const string ESCAPE = " ESCAPE '\\'"; private const string ELEMENT_MATCH = "EXISTS (SELECT 1 FROM json_each(%s) WHERE json_each.value = json_extract(?, '$'))"; - #[\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 $values - */ - #[\Override] - protected function compileIn(string $attribute, array $values, ?string $column = null): string - { - return parent::compileIn($this->collate($attribute, $column), $values, $column); - } - - /** - * @param array $values - */ - #[\Override] - protected function compileNotIn(string $attribute, array $values, ?string $column = null): string - { - return parent::compileNotIn($this->collate($attribute, $column), $values, $column); - } - /** * @param array $values */ @@ -153,56 +114,6 @@ protected function compileJsonOverlapsExpression(string $attribute, array $value return '('.\implode(' OR ', $this->compileElementMatches($attribute, $values[0])).')'; } - 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 \in_array($name, self::COLLATED_COLUMNS, true); - } - - /** - * @param array $queries - * @return list - */ - 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 $values - * @return list - */ - 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]]; - } - private function compileNotContaining(string $attribute, string $expression): string { return '('.$attribute.' IS NOT NULL AND NOT '.$expression.')'; @@ -237,4 +148,16 @@ private function compileSubstrings(string $attribute, array $values, bool $not, \array_values($values), ); } + + #[\Override] + private function isCollated(string $column): bool + { + return \in_array($this->columnName($column), self::COLLATED_COLUMNS, true); + } + + #[\Override] + private function collatesJoin(string $left, string $right): bool + { + return $this->isCollated($left) || $this->isCollated($right); + } } diff --git a/src/Database/Trait/Documents.php b/src/Database/Trait/Documents.php index ceac70b12..fba86ed25 100644 --- a/src/Database/Trait/Documents.php +++ b/src/Database/Trait/Documents.php @@ -3073,12 +3073,16 @@ public function deleteDocument(string $collection, string $id): bool $changed = $this->silent(fn () => $this->relationshipHook->beforeDocumentDelete($collection, $document, $report)); } - $result = $this->authorization->skip(fn () => $this->adapter->deleteDocument($collection, $id)); + // The stored id, which an engine that matches ids case-insensitively may spell differently from $id + $result = $this->authorization->skip(fn () => $this->adapter->deleteDocument($collection, $document->getId())); $this->purgeCachedDocumentInternal($collection->getId(), $id); + if ($document->getId() !== $id) { + $this->purgeCachedDocumentInternal($collection->getId(), $document->getId()); + } if ($result) { - $this->queueDocumentPurge($collection->getId(), $id); + $this->queueDocumentPurge($collection->getId(), $document->getId()); } return $result ? $document : null; diff --git a/tests/e2e/Adapter/PostgresTest.php b/tests/e2e/Adapter/PostgresTest.php index 7cb728001..8a3fc1d7a 100644 --- a/tests/e2e/Adapter/PostgresTest.php +++ b/tests/e2e/Adapter/PostgresTest.php @@ -3,6 +3,7 @@ namespace Tests\E2E\Adapter; use Redis; +use Tests\E2E\Adapter\Scopes\PostgresIdCollationTests; use Utopia\Cache\Adapter\Redis as RedisAdapter; use Utopia\Cache\Cache; use Utopia\Database\Adapter\Postgres; @@ -18,6 +19,8 @@ class PostgresTest extends Base { + use PostgresIdCollationTests; + public static ?Database $database = null; protected static ?PDO $pdo = null; diff --git a/tests/e2e/Adapter/Scopes/PostgresIdCollationTests.php b/tests/e2e/Adapter/Scopes/PostgresIdCollationTests.php new file mode 100644 index 000000000..b342f03df --- /dev/null +++ b/tests/e2e/Adapter/Scopes/PostgresIdCollationTests.php @@ -0,0 +1,122 @@ +getDatabase(); + $database->createCollection(Collection::create(id: 'caseVariantRead', permissions: [ + Permission::create(Role::any()), + Permission::read(Role::any()), + ])); + + $database->createDocument('caseVariantRead', new Document(['$id' => 'abc'])); + + $this->assertSame('abc', $database->getDocument('caseVariantRead', 'ABC')->getId()); + $this->assertSame(['abc'], \array_map( + static fn (Document $document): string => $document->getId(), + $database->find('caseVariantRead', [Query::equal('$id', ['ABC'])]), + )); + + $database->deleteCollection('caseVariantRead'); + } + + public function testIdLookupUsesTheIdIndex(): void + { + $database = $this->getDatabase(); + $pdo = self::$pdo; + $this->assertNotNull($pdo); + + $database->createCollection(Collection::create(id: 'idIndexPlan', permissions: [ + Permission::create(Role::any()), + Permission::read(Role::any()), + ])); + $database->createDocuments('idIndexPlan', \array_map( + static fn (int $i): Document => new Document(['$id' => 'doc'.$i]), + \range(1, 1000), + )); + $pdo->exec('ANALYZE "'.$database->getDatabase().'"."'.$database->getNamespace().'_idIndexPlan"'); + + $table = $database->getNamespace().'_idIndexPlan'; + $scans = function () use ($pdo, $table): int { + $pdo->query('SELECT pg_stat_force_next_flush()'); + $pdo->query('SELECT pg_stat_clear_snapshot()'); + + $statement = $pdo->prepare("SELECT COALESCE(SUM(idx_scan), 0) FROM pg_stat_user_indexes WHERE relname = :table AND RIGHT(indexrelname, 4) = '_uid'"); + $statement->execute([':table' => $table]); + + return (int) $statement->fetchColumn(); + }; + + $before = $scans(); + + $pdo->exec('SET enable_seqscan = off'); + + try { + $results = $database->find('idIndexPlan', [Query::equal('$id', ['doc500'])]); + } finally { + $pdo->exec('RESET enable_seqscan'); + } + + $this->assertCount(1, $results); + $this->assertGreaterThan($before, $scans(), 'A lookup by id must be answered from the _uid index'); + + $database->deleteCollection('idIndexPlan'); + } + + public function testCaseVariantWritesKeepPermissionsConsistent(): void + { + $database = $this->getDatabase(); + $pdo = self::$pdo; + $this->assertNotNull($pdo); + + $database->createCollection(Collection::create(id: 'caseVariantWrite', permissions: [ + Permission::create(Role::any()), + ], documentSecurity: true)); + + $database->createDocument('caseVariantWrite', new Document([ + '$id' => 'abc', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + ])); + + $permissions = function () use ($pdo, $database): array { + $statement = $pdo->prepare('SELECT "_document", "_type" FROM "'.$database->getDatabase().'"."'.$database->getNamespace().'_caseVariantWrite_perms" ORDER BY "_type"'); + $statement->execute(); + + return $statement->fetchAll(\PDO::FETCH_NUM); + }; + + $database->updateDocument('caseVariantWrite', 'ABC', new Document([ + '$permissions' => [ + Permission::read(Role::any()), + Permission::delete(Role::any()), + ], + ])); + + $this->assertSame([['abc', 'delete'], ['abc', 'read']], $permissions()); + + $this->assertFalse($database->getDocument('caseVariantWrite', 'abc')->isEmpty()); + $this->assertTrue($database->deleteDocument('caseVariantWrite', 'ABC')); + + $this->assertSame([], $permissions(), 'Deleting through a case variant must remove the stored id\'s permission rows'); + $this->assertTrue($database->getDocument('caseVariantWrite', 'abc')->isEmpty(), 'The stored id must not be served from the cache'); + + $database->deleteCollection('caseVariantWrite'); + } +} diff --git a/tests/e2e/Adapter/SharedTables/PostgresTest.php b/tests/e2e/Adapter/SharedTables/PostgresTest.php index f58924ebc..560e65c63 100644 --- a/tests/e2e/Adapter/SharedTables/PostgresTest.php +++ b/tests/e2e/Adapter/SharedTables/PostgresTest.php @@ -4,14 +4,22 @@ use Redis; use Tests\E2E\Adapter\Base; +use Tests\E2E\Adapter\Scopes\PostgresIdCollationTests; use Utopia\Cache\Adapter\Redis as RedisAdapter; use Utopia\Cache\Cache; use Utopia\Database\Adapter\Postgres; +use Utopia\Database\Attribute; +use Utopia\Database\Collection; use Utopia\Database\Database; +use Utopia\Database\Index; use Utopia\Database\PDO; +use Utopia\Database\Permission; +use Utopia\Database\Role; class PostgresTest extends Base { + use PostgresIdCollationTests; + public static ?Database $database = null; public static ?PDO $pdo = null; @@ -92,4 +100,42 @@ protected function deleteIndex(string $collection, string $index): bool return true; } + + /** + * Table names are quoted, so a collection whose id differs only by case is another table: the creator of the + * index a tenant without its own copy renames must be found by the exact id. + */ + public function testRenameIndexFindsTheCreatorOfTheExactCollectionId(): void + { + $database = $this->getDatabase(); + $tenant = $database->getTenant(); + + $create = static fn (string $id) => $database->createCollection(Collection::create(id: $id, attributes: [ + Attribute::string(key: 'title', size: 64, required: false), + ], indexes: [ + Index::key(key: 'idx', attributes: ['title']), + ], permissions: [Permission::read(Role::any())])); + + try { + $database->setTenant(998); + $create('RenameCreator'); + $database->setTenant(1000); + $create('renameCreator'); + $database->setTenant(999); + $create('renameCreator'); + + $database->renameIndex('renameCreator', 'idx', 'idx2'); + + $this->assertSame(['idx2'], \array_map( + static fn (Index $index): string => $index->key, + $database->getCollection('renameCreator')->indexes(), + )); + } finally { + foreach ([999 => 'renameCreator', 1000 => 'renameCreator', 998 => 'RenameCreator'] as $owner => $id) { + $database->setTenant($owner); + $database->deleteCollection($id); + } + $database->setTenant($tenant); + } + } } diff --git a/tests/unit/Builder/PostgresIdCollationTest.php b/tests/unit/Builder/PostgresIdCollationTest.php new file mode 100644 index 000000000..3d755da6a --- /dev/null +++ b/tests/unit/Builder/PostgresIdCollationTest.php @@ -0,0 +1,67 @@ + + */ + public static function filters(): array + { + return [ + 'id' => [false, '_uid', '"_uid" COLLATE utf8_ci_ai IN (?)'], + 'shared id' => [true, '_uid', '"_uid" COLLATE utf8_ci_ai IN (?)'], + 'permission document' => [false, '_document', '"_document" COLLATE utf8_ci_ai IN (?)'], + 'shared permission document' => [true, '_document', '"_document" IN (?)'], + 'plain column' => [false, 'name', '"name" IN (?)'], + ]; + } + + #[DataProvider('filters')] + public function testEqualComparesInTheIndexCollation(bool $sharedTables, string $column, string $expected): void + { + $sql = (new Postgres($sharedTables))->from('docs')->filter([Query::equal($column, ['abc'])])->build()->query; + + $this->assertSame('SELECT * FROM "docs" WHERE '.$expected, $sql); + } + + /** + * @return array + */ + public static function joins(): array + { + return [ + 'id to id' => ['b._uid', '"a"."_uid" COLLATE utf8_ci_ai = "b"."_uid"'], + 'id to relationship key' => ['b.authorId', '"a"."_uid" = "b"."authorId"'], + ]; + } + + #[DataProvider('joins')] + public function testJoinOnTwoIdsComparesInTheIndexCollation(string $right, string $expected): void + { + $sql = (new Postgres())->from('a', 'a')->join('b', 'a._uid', $right, '=', 'b')->build()->query; + + $this->assertSame('SELECT * FROM "a" AS "a" JOIN "b" AS "b" ON '.$expected, $sql); + } + + #[DataProvider('joins')] + public function testJoinBuilderOnTwoIdsComparesInTheIndexCollation(string $right, string $expected): void + { + $sql = (new Postgres()) + ->from('a', 'a') + ->joinWhere('b', static function (JoinBuilder $join) use ($right): void { + $join->on('a._uid', $right); + }, alias: 'b') + ->build() + ->query; + + $this->assertSame('SELECT * FROM "a" AS "a" JOIN "b" AS "b" ON '.$expected, $sql); + } +}