Initial commit

This commit is contained in:
root
2026-01-19 17:44:46 +01:00
commit 823af8b11d
8721 changed files with 1130846 additions and 0 deletions

View File

@@ -0,0 +1,54 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\ORM\Repository\Deprecation;
use Espo\ORM\Entity;
/**
* @internal
* @template TEntity of Entity
*/
trait RDBRepositoryDeprecationTrait
{
/**
* Get an entity. If ID is NULL, a new entity is returned.
*
* @deprecated Use `getById` and `getNew`.
* @todo Remove in v10.0.
*/
public function get(?string $id = null): ?Entity
{
if (is_null($id)) {
return $this->getNew();
}
return $this->getById($id);
}
}

View File

@@ -0,0 +1,66 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\ORM\Repository;
use Espo\ORM\Entity;
use Espo\ORM\Query\Select;
class EmptyHookMediator implements HookMediator
{
public function beforeSave(Entity $entity, array $options): void
{}
public function afterSave(Entity $entity, array $options): void
{}
public function beforeRemove(Entity $entity, array $options): void
{}
public function afterRemove(Entity $entity, array $options): void
{}
public function beforeRelate(Entity $entity, string $relationName, Entity $foreignEntity, ?array $columnData, array $options): void
{}
public function afterRelate(Entity $entity, string $relationName, Entity $foreignEntity, ?array $columnData, array $options): void
{}
public function beforeUnrelate(Entity $entity, string $relationName, Entity $foreignEntity, array $options): void
{}
public function afterUnrelate(Entity $entity, string $relationName, Entity $foreignEntity, array $options): void
{}
public function beforeMassRelate(Entity $entity, string $relationName, Select $query, array $options): void
{}
public function afterMassRelate(Entity $entity, string $relationName, Select $query, array $options): void
{}
}

View File

@@ -0,0 +1,100 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\ORM\Repository;
use Espo\ORM\Entity;
use Espo\ORM\Query\Select;
interface HookMediator
{
/**
* @param array<string, mixed> $options
*/
public function beforeSave(Entity $entity, array $options): void;
/**
* @param array<string, mixed> $options
*/
public function afterSave(Entity $entity, array $options): void;
/**
* @param array<string, mixed> $options
*/
public function beforeRemove(Entity $entity, array $options): void;
/**
* @param array<string, mixed> $options
*/
public function afterRemove(Entity $entity, array $options): void;
/**
* @param array<string, mixed>|null $columnData Role values.
* @param array<string, mixed> $options
*/
public function beforeRelate(
Entity $entity,
string $relationName,
Entity $foreignEntity,
?array $columnData,
array $options
): void;
/**
* @param array<string, mixed>|null $columnData Role values.
* @param array<string, mixed> $options
*/
public function afterRelate(
Entity $entity,
string $relationName,
Entity $foreignEntity,
?array $columnData,
array $options
): void;
/**
* @param array<string, mixed> $options
*/
public function beforeUnrelate(Entity $entity, string $relationName, Entity $foreignEntity, array $options): void;
/**
* @param array<string, mixed> $options
*/
public function afterUnrelate(Entity $entity, string $relationName, Entity $foreignEntity, array $options): void;
/**
* @param array<string, mixed> $options
*/
public function beforeMassRelate(Entity $entity, string $relationName, Select $query, array $options): void;
/**
* @param array<string, mixed> $options
*/
public function afterMassRelate(Entity $entity, string $relationName, Select $query, array $options): void;
}

View File

@@ -0,0 +1,42 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\ORM\Repository\Option;
use Espo\ORM\Repository\Option\Traits\Options;
/**
* Mass-relate options.
*
* Immutable.
*/
class MassRelateOptions
{
use Options;
}

View File

@@ -0,0 +1,42 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\ORM\Repository\Option;
use Espo\ORM\Repository\Option\Traits\Options;
/**
* Relate options.
*
* Immutable.
*/
class RelateOptions
{
use Options;
}

View File

@@ -0,0 +1,42 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\ORM\Repository\Option;
use Espo\ORM\Repository\Option\Traits\Options;
/**
* Remove options.
*
* Immutable.
*/
class RemoveOptions
{
use Options;
}

View File

@@ -0,0 +1,38 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\ORM\Repository\Option;
class SaveOption
{
public const SKIP_ALL = 'skipAll';
public const KEEP_NEW = 'keepNew';
public const KEEP_DIRTY = 'keepDirty';
public const KEEP_RELATIONS = 'keepRelations';
}

View File

@@ -0,0 +1,42 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\ORM\Repository\Option;
use Espo\ORM\Repository\Option\Traits\Options;
/**
* Save options.
*
* Immutable.
*/
class SaveOptions
{
use Options;
}

View File

@@ -0,0 +1,100 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\ORM\Repository\Option\Traits;
trait Options
{
/** @var array<string, mixed> */
private array $options;
/**
* @param array<string, mixed> $options
*/
private function __construct(array $options)
{
$this->options = $options;
}
/**
* Create from an associative array.
*
* @param array<string, mixed> $options
*/
public static function fromAssoc(array $options): self
{
return new self($options);
}
/**
* Get an option value. Returns `null` if not set.
*/
public function get(string $option): mixed
{
return $this->options[$option] ?? null;
}
/**
* Whether an option is set.
*/
public function has(string $option): bool
{
return array_key_exists($option, $this->options);
}
/**
* Clone with an option value.
*/
public function with(string $option, mixed $value): self
{
$obj = clone $this;
$obj->options[$option] = $value;
return $obj;
}
/**
* Clone with an option removed.
*/
public function without(string $option): self
{
$obj = clone $this;
unset($obj->options[$option]);
return $obj;
}
/**
* @return array<string, mixed>
*/
public function toAssoc(): array
{
return $this->options;
}
}

View File

@@ -0,0 +1,42 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\ORM\Repository\Option;
use Espo\ORM\Repository\Option\Traits\Options;
/**
* Unrelate options.
*
* Immutable.
*/
class UnrelateOptions
{
use Options;
}

View File

