Skip to content
Draft
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
3 changes: 3 additions & 0 deletions appinfo/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@
['name' => 'api1#updateColumn', 'url' => '/api/1/columns/{columnId}', 'verb' => 'PUT'],
['name' => 'api1#getColumn', 'url' => '/api/1/columns/{columnId}', 'verb' => 'GET'],
['name' => 'api1#deleteColumn', 'url' => '/api/1/columns/{columnId}', 'verb' => 'DELETE'],
// -> relations
['name' => 'api1#indexTableRelations', 'url' => '/api/1/tables/{tableId}/relations', 'verb' => 'GET'],
['name' => 'api1#indexViewRelations', 'url' => '/api/1/views/{viewId}/relations', 'verb' => 'GET'],
// -> rows
['name' => 'api1#indexTableRowsSimple', 'url' => '/api/1/tables/{tableId}/rows/simple', 'verb' => 'GET'],
['name' => 'api1#indexTableRows', 'url' => '/api/1/tables/{tableId}/rows', 'verb' => 'GET'],
Expand Down
72 changes: 70 additions & 2 deletions lib/Controller/Api1Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
use OCA\Tables\ResponseDefinitions;
use OCA\Tables\Service\ColumnService;
use OCA\Tables\Service\ImportService;
use OCA\Tables\Service\RelationService;
use OCA\Tables\Service\RowService;
use OCA\Tables\Service\ShareService;
use OCA\Tables\Service\TableService;
Expand Down Expand Up @@ -57,6 +58,7 @@ class Api1Controller extends ApiController {
private RowService $rowService;
private ImportService $importService;
private ViewService $viewService;
private RelationService $relationService;
private ViewMapper $viewMapper;
private IL10N $l10N;

Expand All @@ -77,6 +79,7 @@ public function __construct(
RowService $rowService,
ImportService $importService,
ViewService $viewService,
RelationService $relationService,
ViewMapper $viewMapper,
V1Api $v1Api,
LoggerInterface $logger,
Expand All @@ -90,6 +93,7 @@ public function __construct(
$this->rowService = $rowService;
$this->importService = $importService;
$this->viewService = $viewService;
$this->relationService = $relationService;
$this->viewMapper = $viewMapper;
$this->userId = $userId;
$this->v1Api = $v1Api;
Expand Down Expand Up @@ -803,13 +807,77 @@ public function indexViewColumns(int $viewId): DataResponse {
}
}

/**
* Get all relation data for a table
*
* @param int $tableId Table ID
* @return DataResponse<Http::STATUS_OK, array<string, array<string, array{id: int, label: string}>>, array{}>|DataResponse<Http::STATUS_FORBIDDEN|Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
*
* 200: Relation data returned
* 403: No permissions
* 404: Not found
*/
#[NoAdminRequired]
#[NoCSRFRequired]
#[CORS]
#[RequirePermission(permission: Application::PERMISSION_READ, type: Application::NODE_TYPE_TABLE, idParam: 'tableId')]
public function indexTableRelations(int $tableId): DataResponse {
try {
return new DataResponse($this->relationService->getRelationsForTable($tableId));
} catch (PermissionError $e) {
$this->logger->warning('A permission error occurred: ' . $e->getMessage(), ['exception' => $e]);
$message = ['message' => $e->getMessage()];
return new DataResponse($message, Http::STATUS_FORBIDDEN);
} catch (InternalError $e) {
$this->logger->error('An internal error or exception occurred: ' . $e->getMessage(), ['exception' => $e]);
$message = ['message' => $e->getMessage()];
return new DataResponse($message, Http::STATUS_INTERNAL_SERVER_ERROR);
} catch (NotFoundError $e) {
$this->logger->info('A not found error occurred: ' . $e->getMessage(), ['exception' => $e]);
$message = ['message' => $e->getMessage()];
return new DataResponse($message, Http::STATUS_NOT_FOUND);
}
}

/**
* Get all relation data for a view
*
* @param int $viewId View ID
* @return DataResponse<Http::STATUS_OK, array<string, array<string, array{id: int, label: string}>>, array{}>|DataResponse<Http::STATUS_FORBIDDEN|Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
*
* 200: Relation data returned
* 403: No permissions
* 404: Not found
*/
#[NoAdminRequired]
#[NoCSRFRequired]
#[CORS]
#[RequirePermission(permission: Application::PERMISSION_READ, type: Application::NODE_TYPE_VIEW, idParam: 'viewId')]
public function indexViewRelations(int $viewId): DataResponse {
try {
return new DataResponse($this->relationService->getRelationsForView($viewId));
} catch (PermissionError $e) {
$this->logger->warning('A permission error occurred: ' . $e->getMessage(), ['exception' => $e]);
$message = ['message' => $e->getMessage()];
return new DataResponse($message, Http::STATUS_FORBIDDEN);
} catch (InternalError $e) {
$this->logger->error('An internal error or exception occurred: ' . $e->getMessage(), ['exception' => $e]);
$message = ['message' => $e->getMessage()];
return new DataResponse($message, Http::STATUS_INTERNAL_SERVER_ERROR);
} catch (NotFoundError $e) {
$this->logger->info('A not found error occurred: ' . $e->getMessage(), ['exception' => $e]);
$message = ['message' => $e->getMessage()];
return new DataResponse($message, Http::STATUS_NOT_FOUND);
}
}

/**
* Create a column
*
* @param int|null $tableId Table ID
* @param int|null $viewId View ID
* @param string $title Title
* @param 'text'|'number'|'datetime'|'select'|'usergroup' $type Column main type
* @param 'text'|'number'|'datetime'|'select'|'usergroup'|'relation'|'relation_lookup' $type Column main type
* @param string|null $subtype Column sub type
* @param bool $mandatory Is the column mandatory
* @param string|null $description Description
Expand Down Expand Up @@ -1572,7 +1640,7 @@ public function createTableShare(int $tableId, string $receiver, string $receive
*
* @param int $tableId Table ID
* @param string $title Title
* @param 'text'|'number'|'datetime'|'select'|'usergroup' $type Column main type
* @param 'text'|'number'|'datetime'|'select'|'usergroup'|'relation'|'relation_lookup' $type Column main type
* @param string|null $subtype Column sub type
* @param bool $mandatory Is the column mandatory
* @param string|null $description Description
Expand Down
2 changes: 2 additions & 0 deletions lib/Db/Column.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ class Column extends EntitySuper implements JsonSerializable {
public const TYPE_NUMBER = 'number';
public const TYPE_DATETIME = 'datetime';
public const TYPE_USERGROUP = 'usergroup';
public const TYPE_RELATION = 'relation';
public const TYPE_RELATION_LOOKUP = 'relation_lookup';

public const SUBTYPE_DATETIME_DATE = 'date';
public const SUBTYPE_DATETIME_TIME = 'time';
Expand Down
53 changes: 53 additions & 0 deletions lib/Db/Row2Mapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ public function delete(Row2 $row): Row2 {
$this->db->beginTransaction();
try {
foreach ($this->columnsHelper->columns as $columnType) {
if ($this->isVirtualColumn($columnType)) {
continue;
}
$this->getCellMapperFromType($columnType)->deleteAllForRow($row->getId());
}
$this->rowSleeveMapper->deleteById($row->getId());
Expand Down Expand Up @@ -195,6 +198,8 @@ public function findAll(array $showColumnIds, int $tableId, ?int $limit = null,
private function getRows(array $rowIds, array $columnIds): array {
$qb = $this->db->getQueryBuilder();

$columnIds = $this->addRelationColumnIdsForSupplementColumns($columnIds);

$qbSqlForColumnTypes = null;
foreach ($this->columnsHelper->columns as $columnType) {
$qbTmp = $this->db->getQueryBuilder();
Expand All @@ -210,6 +215,9 @@ private function getRows(array $rowIds, array $columnIds): array {
$qbTmp->selectAlias($qbTmp->createFunction('NULL'), 'value_type');
}

if ($this->isVirtualColumn($columnType)) {
continue;
}
$qbTmp
->from('tables_row_cells_' . $columnType)
->where($qb->expr()->in('column_id', $qb->createNamedParameter($columnIds, IQueryBuilder::PARAM_INT_ARRAY, ':columnIds')))
Expand Down Expand Up @@ -798,6 +806,10 @@ private function insertCell(int $rowId, int $columnId, $value, ?string $lastEdit
throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage());
}

if ($this->isVirtualColumn($column->getType())) {
return;
}

// insert new cell
$cellMapper = $this->getCellMapper($column);

Expand Down Expand Up @@ -836,6 +848,10 @@ private function insertCell(int $rowId, int $columnId, $value, ?string $lastEdit
* @throws InternalError
*/
private function updateCell(RowCellSuper $cell, RowCellMapperSuper $mapper, $value, Column $column): void {
if ($this->isVirtualColumn($column->getType())) {
return;
}

$this->getCellMapper($column)->applyDataToEntity($column, $cell, $value);
$this->updateMetaData($cell);
$mapper->updateWrapper($cell);
Expand All @@ -846,6 +862,9 @@ private function updateCell(RowCellSuper $cell, RowCellMapperSuper $mapper, $val
*/
private function insertOrUpdateCell(int $rowId, int $columnId, $value): void {
$column = $this->columnMapper->find($columnId);
if ($this->isVirtualColumn($column->getType())) {
return;
}
$cellMapper = $this->getCellMapper($column);
try {
if ($cellMapper->hasMultipleValues()) {
Expand All @@ -872,6 +891,9 @@ private function getCellMapper(Column $column): RowCellMapperSuper {
}

private function getCellMapperFromType(string $columnType): RowCellMapperSuper {
if ($this->isVirtualColumn($columnType)) {
throw new InternalError('Virtual columns do not have cell mappers');
}
$cellMapperClassName = 'OCA\Tables\Db\RowCell' . ucfirst($columnType) . 'Mapper';
/** @var RowCellMapperSuper $cellMapper */
try {
Expand All @@ -893,6 +915,9 @@ private function getColumnDbParamType(Column $column): int {
* @throws InternalError
*/
public function deleteDataForColumn(Column $column): void {
if ($this->isVirtualColumn($column->getType())) {
return;
}
try {
$this->getCellMapper($column)->deleteAllForColumn($column->getId());
} catch (Exception $e) {
Expand Down Expand Up @@ -961,6 +986,9 @@ private function getFormattedDefaultValue(Column $column) {
case Column::TYPE_USERGROUP:
$defaultValue = $this->getCellMapper($column)->filterValueToQueryParam($column, $column->getUsergroupDefault());
break;
case Column::TYPE_RELATION_LOOKUP:
$defaultValue = null;
break;
}
return $defaultValue;
}
Expand Down Expand Up @@ -988,4 +1016,29 @@ private function sortRowsByIds(array $rows, array $wantedRowIds): array {

return $sortedRows;
}

public function isVirtualColumn(string $columnType): bool {
return $columnType === Column::TYPE_RELATION_LOOKUP;
}

/**
* @param int[] $columnIds
* @return int[]
*/
public function addRelationColumnIdsForSupplementColumns(array $columnIds): array {
$allColumns = $this->columnMapper->findAll($columnIds);
foreach ($allColumns as $column) {
if ($column->getType() !== Column::TYPE_RELATION_LOOKUP) {
continue;
}

$customSettings = $column->getCustomSettingsArray();
$relationColumnId = $customSettings['relationColumnId'] ?? null;
if ($relationColumnId && !in_array($relationColumnId, $columnIds)) {
$columnIds[] = $relationColumnId;
}
}
return $columnIds;
}

}
23 changes: 23 additions & 0 deletions lib/Db/RowCellRelation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Tables\Db;

/** @template-extends RowCellSuper<RowCellRelation> */
class RowCellRelation extends RowCellSuper {
protected ?int $value = null;

public function __construct() {
parent::__construct();
$this->addType('value', 'integer');
}

public function jsonSerialize(): array {
return parent::jsonSerializePreparation($this->value);
}
}
40 changes: 40 additions & 0 deletions lib/Db/RowCellRelationMapper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Tables\Db;

use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IDBConnection;

/** @template-extends RowCellMapperSuper<RowCellRelation, int|null, int|null> */
class RowCellRelationMapper extends RowCellMapperSuper {
protected string $table = 'tables_row_cells_relation';

public function __construct(IDBConnection $db) {
parent::__construct($db, $this->table, RowCellRelation::class);
}

/**
* @inheritDoc
*/
public function hasMultipleValues(): bool {
return false;
}

/**
* @inheritDoc
*/
public function getDbParamType() {
return IQueryBuilder::PARAM_INT;
}

public function formatRowData(Column $column, array $row) {
$value = $row['value'];
return (int)$value;
}
}
5 changes: 5 additions & 0 deletions lib/Helper/ColumnsHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ class ColumnsHelper {
Column::TYPE_DATETIME,
Column::TYPE_SELECTION,
Column::TYPE_USERGROUP,
Column::TYPE_RELATION,
Column::TYPE_RELATION_LOOKUP,
];

public function __construct(
Expand All @@ -30,6 +32,9 @@ public function resolveSearchValue(string $placeholder, string $userId, ?Column
if (str_starts_with($placeholder, '@selection-id-')) {
return substr($placeholder, 14);
}
if (str_starts_with($placeholder, '@relation-id-')) {
return substr($placeholder, 13);
}

$placeholderParts = explode(':', $placeholder, 2);
$placeholderName = ltrim($placeholderParts[0], '@');
Expand Down
46 changes: 46 additions & 0 deletions lib/Migration/Version002001Date20260109000000.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 OCP\DB\ISchemaWrapper;
use OCP\DB\Types;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;

class Version002001Date20260109000000 extends SimpleMigrationStep {
public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
/** @var ISchemaWrapper $schema */
$schema = $schemaClosure();

$changes = $this->createRowValueTable($schema, 'relation', Types::INTEGER);
return $changes;
}

private function createRowValueTable(ISchemaWrapper $schema, string $name, string $type): ?ISchemaWrapper {
if (!$schema->hasTable('tables_row_cells_' . $name)) {
$table = $schema->createTable('tables_row_cells_' . $name);
$table->addColumn('id', Types::INTEGER, [
'autoincrement' => true,
'notnull' => true,
]);
$table->addColumn('column_id', Types::INTEGER, ['notnull' => true]);
$table->addColumn('row_id', Types::INTEGER, ['notnull' => true]);
$table->addColumn('value', $type, ['notnull' => false]);
$table->addColumn('last_edit_at', Types::DATETIME, ['notnull' => true]);
$table->addColumn('last_edit_by', Types::STRING, ['notnull' => true, 'length' => 64]);
$table->addIndex(['column_id', 'row_id']);
$table->addIndex(['column_id', 'value']);
$table->setPrimaryKey(['id']);
return $schema;
}

return null;
}
}
Loading
Loading