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
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
1 change: 1 addition & 0 deletions lib/Constants/ColumnType.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ enum ColumnType: string {
case SELECTION = 'selection';
case DATETIME = 'datetime';
case PEOPLE = 'usergroup';
case RELATION = 'relation';
}
72 changes: 70 additions & 2 deletions lib/Controller/Api1Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,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 @@ -60,6 +61,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 @@ -80,6 +82,7 @@ public function __construct(
RowService $rowService,
ImportService $importService,
ViewService $viewService,
RelationService $relationService,
ViewMapper $viewMapper,
V1Api $v1Api,
LoggerInterface $logger,
Expand All @@ -93,6 +96,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 @@ -815,13 +819,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' $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 @@ -1589,7 +1657,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' $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
5 changes: 5 additions & 0 deletions lib/Db/Column.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ 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 SUBTYPE_DATETIME_DATE = 'date';
public const SUBTYPE_DATETIME_TIME = 'time';
Expand All @@ -114,6 +115,10 @@ class Column extends EntitySuper implements JsonSerializable {

public const META_ID_TITLE = 'id';

public const RELATION_TYPE = 'relationType';
public const RELATION_TARGET_ID = 'targetId';
public const RELATION_LABEL_COLUMN = 'labelColumn';

protected ?string $title = null;
protected ?int $tableId = null;
protected ?string $createdBy = null;
Expand Down
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;
Copy link
Contributor

Choose a reason for hiding this comment

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

int(null) is 0. Is 0 a valid id? Could this cause troube?

}
}
4 changes: 4 additions & 0 deletions lib/Helper/ColumnsHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ class ColumnsHelper {
Column::TYPE_DATETIME,
Column::TYPE_SELECTION,
Column::TYPE_USERGROUP,
Column::TYPE_RELATION,
];

/**
Expand All @@ -37,6 +38,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;
}
}
98 changes: 98 additions & 0 deletions lib/Service/ColumnTypes/RelationBusiness.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
<?php

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

namespace OCA\Tables\Service\ColumnTypes;

use OCA\Tables\Db\Column;
use OCA\Tables\Errors\BadRequestError;
use OCA\Tables\Service\RelationService;
use Psr\Log\LoggerInterface;

class RelationBusiness extends SuperBusiness implements IColumnTypeBusiness {

public function __construct(
LoggerInterface $logger,
private RelationService $relationService,
) {
parent::__construct($logger);
}

/**
* @param mixed $value (array|string|null)
* @param Column|null $column
* @return string
*/
public function parseValue($value, ?Column $column = null): string {
if (!$column) {
$this->logger->warning('No column given, but expected on ' . __FUNCTION__ . ' within ' . __CLASS__, ['exception' => new \Exception()]);
return '';
}

$relationData = $this->relationService->getRelationData($column);
// try to find value by label
$matchingRelation = array_filter($relationData, fn (array $relation) => $relation['label'] === $value);
if (!empty($matchingRelation)) {
return json_encode(reset($matchingRelation)['id']);
}

// if not found, try to find by id
if (is_numeric($value) && isset($relationData[(int)$value])) {
return json_encode($value);
}

return '';
}

/**
* @param mixed $value (array|string|null)
* @param Column|null $column
* @return bool
*/
public function canBeParsed($value, ?Column $column = null): bool {
if (!$column) {
$this->logger->warning('No column given, but expected on ' . __FUNCTION__ . ' within ' . __CLASS__, ['exception' => new \Exception()]);
return false;
}
if ($value === null) {
return true;
}

$relationData = $this->relationService->getRelationData($column);
// try to find value by label
$matchingRelation = array_filter($relationData, fn (array $relation) => $relation['label'] === $value);
if (!empty($matchingRelation)) {
return true;
}
// if not found, try to find by id
if (is_numeric($value) && isset($relationData[(int)$value])) {
return true;
}

return false;
}

public function validateValue(mixed $value, Column $column, string $userId, int $tableId, ?int $rowId): void {
if ($value === null || $value === '') {
return;
}
// Validate that the value exists in the target table/view
$relationData = $this->relationService->getRelationData($column);

// Try to find value by label first
$matchingRelation = array_filter($relationData, fn (array $relation) => $relation['label'] === $value);
if (!empty($matchingRelation)) {
return;
}

// If not found by label, try to find by id
if (is_numeric($value) && isset($relationData[(int)$value])) {
return;
}

throw new BadRequestError('Relation value does not exist in the target table/view');
}
}
Loading
Loading