@@ -0,0 +1,737 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\ORM\Repository;
use Espo\ORM\Defs\Params\RelationParam;
use Espo\ORM\Entity;
use Espo\ORM\EntityCollection;
use Espo\ORM\EntityManager;
use Espo\ORM\BaseEntity;
use Espo\ORM\Name\Attribute;
use Espo\ORM\Query\Select;
use Espo\ORM\Query\Part\WhereItem;
use Espo\ORM\Query\Part\Selection;
use Espo\ORM\Query\Part\Join;
use Espo\ORM\Mapper\RDBMapper;
use Espo\ORM\Query\Part\Expression;
use Espo\ORM\Query\Part\Order;
use Espo\ORM\Repository\RDBRelationSelectBuilder as Builder;
use Espo\ORM\SthCollection;
use LogicException;
use RuntimeException;
/**
* An access point for a specific relation of a record.
*
* @template TEntity of Entity = Entity
*/
class RDBRelation
{
private string $entityType;
private ?string $foreignEntityType = null;
private string $relationName;
private ?string $relationType = null;
private bool $noBuilder = false;
public function __construct(
private EntityManager $entityManager,
private Entity $entity,
string $relationName,
private HookMediator $hookMediator
) {
if (!$entity->hasId()) {
throw new RuntimeException("Can't use an entity w/o ID.");
}
if (!$entity->hasRelation($relationName)) {
throw new RuntimeException("Entity does not have a relation '$relationName'.");
}
$this->relationName = $relationName;
$this->relationType = $entity->getRelationType($relationName);
$this->entityType = $entity->getEntityType();
if ($entity instanceof BaseEntity) {
$this->foreignEntityType = $entity->getRelationParam($relationName, RelationParam::ENTITY);
} else {
$this->foreignEntityType = $this->entityManager
->getDefs()
->getEntity($this->entityType)
->getRelation($relationName)
->getForeignEntityType();
}
if ($this->isBelongsToParentType()) {
$this->noBuilder = true;
}
}
/**
* Create a select builder.
*
* @return Builder<TEntity>
*
* @since 9.2.5
*/
public function createBuilder(): Builder
{
return $this->createSelectBuilder();
}
/**
* Create a select builder.
*
* @return Builder<TEntity>
*/
private function createSelectBuilder(?Select $query = null): Builder
{
if ($this->noBuilder) {
throw new RuntimeException("Can't use query builder for the '$this->relationType' relation type.");
}
/** @var Builder<TEntity> */
return new Builder($this->entityManager, $this->entity, $this->relationName, $query);
}
/**
* Clone a query.
*
* @return Builder<TEntity>
*/
public function clone(Select $query): Builder
{
if ($this->noBuilder) {
throw new RuntimeException("Can't use clone for the '$this->relationType' relation type.");
}
if ($query->getFrom() !== $this->foreignEntityType) {
throw new RuntimeException("Passed query doesn't match the entity type.");
}
/** @var Builder<TEntity> */
return $this->createSelectBuilder($query);
}
private function isBelongsToParentType(): bool
{
return $this->relationType === Entity::BELONGS_TO_PARENT;
}
private function getMapper(): RDBMapper
{
$mapper = $this->entityManager->getMapper();
/** @noinspection PhpConditionAlreadyCheckedInspection */
if (!$mapper instanceof RDBMapper) {
throw new LogicException();
}
return $mapper;
}
/**
* Find related records.
*
* @return EntityCollection<TEntity>|SthCollection<TEntity>
*/
public function find(): EntityCollection|SthCollection
{
if ($this->isBelongsToParentType()) {
/** @var EntityCollection<TEntity> $collection */
$collection = $this->entityManager->getCollectionFactory()->create();
$entity = $this->getMapper()->selectRelated($this->entity, $this->relationName);
if ($entity) {
$collection[] = $entity;
}
$collection->setAsFetched();
return $collection;
}
return $this->createSelectBuilder()->find();
}
/**
* Find a first record.
*
* @return TEntity
*/
public function findOne(): ?Entity
{
if ($this->isBelongsToParentType()) {
$entity = $this->getMapper()->selectRelated($this->entity, $this->relationName);
if ($entity && !$entity instanceof Entity) {
throw new LogicException();
}
/** @var TEntity */
return $entity;
}
$collection = $this
->sth()
->limit(0, 1)
->find();
foreach ($collection as $entity) {
return $entity;
}
return null;
}
/**
* Get a number of related records.
*/
public function count(): int
{
return $this->createSelectBuilder()->count();
}
/**
* Add JOIN.
*
* @param Join|string $target
* A relation name or table. A relation name should be in camelCase, a table in CamelCase.
* @param string|null $alias An alias.
* @param WhereItem|array<string|int, mixed>|null $conditions Join conditions.
* @return Builder<TEntity>
*/
public function join($target, ?string $alias = null, $conditions = null): Builder
{
return $this->createSelectBuilder()->join($target, $alias, $conditions);
}
/**
* Add LEFT JOIN.
*
* @param Join|string $target
* A relation name or table. A relation name should be in camelCase, a table in CamelCase.
* @param string|null $alias An alias.
* @param WhereItem|array<string|int, mixed>|null $conditions Join conditions.
* @return Builder<TEntity>
*/
public function leftJoin($target, ?string $alias = null, $conditions = null): Builder
{
return $this->createSelectBuilder()->leftJoin($target, $alias, $conditions);
}
/**
* Set DISTINCT parameter.
*
* @return Builder<TEntity>
*/
public function distinct(): Builder
{
return $this->createSelectBuilder()->distinct();
}
/**
* Set to return STH collection. Recommended for fetching large number of records.
*
* @return Builder<TEntity>
*/
public function sth(): Builder
{
return $this->createSelectBuilder()->sth();
}
/**
* Add a WHERE clause.
*
* Usage options:
* * `where(WhereItem $clause)`
* * `where(array $clause)`
* * `where(string $key, string $value)`
*
* @param WhereItem|array<string|int, mixed>|string $clause A key or where clause.
* @param array<int, mixed>|scalar|null $value A value. Should be omitted if the first argument is not string.
* @return Builder<TEntity>
*/
public function where($clause = [], $value = null): Builder
{
return $this->createSelectBuilder()->where($clause, $value);
}
/**
* Add a HAVING clause.
*
* Usage options:
* * `having(WhereItem $clause)`
* * `having(array $clause)`
* * `having(string $key, string $value)`
*
* @param WhereItem|array<string|int, mixed>|string $clause A key or where clause.
* @param array<int, mixed>|string|null $value A value. Should be omitted if the first argument is not string.
* @return Builder<TEntity>
*/
public function having($clause = [], $value = null): Builder
{
return $this->createSelectBuilder()->having($clause, $value);
}
/**
* Apply ORDER. Passing an array will override previously set items.
* Passing non-array will append an item,
*
* Usage options:
* * `order(Order $expression)
* * `order([$expr1, $expr2, ...])
* * `order(string $expression, string $direction)
*
* @param Order|Order[]|Expression|string|array<int, string[]>|string[] $orderBy
* An attribute to order by or an array or order items.
* Passing an array will reset a previously set order.
* @param (Order::ASC|Order::DESC)|bool|null $direction A direction.
* @return Builder<TEntity>
*/
public function order($orderBy = Attribute::ID, $direction = null): Builder
{
return $this->createSelectBuilder()->order($orderBy, $direction);
}
/**
* Apply OFFSET and LIMIT.
*
* @return Builder<TEntity>
*/
public function limit(?int $offset = null, ?int $limit = null): Builder
{
return $this->createSelectBuilder()->limit($offset, $limit);
}
/**
* Specify SELECT. Columns and expressions to be selected. If not called, then
* all entity attributes will be selected. Passing an array will reset
* previously set items. Passing a SelectExpression|Expression|string will append the item.
*
* Usage options:
* * `select(SelectExpression $expression)`
* * `select([$expr1, $expr2, ...])`
* * `select(string $expression, string $alias)`
*
* @param Selection|Selection[]|Expression|Expression[]|string[]|string|array<int, string[]|string> $select
* An array of expressions or one expression.
* @param string|null $alias An alias. Actual if the first parameter is not an array.
* @return Builder<TEntity>
*/
public function select($select = [], ?string $alias = null): Builder
{
return $this->createSelectBuilder()->select($select, $alias);
}
/**
* Specify GROUP BY.
* Passing an array will reset previously set items.
* Passing a string|Expression will append an item.
*
* Usage options:
* * `groupBy(Expression|string $expression)`
* * `groupBy([$expr1, $expr2, ...])`
*
* @param Expression|Expression[]|string|string[] $groupBy
* @return Builder<TEntity>
*/
public function group($groupBy): Builder
{
return $this->createSelectBuilder()->group($groupBy);
}
/**
* @deprecated Use `group` method.
* @param Expression|Expression[]|string|string[] $groupBy
* @return Builder<TEntity>
*/
public function groupBy($groupBy): Builder
{
return $this->group($groupBy);
}
/**
* Apply middle table conditions for a many-to-many relationship.
*
* Usage example:
* `->columnsWhere(['column' => $value])`
*
* @param WhereItem|array<string|int, mixed> $clause Where clause.
* @return Builder<TEntity>
*/
public function columnsWhere($clause): Builder
{
return $this->createSelectBuilder()->columnsWhere($clause);
}
private function processCheckForeignEntity(Entity $entity): void
{
if ($this->foreignEntityType && $this->foreignEntityType !== $entity->getEntityType()) {
throw new RuntimeException("Entity type doesn't match an entity type of the relation.");
}
if (!$entity->hasId()) {
throw new RuntimeException("Can't use an entity w/o ID.");
}
}
/**
* Whether related with an entity.
*
* @throws RuntimeException
*/
public function isRelated(Entity $entity): bool
{
if (!$entity->hasId()) {
throw new RuntimeException("Can't use an entity w/o ID.");
}
if ($this->isBelongsToParentType()) {
return $this->isRelatedBelongsToParent($entity);
}
if ($this->relationType === Entity::BELONGS_TO) {
return $this->isRelatedBelongsTo($entity);
}
$this->processCheckForeignEntity($entity);
return (bool) $this->createSelectBuilder()
->select([Attribute::ID])
->where([Attribute::ID => $entity->getId()])
->findOne();
}
/**
* Whether related with another entity. An entity is specified by an ID.
* Does not work with 'belongsToParent' relations.
*/
public function isRelatedById(string $id): bool
{
if ($this->isBelongsToParentType()) {
throw new LogicException("Can't use isRelatedById for 'belongsToParent'.");
}
return (bool) $this->createSelectBuilder()
->select([Attribute::ID])
->where([Attribute::ID => $id])
->findOne();
}
private function isRelatedBelongsToParent(Entity $entity): bool
{
$fromEntity = $this->entity;
$idAttribute = $this->relationName . 'Id';
$typeAttribute = $this->relationName . 'Type';
if (!$fromEntity->has($idAttribute) || !$fromEntity->has($typeAttribute)) {
$fromEntity = $this->entityManager->getEntityById($fromEntity->getEntityType(), $fromEntity->getId());
}
if (!$fromEntity) {
return false;
}
return
$fromEntity->get($idAttribute) === $entity->getId() &&
$fromEntity->get($typeAttribute) === $entity->getEntityType();
}
private function isRelatedBelongsTo(Entity $entity): bool
{
$fromEntity = $this->entity;
$idAttribute = $this->relationName . 'Id';
if (!$fromEntity->has($idAttribute)) {
$fromEntity = $this->entityManager->getEntityById($fromEntity->getEntityType(), $fromEntity->getId());
}
if (!$fromEntity) {
return false;
}
return $fromEntity->get($idAttribute) === $entity->getId();
}
/**
* Relate with an entity by ID.
*
* @param array<string, mixed>|null $columnData Role values.
* @param array<string, mixed> $options
*/
public function relateById(string $id, ?array $columnData = null, array $options = []): void
{
if ($this->isBelongsToParentType()) {
throw new RuntimeException("Can't relate 'belongToParent'.");
}
if ($id === '') {
throw new RuntimeException();
}
/** @var string $foreignEntityType */
$foreignEntityType = $this->foreignEntityType;
$seed = $this->entityManager->getEntityFactory()->create($foreignEntityType);
$seed->set(Attribute::ID, $id);
$seed->setAsFetched();
if ($seed instanceof BaseEntity) {
$seed->setAsPartiallyLoaded();
}
$this->relate($seed, $columnData, $options);
}
/**
* Unrelate from an entity by ID.
*
* @param array<string, mixed> $options
*/
public function unrelateById(string $id, array $options = []): void
{
if ($this->isBelongsToParentType()) {
throw new RuntimeException("Can't unrelate 'belongToParent'.");
}
if ($id === '') {
throw new RuntimeException();
}
/** @var string $foreignEntityType */
$foreignEntityType = $this->foreignEntityType;
$seed = $this->entityManager->getEntityFactory()->create($foreignEntityType);
$seed->set(Attribute::ID, $id);
$seed->setAsFetched();
if ($seed instanceof BaseEntity) {
$seed->setAsPartiallyLoaded();
}
$this->unrelate($seed, $options);
}
/**
* Update relationship columns by ID. For many-to-many relationships.
*
* @param array<string, mixed> $columnData Role values.
*/
public function updateColumnsById(string $id, array $columnData): void
{
if ($this->isBelongsToParentType()) {
throw new RuntimeException("Can't update columns by ID 'belongToParent'.");
}
if ($id === '') {
throw new RuntimeException();
}
/** @var string $foreignEntityType */
$foreignEntityType = $this->foreignEntityType;
$seed = $this->entityManager->getEntityFactory()->create($foreignEntityType);
$seed->set(Attribute::ID, $id);
$seed->setAsFetched();
if ($seed instanceof BaseEntity) {
$seed->setAsPartiallyLoaded();
}
$this->updateColumns($seed, $columnData);
}
/**
* Relate with an entity.
*
* @param array<string, mixed>|null $columnData Role values.
* @param array<string, mixed> $options
*/
public function relate(Entity $entity, ?array $columnData = null, array $options = []): void
{
$this->processCheckForeignEntity($entity);
$this->beforeRelate($entity, $columnData, $options);
$result = $this->getMapper()->relate($this->entity, $this->relationName, $entity, $columnData);
if (!$result) {
return;
}
$this->afterRelate($entity, $columnData, $options);
}
/**
* Unrelate from an entity.
*
* @param array<string, mixed> $options
*/
public function unrelate(Entity $entity, array $options = []): void
{
$this->processCheckForeignEntity($entity);
$this->beforeUnrelate($entity, $options);
$this->getMapper()->unrelate($this->entity, $this->relationName, $entity);
$this->afterUnrelate($entity, $options);
}
/**
* Mass-relate.
*
* @param array<string, mixed> $options
*/
public function massRelate(Select $query, array $options = []): void
{
if ($this->isBelongsToParentType()) {
throw new RuntimeException("Can't mass relate 'belongToParent'.");
}
if ($query->getFrom() !== $this->foreignEntityType) {
throw new RuntimeException("Passed query doesn't match foreign entity type.");
}
$this->beforeMassRelate($query, $options);
$this->getMapper()->massRelate($this->entity, $this->relationName, $query);
$this->afterMassRelate($query, $options);
}
/**
* Update relationship columns. For many-to-many relationships.
*
* @param array<string, mixed> $columnData Role values.
*/
public function updateColumns(Entity $entity, array $columnData): void
{
$this->processCheckForeignEntity($entity);
if ($this->relationType !== Entity::MANY_MANY) {
throw new RuntimeException("Can't update not many-to-many relation.");
}
if (!$entity->hasId()) {
throw new RuntimeException("Entity w/o ID.");
}
$id = $entity->getId();
$this->getMapper()->updateRelationColumns($this->entity, $this->relationName, $id, $columnData);
}
/**
* Get a relationship column value. For many-to-many relationships.
*
* @return string|int|float|bool|null
*/
public function getColumn(Entity $entity, string $column)
{
$this->processCheckForeignEntity($entity);
if ($this->relationType !== Entity::MANY_MANY) {
throw new RuntimeException("Can't get a column of not many-to-many relation.");
}
if (!$entity->hasId()) {
throw new RuntimeException("Entity w/o ID.");
}
$id = $entity->getId();
return $this->getMapper()->getRelationColumn($this->entity, $this->relationName, $id, $column);
}
/**
* Get a relationship column value by a foreign record ID. For many-to-many relationships.
*/
public function getColumnById(string $id, string $column): string|int|float|bool|null
{
if ($this->relationType !== Entity::MANY_MANY) {
throw new RuntimeException("Can't get a column of not many-to-many relation.");
}
return $this->getMapper()->getRelationColumn($this->entity, $this->relationName, $id, $column);
}
/**
* @param array<string, mixed>|null $columnData Role values.
* @param array<string, mixed> $options
*/
private function beforeRelate(Entity $entity, ?array $columnData, array $options): void
{
$this->hookMediator->beforeRelate($this->entity, $this->relationName, $entity, $columnData, $options);
}
/**
* @param array<string, mixed>|null $columnData Role values.
* @param array<string, mixed> $options
*/
private function afterRelate(Entity $entity, ?array $columnData, array $options): void
{
$this->hookMediator->afterRelate($this->entity, $this->relationName, $entity, $columnData, $options);
}
/**
* @param array<string, mixed> $options
*/
private function beforeUnrelate(Entity $entity, array $options): void
{
$this->hookMediator->beforeUnrelate($this->entity, $this->relationName, $entity, $options);
}
/**
* @param array<string, mixed> $options
*/
private function afterUnrelate(Entity $entity, array $options): void
{
$this->hookMediator->afterUnrelate($this->entity, $this->relationName, $entity, $options);
}
/**
* @param array<string, mixed> $options
*/
private function beforeMassRelate(Select $query, array $options): void
{
$this->hookMediator->beforeMassRelate($this->entity, $this->relationName, $query, $options);
}
/**
* @param array<string, mixed> $options
*/
private function afterMassRelate(Select $query, array $options): void
{
$this->hookMediator->afterMassRelate($this->entity, $this->relationName, $query, $options);
}
}

