Skip to content
Open
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion appinfo/info.xml
Original file line number Diff line number Diff line change
Expand Up @@ -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.

]]></description>
<version>2.5.0-dev.0</version>
<version>2.5.0-dev.1</version>
<licence>AGPL-3.0-or-later</licence>
<author>Nextcloud GmbH and Nextcloud contributors</author>
<namespace>Tables</namespace>
Expand Down
102 changes: 102 additions & 0 deletions lib/BackgroundJob/BackfillRowUuids.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Tables\BackgroundJob;

use OCA\Tables\AppInfo\Application;
use OCA\Tables\Vendor\Symfony\Component\Uid\Uuid;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\IJobList;
use OCP\BackgroundJob\TimedJob;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IAppConfig;
use OCP\IDBConnection;
use Psr\Log\LoggerInterface;

class BackfillRowUuids extends TimedJob {

private const BATCH_SIZE = 500;
private const TIME_BUDGET = 5;
private const SQLITE_BATCH_PAUSE_MICROSECONDS = 10_000;
private const CURSOR_KEY = 'row_uuid_backfill_cursor';

public function __construct(
ITimeFactory $time,
private readonly IDBConnection $connection,
private readonly IAppConfig $config,
private readonly IJobList $jobList,
private readonly LoggerInterface $logger,
) {
parent::__construct($time);
$this->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<int> $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;
}
}
}
12 changes: 6 additions & 6 deletions lib/Controller/RowOCSController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down
10 changes: 10 additions & 0 deletions lib/Db/Row2.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
}
Expand Down Expand Up @@ -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,
Expand Down
7 changes: 7 additions & 0 deletions lib/Db/Row2Mapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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());
Expand Down Expand Up @@ -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());
Expand Down
24 changes: 24 additions & 0 deletions lib/Db/RowSleeve.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;
Expand All @@ -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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why only v7 UUIDs accepted?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They can be sorted while still being random. Other versions cannot guarantee that.

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,
Expand Down
37 changes: 37 additions & 0 deletions lib/Db/RowSleeveMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand All @@ -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[]
Expand All @@ -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',
Expand Down
46 changes: 46 additions & 0 deletions lib/Migration/Version2500Date20261120000000.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Tables\Migration;

use Closure;
use OCA\Tables\BackgroundJob\BackfillRowUuids;
use OCP\BackgroundJob\IJobList;
use OCP\DB\ISchemaWrapper;
use OCP\DB\Types;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;

class Version2500Date20261120000000 extends SimpleMigrationStep {
public function __construct(
private readonly IJobList $jobList,
) {
}

public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
/** @var ISchemaWrapper $schema */
$schema = $schemaClosure();
$table = $schema->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);
}
}
2 changes: 2 additions & 0 deletions lib/ResponseDefinitions.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@
*
* @psalm-type TablesRow = array{
* id: int,
* uuid: ?string,
* tableId: int,
* createdBy: string,
* createdAt: string,
Expand All @@ -98,6 +99,7 @@
*
* @psalm-type TablesPublicRow = array{
* id: int,
* uuid: ?string,
* createdAt: string,
* lastEditAt: string,
* data: ?array{columnId: int, value: mixed},
Expand Down
Loading