diff --git a/appinfo/info.xml b/appinfo/info.xml index 4edcef88db..506468495d 100644 --- a/appinfo/info.xml +++ b/appinfo/info.xml @@ -26,7 +26,7 @@ Share your tables and views with users and groups within your cloud. Have a good time and manage whatever you want. ]]> - 2.5.0-dev.0 + 2.5.0-dev.1 AGPL-3.0-or-later Nextcloud GmbH and Nextcloud contributors Tables diff --git a/lib/BackgroundJob/BackfillRowUuids.php b/lib/BackgroundJob/BackfillRowUuids.php new file mode 100644 index 0000000000..8c214ab28e --- /dev/null +++ b/lib/BackgroundJob/BackfillRowUuids.php @@ -0,0 +1,102 @@ +setInterval(60); + $this->setAllowParallelRuns(false); + } + + public function run(mixed $argument): void { + $deadline = $this->time->getTime() + self::TIME_BUDGET; + $cursor = $this->config->getValueInt(Application::APP_ID, self::CURSOR_KEY, 0, true); + $select = $this->connection->getQueryBuilder(); + $select->select('id')->from('tables_row_sleeves') + ->where($select->expr()->isNull('uuid')) + ->andWhere($select->expr()->gt('id', $select->createParameter('cursor'))) + ->orderBy('id', 'ASC')->setMaxResults(self::BATCH_SIZE); + $update = $this->connection->getQueryBuilder(); + $update->update('tables_row_sleeves')->set('uuid', $update->createParameter('uuid')) + ->where($update->expr()->eq('id', $update->createParameter('id'))) + ->andWhere($update->expr()->isNull('uuid')); + + try { + do { + $select->setParameter('cursor', $cursor, IQueryBuilder::PARAM_INT); + $result = $select->executeQuery(); + $ids = array_map(intval(...), $result->fetchFirstColumn()); + $result->closeCursor(); + if ($ids === []) { + if ($cursor === 0) { + $this->jobList->remove(self::class); + $this->config->deleteKey(Application::APP_ID, self::CURSOR_KEY); + return; + } + $cursor = 0; + continue; + } + + $cursor = $this->processBatch($ids, $update, $deadline); + if ($this->connection->getDatabaseProvider() === IDBConnection::PLATFORM_SQLITE && $this->time->getTime() < $deadline) { + // Yield SQLite's single writer between committed batches. + usleep(self::SQLITE_BATCH_PAUSE_MICROSECONDS); + } + } while ($this->time->getTime() < $deadline); + // A lagging cursor only repeats a NULL scan, so one write per run spares the shared config cache. + $this->config->setValueInt(Application::APP_ID, self::CURSOR_KEY, $cursor, true); + } catch (\Throwable $e) { + $this->logger->error('Row UUID backfill will retry on its next run.', ['exception' => $e]); + } + } + + /** @param non-empty-list $ids */ + private function processBatch(array $ids, IQueryBuilder $update, int $deadline): int { + $this->connection->beginTransaction(); + try { + foreach ($ids as $id) { + $update->setParameter('id', $id, IQueryBuilder::PARAM_INT); + $update->setParameter('uuid', Uuid::v7()->toRfc4122()); + $update->executeStatement(); + if ($this->time->getTime() >= $deadline) { + break; + } + } + $this->connection->commit(); + return $id; + } catch (\Throwable $e) { + $this->connection->rollBack(); + throw $e; + } + } +} diff --git a/lib/Controller/RowOCSController.php b/lib/Controller/RowOCSController.php index 13ddd4e946..265966d66b 100644 --- a/lib/Controller/RowOCSController.php +++ b/lib/Controller/RowOCSController.php @@ -87,11 +87,11 @@ public function createRow(string $nodeCollection, int $nodeId, mixed $data): Dat try { if ($tableId !== null && $this->federationService->isNodeFederated($tableId, 'table')) { $table = $this->tableService->find($nodeId, true); - return new DataResponse($this->federationService->createRow($table, $data)); + return new DataResponse($this->federationService->createRow($table, $data) + ['uuid' => null]); } if ($viewId !== null && $this->federationService->isNodeFederated($viewId, 'view')) { $view = $this->viewService->find($nodeId, false, $this->userId); - return new DataResponse($this->federationService->createRow($view, $data)); + return new DataResponse($this->federationService->createRow($view, $data) + ['uuid' => null]); } return new DataResponse($this->rowService->create($tableId, $viewId, $newRowData)->jsonSerialize()); } catch (BadRequestError $e) { @@ -140,11 +140,11 @@ public function updateRow(string $nodeCollection, int $nodeId, int $rowId, mixed try { if ($tableId !== null && $this->federationService->isNodeFederated($tableId, 'table')) { $table = $this->tableService->find($nodeId, true); - return new DataResponse($this->federationService->updateRow($table, $rowId, $data)); + return new DataResponse($this->federationService->updateRow($table, $rowId, $data) + ['uuid' => null]); } if ($viewId !== null && $this->federationService->isNodeFederated($viewId, 'view')) { $view = $this->viewService->find($nodeId, false, $this->userId); - return new DataResponse($this->federationService->updateRow($view, $rowId, $data)); + return new DataResponse($this->federationService->updateRow($view, $rowId, $data) + ['uuid' => null]); } return new DataResponse($this->rowService->updateSet($rowId, $viewId, $data, $this->userId, $tableId)->jsonSerialize()); } catch (BadRequestError $e) { @@ -185,11 +185,11 @@ public function deleteRow(string $nodeCollection, int $nodeId, int $rowId): Data try { if ($tableId !== null && $this->federationService->isNodeFederated($tableId, 'table')) { $table = $this->tableService->find($nodeId, true); - return new DataResponse($this->federationService->deleteRow($table, $rowId)); + return new DataResponse($this->federationService->deleteRow($table, $rowId) + ['uuid' => null]); } if ($viewId !== null && $this->federationService->isNodeFederated($viewId, 'view')) { $view = $this->viewService->find($nodeId, false, $this->userId); - return new DataResponse($this->federationService->deleteRow($view, $rowId)); + return new DataResponse($this->federationService->deleteRow($view, $rowId) + ['uuid' => null]); } return new DataResponse($this->rowService->delete($rowId, $viewId, $this->userId, $tableId)->jsonSerialize()); } catch (NotFoundError $e) { diff --git a/lib/Db/Row2.php b/lib/Db/Row2.php index 0755bb325a..67f93164bb 100644 --- a/lib/Db/Row2.php +++ b/lib/Db/Row2.php @@ -17,6 +17,7 @@ */ class Row2 implements JsonSerializable { private ?int $id = null; + private ?string $uuid = null; private ?int $tableId = null; private ?string $createdBy = null; private ?string $createdAt = null; @@ -36,6 +37,14 @@ public function setId(int $id): void { $this->id = $id; } + public function getUuid(): ?string { + return $this->uuid; + } + + public function setUuid(?string $uuid): void { + $this->uuid = $uuid; + } + public function getTableId(): ?int { return $this->tableId; } @@ -165,6 +174,7 @@ public function filterDataByAliasByColumns(array $columns): array { public function jsonSerialize(): array { return [ 'id' => $this->id, + 'uuid' => $this->uuid, 'tableId' => $this->tableId, 'createdBy' => $this->createdBy, 'createdAt' => $this->createdAt, diff --git a/lib/Db/Row2Mapper.php b/lib/Db/Row2Mapper.php index 7f3ff173da..19e45b3f21 100644 --- a/lib/Db/Row2Mapper.php +++ b/lib/Db/Row2Mapper.php @@ -44,6 +44,10 @@ public function __construct( ) { } + public function importSleeve(RowSleeve $sleeve, ?string $archivedUuid): RowSleeve { + return $this->rowSleeveMapper->insertImported($sleeve, $archivedUuid); + } + /** * @param Row2 $row * @return Row2 @@ -734,6 +738,7 @@ private function parseEntities(IResult $result, array $sleeves): array { foreach ($sleeves as $sleeve) { $rows[$sleeve->getId()] = new Row2(); $rows[$sleeve->getId()]->setId($sleeve->getId()); + $rows[$sleeve->getId()]->setUuid($sleeve->getUuid()); $rows[$sleeve->getId()]->setCreatedBy($sleeve->getCreatedBy()); $rows[$sleeve->getId()]->setCreatedAt($sleeve->getCreatedAt()); $rows[$sleeve->getId()]->setLastEditBy($sleeve->getLastEditBy()); @@ -867,6 +872,8 @@ public function insert(Row2 $row, ?string $userId = null): Row2 { $row->setId($rowSleeve->getId()); } + $row->setUuid($rowSleeve->getUuid()); + // write all cells to its db-table foreach ($row->getData() as $cell) { $this->insertCell($rowSleeve->getId(), $cell['columnId'], $cell['value'], $rowSleeve->getLastEditAt(), $rowSleeve->getLastEditBy()); diff --git a/lib/Db/RowSleeve.php b/lib/Db/RowSleeve.php index b909a3f44f..82f8b72a37 100644 --- a/lib/Db/RowSleeve.php +++ b/lib/Db/RowSleeve.php @@ -8,10 +8,13 @@ namespace OCA\Tables\Db; use JsonSerializable; +use OCA\Tables\Vendor\Symfony\Component\Uid\Uuid; +use OCA\Tables\Vendor\Symfony\Component\Uid\UuidV7; use OCP\AppFramework\Db\Entity; /** * @psalm-suppress PropertyNotSetInConstructor + * @method getUuid(): ?string * @method getTableId(): ?int * @method setTableId(int $columnId) * @method getCreatedBy(): string @@ -25,6 +28,7 @@ */ class RowSleeve extends Entity implements JsonSerializable { protected ?int $tableId = null; + protected ?string $uuid = null; protected ?string $createdBy = null; protected ?string $createdAt = null; protected ?string $lastEditBy = null; @@ -33,11 +37,31 @@ class RowSleeve extends Entity implements JsonSerializable { public function __construct() { $this->addType('id', 'integer'); $this->addType('tableId', 'integer'); + $this->addType('uuid', 'string'); + } + + /** + * Hydration uses Entity::setter() instead, so stored values load unchanged. + */ + public function setUuid(?string $uuid): void { + $uuid = $uuid !== null ? (new UuidV7($uuid))->toRfc4122() : null; + if ($this->uuid !== null && $uuid !== $this->uuid) { + throw new \InvalidArgumentException('Row UUIDs are immutable.'); + } + $this->uuid = $uuid; + $this->markFieldUpdated('uuid'); + } + + public function assignUuid(): void { + if ($this->uuid === null) { + $this->setUuid(Uuid::v7()->toRfc4122()); + } } public function jsonSerialize(): array { return [ 'id' => $this->id, + 'uuid' => $this->uuid, 'tableId' => $this->tableId, 'createdBy' => $this->createdBy, 'createdAt' => $this->createdAt, diff --git a/lib/Db/RowSleeveMapper.php b/lib/Db/RowSleeveMapper.php index b627424ba5..09541a8a0c 100644 --- a/lib/Db/RowSleeveMapper.php +++ b/lib/Db/RowSleeveMapper.php @@ -8,6 +8,7 @@ namespace OCA\Tables\Db; use OCP\AppFramework\Db\DoesNotExistException; +use OCP\AppFramework\Db\Entity; use OCP\AppFramework\Db\MultipleObjectsReturnedException; use OCP\AppFramework\Db\QBMapper; use OCP\DB\Exception; @@ -28,6 +29,15 @@ public function __construct( parent::__construct($db, $this->table, RowSleeve::class); } + /** + * @param RowSleeve $entity + * @return RowSleeve + */ + public function insert(Entity $entity): Entity { + $entity->assignUuid(); + return parent::insert($entity); + } + /** * @throws MultipleObjectsReturnedException * @throws DoesNotExistException @@ -41,6 +51,32 @@ public function find(int $id): RowSleeve { return $this->findEntity($qb); } + public function findByUuid(string $uuid): RowSleeve { + $qb = $this->db->getQueryBuilder(); + $qb->select('*')->from($this->table) + ->where($qb->expr()->eq('uuid', $qb->createNamedParameter($uuid))); + return $this->findEntity($qb); + } + + /** + * Keeps an archived UUID unless another row already has it, in which case + * the imported row gets a new one. + * + * @throws Exception + */ + public function insertImported(RowSleeve $sleeve, ?string $archivedUuid): RowSleeve { + // Look the UUID up rather than running into the unique index, because the + // import runs inside a transaction that a constraint violation would cancel. + if ($archivedUuid !== null) { + try { + $this->findByUuid($archivedUuid); + } catch (DoesNotExistException) { + $sleeve->setUuid($archivedUuid); + } + } + return $this->insert($sleeve); + } + /** * @param int[] $ids * @return RowSleeve[] @@ -51,6 +87,7 @@ public function findMultiple(array $ids): array { $qb = $this->db->getQueryBuilder(); $qb->select( $sleeveAlias . '.id', + $sleeveAlias . '.uuid', $sleeveAlias . '.table_id', $sleeveAlias . '.created_by', $sleeveAlias . '.created_at', diff --git a/lib/Migration/Version2500Date20261120000000.php b/lib/Migration/Version2500Date20261120000000.php new file mode 100644 index 0000000000..c17b7e1e6c --- /dev/null +++ b/lib/Migration/Version2500Date20261120000000.php @@ -0,0 +1,46 @@ +getTable('tables_row_sleeves'); + if (!$table->hasColumn('uuid')) { + $table->addColumn('uuid', Types::STRING, [ + 'notnull' => false, + 'default' => null, + 'length' => 36, + ]); + } + if (!$table->hasIndex('tables_row_uuid_uniq')) { + $table->addUniqueIndex(['uuid'], 'tables_row_uuid_uniq'); + } + return $schema; + } + + public function postSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void { + $this->jobList->add(BackfillRowUuids::class); + } +} diff --git a/lib/ResponseDefinitions.php b/lib/ResponseDefinitions.php index dd41a0bf4f..ad037ebfeb 100644 --- a/lib/ResponseDefinitions.php +++ b/lib/ResponseDefinitions.php @@ -87,6 +87,7 @@ * * @psalm-type TablesRow = array{ * id: int, + * uuid: ?string, * tableId: int, * createdBy: string, * createdAt: string, @@ -98,6 +99,7 @@ * * @psalm-type TablesPublicRow = array{ * id: int, + * uuid: ?string, * createdAt: string, * lastEditAt: string, * data: ?array{columnId: int, value: mixed}, diff --git a/lib/Service/RowService.php b/lib/Service/RowService.php index f14cf87110..aeb9b9c561 100644 --- a/lib/Service/RowService.php +++ b/lib/Service/RowService.php @@ -12,6 +12,7 @@ use OCA\Tables\Db\ColumnMapper; use OCA\Tables\Db\Row2; use OCA\Tables\Db\Row2Mapper; +use OCA\Tables\Db\RowSleeve; use OCA\Tables\Db\Table; use OCA\Tables\Db\TableMapper; use OCA\Tables\Db\View; @@ -29,12 +30,11 @@ use OCA\Tables\ResponseDefinitions; use OCA\Tables\Service\ColumnTypes\IColumnTypeBusiness; use OCA\Tables\Service\ValueObject\ViewColumnInformation; +use OCA\Tables\Vendor\Symfony\Component\Uid\UuidV7; use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\Db\MultipleObjectsReturnedException; use OCP\DB\Exception; -use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\EventDispatcher\IEventDispatcher; -use OCP\IDBConnection; use Psr\Container\ContainerExceptionInterface; use Psr\Container\NotFoundExceptionInterface; use Psr\Log\LoggerInterface; @@ -58,7 +58,6 @@ public function __construct( private readonly ColumnsHelper $columnsHelper, private readonly ActivityManager $activityManager, private readonly NotificationHelper $notificationHelper, - private readonly IDBConnection $connection, private readonly RowVisibilityService $rowVisibility, ) { parent::__construct($logger, $userId, $permissionsService); @@ -1017,20 +1016,23 @@ private function buildAliasByColumnId(array $columns): array { * @throws InternalError */ public function importRow(Table $table, array $row): int { - $qb = $this->connection->getQueryBuilder(); + $tableId = $table->getId(); + $owner = $table->getOwnership(); + if ($tableId === null || $owner === null) { + throw new \InvalidArgumentException('An imported row requires a stored destination table and owner.'); + } + + $archivedUuid = $row['uuid'] ?? null; + $archivedUuid = is_string($archivedUuid) && UuidV7::isValid($archivedUuid) ? strtolower($archivedUuid) : null; + + $sleeve = new RowSleeve(); + $sleeve->setTableId($tableId); + $sleeve->setCreatedBy($owner); + $sleeve->setCreatedAt($row['createdAt']); + $sleeve->setLastEditBy($owner); + $sleeve->setLastEditAt($row['lastEditAt']); try { - $qb->insert('tables_row_sleeves') - ->values([ - 'table_id' => $qb->createNamedParameter($table->getId(), IQueryBuilder::PARAM_INT), - 'created_by' => $qb->createNamedParameter($table->getOwnership()), - 'created_at' => $qb->createNamedParameter($row['createdAt']), - 'last_edit_by' => $qb->createNamedParameter($table->getOwnership()), - 'last_edit_at' => $qb->createNamedParameter($row['lastEditAt']), - ]); - $qb->executeStatement(); - $id = $this->connection->lastInsertId('*PREFIX*tables_row_sleeves'); - - return $id; + return $this->row2Mapper->importSleeve($sleeve, $archivedUuid)->getId(); } catch (\Exception $e) { $this->logger->error('userMigrationImport insert error: ' . $e->getMessage()); throw new InternalError('userMigrationImport insert error: ' . $e->getMessage()); diff --git a/openapi.json b/openapi.json index 32737ee685..803dcb640d 100644 --- a/openapi.json +++ b/openapi.json @@ -657,6 +657,7 @@ "type": "object", "required": [ "id", + "uuid", "createdAt", "lastEditAt", "data", @@ -667,6 +668,10 @@ "type": "integer", "format": "int64" }, + "uuid": { + "type": "string", + "nullable": true + }, "createdAt": { "type": "string" }, @@ -715,6 +720,7 @@ "type": "object", "required": [ "id", + "uuid", "tableId", "createdBy", "createdAt", @@ -728,6 +734,10 @@ "type": "integer", "format": "int64" }, + "uuid": { + "type": "string", + "nullable": true + }, "tableId": { "type": "integer", "format": "int64" diff --git a/package-lock.json b/package-lock.json index bff4c53b3f..bc7c27a630 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "tables", - "version": "2.5.0-dev.0", + "version": "2.5.0-dev.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "tables", - "version": "2.5.0-dev.0", + "version": "2.5.0-dev.1", "license": "AGPL-3.0-or-later", "dependencies": { "@material-symbols/svg-400": "^0.49.0", diff --git a/package.json b/package.json index ce165fbc60..7c82860b1f 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "tables", "description": "Manage data within tables.", - "version": "2.5.0-dev.0", + "version": "2.5.0-dev.1", "author": "Nextcloud GmbH and Nextcloud contributors", "bugs": { "url": "https://github.com/nextcloud/tables/issues" diff --git a/src/types/openapi/openapi.ts b/src/types/openapi/openapi.ts index 63aa6dbe62..c821508e1a 100644 --- a/src/types/openapi/openapi.ts +++ b/src/types/openapi/openapi.ts @@ -1306,6 +1306,7 @@ export type components = { readonly PublicRow: { /** Format: int64 */ readonly id: number; + readonly uuid: string | null; readonly createdAt: string; readonly lastEditAt: string; readonly data: { @@ -1324,6 +1325,7 @@ export type components = { readonly Row: { /** Format: int64 */ readonly id: number; + readonly uuid: string | null; /** Format: int64 */ readonly tableId: number; readonly createdBy: string; diff --git a/tests/unit/BackgroundJob/BackfillRowUuidsTest.php b/tests/unit/BackgroundJob/BackfillRowUuidsTest.php new file mode 100644 index 0000000000..0310b5f2d7 --- /dev/null +++ b/tests/unit/BackgroundJob/BackfillRowUuidsTest.php @@ -0,0 +1,221 @@ +connectionAdapter->beginTransaction(); + $delete = $this->connectionAdapter->getQueryBuilder(); + $delete->delete('tables_row_sleeves')->where($delete->expr()->gt('id', $delete->createNamedParameter(0)))->executeStatement(); + $this->settings = []; + $this->config = $this->createMock(IAppConfig::class); + $this->config->method('getValueInt')->willReturnCallback(fn ($app, $key, $default) => $this->settings[$key] ?? $default); + $this->config->method('setValueInt')->willReturnCallback(function ($app, $key, $value): bool { + $this->settings[$key] = $value; + return true; + }); + $this->config->method('deleteKey')->willReturnCallback(function ($app, $key): void { + unset($this->settings[$key]); + }); + $this->jobList = $this->createMock(IJobList::class); + $this->mapper = new RowSleeveMapper($this->connectionAdapter, new NullLogger()); + } + + protected function tearDown(): void { + $this->connectionAdapter->rollBack(); + parent::tearDown(); + } + + private function historicalRows(int $count): array { + $insert = $this->connectionAdapter->getQueryBuilder(); + $insert->insert('tables_row_sleeves')->values([ + 'table_id' => $insert->createNamedParameter(991), + 'created_by' => $insert->createNamedParameter('original-author'), + 'created_at' => $insert->createNamedParameter('2020-01-01 00:00:00'), + 'last_edit_by' => $insert->createNamedParameter('original-editor'), + 'last_edit_at' => $insert->createNamedParameter('2020-01-02 00:00:00'), + ]); + $ids = []; + for ($i = 0; $i < $count; $i++) { + $insert->executeStatement(); + $ids[] = $insert->getLastInsertId(); + } + return $ids; + } + + private function job(ITimeFactory $clock, ?LoggerInterface $logger = null): BackfillRowUuids { + return new BackfillRowUuids($clock, $this->connectionAdapter, $this->config, $this->jobList, $logger ?? new NullLogger()); + } + + public function testTimeBudgetCheckpointsProcessedPrefixAndResumePreservesMetadata(): void { + $ids = $this->historicalRows(3); + $clock = $this->createMock(ITimeFactory::class); + $clock->method('getTime')->willReturnOnConsecutiveCalls(0, 5, 5, 5); + $this->jobList->expects($this->once())->method('remove')->with(BackfillRowUuids::class); + $this->job($clock)->run(null); + $this->assertSame($ids[0], $this->settings['row_uuid_backfill_cursor']); + $uuid = $this->mapper->find($ids[0])->getUuid(); + $this->assertNotNull($uuid); + $this->assertNull($this->mapper->find($ids[1])->getUuid()); + + $clock = $this->createMock(ITimeFactory::class); + $clock->method('getTime')->willReturn(10); + $this->job($clock)->run(null); + $this->assertSame($uuid, $this->mapper->find($ids[0])->getUuid()); + foreach ($ids as $id) { + $row = $this->mapper->find($id); + $this->assertNotNull($row->getUuid()); + $this->assertSame('original-author', $row->getCreatedBy()); + $this->assertSame('original-editor', $row->getLastEditBy()); + $this->assertSame('2020-01-01 00:00:00', $row->getCreatedAt()); + $this->assertSame('2020-01-02 00:00:00', $row->getLastEditAt()); + } + $this->assertSame([], $this->settings); + } + + public function testFinalPassRevisitsNullsBelowCursor(): void { + $ids = $this->historicalRows(2); + $this->settings['row_uuid_backfill_cursor'] = $ids[1] + 100; + $clock = $this->createMock(ITimeFactory::class); + $clock->method('getTime')->willReturn(0); + $this->jobList->expects($this->once())->method('remove'); + $this->job($clock)->run(null); + $this->assertNotNull($this->mapper->find($ids[0])->getUuid()); + $this->assertNotNull($this->mapper->find($ids[1])->getUuid()); + } + + public function testCommittedWorkSurvivesCheckpointFailure(): void { + $ids = $this->historicalRows(1); + $config = $this->createMock(IAppConfig::class); + $config->method('getValueInt')->willReturn(0); + $config->method('setValueInt')->willThrowException(new \RuntimeException('Checkpoint unavailable')); + $logger = $this->createMock(LoggerInterface::class); + $logger->expects($this->once())->method('error'); + $clock = $this->createMock(ITimeFactory::class); + $clock->method('getTime')->willReturnOnConsecutiveCalls(0, 5, 5, 5); + $job = new BackfillRowUuids($clock, $this->connectionAdapter, $config, $this->jobList, $logger); + $job->run(null); + $uuid = $this->mapper->find($ids[0])->getUuid(); + $this->assertNotNull($uuid); + $resumeClock = $this->createMock(ITimeFactory::class); + $resumeClock->method('getTime')->willReturn(10); + $this->jobList->expects($this->once())->method('remove'); + $this->job($resumeClock)->run(null); + $this->assertSame($uuid, $this->mapper->find($ids[0])->getUuid()); + } + + public function testCheckpointIsWrittenLazilyOncePerExecution(): void { + $ids = $this->historicalRows(501); + $config = $this->createMock(IAppConfig::class); + $config->method('getValueInt')->with(Application::APP_ID, 'row_uuid_backfill_cursor', 0, true)->willReturn(0); + $config->expects($this->once())->method('setValueInt')->with(Application::APP_ID, 'row_uuid_backfill_cursor', $ids[500], true)->willReturn(true); + $calls = 0; + $clock = $this->createMock(ITimeFactory::class); + $clock->method('getTime')->willReturnCallback(function () use (&$calls): int { + return ++$calls > 503 ? 5 : 0; + }); + $job = new BackfillRowUuids($clock, $this->connectionAdapter, $config, $this->jobList, new NullLogger()); + $job->run(null); + $this->assertNotNull($this->mapper->find($ids[500])->getUuid()); + } + + public function testFailedBatchRollsBackItsPrefixBeforeRetrying(): void { + $ids = $this->historicalRows(2); + $actualUpdate = $this->connectionAdapter->getQueryBuilder(); + $update = $this->createMock(IQueryBuilder::class); + foreach (['update', 'set', 'where', 'andWhere', 'setParameter'] as $method) { + $update->method($method)->willReturnCallback(function (...$arguments) use ($actualUpdate, $update, $method) { + $actualUpdate->$method(...$arguments); + return $update; + }); + } + $update->method('expr')->willReturn($actualUpdate->expr()); + $update->method('createParameter')->willReturnCallback(fn ($name) => $actualUpdate->createParameter($name)); + $calls = 0; + $update->method('executeStatement')->willReturnCallback(function () use ($actualUpdate, &$calls): int { + if (++$calls === 2) { + throw new \RuntimeException('Database write interrupted'); + } + return $actualUpdate->executeStatement(); + }); + $connection = $this->createMock(IDBConnection::class); + $connection->method('getQueryBuilder')->willReturnOnConsecutiveCalls($this->connectionAdapter->getQueryBuilder(), $update); + $connection->expects($this->once())->method('beginTransaction')->willReturnCallback(fn () => $this->connectionAdapter->beginTransaction()); + $connection->expects($this->once())->method('rollBack')->willReturnCallback(fn () => $this->connectionAdapter->rollBack()); + $connection->expects($this->never())->method('commit'); + $clock = $this->createMock(ITimeFactory::class); + $clock->method('getTime')->willReturn(0); + $logger = $this->createMock(LoggerInterface::class); + $logger->expects($this->once())->method('error'); + $job = new BackfillRowUuids($clock, $connection, $this->config, $this->jobList, $logger); + $job->run(null); + $this->assertSame([], $this->settings); + $this->assertNull($this->mapper->find($ids[0])->getUuid()); + $this->assertNull($this->mapper->find($ids[1])->getUuid()); + $this->jobList->expects($this->once())->method('remove'); + $this->job($clock)->run(null); + $this->assertNotNull($this->mapper->find($ids[0])->getUuid()); + $this->assertNotNull($this->mapper->find($ids[1])->getUuid()); + } + + public function testInterleavedAssignmentAndDeletionAreNotOverwritten(): void { + $ids = $this->historicalRows(3); + $uuid = '019f90c5-8576-7f0b-9b14-9bf49b2826cf'; + $assign = $this->connectionAdapter->getQueryBuilder(); + $assign->update('tables_row_sleeves')->set('uuid', $assign->createNamedParameter($uuid)) + ->where($assign->expr()->eq('id', $assign->createNamedParameter($ids[1]))); + $delete = $this->connectionAdapter->getQueryBuilder(); + $delete->delete('tables_row_sleeves')->where($delete->expr()->eq('id', $delete->createNamedParameter($ids[2]))); + $clock = $this->createMock(ITimeFactory::class); + $calls = 0; + $clock->method('getTime')->willReturnCallback(function () use (&$calls, $assign, $delete): int { + if (++$calls === 2) { + $assign->executeStatement(); + $delete->executeStatement(); + } + return 0; + }); + $this->jobList->expects($this->once())->method('remove'); + $this->job($clock)->run(null); + $this->assertNotNull($this->mapper->find($ids[0])->getUuid()); + $this->assertSame($uuid, $this->mapper->find($ids[1])->getUuid()); + $this->expectException(\OCP\AppFramework\Db\DoesNotExistException::class); + $this->mapper->find($ids[2]); + } + + public function testMoreThanOneBatchCompletesWithUniqueIdentities(): void { + $ids = $this->historicalRows(501); + $clock = $this->createMock(ITimeFactory::class); + $clock->method('getTime')->willReturn(0); + $this->jobList->expects($this->once())->method('remove'); + $this->job($clock)->run(null); + $uuids = array_map(fn ($id) => $this->mapper->find($id)->getUuid(), $ids); + $this->assertNotContains(null, $uuids); + $this->assertCount(501, array_unique($uuids)); + } +} diff --git a/tests/unit/Database/DatabaseTestCase.php b/tests/unit/Database/DatabaseTestCase.php index 4519504a84..ff09e4bff3 100644 --- a/tests/unit/Database/DatabaseTestCase.php +++ b/tests/unit/Database/DatabaseTestCase.php @@ -15,6 +15,7 @@ use OC\DB\MigrationService; use OC\Migration\NullOutput; use OC\SystemConfig; +use OCA\Tables\Vendor\Symfony\Component\Uid\Uuid; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\Server; use PHPUnit\Framework\TestCase; @@ -234,6 +235,7 @@ protected function createTestColumn(int $tableId, array $data = []) { protected function createTestRow(int $tableId, array $data = []) { $defaultData = [ 'table_id' => $tableId, + 'uuid' => Uuid::v7()->toRfc4122(), 'created_by' => 'user1', 'created_at' => date('Y-m-d H:i:s'), 'last_edit_by' => 'user1', diff --git a/tests/unit/Db/RowSleeveMapperTest.php b/tests/unit/Db/RowSleeveMapperTest.php new file mode 100644 index 0000000000..d9fa721ace --- /dev/null +++ b/tests/unit/Db/RowSleeveMapperTest.php @@ -0,0 +1,100 @@ +mapper = new RowSleeveMapper($this->connectionAdapter, new NullLogger()); + $this->connectionAdapter->beginTransaction(); + } + + protected function tearDown(): void { + $this->connectionAdapter->rollBack(); + parent::tearDown(); + } + + private function sleeve(int $tableId = 1): RowSleeve { + $sleeve = new RowSleeve(); + $sleeve->setTableId($tableId); + $sleeve->setCreatedBy('alice'); + $sleeve->setLastEditBy('alice'); + $sleeve->setCreatedAt('2020-01-01 00:00:00'); + $sleeve->setLastEditAt('2020-01-02 00:00:00'); + return $sleeve; + } + + public function testEveryInsertionGetsStoredUuidAndProjectionIncludesIt(): void { + $first = $this->mapper->insert($this->sleeve()); + $second = $this->mapper->insert($this->sleeve(2)); + $this->assertNotNull($first->getUuid()); + $this->assertNotSame($first->getUuid(), $second->getUuid()); + $this->assertSame($first->getUuid(), $this->mapper->find($first->getId())->getUuid()); + $this->assertSame($first->getUuid(), $this->mapper->findMultiple([$first->getId()])[0]->getUuid()); + $this->assertSame($first->getId(), $this->mapper->findByUuid($first->getUuid())->getId()); + } + + public function testExplicitLegacyIdAlsoGetsUuid(): void { + $sleeve = $this->sleeve(); + $sleeve->setId(900001); + $this->mapper->insert($sleeve); + $this->assertNotNull($this->mapper->find(900001)->getUuid()); + } + + public function testImportKeepsUnusedUuidAndReplacesOneInUse(): void { + $uuid = '019f90c5-8576-7f0b-9b14-9bf49b2826cf'; + $first = $this->mapper->insertImported($this->sleeve(), $uuid); + $this->assertSame($uuid, $first->getUuid()); + $second = $this->mapper->insertImported($this->sleeve(2), $uuid); + $this->assertNotNull($second->getUuid()); + $this->assertNotSame($uuid, $second->getUuid()); + $this->assertSame($uuid, $this->mapper->find($first->getId())->getUuid()); + $this->assertSame($second->getUuid(), $this->mapper->find($second->getId())->getUuid()); + } + + public function testImportWithoutArchivedIdentityGetsNewUuid(): void { + $sleeve = $this->mapper->insertImported($this->sleeve(), null); + $this->assertNotNull($sleeve->getUuid()); + $this->assertSame($sleeve->getUuid(), $this->mapper->find($sleeve->getId())->getUuid()); + } + + public function testUniqueIndexAppliesAcrossTables(): void { + $first = $this->mapper->insert($this->sleeve()); + $second = $this->sleeve(2); + $second->setUuid($first->getUuid()); + $this->expectException(Exception::class); + $this->mapper->insert($second); + } + + public function testMultipleHistoricalNullsRemainReadable(): void { + $insert = $this->connectionAdapter->getQueryBuilder(); + $insert->insert('tables_row_sleeves')->values([ + 'table_id' => $insert->createNamedParameter(1), + 'created_by' => $insert->createNamedParameter('alice'), + 'created_at' => $insert->createNamedParameter('2020-01-01 00:00:00'), + 'last_edit_by' => $insert->createNamedParameter('alice'), + 'last_edit_at' => $insert->createNamedParameter('2020-01-01 00:00:00'), + ]); + $insert->executeStatement(); + $first = $insert->getLastInsertId(); + $insert->executeStatement(); + $second = $insert->getLastInsertId(); + $this->assertNull($this->mapper->find($first)->getUuid()); + $this->assertNull($this->mapper->find($second)->getUuid()); + } +} diff --git a/tests/unit/Db/RowSleeveTest.php b/tests/unit/Db/RowSleeveTest.php new file mode 100644 index 0000000000..55ff23956c --- /dev/null +++ b/tests/unit/Db/RowSleeveTest.php @@ -0,0 +1,74 @@ + 17, 'uuid' => null]); + $this->assertNull($sleeve->getUuid()); + $this->assertNull($sleeve->jsonSerialize()['uuid']); + $this->assertSame([], $sleeve->getUpdatedFields()); + } + + public function testHydrationPreservesAssignedUuid(): void { + $sleeve = RowSleeve::fromRow(['id' => 17, 'uuid' => self::UUID]); + $this->assertSame(self::UUID, $sleeve->getUuid()); + $this->assertSame([], $sleeve->getUpdatedFields()); + } + + public function testHydrationDoesNotRejectStoredValues(): void { + $sleeve = RowSleeve::fromRow(['id' => 17, 'uuid' => 'not-a-uuid']); + $this->assertSame('not-a-uuid', $sleeve->getUuid()); + $this->assertSame([], $sleeve->getUpdatedFields()); + } + + public function testAssignmentIsExplicitAndIdempotent(): void { + $sleeve = new RowSleeve(); + $this->assertNull($sleeve->getUuid()); + $sleeve->assignUuid(); + $uuid = $sleeve->getUuid(); + $this->assertMatchesRegularExpression('/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/D', $uuid); + $this->assertArrayHasKey('uuid', $sleeve->getUpdatedFields()); + $sleeve->assignUuid(); + $this->assertSame($uuid, $sleeve->jsonSerialize()['uuid']); + } + + public function testArchiveUuidIsNormalized(): void { + $sleeve = new RowSleeve(); + $sleeve->setUuid(strtoupper(self::UUID)); + $this->assertSame(self::UUID, $sleeve->getUuid()); + } + + /** @dataProvider immutableChanges */ + public function testAssignedIdentityCannotChange(?string $uuid): void { + $sleeve = RowSleeve::fromRow(['uuid' => self::UUID]); + $this->expectException(\InvalidArgumentException::class); + $sleeve->setUuid($uuid); + } + + public static function immutableChanges(): array { + return [[null], ['019f90c5-8576-7f0b-9b14-9bf49b2826c0']]; + } + + /** @dataProvider invalidUuids */ + public function testInvalidUuidFails(string $uuid): void { + $this->expectException(\InvalidArgumentException::class); + (new RowSleeve())->setUuid($uuid); + } + + public static function invalidUuids(): array { + return [[''], ['invalid'], ['019f90c5-8576-4f0b-9b14-9bf49b2826cf'], ['019f90c5-8576-7f0b-0b14-9bf49b2826cf']]; + } +} diff --git a/tests/unit/Service/LegacyRowMapperTest.php b/tests/unit/Service/LegacyRowMapperTest.php index 7822d50556..4933feb744 100644 --- a/tests/unit/Service/LegacyRowMapperTest.php +++ b/tests/unit/Service/LegacyRowMapperTest.php @@ -139,7 +139,8 @@ public function testMigrateLegacyRow() { self::assertTrue($data === $data2); $row2Serialized = $row2->jsonSerialize(); - unset($row2Serialized['dataByAlias']); + $this->assertNull($row2Serialized['uuid']); + unset($row2Serialized['dataByAlias'], $row2Serialized['uuid']); self::assertTrue($legacyRow->jsonSerialize() === $row2Serialized); } } diff --git a/tests/unit/Service/RowServiceUuidTest.php b/tests/unit/Service/RowServiceUuidTest.php new file mode 100644 index 0000000000..9469fb4579 --- /dev/null +++ b/tests/unit/Service/RowServiceUuidTest.php @@ -0,0 +1,90 @@ +rows = $this->createMock(Row2Mapper::class); + $this->service = new RowService(new NullLogger(), 'alice', $this->createMock(PermissionsService::class), $this->createMock(ColumnMapper::class), + $this->createMock(ViewMapper::class), $this->createMock(TableMapper::class), $this->rows, $this->createMock(IEventDispatcher::class), + $this->createMock(ColumnsHelper::class), $this->createMock(ActivityManager::class), $this->createMock(NotificationHelper::class), + $this->createMock(RowVisibilityService::class)); + } + + private function row(): Row2 { + $row = new Row2(); + $row->setId(13); + $row->setTableId(5); + $row->setUuid('019f90c5-8576-7f0b-9b14-9bf49b2826cf'); + $row->setData([['columnId' => 1, 'value' => 'visible'], ['columnId' => 2, 'value' => 'hidden']]); + return $row; + } + + /** @dataProvider archiveIdentities */ + public function testArchiveIdentityGoesThroughSleeveInsertionBoundary(mixed $uuid, ?string $expected, bool $includeUuid = true): void { + $table = new Table(); + $table->setId(5); + $table->setOwnership('alice'); + $this->rows->expects($this->once())->method('importSleeve')->willReturnCallback(function (RowSleeve $sleeve, ?string $archivedUuid) use ($expected): RowSleeve { + $this->assertSame($expected, $archivedUuid); + $this->assertNull($sleeve->getUuid()); + $this->assertSame(5, $sleeve->getTableId()); + $this->assertSame('alice', $sleeve->getCreatedBy()); + $sleeve->setId(99); + return $sleeve; + }); + $archive = ['createdAt' => '2020-01-01 00:00:00', 'lastEditAt' => '2020-01-02 00:00:00']; + if ($includeUuid) { + $archive['uuid'] = $uuid; + } + $this->assertSame(99, $this->service->importRow($table, $archive)); + } + + public static function archiveIdentities(): array { + return [ + 'older archive without UUID' => [null, null, false], + 'no UUID' => [null, null], + 'UUIDv7 in upper case' => ['019F90C5-8576-7F0B-9B14-9BF49B2826CF', '019f90c5-8576-7f0b-9b14-9bf49b2826cf'], + 'not a string' => [3, null], + 'array' => [[], null], + 'empty string' => ['', null], + 'UUIDv4' => ['019f90c5-8576-4f0b-9b14-9bf49b2826cf', null], + ]; + } + + public function testPublicFormatterKeepsUuidAndRemovesPrivateMetadata(): void { + $row = $this->row(); + $result = $this->service->formatRowsForPublicShare([$row])[0]; + $this->assertSame($row->getUuid(), $result['uuid']); + $this->assertArrayNotHasKey('tableId', $result); + $this->assertArrayNotHasKey('createdBy', $result); + $this->assertArrayNotHasKey('lastEditBy', $result); + } +}