View File

@@ -0,0 +1,547 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\ORM\Repository;
use Espo\ORM\Collection;
use Espo\ORM\Defs\Params\RelationParam;
use Espo\ORM\EntityCollection;
use Espo\ORM\Mapper\RDBMapper;
use Espo\ORM\Name\Attribute;
use Espo\ORM\SthCollection;
use Espo\ORM\Entity;
use Espo\ORM\EntityManager;
use Espo\ORM\BaseEntity;
use Espo\ORM\Query\Select;
use Espo\ORM\Query\SelectBuilder;
use Espo\ORM\Query\Part\WhereItem;
use Espo\ORM\Query\Part\Selection;
use Espo\ORM\Query\Part\Join;
use Espo\ORM\Query\Part\Expression;
use Espo\ORM\Query\Part\Order;
use LogicException;
use RuntimeException;
use InvalidArgumentException;
/**
* Builds select parameters for related records for RDB repository.
*
* @template TEntity of Entity = Entity
*/
class RDBRelationSelectBuilder
{
private string $foreignEntityType;
private ?string $relationType;
private SelectBuilder $builder;
private ?string $middleTableAlias = null;
private bool $returnSthCollection = false;
public function __construct(
private EntityManager $entityManager,
private Entity $entity,
private string $relationName,
?Select $query = null
) {
$this->relationType = $entity->getRelationType($relationName);
$entityType = $entity->getEntityType();
if ($entity instanceof BaseEntity) {
$this->foreignEntityType = $entity->getRelationParam($relationName, RelationParam::ENTITY);
} else {
$this->foreignEntityType = $this->entityManager
->getDefs()
->getEntity($entityType)
->getRelation($relationName)
->getForeignEntityType();
}
$this->builder = $query ?
$this->cloneQueryToBuilder($query) :
$this->createSelectBuilder()->from($this->foreignEntityType);
}
private function cloneQueryToBuilder(Select $query): SelectBuilder
{
$where = $query->getWhere();
if ($where === null) {
return $this->createSelectBuilder()->clone($query);
}
$rawQuery = $query->getRaw();
$rawQuery['whereClause'] = $this->applyRelationAliasToWhereClause($where->getRaw());
$newQuery = Select::fromRaw($rawQuery);
return $this->createSelectBuilder()->clone($newQuery);
}
private function createSelectBuilder(): SelectBuilder
{
return new SelectBuilder();
}
private function getMapper(): RDBMapper
{
$mapper = $this->entityManager->getMapper();
/** @noinspection PhpConditionAlreadyCheckedInspection */
if (!$mapper instanceof RDBMapper) {
throw new LogicException();
}
return $mapper;
}
/**
* Apply middle table conditions for a many-to-many relationship.
*
* Usage example:
* `->columnsWhere(['column' => $value])`
*
* @param WhereItem|array<int|string, mixed> $clause Where clause.
* @return self<TEntity>
*/
public function columnsWhere($clause): self
{
if ($this->relationType !== Entity::MANY_MANY) {
throw new RuntimeException("Can't add columns where for not many-to-many relationship.");
}
if ($clause instanceof WhereItem) {
$clause = $clause->getRaw();
}
if (!is_array($clause)) {
throw new InvalidArgumentException();
}
$transformedWhere = $this->applyMiddleAliasToWhere($clause);
$this->where($transformedWhere);
return $this;
}
/**
* @param array<string|int, mixed> $where
* @return array<string|int, mixed>
*/
private function applyMiddleAliasToWhere(array $where): array
{
$transformedWhere = [];
$middleName = lcfirst($this->getRelationParam(RelationParam::RELATION_NAME));
foreach ($where as $key => $value) {
$transformedKey = $key;
$transformedValue = $value;
if (
is_string($key) &&
strlen($key) &&
!str_contains($key, '.') &&
$key[0] === strtolower($key[0])
) {
$transformedKey = $middleName . '.' . $key;
}
if (is_array($value)) {
$transformedValue = $this->applyMiddleAliasToWhere($value);
}
$transformedWhere[$transformedKey] = $transformedValue;
}
return $transformedWhere;
}
/**
* Find related records by a criteria.
*
* @return EntityCollection<TEntity>|SthCollection<TEntity>
*/
public function find(): EntityCollection|SthCollection
{
$query = $this->builder->build();
$related = $this->getMapper()->selectRelated($this->entity, $this->relationName, $query);
if ($related instanceof Collection) {
/** @var Collection<TEntity> $related */
/** @var EntityCollection<TEntity>|SthCollection<TEntity> */
return $this->handleReturnCollection($related);
}
/** @var EntityCollection<TEntity> $collection */
$collection = $this->entityManager->getCollectionFactory()->create($this->foreignEntityType);
$collection->setAsFetched();
if ($related instanceof Entity) {
$collection[] = $related;
}
return $collection;
}
/**
* Find a first related records by a criteria.
*
* @return TEntity
*/
public function findOne(): ?Entity
{
$queryTemp = $this->builder->build();
$returnSthCollection = $this->returnSthCollection;
$offset = $queryTemp->getOffset();
$limit = $queryTemp->getLimit();
$collection = $this
->sth()
->limit(0, 1)
->find();
$this->returnSthCollection = $returnSthCollection;
$this->limit($offset, $limit);
foreach ($collection as $entity) {
return $entity;
}
return null;
}
/**
* Get a number of related records that meet criteria.
*/
public function count(): int
{
$query = $this->builder->build();
return $this->getMapper()->countRelated($this->entity, $this->relationName, $query);
}
/**
* Add JOIN.
*
* @param Join|string $target
* A relation name or table. A relation name should be in camelCase, a table in CamelCase.
* @param string|null $alias An alias.
* @param WhereItem|array<string|int, mixed>|null $conditions Join conditions.
* @return self<TEntity>
*/
public function join($target, ?string $alias = null, $conditions = null): self
{
$this->builder->join($target, $alias, $conditions);
return $this;
}
/**
* Add LEFT JOIN.
*
* @param Join|string $target
* A relation name or table. A relation name should be in camelCase, a table in CamelCase.
* @param string|null $alias An alias.
* @param WhereItem|array<int|string, mixed>|null $conditions Join conditions.
* @return self<TEntity>
*/
public function leftJoin($target, ?string $alias = null, $conditions = null): self
{
$this->builder->leftJoin($target, $alias, $conditions);
return $this;
}
/**
* Set DISTINCT parameter.
*
* @return self<TEntity>
*/
public function distinct(): self
{
$this->builder->distinct();
return $this;
}
/**
* Return STH collection. Recommended for fetching large number of records.
*
* @return self<TEntity>
*/
public function sth(): self
{
$this->returnSthCollection = true;
return $this;
}
/**
* Add a WHERE clause.
*
* Usage options:
* * `where(WhereItem $clause)`
* * `where(array $clause)`
* * `where(string $key, string $value)`
*
* @param WhereItem|array<int|string, mixed>|string $clause A key or where clause.
* @param array<int, mixed>|scalar|null $value A value. Should be omitted if the first argument is not string.
* @return self<TEntity>
*/
public function where($clause = [], $value = null): self
{
if ($this->isManyMany()) {
if ($clause instanceof WhereItem) {
$clause = $this->applyRelationAliasToWhereClause($clause->getRaw());
} else if (is_string($clause)) {
$clause = $this->applyRelationAliasToWhereClauseKey($clause);
} else if (is_array($clause)) {
$clause = $this->applyRelationAliasToWhereClause($clause);
}
}
$this->builder->where($clause, $value);
return $this;
}
/**
* Add a HAVING clause.
*
* Usage options:
* * `having(WhereItem $clause)`
* * `having(array $clause)`
* * `having(string $key, string $value)`
*
* @param WhereItem|array<int|string, mixed>|string $clause A key or where clause.
* @param array<int, mixed>|string|null $value A value. Should be omitted if the first argument is not string.
* @return self<TEntity>
*/
public function having($clause = [], $value = null): self
{
$this->builder->having($clause, $value);
return $this;
}
/**
* Apply ORDER. Passing an array will override previously set items.
* Passing non-array will append an item,
*
* Usage options:
* * `order(Order $expression)
* * `order([$expr1, $expr2, ...])
* * `order(string $expression, string $direction)
*
* @param Order|Order[]|Expression|string|array<int, string[]>|string[] $orderBy
* An attribute to order by or an array or order items.
* Passing an array will reset a previously set order.
* @param (Order::ASC|Order::DESC)|bool|null $direction Select::ORDER_ASC|Select::ORDER_DESC.
* @return self<TEntity>
*/
public function order($orderBy = Attribute::ID, $direction = null): self
{
$this->builder->order($orderBy, $direction);
return $this;
}
/**
* Apply OFFSET and LIMIT.
*
* @return self<TEntity>
*/
public function limit(?int $offset = null, ?int $limit = null): self
{
$this->builder->limit($offset, $limit);
return $this;
}
/**
* Specify SELECT. Columns and expressions to be selected. If not called, then
* all entity attributes will be selected. Passing an array will reset
* previously set items. Passing a SelectExpression|Expression|string will append the item.
*
* Usage options:
* * `select(SelectExpression $expression)`
* * `select([$expr1, $expr2, ...])`
* * `select(string $expression, string $alias)`
*
* @param Selection|Selection[]|Expression|Expression[]|string[]|string|array<int, string[]|string> $select
* An array of expressions or one expression.
* @param string|null $alias An alias. Actual if the first parameter is not an array.
* @return self<TEntity>
*/
public function select($select, ?string $alias = null): self
{
$this->builder->select($select, $alias);
return $this;
}
/**
* Specify GROUP BY.
* Passing an array will reset previously set items.
* Passing a string|Expression will append an item.
*
* Usage options:
* * `groupBy(Expression|string $expression)`
* * `groupBy([$expr1, $expr2, ...])`
*
* @param Expression|Expression[]|string|string[] $groupBy
* @return self<TEntity>
*/
public function group($groupBy): self
{
$this->builder->group($groupBy);
return $this;
}
/**
* @deprecated Use `group` method.
* @param Expression|Expression[]|string|string[] $groupBy
* @return self<TEntity>
*/
public function groupBy($groupBy): self
{
return $this->group($groupBy);
}
private function getMiddleTableAlias(): ?string
{
if (!$this->isManyMany()) {
return null;
}
if (!$this->middleTableAlias) {
$middleName = $this->getRelationParam(RelationParam::RELATION_NAME);
if (!$middleName) {
throw new RuntimeException("No relation name.");
}
$this->middleTableAlias = lcfirst($middleName);
}
return $this->middleTableAlias;
}
private function applyRelationAliasToWhereClauseKey(string $item): string
{
if (!$this->isManyMany()) {
return $item;
}
$alias = $this->getMiddleTableAlias();
return str_replace('@relation.', $alias . '.', $item);
}
/**
* @param array<int|string, mixed> $where
* @return array<int|string, mixed>
*/
private function applyRelationAliasToWhereClause(array $where): array
{
if (!$this->isManyMany()) {
return $where;
}
$transformedWhere = [];
foreach ($where as $key => $value) {
$transformedKey = $key;
$transformedValue = $value;
if (is_string($key)) {
$transformedKey = $this->applyRelationAliasToWhereClauseKey($key);
}
if (is_array($value)) {
$transformedValue = $this->applyRelationAliasToWhereClause($value);
}
$transformedWhere[$transformedKey] = $transformedValue;
}
return $transformedWhere;
}
private function isManyMany(): bool
{
return $this->relationType === Entity::MANY_MANY;
}
/**
* @param Collection<TEntity> $collection
* @return Collection<TEntity>
*/
private function handleReturnCollection(Collection $collection): Collection
{
if (!$collection instanceof SthCollection) {
return $collection;
}
if ($this->returnSthCollection) {
return $collection;
}
/** @var Collection<TEntity> */
return $this->entityManager->getCollectionFactory()->createFromSthCollection($collection);
}
/**
* @return mixed
* @noinspection PhpSameParameterValueInspection
*/
private function getRelationParam(string $param)
{
if ($this->entity instanceof BaseEntity) {
return $this->entity->getRelationParam($this->relationName, $param);
}
$entityDefs = $this->entityManager
->getDefs()
->getEntity($this->entity->getEntityType());
if (!$entityDefs->hasRelation($this->relationName)) {
return null;
}
return $entityDefs->getRelation($this->relationName)->getParam($param);
}
}

