diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 7f8d5757a..70fbdf49e 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -1102,8 +1102,9 @@ public function createDocument(Document $collection, Document $document): Docume $statement = $this->executeResult($result, Event::DocumentCreate); $this->execute($statement); - $lastInsertedId = $this->getDriver()->lastInsertId(); - $document[Document::SEQUENCE] ??= $lastInsertedId; + if (empty($document->getSequence())) { + $document[Document::SEQUENCE] = $this->getDriver()->lastInsertId(); + } $context = $this->writeContext(); $this->runWriteHooks(fn ($hook) => $hook->afterDocumentCreate($name, [$document], $context)); diff --git a/tests/e2e/Adapter/Scopes/DocumentTests.php b/tests/e2e/Adapter/Scopes/DocumentTests.php index 973550113..9a176685e 100644 --- a/tests/e2e/Adapter/Scopes/DocumentTests.php +++ b/tests/e2e/Adapter/Scopes/DocumentTests.php @@ -2948,6 +2948,38 @@ public function testUpdateDocument(): void $this->assertEquals($id, $new->getId()); } + public function testDocumentRecreatedWithItsSequenceInAFreshSessionKeepsIt(): void + { + $database = $this->getDatabase(); + $collection = 'own_sequence_'.\substr(\uniqid(), -6); + $database->createCollection(Collection::create( + id: $collection, + attributes: [Attribute::string(key: 'name', size: 20, required: true)], + permissions: [Permission::create(Role::any()), Permission::read(Role::any()), Permission::delete(Role::any())], + )); + + $document = $database->createDocument($collection, new Document([ + '$id' => 'own', + 'name' => 'first', + '$permissions' => [Permission::read(Role::any())], + ])); + $database->deleteDocument($collection, 'own'); + + $adapter = $database->getAdapter(); + if ($adapter instanceof Postgres) { + $driver = $adapter->getDriver(); + $this->assertInstanceOf(DatabasePDO::class, $driver); + $driver->exec('DISCARD SEQUENCES'); + } + + $recreated = $database->createDocument($collection, $document); + + $this->assertSame($document->getSequence(), $recreated->getSequence()); + $this->assertSame($document->getSequence(), $database->getDocument($collection, 'own')->getSequence()); + + $database->deleteCollection($collection); + } + public function testDeleteDocument(): void { $document = $this->initDocumentsFixture();