pagination: joins

This commit is contained in:
2023-01-09 14:21:11 +01:00
parent d115d8b970
commit 6dcd7031bb
14 changed files with 424 additions and 69 deletions

View File

@@ -32,11 +32,14 @@ namespace Core\API\Groups {
use Core\API\Parameter\StringType;
use Core\API\Traits\Pagination;
use Core\Driver\SQL\Column\Column;
use Core\Driver\SQL\Condition\Compare;
use Core\Driver\SQL\Expression\Alias;
use Core\Driver\SQL\Expression\Count;
use Core\Driver\SQL\Join\InnerJoin;
use Core\Objects\Context;
use Core\Objects\DatabaseEntity\Controller\NMRelation;
use Core\Objects\DatabaseEntity\Group;
use Core\Objects\DatabaseEntity\User;
class Fetch extends GroupsAPI {
@@ -98,13 +101,48 @@ namespace Core\API\Groups {
return $this->createError("Group not found");
} else {
$this->result["group"] = $group->jsonSerialize();
$this->result["group"]["members"] = $group->getMembers($sql);
}
return true;
}
}
class GetMembers extends GroupsAPI {
use Pagination;
public function __construct(Context $context, bool $externalCall = false) {
$paginationParams = self::getPaginationParameters(["id", "name", "fullName"]);
$paginationParams["id"] = new Parameter("id", Parameter::TYPE_INT);
parent::__construct($context, $externalCall, $paginationParams);
}
protected function _execute(): bool {
$sql = $this->context->getSQL();
$nmTable = NMRelation::buildTableName(User::class, Group::class);
$condition = new Compare("group_id", $this->getParam("id"));
$nmJoin = new InnerJoin($nmTable, "$nmTable.user_id", "User.id");
if (!$this->initPagination($sql, User::class, $condition, 100, [$nmJoin])) {
return false;
}
$userQuery = $this->createPaginationQuery($sql, null, [$nmJoin]);
$users = $userQuery->execute();
if ($users !== false && $users !== null) {
$this->result["members"] = [];
foreach ($users as $user) {
$this->result["users"][] = $user->jsonSerialize(["id", "name", "fullName", "profilePicture"]);
}
} else {
return $this->createError("Error fetching group members: " . $sql->getLastError());
}
return true;
}
}
class Create extends GroupsAPI {
public function __construct(Context $context, $externalCall = false) {
parent::__construct($context, $externalCall, array(
@@ -160,17 +198,92 @@ namespace Core\API\Groups {
$sql = $this->context->getSQL();
$group = Group::find($sql, $id);
if ($group === false) {
return $this->createError("Error fetching group: " . $sql->getLastError());
} else if ($group === null) {
return $this->createError("This group does not exist.");
} else {
$this->success = ($group->delete($sql) !== FALSE);
$this->lastError = $sql->getLastError();
return $this->success;
}
}
}
$this->success = ($group !== FALSE);
$this->lastError = $sql->getLastError();
class AddMember extends GroupsAPI {
public function __construct(Context $context, bool $externalCall = false) {
parent::__construct($context, $externalCall, [
new Parameter("id", Parameter::TYPE_INT),
new Parameter("userId", Parameter::TYPE_INT)
]);
}
if ($this->success && $group === null) {
protected function _execute(): bool {
$sql = $this->context->getSQL();
$groupId = $this->getParam("id");
$userId = $this->getParam("userId");
$group = Group::find($sql, $groupId);
if ($group === false) {
return $this->createError("Error fetching group: " . $sql->getLastError());
} else if ($group === null) {
return $this->createError("This group does not exist.");
}
$this->success = ($group->delete($sql) !== FALSE);
$this->lastError = $sql->getLastError();
return $this->success;
$user = User::find($sql, $userId, true);
if ($user === false) {
return $this->createError("Error fetching user: " . $sql->getLastError());
} else if ($user === null) {
return $this->createError("This user does not exist.");
} else if (isset($user->getGroups()[$groupId])) {
return $this->createError("This user is already member of this group.");
}
$user->groups[$groupId] = $group;
$this->success = $user->save($sql, ["groups"], true);
if (!$this->success) {
return $this->createError("Error saving user: " . $sql->getLastError());
} else {
return true;
}
}
}
class RemoveMember extends GroupsAPI {
public function __construct(Context $context, bool $externalCall = false) {
parent::__construct($context, $externalCall, [
new Parameter("id", Parameter::TYPE_INT),
new Parameter("userId", Parameter::TYPE_INT)
]);
}
protected function _execute(): bool {
$sql = $this->context->getSQL();
$groupId = $this->getParam("id");
$userId = $this->getParam("userId");
$group = Group::find($sql, $groupId);
if ($group === false) {
return $this->createError("Error fetching group: " . $sql->getLastError());
} else if ($group === null) {
return $this->createError("This group does not exist.");
}
$user = User::find($sql, $userId, true);
if ($user === false) {
return $this->createError("Error fetching user: " . $sql->getLastError());
} else if ($user === null) {
return $this->createError("This user does not exist.");
} else if (!isset($user->getGroups()[$groupId])) {
return $this->createError("This user is not member of this group.");
}
unset($user->groups[$groupId]);
$this->success = $user->save($sql, ["groups"], true);
if (!$this->success) {
return $this->createError("Error saving user: " . $sql->getLastError());
} else {
return true;
}
}
}
}

View File

@@ -92,7 +92,7 @@ namespace Core\API\Language {
$sql = $this->context->getSQL();
$currentUser = $this->context->getUser();
$currentUser->language = $this->language;
$this->success = $currentUser->save($sql, ["language_id"]);
$this->success = $currentUser->save($sql, ["language"]);
$this->lastError = $sql->getLastError();
return $this->success;
}

View File

@@ -148,7 +148,7 @@ namespace Core\API\TFA {
$this->lastError = $sql->getLastError();
if ($this->success) {
$currentUser->setTwoFactorToken($twoFactorToken);
$this->success = $currentUser->save($sql, ["two_factor_token_id"]);
$this->success = $currentUser->save($sql, ["twoFactorToken"]);
$this->lastError = $sql->getLastError();
}

View File

@@ -21,14 +21,14 @@ trait Pagination {
];
}
function initPagination(SQL $sql, string $class, ?Condition $condition = null, int $maxPageSize = 100): bool {
function initPagination(SQL $sql, string $class, ?Condition $condition = null, int $maxPageSize = 100, ?array $joins = null): bool {
$this->paginationClass = $class;
$this->paginationCondition = $condition;
if (!$this->validateParameters($maxPageSize)) {
return false;
}
$this->entityCount = call_user_func("$this->paginationClass::count", $sql, $condition);
$this->entityCount = call_user_func("$this->paginationClass::count", $sql, $condition, $joins);
if ($this->entityCount === false) {
return $this->createError("Error fetching $this->paginationClass::count: " . $sql->getLastError());
}
@@ -60,7 +60,7 @@ trait Pagination {
return true;
}
function createPaginationQuery(SQL $sql, array $additionalValues = []): DatabaseEntityQuery {
function createPaginationQuery(SQL $sql, ?array $additionalValues = null, ?array $joins = null): DatabaseEntityQuery {
$page = $this->getParam("page");
$count = $this->getParam("count");
$orderBy = $this->getParam("orderBy");
@@ -76,12 +76,18 @@ trait Pagination {
$entityQuery->where($this->paginationCondition);
}
if (!empty($additionalValues)) {
if ($additionalValues) {
foreach ($additionalValues as $additionalValue) {
$entityQuery->addCustomValue($additionalValue);
}
}
if ($joins) {
foreach ($joins as $join) {
$entityQuery->addJoin($join);
}
}
if ($orderBy) {
$handler = $baseQuery->getHandler();
$baseTable = $handler->getTableName();

View File

@@ -1236,7 +1236,7 @@ namespace Core\API\User {
if ($this->success) {
$currentUser->gpgKey = $gpgKey;
if ($currentUser->save($sql, ["gpg_key_id"])) {
if ($currentUser->save($sql, ["gpgKey"])) {
$this->result["gpg"] = $gpgKey->jsonSerialize();
} else {
return $this->createError("Error updating user details: " . $sql->getLastError());
@@ -1490,7 +1490,7 @@ namespace Core\API\User {
$sql = $this->context->getSQL();
$currentUser->profilePicture = $fileName;
if ($currentUser->save($sql, ["profile_picture"])) {
if ($currentUser->save($sql, ["profilePicture"])) {
$this->result["profilePicture"] = $fileName;
} else {
return $this->createError("Error updating user details: " . $sql->getLastError());
@@ -1517,7 +1517,7 @@ namespace Core\API\User {
}
$currentUser->profilePicture = null;
if (!$currentUser->save($sql, ["profile_picture"])) {
if (!$currentUser->save($sql, ["profilePicture"])) {
return $this->createError("Error updating user details: " . $sql->getLastError());
}

View File

@@ -24,7 +24,7 @@ class ApiKey extends DatabaseEntity {
public function refresh(SQL $sql, int $days): bool {
$this->validUntil = (new \DateTime())->modify("+$days days");
return $this->save($sql, ["valid_until"]);
return $this->save($sql, ["validUntil"]);
}
public function revoke(SQL $sql): bool {

View File

@@ -161,10 +161,9 @@ abstract class DatabaseEntity implements ArrayAccess, JsonSerializable {
}
}
// TODO: rather take property names here instead of $columns? and translate then using DatabaseEntityHandler::columns[$propertyName]
public function save(SQL $sql, ?array $columns = null, bool $saveNM = false): bool {
public function save(SQL $sql, ?array $properties = null, bool $saveNM = false): bool {
$handler = self::getHandler($sql);
$res = $handler->insertOrUpdate($this, $columns, $saveNM);
$res = $handler->insertOrUpdate($this, $properties, $saveNM);
if ($res === false) {
return false;
} else if ($this->id === null) {
@@ -233,7 +232,7 @@ abstract class DatabaseEntity implements ArrayAccess, JsonSerializable {
return $this->id;
}
public static function count(SQL $sql, ?Condition $condition = null): int|bool {
public static function count(SQL $sql, ?Condition $condition = null, ?array $joins = []): int|bool {
$handler = self::getHandler($sql);
$query = $sql->select(new Count())
->from($handler->getTableName());
@@ -242,6 +241,12 @@ abstract class DatabaseEntity implements ArrayAccess, JsonSerializable {
$query->where($condition);
}
if ($joins) {
foreach ($joins as $join) {
$query->addJoin($join);
}
}
$res = $query->execute();
if (!empty($res)) {

View File

@@ -366,7 +366,7 @@ class DatabaseEntityHandler implements Persistable {
}
}
public function updateNM(DatabaseEntity $entity): bool {
public function updateNM(DatabaseEntity $entity, ?array $properties = null): bool {
if (empty($this->nmRelations)) {
return true;
}
@@ -381,12 +381,18 @@ class DatabaseEntityHandler implements Persistable {
// delete from n:m table if no longer exists
$doDelete = true;
$deleteStatement = $this->sql->delete($nmTable)
->whereEq($thisIdColumn, $entity->getId());
->whereEq($thisIdColumn, $entity->getId()); // this condition is important
if (!empty($dataColumns)) {
$conditions = [];
$doDelete = false;
foreach ($dataColumns[$thisTableName] as $propertyName => $columnName) {
if ($properties !== null && !in_array($propertyName, $properties)) {
continue;
}
$property = $this->properties[$propertyName];
$entityIds = array_keys($property->getValue($entity));
if (!empty($entityIds)) {
@@ -399,24 +405,31 @@ class DatabaseEntityHandler implements Persistable {
if (!empty($conditions)) {
$deleteStatement->where(new CondOr(...$conditions));
$doDelete = true;
}
} else {
$property = next($nmRelation->getProperties($this));
$entityIds = array_keys($property->getValue($entity));
if (!empty($entityIds)) {
$deleteStatement->where(
new CondNot(new CondIn(new Column($refIdColumn), $entityIds))
);
if ($properties !== null && !in_array($property->getName(), $properties)) {
$doDelete = false;
} else {
$entityIds = array_keys($property->getValue($entity));
if (!empty($entityIds)) {
$deleteStatement->where(
new CondNot(new CondIn(new Column($refIdColumn), $entityIds))
);
}
}
}
$deleteStatement->execute();
if ($doDelete) {
$deleteStatement->execute();
}
}
return $this->insertNM($entity, true);
return $this->insertNM($entity, true, $properties);
}
public function insertNM(DatabaseEntity $entity, bool $ignoreExisting = true): bool {
public function insertNM(DatabaseEntity $entity, bool $ignoreExisting = true, ?array $properties = null): bool {
if (empty($this->nmRelations)) {
return true;
@@ -446,7 +459,12 @@ class DatabaseEntityHandler implements Persistable {
]));
}
$doInsert = false;
foreach ($nmRelation->getProperties($this) as $property) {
if ($properties !== null || !in_array($property->getName(), $properties)) {
continue;
}
$property->setAccessible(true);
$relEntities = $property->getValue($entity);
foreach ($relEntities as $relEntity) {
@@ -457,10 +475,13 @@ class DatabaseEntityHandler implements Persistable {
}
}
$statement->addRow(...$nmRow);
$doInsert = true;
}
}
$success = $statement->execute() && $success;
if ($doInsert) {
$success = $statement->execute() && $success;
}
}
return $success;
@@ -656,10 +677,10 @@ class DatabaseEntityHandler implements Persistable {
return $query;
}
private function prepareRow(DatabaseEntity $entity, string $action, ?array $columns = null): bool|array {
private function prepareRow(DatabaseEntity $entity, string $action, ?array $properties = null): bool|array {
$row = [];
foreach ($this->columns as $propertyName => $column) {
if ($columns && !in_array($column->getName(), $columns)) {
if ($properties !== null && !in_array($propertyName, $properties)) {
continue;
}
@@ -690,8 +711,8 @@ class DatabaseEntityHandler implements Persistable {
return $row;
}
public function update(DatabaseEntity $entity, ?array $columns = null, bool $saveNM = false) {
$row = $this->prepareRow($entity, "update", $columns);
public function update(DatabaseEntity $entity, ?array $properties = null, bool $saveNM = false) {
$row = $this->prepareRow($entity, "update", $properties);
if ($row === false) {
return false;
}
@@ -704,9 +725,9 @@ class DatabaseEntityHandler implements Persistable {
$query->set($columnName, $value);
}
$res = $query->execute();
$res = empty($row) ? true : $query->execute();
if ($res && $saveNM) {
$res = $this->updateNM($entity);
$res = $this->updateNM($entity, $properties);
}
return $res;
@@ -742,12 +763,12 @@ class DatabaseEntityHandler implements Persistable {
}
}
public function insertOrUpdate(DatabaseEntity $entity, ?array $columns = null, bool $saveNM = false) {
public function insertOrUpdate(DatabaseEntity $entity, ?array $properties = null, bool $saveNM = false) {
$id = $entity->getId();
if ($id === null) {
return $this->insert($entity);
} else {
return $this->update($entity, $columns, $saveNM);
return $this->update($entity, $properties, $saveNM);
}
}

View File

@@ -99,7 +99,7 @@ class MailQueueItem extends DatabaseEntity {
$this->status = self::STATUS_SUCCESS;
}
$this->save($context->getSQL(), ["status", "retry_count", "next_try", "error_message"]);
$this->save($context->getSQL(), ["status", "retryCount", "nextTry", "errorMessage"]);
return $success;
}
}

View File

@@ -98,7 +98,7 @@ class User extends DatabaseEntity {
public function update(SQL $sql): bool {
$this->lastOnline = new \DateTime();
return $this->save($sql, ["last_online", "language_id"]);
return $this->save($sql, ["lastOnline", "language"]);
}
public function setTwoFactorToken(TwoFactorToken $twoFactorToken) {

View File

@@ -58,7 +58,7 @@ class UserToken extends DatabaseEntity {
public function updateDurability(SQL $sql, int $validHours): bool {
$this->validUntil = (new \DateTime())->modify("+$validHours HOURS");
return $this->save($sql, ["valid_until"]);
return $this->save($sql, ["validUntil"]);
}
public function getToken(): string {