View File

@@ -0,0 +1,789 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\ORM\Repository;
use Espo\Core\ORM\Repository\Option\SaveContext;
use Espo\ORM\Defs\RelationDefs;
use Espo\ORM\EntityCollection;
use Espo\ORM\EntityManager;
use Espo\ORM\EntityFactory;
use Espo\ORM\Name\Attribute;
use Espo\ORM\Relation\Relations;
use Espo\ORM\Relation\RelationsMap;
use Espo\ORM\Repository\Deprecation\RDBRepositoryDeprecationTrait;
use Espo\ORM\Repository\Option\SaveOption;
use Espo\ORM\SthCollection;
use Espo\ORM\BaseEntity;
use Espo\ORM\Entity;
use Espo\ORM\Mapper\RDBMapper;
use Espo\ORM\Query\Select;
use Espo\ORM\Query\Part\WhereItem;
use Espo\ORM\Query\Part\Selection;
use Espo\ORM\Query\Part\Join;
use Espo\ORM\Query\Part\Expression;
use Espo\ORM\Query\Part\Order;
use Espo\ORM\Mapper\BaseMapper;
use Espo\ORM\Type\RelationType;
use RuntimeException;
/**
* A relation database repository.
*
* @template TEntity of Entity
* @implements Repository<TEntity>
*/
class RDBRepository implements Repository
{
/** @phpstan-use RDBRepositoryDeprecationTrait<TEntity> */
use RDBRepositoryDeprecationTrait;
protected HookMediator $hookMediator;
protected RDBTransactionManager $transactionManager;
public function __construct(
protected string $entityType,
protected EntityManager $entityManager,
protected EntityFactory $entityFactory,
?HookMediator $hookMediator = null,
private ?RelationsMap $relationsMap = null,
) {
$this->hookMediator = $hookMediator ?? (new EmptyHookMediator());
$this->transactionManager = new RDBTransactionManager($entityManager->getTransactionManager());
}
public function getEntityType(): string
{
return $this->entityType;
}
/**
* Get a new entity.
*
* @return TEntity
*/
public function getNew(): Entity
{
$entity = $this->entityFactory->create($this->entityType);
if ($entity instanceof BaseEntity) {
$entity->populateDefaults();
}
/** @var TEntity */
return $entity;
}
/**
* Fetch an entity by ID.
*
* @return ?TEntity
*/
public function getById(string $id): ?Entity
{
$selectQuery = $this->entityManager
->getQueryBuilder()
->select()
->from($this->entityType)
->where([Attribute::ID => $id])
->build();
/** @var ?TEntity $entity */
$entity = $this->getMapper()->selectOne($selectQuery);
return $entity;
}
protected function processCheckEntity(Entity $entity): void
{
if ($entity->getEntityType() !== $this->entityType) {
throw new RuntimeException("An entity type doesn't match the repository.");
}
}
/**
* @param TEntity $entity
* @param array<string, mixed> $options
*/
public function save(Entity $entity, array $options = []): void
{
if (!isset($options[SaveContext::NAME])) {
$options[SaveContext::NAME] = new SaveContext();
}
$this->processCheckEntity($entity);
if ($entity instanceof BaseEntity) {
$entity->setAsBeingSaved();
}
if (empty($options['skipBeforeSave']) && empty($options[SaveOption::SKIP_ALL])) {
$this->beforeSave($entity, $options);
}
$isSaved = false;
if ($entity instanceof BaseEntity) {
$isSaved = $entity->isSaved();
}
if ($entity->isNew() && !$isSaved) {
$this->getMapper()->insert($entity);
} else {
$this->getMapper()->update($entity);
}
$this->saveSetRelations($entity);
if ($entity instanceof BaseEntity) {
$entity->setAsSaved();
}
if (
empty($options['skipAfterSave']) &&
empty($options[SaveOption::SKIP_ALL])
) {
$this->afterSave($entity, $options);
}
if ($entity->isNew()) {
if (empty($options[SaveOption::KEEP_NEW])) {
$entity->setAsNotNew();
$entity->updateFetchedValues();
}
} else if (empty($options[SaveOption::KEEP_DIRTY])) {
$entity->updateFetchedValues();
}
if ($entity instanceof BaseEntity) {
$entity->setAsNotBeingSaved();
}
if (empty($options[SaveOption::KEEP_RELATIONS])) {
$this->relationsMap?->get($entity)?->resetAll();
}
}
/**
* Restore a record flagged as deleted.
*/
public function restoreDeleted(string $id): void
{
$mapper = $this->getMapper();
if (!$mapper instanceof BaseMapper) {
throw new RuntimeException("Not supported 'restoreDeleted'.");
}
$mapper->restoreDeleted($this->entityType, $id);
}
/**
* Get an access point for a specific relation of a record.
*
* @param TEntity $entity
* @return RDBRelation<Entity>
*/
public function getRelation(Entity $entity, string $relationName): RDBRelation
{
return new RDBRelation($this->entityManager, $entity, $relationName, $this->hookMediator);
}
/**
* Remove a record (mark as deleted).
*/
public function remove(Entity $entity, array $options = []): void
{
$this->processCheckEntity($entity);
$this->beforeRemove($entity, $options);
$this->getMapper()->delete($entity);
$this->afterRemove($entity, $options);
}
/**
* Find records.
*
* @return EntityCollection<TEntity>|SthCollection<TEntity>
*/
public function find(): EntityCollection|SthCollection
{
return $this->createBuilder()->find();
}
/**
* Find one record.
*/
public function findOne(): ?Entity
{
$collection = $this->limit(0, 1)->find();
foreach ($collection as $entity) {
return $entity;
}
return null;
}
/**
* Find records by an SQL query.
*
* @return SthCollection<TEntity>
*/
public function findBySql(string $sql): SthCollection
{
$mapper = $this->getMapper();
if (!$mapper instanceof BaseMapper) {
throw new RuntimeException("Not supported 'findBySql'.");
}
/** @var SthCollection<TEntity> */
return $mapper->selectBySql($this->entityType, $sql);
}
/**
* Get a number of records.
*/
public function count(): int
{
return $this->createBuilder()->count();
}
/**
* Get a max value.
*
* @return int|float
*/
public function max(string $attribute)
{
return $this->createBuilder()->max($attribute);
}
/**
* Get a min value.
*
* @return int|float
*/
public function min(string $attribute)
{
return $this->createBuilder()->min($attribute);
}
/**
* Get a sum value.
*
* @return int|float
*/
public function sum(string $attribute)
{
return $this->createBuilder()->sum($attribute);
}
/**
* Clone an existing query for a further modification and usage by 'find' or 'count' methods.
*
* @return RDBSelectBuilder<TEntity>
*/
public function clone(Select $query): RDBSelectBuilder
{
if ($this->entityType !== $query->getFrom()) {
throw new RuntimeException("Can't clone a query of a different entity type.");
}
/** @var RDBSelectBuilder<TEntity> $builder */
$builder = new RDBSelectBuilder($this->entityManager, $this->entityType, $query);
return $builder;
}
/**
* Add JOIN.
*
* @param Join|string $target
* A relation name or table. A relation name should be in camelCase, a table in CamelCase.
* @param string|null $alias An alias.
* @param WhereItem|array<scalar, mixed>|null $conditions Join conditions.
* @return RDBSelectBuilder<TEntity>
*/
public function join($target, ?string $alias = null, $conditions = null): RDBSelectBuilder
{
return $this->createBuilder()->join($target, $alias, $conditions);
}
/**
* Add LEFT JOIN.
*
* @param Join|string $target
* A relation name or table. A relation name should be in camelCase, a table in CamelCase.
* @param string|null $alias An alias.
* @param WhereItem|array<scalar, mixed>|null $conditions Join conditions.
* @return RDBSelectBuilder<TEntity>
*/
public function leftJoin($target, ?string $alias = null, $conditions = null): RDBSelectBuilder
{
return $this->createBuilder()->leftJoin($target, $alias, $conditions);
}
/**
* Set DISTINCT parameter.
*
* @return RDBSelectBuilder<TEntity>
*/
public function distinct(): RDBSelectBuilder
{
return $this->createBuilder()->distinct();
}
/**
* Lock selected rows. To be used within a transaction.
*
* @return RDBSelectBuilder<TEntity>
*/
public function forUpdate(): RDBSelectBuilder
{
return $this->createBuilder()->forUpdate();
}
/**
* Set to return STH collection. Recommended fetching large number of records.
*
* @return RDBSelectBuilder<TEntity>
*/
public function sth(): RDBSelectBuilder
{
return $this->createBuilder()->sth();
}
/**
* Add a WHERE clause.
*
* Usage options:
* * `where(WhereItem $clause)`
* * `where(array $clause)`
* * `where(string $key, string $value)`
*
* @param WhereItem|array<scalar, mixed>|string $clause A key or where clause.
* @param mixed[]|scalar|null $value A value. Should be omitted if the first argument is not string.
* @return RDBSelectBuilder<TEntity>
*/
public function where($clause = [], $value = null): RDBSelectBuilder
{
return $this->createBuilder()->where($clause, $value);
}
/**
* Add a HAVING clause.
*
* Usage options:
* * `having(WhereItem $clause)`
* * `having(array $clause)`
* * `having(string $key, string $value)`
*
* @param WhereItem|array<scalar, mixed>|string $clause A key or where clause.
* @param mixed[]|scalar|null $value A value. Should be omitted if the first argument is not string.
* @return RDBSelectBuilder<TEntity>
*/
public function having($clause = [], $value = null): RDBSelectBuilder
{
return $this->createBuilder()->having($clause, $value);
}
/**
* Apply ORDER. Passing an array will override previously set items.
* Passing non-array will append an item,
*
* Usage options:
* * `order(Order $expression)
* * `order([$expr1, $expr2, ...])
* * `order(string $expression, string $direction)
*
* @param Order|Order[]|Expression|string|array<int, string[]>|string[] $orderBy
* An attribute to order by or an array or order items.
* Passing an array will reset a previously set order.
* @param (Order::ASC|Order::DESC)|bool|null $direction A direction.
* @return RDBSelectBuilder<TEntity>
*/
public function order($orderBy = Attribute::ID, $direction = null): RDBSelectBuilder
{
return $this->createBuilder()->order($orderBy, $direction);
}
/**
* Apply OFFSET and LIMIT.
*
* @return RDBSelectBuilder<TEntity>
*/
public function limit(?int $offset = null, ?int $limit = null): RDBSelectBuilder
{
return $this->createBuilder()->limit($offset, $limit);
}
/**
* Specify SELECT. Columns and expressions to be selected. If not called, then
* all entity attributes will be selected. Passing an array will reset
* previously set items. Passing a SelectExpression|Expression|string will append the item.
*
* Usage options:
* * `select(SelectExpression $expression)`
* * `select([$expr1, $expr2, ...])`
* * `select(string $expression, string $alias)`
*
* @param Selection|Selection[]|Expression|Expression[]|string[]|string|array<int, string[]|string> $select
* An array of expressions or one expression.
* @param string|null $alias An alias. Actual if the first parameter is not an array.
* @return RDBSelectBuilder<TEntity>
*/
public function select($select = [], ?string $alias = null): RDBSelectBuilder
{
return $this->createBuilder()->select($select, $alias);
}
/**
* Specify GROUP BY.
* Passing an array will reset previously set items.
* Passing a string|Expression will append an item.
*
* Usage options:
* * `groupBy(Expression|string $expression)`
* * `groupBy([$expr1, $expr2, ...])`
*
* @param Expression|Expression[]|string|string[] $groupBy
* @return RDBSelectBuilder<TEntity>
*/
public function group($groupBy): RDBSelectBuilder
{
return $this->createBuilder()->group($groupBy);
}
/**
* Create a select builder.
*
* @return RDBSelectBuilder<TEntity>
*
* @since 9.2.5
*/
public function createBuilder(): RDBSelectBuilder
{
/** @var RDBSelectBuilder<TEntity> $builder */
$builder = new RDBSelectBuilder($this->entityManager, $this->entityType);
return $builder;
}
/**
* Create a select builder.
*
* @return RDBSelectBuilder<TEntity>
*
* @deprecated Since v9.2.5. Use `createBuilder` instead.
* @todo Remove in v10.0.
*/
protected function createSelectBuilder(): RDBSelectBuilder
{
return $this->createBuilder();
}
/**
* Use hooks instead.
*
* @param array<string, mixed> $options
* @return void
*/
protected function beforeSave(Entity $entity, array $options = [])
{
$this->hookMediator->beforeSave($entity, $options);
}
/**
* @deprecated Use hooks instead.
*
* @param array<string, mixed> $options
* @return void
*/
protected function afterSave(Entity $entity, array $options = [])
{
$this->hookMediator->afterSave($entity, $options);
}
/**
* @deprecated Use hooks instead.
*
* @param array<string, mixed> $options
* @return void
*/
protected function beforeRemove(Entity $entity, array $options = [])
{
$this->hookMediator->beforeRemove($entity, $options);
}
/**
* @deprecated Use hooks instead.
*
* @param array<string, mixed> $options
* @return void
*/
protected function afterRemove(Entity $entity, array $options = [])
{
$this->hookMediator->afterRemove($entity, $options);
}
protected function getMapper(): RDBMapper
{
$mapper = $this->entityManager->getMapper();
if (!$mapper instanceof RDBMapper) {
throw new RuntimeException("Mapper is not RDB.");
}
return $mapper;
}
/**
* @deprecated As of v6.0. Use hooks instead.
* @phpstan-ignore-next-line
*/
protected function beforeRelate(Entity $entity, $relationName, $foreign, $data = null, array $options = [])
{}
/**
* @deprecated As of v6.0. Use hooks instead.
* @phpstan-ignore-next-line
*/
protected function afterRelate(Entity $entity, $relationName, $foreign, $data = null, array $options = [])
{}
/**
* @deprecated As of v6.0. Use hooks instead.
* @phpstan-ignore-next-line
*/
protected function beforeUnrelate(Entity $entity, $relationName, $foreign, array $options = [])
{}
/**
* @deprecated As of v6.0. Use hooks instead.
* @phpstan-ignore-next-line
*/
protected function afterUnrelate(Entity $entity, $relationName, $foreign, array $options = [])
{}
/**
* @deprecated As of v6.0. Use hooks instead.
* @phpstan-ignore-next-line
*/
protected function beforeMassRelate(Entity $entity, $relationName, array $params = [], array $options = [])
{}
/**
* @deprecated As of v6.0. Use hooks instead.
* @phpstan-ignore-next-line
*/
protected function afterMassRelate(Entity $entity, $relationName, array $params = [], array $options = [])
{}
/**
* @param TEntity $entity
*/
private function saveSetRelations(Entity $entity): void
{
if (!$this->relationsMap) {
return;
}
$relations = $this->relationsMap->get($entity);
if (!$relations) {
return;
}
foreach ($entity->getRelationList() as $relation) {
if (!$relations->isSet($relation)) {
continue;
}
$this->saveSetRelation($entity, $relations, $relation);
}
}
/**
* @param TEntity $entity
*/
private function saveSetRelation(Entity $entity, Relations $relations, string $name): void
{
$related = $relations->getSet($name);
$type = $entity->getRelationType($name);
if ($type === RelationType::HAS_ONE) {
$this->saveSetRelationHasOne($entity, $name, $related);
} else if ($type === RelationType::BELONGS_TO) {
$this->saveSetRelationBelongsTo($entity, $name, $related);
} else if ($type === RelationType::BELONGS_TO_PARENT) {
$this->saveSetRelationBelongsToParent($entity, $name, $related);
}
}
/**
* @param TEntity $entity
*/
private function saveSetRelationHasOne(Entity $entity, string $name, ?Entity $related): void
{
$idAttribute = $name . 'Id';
$defs = $this->getRelationDefs($name);
$foreignKey = $defs->getForeignKey();
$foreignEntityType = $defs->getForeignEntityType();
$foreign = $defs->tryGetForeignRelationName();
$previous = $this->entityManager
->getRDBRepository($foreignEntityType)
->where([$foreignKey => $entity->getId()])
->findOne();
if (!$entity->isNew()) {
$entity->setFetched($idAttribute, $previous ? $previous->getId() : null);
}
if ($previous) {
if (!$related) {
$this->getRelation($entity, $name)->unrelate($previous);
return;
}
if ($previous->getId() === $related->getId()) {
return;
}
}
if (!$related) {
return;
}
$this->getRelation($entity, $name)->relate($related);
$related->set($foreignKey, $entity->getId());
$related->setFetched($foreignKey, $entity->getId());
$related->clear($foreign . 'Name');
}
/**
* @param TEntity $entity
*/
private function saveSetRelationBelongsTo(Entity $entity, string $name, ?Entity $related): void
{
$setId = $entity->get($name . 'Id');
if (!$related) {
if ($setId) {
$this->getRelation($entity, $name)->unrelateById($setId);
}
return;
}
$defs = $this->getRelationDefs($name);
$foreignType = $defs->tryGetForeignRelationName() ?
$this->entityManager
->getDefs()
->getEntity($defs->getForeignEntityType())
->getRelation($defs->getForeignRelationName())
->getType() :
null;
if ($setId === $related->getId() && $foreignType !== RelationType::HAS_ONE) {
return;
}
$this->getRelation($entity, $name)->relate($related);
}
private function getRelationDefs(string $relation): RelationDefs
{
return $this->entityManager
->getDefs()
->getEntity($this->entityType)
->getRelation($relation);
}
/**
* @param TEntity $entity
*/
private function saveSetRelationBelongsToParent(Entity $entity, string $name, ?Entity $related): void
{
$setId = $entity->get($name . 'Id');
$setType = $entity->get($name . 'Type');
if (!$related) {
if (!$setType && !$setId) {
return;
}
$entity->setMultiple([
$name . 'Id' => null,
$name . 'Type' => null,
$name . 'Name' => null,
]);
if (!$setType || !$setId) {
return;
}
$previous = $this->entityManager->getEntityById($setType, $setId);
if (!$previous) {
return;
}
$this->getRelation($entity, $name)->unrelate($previous);
return;
}
if ($setType === $related->getEntityType() && $setId === $related->getId()) {
return;
}
$this->getRelation($entity, $name)->relate($related);
}
public function deleteFromDb(string $id, bool $onlyDeleted = false): void
{
$mapper = $this->getMapper();
if (!$mapper instanceof BaseMapper) {
throw new RuntimeException("Not supported 'deleteFromDb'.");
}
$mapper->deleteFromDb($this->entityType, $id, $onlyDeleted);
}
}

View File

@@ -0,0 +1,427 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\ORM\Repository;
use Espo\ORM\Collection;
use Espo\ORM\EntityCollection;
use Espo\ORM\Name\Attribute;
use Espo\ORM\SthCollection;
use Espo\ORM\Entity;
use Espo\ORM\EntityManager;
use Espo\ORM\Query\Select;
use Espo\ORM\Query\SelectBuilder;
use Espo\ORM\Query\Part\WhereItem;
use Espo\ORM\Query\Part\Selection;
use Espo\ORM\Query\Part\Join;
use Espo\ORM\Mapper\Mapper;
use Espo\ORM\Query\Part\Expression;
use Espo\ORM\Query\Part\Order;
use Espo\ORM\Mapper\BaseMapper;
use LogicException;
use RuntimeException;
/**
* Builds select parameters for an RDB repository. Contains 'find' methods.
*
* @template TEntity of Entity
*/
class RDBSelectBuilder
{
private SelectBuilder $builder;
/** @var RDBRepository<TEntity> */
private RDBRepository $repository;
private bool $returnSthCollection = false;
public function __construct(
private EntityManager $entityManager,
string $entityType,
?Select $query = null
) {
/** @var RDBRepository<TEntity> $repository */
$repository = $this->entityManager->getRepository($entityType);
$this->repository = $repository;
if ($query && $query->getFrom() !== $entityType) {
throw new RuntimeException("SelectBuilder: Passed query doesn't match the entity type.");
}
$this->builder = new SelectBuilder();
if ($query) {
$this->builder->clone($query);
}
if (!$query) {
$this->builder->from($entityType);
}
}
protected function getMapper(): Mapper
{
return $this->entityManager->getMapper();
}
/**
* @return EntityCollection<TEntity>|SthCollection<TEntity>
*/
public function find(): EntityCollection|SthCollection
{
$query = $this->builder->build();
/** @var Collection<TEntity> $collection */
$collection = $this->getMapper()->select($query);
return $this->handleReturnCollection($collection);
}
/**
* @return ?TEntity
*/
public function findOne(): ?Entity
{
$query = $this->builder->build();
$args = func_get_args();
// For bc.
// @todo Remove in v10.0.
if (
count($args) &&
is_array($args[0]) &&
!empty($args[0]['withDeleted'])
) {
$query = SelectBuilder::create()
->clone($query)
->withDeleted()
->build();
}
$cloned = $this->repository->clone($query);
$collection = $cloned
->sth()
->limit(0, 1)
->find();
foreach ($collection as $entity) {
return $entity;
}
return null;
}
/**
* Get a number of records.
*/
public function count(): int
{
$query = $this->builder->build();
return $this->getMapper()->count($query);
}
/**
* Get a max value.
*
* @return int|float
*/
public function max(string $attribute)
{
$query = $this->builder->build();
$mapper = $this->getMapper();
if (!$mapper instanceof BaseMapper) {
throw new RuntimeException("Not supported 'max'.");
}
return $mapper->max($query, $attribute);
}
/**
* Get a min value.
*
* @return int|float
*/
public function min(string $attribute)
{
$query = $this->builder->build();
$mapper = $this->getMapper();
if (!$mapper instanceof BaseMapper) {
throw new RuntimeException("Not supported 'min'.");
}
return $mapper->min($query, $attribute);
}
/**
* Get a sum value.
*
* @return int|float
*/
public function sum(string $attribute)
{
$query = $this->builder->build();
$mapper = $this->getMapper();
if (!$mapper instanceof BaseMapper) {
throw new RuntimeException("Not supported 'sum'.");
}
return $mapper->sum($query, $attribute);
}
/**
* Add JOIN.
*
* @param Join|string $target
* A relation name or table. A relation name should be in camelCase, a table in CamelCase.
* @param string|null $alias An alias.
* @param WhereItem|array<mixed, mixed>|null $conditions Join conditions.
* @return RDBSelectBuilder<TEntity>
*/
public function join($target, ?string $alias = null, $conditions = null): self
{
$this->builder->join($target, $alias, $conditions);
return $this;
}
/**
* Add LEFT JOIN.
*
* @param Join|string $target
* A relation name or table. A relation name should be in camelCase, a table in CamelCase.
* @param string|null $alias An alias.
* @param WhereItem|array<string|int, mixed>|null $conditions Join conditions.
*
* @return RDBSelectBuilder<TEntity>
*/
public function leftJoin($target, ?string $alias = null, $conditions = null): self
{
$this->builder->leftJoin($target, $alias, $conditions);
return $this;
}
/**
* Set DISTINCT parameter.
*
* @return RDBSelectBuilder<TEntity>
*/
public function distinct(): self
{
$this->builder->distinct();
return $this;
}
/**
* Lock selected rows. To be used within a transaction.
*
* @return RDBSelectBuilder<TEntity>
*/
public function forUpdate(): self
{
$this->builder->forUpdate();
$this->sth();
return $this;
}
/**
* Set to return STH collection. Recommended for fetching large number of records.
*
* @todo Remove.
* @return RDBSelectBuilder<TEntity>
*/
public function sth(): self
{
$this->returnSthCollection = true;
return $this;
}
/**
* Add a WHERE clause.
*
* Usage options:
* * `where(WhereItem $clause)`
* * `where(array $clause)`
* * `where(string $key, string $value)`
*
* @param WhereItem|array<mixed, mixed>|string $clause A key or where clause.
* @param mixed[]|scalar|null $value A value. Should be omitted if the first argument is not string.
* @return RDBSelectBuilder<TEntity>
*/
public function where($clause = [], $value = null): self
{
$this->builder->where($clause, $value);
return $this;
}
/**
* Add a HAVING clause.
*
* Usage options:
* * `having(WhereItem $clause)`
* * `having(array $clause)`
* * `having(string $key, string $value)`
*
* @param WhereItem|array<mixed, mixed>|string $clause A key or where clause.
* @param mixed[]|scalar|null $value A value. Should be omitted if the first argument is not string.
* @return RDBSelectBuilder<TEntity>
*/
public function having($clause = [], $value = null): self
{
$this->builder->having($clause, $value);
return $this;
}
/**
* Apply ORDER. Passing an array will override previously set items.
* Passing non-array will append an item,
*
* Usage options:
* * `order(OrderExpression $expression)
* * `order([$expr1, $expr2, ...])
* * `order(string $expression, string $direction)
*
* @param Order|Order[]|Expression|string|array<int, string[]>|string[] $orderBy
* An attribute to order by or an array or order items.
* Passing an array will reset a previously set order.
* @param (Order::ASC|Order::DESC)|bool|null $direction A direction.
* @return RDBSelectBuilder<TEntity>
*/
public function order($orderBy = Attribute::ID, $direction = null): self
{
$this->builder->order($orderBy, $direction);
return $this;
}
/**
* Apply OFFSET and LIMIT.
*
* @return RDBSelectBuilder<TEntity>
*/
public function limit(?int $offset = null, ?int $limit = null): self
{
$this->builder->limit($offset, $limit);
return $this;
}
/**
* Specify SELECT. Columns and expressions to be selected. If not called, then
* all entity attributes will be selected. Passing an array will reset
* previously set items. Passing a string|Expression|SelectExpression will append the item.
*
* Usage options:
* * `select([$expr1, $expr2, ...])`
* * `select([[$expr1, $alias1], [$expr2, $alias2], ...])`
* * `select([$selectItem1, $selectItem2, ...])`
* * `select(string|Expression $expression)`
* * `select(string|Expression $expression, string $alias)`
* * `select(SelectExpression $selectItem)`
*
* @param Selection|Selection[]|Expression|Expression[]|string[]|string|array<int, string[]|string> $select
* An array of expressions or one expression.
* @param string|null $alias An alias. Actual if the first parameter is a string.
* @return RDBSelectBuilder<TEntity>
*/
public function select($select, ?string $alias = null): self
{
$this->builder->select($select, $alias);
return $this;
}
/**
* Specify GROUP BY.
* Passing an array will reset previously set items.
* Passing a string|Expression will append an item.
*
* Usage options:
* * `groupBy(Expression|string $expression)`
* * `groupBy([$expr1, $expr2, ...])`
*
* @param Expression|Expression[]|string|string[] $groupBy
* @return RDBSelectBuilder<TEntity>
*/
public function group($groupBy): self
{
$this->builder->group($groupBy);
return $this;
}
/**
* @deprecated Use `group` method.
*
* @return RDBSelectBuilder<TEntity>
* @param Expression|Expression[]|string|string[] $groupBy
*/
public function groupBy($groupBy): self
{
return $this->group($groupBy);
}
/**
* @param Collection<TEntity> $collection
* @return EntityCollection<TEntity>|SthCollection<TEntity>
*/
protected function handleReturnCollection(Collection $collection): EntityCollection|SthCollection
{
if (!$collection instanceof SthCollection) {
if (!$collection instanceof EntityCollection) {
throw new LogicException();
}
return $collection;
}
if ($this->returnSthCollection) {
return $collection;
}
/** @var EntityCollection<TEntity> */
return $this->entityManager->getCollectionFactory()->createFromSthCollection($collection);
}
}

View File

@@ -0,0 +1,87 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\ORM\Repository;
use Espo\ORM\TransactionManager;
use RuntimeException;
/**
* Wrapper for TransactionManager to be used within RDBRepository in beforeSave and afterSave methods.
*/
class RDBTransactionManager
{
private int $level = 0;
public function __construct(private TransactionManager $transactionManager)
{}
public function isStarted(): bool
{
return $this->level > 0;
}
public function start(): void
{
if ($this->isStarted()) {
throw new RuntimeException("Can't start a transaction more than once.");
}
$this->transactionManager->start();
$this->level = $this->transactionManager->getLevel();
}
public function commit(): void
{
if (!$this->isStarted()) {
throw new RuntimeException("Can't commit not started transaction.");
}
while ($this->transactionManager->getLevel() >= $this->level) {
$this->transactionManager->commit();
}
$this->level = 0;
}
public function rollback(): void
{
if (!$this->isStarted()) {
throw new RuntimeException("Can't rollback not started transaction.");
}
while ($this->transactionManager->getLevel() >= $this->level) {
$this->transactionManager->rollback();
}
$this->level = 0;
}
}

View File

@@ -0,0 +1,70 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\ORM\Repository;
use Espo\ORM\Entity;
/**
* An access point for record fetching and storing.
*
* @template TEntity of Entity
*/
interface Repository
{
/**
* Get a new entity.
*
* @return TEntity
*/
public function getNew(): Entity;
/**
* Fetch an entity by ID.
*
* @return ?TEntity
*/
public function getById(string $id): ?Entity;
/**
* Store an entity.
*
* @param TEntity $entity
* @param array<string, mixed> $options
*/
public function save(Entity $entity, array $options = []): void;
/**
* Remove an entity.
*
* @param TEntity $entity
* @param array<string, mixed> $options
*/
public function remove(Entity $entity, array $options = []): void;
}

View File

@@ -0,0 +1,40 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\ORM\Repository;
use Espo\ORM\Entity;
interface RepositoryFactory
{
/**
* @return Repository<Entity>
*/
public function create(string $entityType): Repository;
}

View File

@@ -0,0 +1,57 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\ORM\Repository;
use Espo\ORM\Entity;
use ReflectionClass;
use InvalidArgumentException;
class Util
{
/**
* @internal
* @param class-string<Entity> $className
*/
public static function getEntityTypeByClass(string $className): string
{
$class = new ReflectionClass($className);
if (!$class->implementsInterface(Entity::class)) {
throw new InvalidArgumentException();
}
if ($class->hasConstant('ENTITY_TYPE')) {
return (string) $class->getConstant('ENTITY_TYPE');
}
return $class->getShortName();
}
}