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,60 @@
<?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\Query;
use RuntimeException;
trait BaseBuilderTrait
{
/**
* Must be protected for compatibility reasons.
*
* @var array<string, mixed>
*/
protected $params = [];
public function __construct()
{
}
private function isEmpty(): bool
{
return empty($this->params);
}
private function cloneInternal(Query $query): void
{
if (!$this->isEmpty()) {
throw new RuntimeException("Clone can be called only on a new empty builder instance.");
}
$this->params = $query->getRaw();
}
}

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\Query;
trait BaseTrait
{
/**
* @var array<string, mixed>
*/
private $params = [];
/**
* Get parameters in RAW format.
*
* @return array<string, mixed>
*/
public function getRaw(): array
{
return $this->params;
}
/**
* Create from RAW params.
*
* @param array<string, mixed> $params
*/
public static function fromRaw(array $params): self
{
$obj = new self();
$obj->validateRawParams($params);
$obj->params = $params;
return $obj;
}
/**
* @param array<string, mixed> $params
*/
private function validateRawParams(array $params): 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\Query;
/**
* Builds query parameters.
* Builder instances are one-off, meaning that you need to instantiate it for every new building process.
*/
interface Builder
{
/**
* Build a query instance.
*/
public function build(): Query;
}

View File

@@ -0,0 +1,81 @@
<?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\Query;
use RuntimeException;
/**
* Delete parameters.
*
* Immutable.
*/
class Delete implements Query
{
use SelectingTrait;
use BaseTrait;
/**
* Get an entity type.
*/
public function getFrom(): string
{
return $this->params['from'];
}
/**
* Get a from-alias
*/
public function getFromAlias(): ?string
{
return $this->params['fromAlias'] ?? null;
}
/**
* Get a LIMIT.
*/
public function getLimit(): ?int
{
return $this->params['limit'] ?? null;
}
/**
* @param array<string, mixed> $params
*/
private function validateRawParams(array $params): void
{
$this->validateRawParamsSelecting($params);
$from = $params['from'] ?? null;
if (!$from || !is_string($from)) {
throw new RuntimeException("Select params: Missing 'from'.");
}
}
}

View File

@@ -0,0 +1,88 @@
<?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\Query;
use RuntimeException;
class DeleteBuilder implements Builder
{
use SelectingBuilderTrait;
/**
* Create an instance.
*/
public static function create(): self
{
return new self();
}
/**
* Build a DELETE query.
*/
public function build(): Delete
{
return Delete::fromRaw($this->params);
}
/**
* Clone an existing query for a subsequent modifying and building.
*/
public function clone(Delete $query): self
{
$this->cloneInternal($query);
return $this;
}
/**
* Set FROM parameter. For what entity type to build a query.
*/
public function from(string $entityType, ?string $alias = null): self
{
if (isset($this->params['from'])) {
throw new RuntimeException("Method 'from' can be called only once.");
}
$this->params['from'] = $entityType;
$this->params['fromAlias'] = $alias;
return $this;
}
/**
* Apply LIMIT.
*/
public function limit(?int $limit = null): self
{
$this->params['limit'] = $limit;
return $this;
}
}

View File

@@ -0,0 +1,72 @@
<?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\Query;
use RuntimeException;
/**
* Insert parameters.
*
* Immutable.
*/
class Insert implements Query
{
use BaseTrait;
/**
* @param array<string, mixed> $params
*/
private function validateRawParams(array $params): void
{
$into = $params['into'] ?? null;
if (!$into || !is_string($into)) {
throw new RuntimeException("Bad or missing 'into' parameter.");
}
$columns = $params['columns'] ?? [];
if (!is_array($columns)) {
throw new RuntimeException("Bad 'columns' parameter.");
}
$values = $params['values'] ?? [];
if (!is_array($values)) {
throw new RuntimeException("Bad 'values' parameter.");
}
$updateSet = $params['updateSet'] ?? null;
if ($updateSet && !is_array($updateSet)) {
throw new RuntimeException("Bad 'updateSet' parameter.");
}
}
}

View File

@@ -0,0 +1,122 @@
<?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\Query;
class InsertBuilder implements Builder
{
use BaseBuilderTrait;
/**
* @var array<string, mixed>
*/
protected $params = [];
/**
* Create an instance.
*/
public static function create(): self
{
return new self();
}
/**
* Build a INSERT query.
*/
public function build(): Insert
{
return Insert::fromRaw($this->params);
}
/**
* Clone an existing query for a subsequent modifying and building.
*/
public function clone(Insert $query): self
{
$this->cloneInternal($query);
return $this;
}
/**
* Into what entity type to insert.
*/
public function into(string $entityType): self
{
$this->params['into'] = $entityType;
return $this;
}
/**
* What columns to set with values. A list of columns.
*
* @param string[] $columns
*/
public function columns(array $columns): self
{
$this->params['columns'] = $columns;
return $this;
}
/**
* What values to insert. A key-value map or a list of key-value maps.
*
* @param array<string, ?scalar>|array<string, ?scalar>[] $values
*/
public function values(array $values): self
{
$this->params['values'] = $values;
return $this;
}
/**
* Values to set on duplicate key. A key-value map.
*
* @param array<string, ?scalar> $updateSet
*/
public function updateSet(array $updateSet): self
{
$this->params['updateSet'] = $updateSet;
return $this;
}
/**
* For a mass insert by a select sub-query.
*/
public function valuesQuery(SelectingQuery $query): self
{
$this->params['valuesQuery'] = $query;
return $this;
}
}

View File

@@ -0,0 +1,59 @@
<?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\Query;
use RuntimeException;
/**
* LOCK TABLE parameters.
*
* Immutable.
*/
class LockTable implements Query
{
use BaseTrait;
public const MODE_SHARE = 'SHARE';
public const MODE_EXCLUSIVE = 'EXCLUSIVE';
/**
* @param array<string, mixed> $params
*/
protected function validateRawParams(array $params): void
{
if (empty($params['table'])) {
throw new RuntimeException("LockTable params: No table specified.");
}
if (empty($params['mode'])) {
throw new RuntimeException("LockTable params: No mode specified.");
}
}
}

View File

@@ -0,0 +1,91 @@
<?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\Query;
class LockTableBuilder implements Builder
{
use BaseBuilderTrait;
/**
* Create an instance.
*/
public static function create(): self
{
return new self();
}
/**
* Build a LOCK TABLE query.
*/
public function build(): LockTable
{
return LockTable::fromRaw($this->params);
}
/**
* Clone an existing query for a subsequent modifying and building.
*/
public function clone(LockTable $query): self
{
$this->cloneInternal($query);
return $this;
}
/**
* What entity type to lock.
*/
public function table(string $entityType): self
{
$this->params['table'] = $entityType;
return $this;
}
/**
* In SHARE mode.
*/
public function inShareMode(): self
{
$this->params['mode'] = LockTable::MODE_SHARE;
return $this;
}
/**
* In EXCLUSIVE mode.
*/
public function inExclusiveMode(): self
{
$this->params['mode'] = LockTable::MODE_EXCLUSIVE;
return $this;
}
}

View File

@@ -0,0 +1,217 @@
<?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\Query\Part;
use Espo\ORM\Query\Part\Where\AndGroup;
use Espo\ORM\Query\Part\Where\Comparison;
use Espo\ORM\Query\Part\Where\Exists;
use Espo\ORM\Query\Part\Where\Not;
use Espo\ORM\Query\Part\Where\OrGroup;
use Espo\ORM\Query\Select;
/**
* A util-class for creating items that can be used as a where-clause.
*/
class Condition
{
private function __construct()
{}
/**
* Create 'AND' group.
*/
public static function and(WhereItem ...$items): AndGroup
{
return AndGroup::create(...$items);
}
/**
* Create 'OR' group.
*/
public static function or(WhereItem ...$items): OrGroup
{
return OrGroup::create(...$items);
}
/**
* Create 'NOT'.
*/
public static function not(WhereItem $item): Not
{
return Not::create($item);
}
/**
* Create `EXISTS`.
*/
public static function exists(Select $subQuery): Exists
{
return Exists::create($subQuery);
}
/**
* Create a column reference expression.
*
* @param string $expression Examples: `columnName`, `alias.columnName`.
*/
public static function column(string $expression): Expression
{
return Expression::column($expression);
}
/**
* Create '=' comparison.
*
* @param Expression $argument1 An expression.
* @param Expression|Select|string|int|float|bool|null $argument2 A scalar, expression or sub-query.
*/
public static function equal(
Expression $argument1,
Expression|Select|string|int|float|bool|null $argument2
): Comparison {
return Comparison::equal($argument1, $argument2);
}
/**
* Create '!=' comparison.
*
* @param Expression $argument1 An expression.
* @param Expression|Select|string|int|float|bool|null $argument2 A scalar, expression or sub-query.
*/
public static function notEqual(
Expression $argument1,
Expression|Select|string|int|float|bool|null $argument2
): Comparison {
return Comparison::notEqual($argument1, $argument2);
}
/**
* Create 'LIKE' comparison.
*
* @param Expression $subject What to test.
* @param Expression|string $pattern A pattern.
*/
public static function like(Expression $subject, Expression|string $pattern): Comparison
{
return Comparison::like($subject, $pattern);
}
/**
* Create 'NOT LIKE' comparison.
*
* @param Expression $subject What to test.
* @param Expression|string $pattern A pattern.
*/
public static function notLike(Expression $subject, Expression|string $pattern): Comparison
{
return Comparison::notLike($subject, $pattern);
}
/**
* Create '>' comparison.
*
* @param Expression $argument1 An expression.
* @param Expression|Select|string|int|float $argument2 A scalar, expression or sub-query.
*/
public static function greater(
Expression $argument1,
Expression|Select|string|int|float $argument2
): Comparison {
return Comparison::greater($argument1, $argument2);
}
/**
* Create '>=' comparison.
*
* @param Expression $argument1 An expression.
* @param Expression|Select|string|int|float $argument2 A scalar, expression or sub-query.
*/
public static function greaterOrEqual(
Expression $argument1,
Expression|Select|string|int|float $argument2
): Comparison {
return Comparison::greaterOrEqual($argument1, $argument2);
}
/**
* Create '<' comparison.
*
* @param Expression $argument1 An expression.
* @param Expression|Select|string|int|float $argument2 A scalar, expression or sub-query.
*/
public static function less(
Expression $argument1,
Expression|Select|string|int|float $argument2
): Comparison {
return Comparison::less($argument1, $argument2);
}
/**
* Create '<=' comparison.
*
* @param Expression $argument1 An expression.
* @param Expression|Select|string|int|float $argument2 A scalar, expression or sub-query.
*/
public static function lessOrEqual(
Expression $argument1,
Expression|Select|string|int|float $argument2
): Comparison {
return Comparison::lessOrEqual($argument1, $argument2);
}
/**
* Create 'IN' comparison.
*
* @param Expression $subject What to test.
* @param Select|scalar[] $set A set of values. A select query or array of scalars.
*/
public static function in(Expression $subject, Select|array $set): Comparison
{
return Comparison::in($subject, $set);
}
/**
* Create 'NOT IN' comparison.
*
* @param Expression $subject What to test.
* @param Select|scalar[] $set A set of values. A select query or array of scalars.
*/
public static function notIn(Expression $subject, Select|array $set): Comparison
{
return Comparison::notIn($subject, $set);
}
}

View File

@@ -0,0 +1,820 @@
<?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\Query\Part;
use Espo\ORM\Query\Part\Expression\Util;
use RuntimeException;
/**
* A complex expression. Can be a function or a simple column reference. Immutable.
*/
class Expression implements WhereItem
{
private string $expression;
public function __construct(string $expression)
{
if ($expression === '') {
throw new RuntimeException("Expression can't be empty.");
}
if (str_ends_with($expression, ':')) {
throw new RuntimeException("Expression should not end with `:`.");
}
$this->expression = $expression;
}
public function getRaw(): array
{
return [$this->getRawKey() => null];
}
public function getRawKey(): string
{
return $this->expression . ':';
}
public function getRawValue(): mixed
{
return null;
}
/**
* Get a string expression.
*/
public function getValue(): string
{
return $this->expression;
}
/**
* Create an expression from a string.
*/
public static function create(string $expression): self
{
return new self($expression);
}
/**
* Create an expression from a scalar value or NULL.
*
* @param string|float|int|bool|null $value A scalar or NULL.
*/
public static function value(string|float|int|bool|null $value): self
{
return self::create(self::stringifyArgument($value));
}
/**
* Create a column reference expression.
*
* @param string $expression Examples: `columnName`, `alias.columnName`.
*/
public static function column(string $expression): self
{
$string = $expression;
if (strlen($string) && $string[0] === '@') {
$string = substr($string, 1);
}
if ($string === '') {
throw new RuntimeException("Empty column.");
}
if (!preg_match('/^[a-zA-Z\d.]+$/', $string)) {
throw new RuntimeException("Bad column. Must be of letters, digits. Can have a dot.");
}
return self::create($expression);
}
/**
* Create an alias reference expression.
*
* @param string $expression Examples: `someAlias`, `subQueryAlias.someAlias`.
* @since 8.1.0
*/
public static function alias(string $expression): self
{
if ($expression === '') {
throw new RuntimeException("Empty alias.");
}
if (!preg_match('/^[a-zA-Z\d.]+$/', $expression)) {
throw new RuntimeException("Bad alias expression. Must be of letters, digits. Can have a dot.");
}
if (str_contains($expression, '.')) {
[$left, $right] = explode('.', $expression, 2);
return self::create($left . '.#' . $right);
}
return self::create('#' . $expression);
}
/**
* 'COUNT' function.
*
* @param Expression $expression
*/
public static function count(Expression $expression): self
{
return self::composeFunction('COUNT', $expression);
}
/**
* 'MIN' function.
*
* @param Expression $expression
*/
public static function min(Expression $expression): self
{
return self::composeFunction('MIN', $expression);
}
/**
* 'MAX' function.
*
* @param Expression $expression
*/
public static function max(Expression $expression): self
{
return self::composeFunction('MAX', $expression);
}
/**
* 'SUM' function.
*
* @param Expression $expression
*/
public static function sum(Expression $expression): self
{
return self::composeFunction('SUM', $expression);
}
/**
* 'AVG' function.
*
* @param Expression $expression
*/
public static function average(Expression $expression): self
{
return self::composeFunction('AVG', $expression);
}
/**
* 'IF' function. Return $then if a condition is true, $else otherwise.
*
* @param Expression $condition A condition.
* @param Expression|string|int|float|bool|null $then Then.
* @param Expression|string|int|float|bool|null $else Else.
*/
public static function if(
Expression $condition,
Expression|string|int|float|bool|null $then,
Expression|string|int|float|bool|null $else
): self {
return self::composeFunction('IF', $condition, $then, $else);
}
/**
* 'CASE' expression. Even arguments define 'WHEN' conditions, following odd arguments
* define 'THEN' values. The last unmatched argument defines the 'ELSE' value.
*
* @param Expression|scalar|null ...$arguments Arguments.
*/
public static function switch(Expression|string|int|float|bool|null ...$arguments): self
{
if (count($arguments) < 2) {
throw new RuntimeException("Too few arguments.");
}
return self::composeFunction('SWITCH', ...$arguments);
}
/**
* 'CASE' expression that maps keys to values. The first argument is the value to map.
* Odd arguments define keys, the following even arguments define mapped values.
* The last unmatched argument defines the 'ELSE' value.
*
* @param Expression|scalar|null ...$arguments Arguments.
*/
public static function map(Expression|string|int|float|bool|null ...$arguments): self
{
if (count($arguments) < 3) {
throw new RuntimeException("Too few arguments.");
}
return self::composeFunction('MAP', ...$arguments);
}
/**
* 'IFNULL' function. If the first argument is not NULL, returns it,
* otherwise returns the second argument.
*
* @param Expression $value A value.
* @param Expression|string|int|float|bool $fallbackValue A fallback value.
*/
public static function ifNull(Expression $value, Expression|string|int|float|bool $fallbackValue): self
{
return self::composeFunction('IFNULL', $value, $fallbackValue);
}
/**
* 'NULLIF' function. If $arg1 = $arg2, returns NULL,
* otherwise returns the first argument.
*
* @param Expression|string|int|float|bool $argument1
* @param Expression|string|int|float|bool $argument2
*/
public static function nullIf(
Expression|string|int|float|bool $argument1,
Expression|string|int|float|bool $argument2
): self {
return self::composeFunction('NULLIF', $argument1, $argument2);
}
/**
* 'LIKE' operator.
*
* Example: `like(Expression:column('test'), 'test%'`.
*
* @param Expression $subject A subject.
* @param Expression|string $pattern A pattern.
*/
public static function like(Expression $subject, Expression|string $pattern): self
{
return self::composeFunction('LIKE', $subject, $pattern);
}
/**
* '=' operator.
*
* @param Expression|string|int|float|bool $argument1
* @param Expression|string|int|float|bool $argument2
*/
public static function equal(
Expression|string|int|float|bool $argument1,
Expression|string|int|float|bool $argument2
): self {
return self::composeFunction('EQUAL', $argument1, $argument2);
}
/**
* '<>' operator.
*
* @param Expression|string|int|float|bool $argument1
* @param Expression|string|int|float|bool $argument2
*/
public static function notEqual(
Expression|string|int|float|bool $argument1,
Expression|string|int|float|bool $argument2
): self {
return self::composeFunction('NOT_EQUAL', $argument1, $argument2);
}
/**
* '>' operator.
*
* @param Expression|string|int|float|bool $argument1
* @param Expression|string|int|float|bool $argument2
*/
public static function greater(
Expression|string|int|float|bool $argument1,
Expression|string|int|float|bool $argument2
): self {
return self::composeFunction('GREATER_THAN', $argument1, $argument2);
}
/**
* '<' operator.
*
* @param Expression|string|int|float|bool $argument1
* @param Expression|string|int|float|bool $argument2
*/
public static function less(
Expression|string|int|float|bool $argument1,
Expression|string|int|float|bool $argument2
): self {
return self::composeFunction('LESS_THAN', $argument1, $argument2);
}
/**
* '>=' operator.
*
* @param Expression|string|int|float|bool $argument1
* @param Expression|string|int|float|bool $argument2
*/
public static function greaterOrEqual(
Expression|string|int|float|bool $argument1,
Expression|string|int|float|bool $argument2
): self {
return self::composeFunction('GREATER_THAN_OR_EQUAL', $argument1, $argument2);
}
/**
* '<=' operator.
*
* @param Expression|string|int|float|bool $argument1
* @param Expression|string|int|float|bool $argument2
*/
public static function lessOrEqual(
Expression|string|int|float|bool $argument1,
Expression|string|int|float|bool $argument2
): self {
return self::composeFunction('LESS_THAN_OR_EQUAL', $argument1, $argument2);
}
/**
* 'IS NULL' operator.
*
* @param Expression $expression
*/
public static function isNull(Expression $expression): self
{
return self::composeFunction('IS_NULL', $expression);
}
/**
* 'IS NOT NULL' operator.
*
* @param Expression $expression
*/
public static function isNotNull(Expression $expression): self
{
return self::composeFunction('IS_NOT_NULL', $expression);
}
/**
* 'IN' operator. Check whether a value is within a set of values.
*
* @param Expression $expression
* @param Expression[]|string[]|int[]|float[]|bool[] $values
*/
public static function in(Expression $expression, array $values): self
{
return self::composeFunction('IN', $expression, ...$values);
}
/**
* 'NOT IN' operator. Check whether a value is not within a set of values.
*
* @param Expression $expression
* @param Expression[]|string[]|int[]|float[]|bool[] $values
*/
public static function notIn(Expression $expression, array $values): self
{
return self::composeFunction('NOT_IN', $expression, ...$values);
}
/**
* 'COALESCE' function. Returns the first non-NULL value in the list.
*/
public static function coalesce(Expression ...$expressions): self
{
return self::composeFunction('COALESCE', ...$expressions);
}
/**
* 'MONTH' function. Returns a month number of a passed date or date-time.
*
* @param Expression $date
*/
public static function month(Expression $date): self
{
return self::composeFunction('MONTH_NUMBER', $date);
}
/**
* 'WEEK' function. Returns a week number of a passed date or date-time.
*
* @param Expression $date
* @param int $weekStart A week start. `0` for Sunday, `1` for Monday.
*/
public static function week(Expression $date, int $weekStart = 0): self
{
if ($weekStart !== 0 && $weekStart !== 1) {
throw new RuntimeException("Week start can be only 0 or 1.");
}
if ($weekStart === 1) {
return self::composeFunction('WEEK_NUMBER_1', $date);
}
return self::composeFunction('WEEK_NUMBER', $date);
}
/**
* 'DAYOFWEEK' function. A day of week of a passed date or date-time. 1..7.
*
* @param Expression $date
*/
public static function dayOfWeek(Expression $date): self
{
return self::composeFunction('DAYOFWEEK', $date);
}
/**
* 'DAYOFMONTH' function. A day of month of a passed date or date-time. 1..31.
*
* @param Expression $date
*/
public static function dayOfMonth(Expression $date): self
{
return self::composeFunction('DAYOFMONTH', $date);
}
/**
* 'YEAR' function. A year number of a passed date or date-time.
*
* @param Expression $date
*/
public static function year(Expression $date): self
{
return self::composeFunction('YEAR', $date);
}
/**
* 'YEAR' function taking into account a fiscal year start.
*
* @param Expression $date
* @param int $fiscalYearStart A month number of a fiscal year start. 1..12.
*/
public static function yearFiscal(Expression $date, int $fiscalYearStart = 1): self
{
if ($fiscalYearStart < 1 || $fiscalYearStart > 12) {
throw new RuntimeException("Bad fiscal year start.");
}
return self::composeFunction('YEAR_' . strval($fiscalYearStart), $date);
}
/**
* 'QUARTER' function. A quarter number of a passed date or date-time. 1..4.
*
* @param Expression $date
*/
public static function quarter(Expression $date): self
{
return self::composeFunction('QUARTER_NUMBER', $date);
}
/**
* 'HOUR' function. A hour number of a passed date-time. 0..23.
*
* @param Expression $dateTime
*/
public static function hour(Expression $dateTime): self
{
return self::composeFunction('HOUR', $dateTime);
}
/**
* 'MINUTE' function. A minute number of a passed date-time. 0..59.
*
* @param Expression $dateTime
*/
public static function minute(Expression $dateTime): self
{
return self::composeFunction('MINUTE', $dateTime);
}
/**
* 'SECOND' function. A second number of a passed date-time. 0..59.
*
* @param Expression $dateTime
*/
public static function second(Expression $dateTime): self
{
return self::composeFunction('SECOND', $dateTime);
}
/**
* 'UNIX_TIMESTAMP' function. Seconds.
*
* @param Expression $dateTime
* @since 9.0.0
*/
public static function unixTimestamp(Expression $dateTime): self
{
return self::composeFunction('UNIX_TIMESTAMP', $dateTime);
}
/**
* 'NOW' function. A current date and time.
*/
public static function now(): self
{
return self::composeFunction('NOW');
}
/**
* 'DATE' function. Returns a date part of a date-time.
*
* @param Expression $dateTime
*/
public static function date(Expression $dateTime): self
{
return self::composeFunction('DATE', $dateTime);
}
/**
* Time zone conversion function. Converts a passed data-time applying a hour offset.
*
* @param Expression $date
*/
public static function convertTimezone(Expression $date, float $offset): self
{
return self::composeFunction('TZ', $date, $offset);
}
/**
* 'CONCAT' function. Concatenates multiple strings.
*
* @param Expression|string ...$strings Strings.
*/
public static function concat(Expression|string ...$strings): self
{
return self::composeFunction('CONCAT', ...$strings);
}
/**
* 'LEFT' function. Returns a specified number of characters from the left of a string.
*/
public static function left(Expression $string, int $offset): self
{
return self::composeFunction('LEFT', $string, $offset);
}
/**
* 'LOWER' function. Converts a string to a lower case.
*/
public static function lowerCase(Expression $string): self
{
return self::composeFunction('LOWER', $string);
}
/**
* 'UPPER' function. Converts a string to an upper case.
*/
public static function upperCase(Expression $string): self
{
return self::composeFunction('UPPER', $string);
}
/**
* 'TRIM' function. Removes leading and trailing spaces.
*/
public static function trim(Expression $string): self
{
return self::composeFunction('TRIM', $string);
}
/**
* 'BINARY' function. Converts a string value to a binary string.
*/
public static function binary(Expression $string): self
{
return self::composeFunction('BINARY', $string);
}
/**
* 'CHAR_LENGTH' function. A number of characters in a string.
*/
public static function charLength(Expression $string): self
{
return self::composeFunction('CHAR_LENGTH', $string);
}
/**
* 'REPLACE' function. Replaces all the occurrences of a sub-string within a string.
*
* @param Expression $haystack A subject.
* @param Expression|string $needle A string to be replaced.
* @param Expression|string $replaceWith A string to replace with.
*/
public static function replace(
Expression $haystack,
Expression|string $needle,
Expression|string $replaceWith
): self {
return self::composeFunction('REPLACE', $haystack, $needle, $replaceWith);
}
/**
* 'FIELD' operator (in MySQL). Returns an index (position) of an expression
* in a list. Returns `0` if not found. The first index is `1`.
*
* @param Expression $expression
* @param Expression[]|string[]|int[]|float[] $list
*/
public static function positionInList(Expression $expression, array $list): self
{
return self::composeFunction('POSITION_IN_LIST', $expression, ...$list);
}
/**
* 'ADD' function. Adds two or more numbers.
*
* @param Expression|int|float ...$arguments
*/
public static function add(Expression|int|float ...$arguments): self
{
if (count($arguments) < 2) {
throw new RuntimeException("Too few arguments.");
}
return self::composeFunction('ADD', ...$arguments);
}
/**
* 'SUB' function. Subtraction.
*
* @param Expression|int|float ...$arguments
*/
public static function subtract(Expression|int|float ...$arguments): self
{
if (count($arguments) < 2) {
throw new RuntimeException("Too few arguments.");
}
return self::composeFunction('SUB', ...$arguments);
}
/**
* 'MUL' function. Multiplication.
*
* @param Expression|int|float ...$arguments
*/
public static function multiply(Expression|int|float ...$arguments): self
{
if (count($arguments) < 2) {
throw new RuntimeException("Too few arguments.");
}
return self::composeFunction('MUL', ...$arguments);
}
/**
* 'DIV' function. Division.
*
* @param Expression|int|float ...$arguments
*/
public static function divide(Expression|int|float ...$arguments): self
{
if (count($arguments) < 2) {
throw new RuntimeException("Too few arguments.");
}
return self::composeFunction('DIV', ...$arguments);
}
/**
* 'MOD' function. Returns a remainder of a number divided by another number.
*
* @param Expression|int|float ...$arguments
*/
public static function modulo(Expression|int|float ...$arguments): self
{
if (count($arguments) < 2) {
throw new RuntimeException("Too few arguments.");
}
return self::composeFunction('MOD', ...$arguments);
}
/**
* 'FLOOR' function. The largest integer value not greater than the argument.
*/
public static function floor(Expression $number): self
{
return self::composeFunction('FLOOR', $number);
}
/**
* 'CEIL' function. The largest integer value not greater than the argument.
*/
public static function ceil(Expression $number): self
{
return self::composeFunction('CEIL', $number);
}
/**
* 'ROUND' function. Rounds a number to a specified number of decimal places.
*/
public static function round(Expression $number, int $precision = 0): self
{
return self::composeFunction('ROUND', $number, $precision);
}
/**
* 'GREATEST' function. A max value from a list of expressions.
*/
public static function greatest(Expression ...$arguments): self
{
return self::composeFunction('GREATEST', ...$arguments);
}
/**
* 'LEAST' function. A min value from a list of expressions.
*/
public static function least(Expression ...$arguments): self
{
return self::composeFunction('LEAST', ...$arguments);
}
/**
* 'ANY_VALUE' function.
*
* @since 9.1.6
*/
public function anyValue(Expression $expression): self
{
return self::composeFunction('ANY_VALUE', $expression);
}
/**
* 'AND' operator. Returns TRUE if all arguments are TRUE.
*/
public static function and(Expression ...$arguments): self
{
return self::composeFunction('AND', ...$arguments);
}
/**
* 'OR' operator. Returns TRUE if at least one argument is TRUE.
*/
public static function or(Expression ...$arguments): self
{
return self::composeFunction('OR', ...$arguments);
}
/**
* 'NOT' operator. Negates an expression.
*/
public static function not(Expression $argument): self
{
return self::composeFunction('NOT', $argument);
}
/**
* 'ROW' constructor.
*/
public static function row(Expression ...$arguments): self
{
return self::composeFunction('ROW', ...$arguments);
}
private static function composeFunction(
string $function,
Expression|bool|int|float|string|null ...$arguments
): self {
return Util::composeFunction($function, ...$arguments);
}
private static function stringifyArgument(Expression|bool|int|float|string|null $argument): string
{
return Util::stringifyArgument($argument);
}
}

View File

@@ -0,0 +1,88 @@
<?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\Query\Part\Expression;
use Espo\ORM\Query\Part\Expression;
class Util
{
/**
* Compose an expression by a function name and arguments.
*
* @param Expression|bool|int|float|string|null ...$arguments Arguments
*/
public static function composeFunction(
string $function,
Expression|bool|int|float|string|null ...$arguments
): Expression {
$stringifiedItems = array_map(
function ($item) {
return self::stringifyArgument($item);
},
$arguments
);
$expression = $function . ':(' . implode(', ', $stringifiedItems) . ')';
return Expression::create($expression);
}
/**
* Stringify an argument.
*
* @param Expression|bool|int|float|string|null $argument
*/
public static function stringifyArgument(Expression|bool|int|float|string|null $argument): string
{
if ($argument instanceof Expression) {
return $argument->getValue();
}
if (is_null($argument)) {
return 'NULL';
}
if (is_bool($argument)) {
return $argument ? 'TRUE': 'FALSE';
}
if (is_int($argument)) {
return strval($argument);
}
if (is_float($argument)) {
return strval($argument);
}
return '\'' . str_replace('\'', '\\\'', $argument) . '\'';
}
}

View File

@@ -0,0 +1,300 @@
<?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\Query\Part;
use Espo\ORM\Query\Part\Join\JoinType;
use Espo\ORM\Query\Select;
use LogicException;
use RuntimeException;
/**
* A join item. Immutable.
*/
class Join
{
/** A table join. */
public const MODE_TABLE = 0;
/** A relation join. */
public const MODE_RELATION = 1;
/** A sub-query join. */
public const MODE_SUB_QUERY = 3;
private ?WhereItem $conditions = null;
private bool $onlyMiddle = false;
private bool $isLateral = false;
private ?JoinType $type = null;
private function __construct(
private string|Select $target,
private ?string $alias = null
) {
if ($target === '' || $alias === '') {
throw new RuntimeException("Bad join.");
}
}
/**
* Get a join target. A relation name, table or sub-query.
* A relation name is in camelCase, a table is in CamelCase.
*/
public function getTarget(): string|Select
{
return $this->target;
}
/**
* Get an alias.
*/
public function getAlias(): ?string
{
return $this->alias;
}
/**
* Get join conditions.
*/
public function getConditions(): ?WhereItem
{
return $this->conditions;
}
/**
* Is a sub-query join.
*/
public function isSubQuery(): bool
{
return !is_string($this->target);
}
/**
* Is a table join.
*/
public function isTable(): bool
{
return is_string($this->target) && $this->target[0] === ucfirst($this->target[0]);
}
/**
* Is a relation join.
*/
public function isRelation(): bool
{
return !$this->isSubQuery() && !$this->isTable();
}
/**
* Get a join mode.
*
* @return self::MODE_TABLE|self::MODE_RELATION|self::MODE_SUB_QUERY
*/
public function getMode(): int
{
if ($this->isSubQuery()) {
return self::MODE_SUB_QUERY;
}
if ($this->isRelation()) {
return self::MODE_RELATION;
}
return self::MODE_TABLE;
}
/**
* Is only middle table to be joined.
*/
public function isOnlyMiddle(): bool
{
return $this->onlyMiddle;
}
/**
* Is LATERAL.
*
* @since 9.1.6
*/
public function isLateral(): bool
{
return $this->isLateral;
}
/**
* Get a join type.
*
* @return JoinType|null
*
* @since 9.2.0
*/
public function getType(): ?JoinType
{
return $this->type;
}
/**
* Create.
*
* @param string|Select $target
* A relation name, table or sub-query. A relation name should be in camelCase, a table in CamelCase.
* When joining a table or sub-query, conditions should be specified.
* When joining a relation, conditions will be applied automatically, additional conditions can
* be specified as well.
* @param ?string $alias An alias.
*/
public static function create(string|Select $target, ?string $alias = null): self
{
return new self($target, $alias);
}
/**
* Create with a table target.
*
* @param string $table A table name. Should start with an upper case letter.
* @param ?string $alias An alias.
*/
public static function createWithTableTarget(string $table, ?string $alias = null): self
{
return self::create(ucfirst($table), $alias);
}
/**
* Create with a relation target. Conditions will be applied automatically.
*
* @param string $relation A relation name. Should start with a lower case letter.
* @param ?string $alias An alias.
*/
public static function createWithRelationTarget(string $relation, ?string $alias = null): self
{
return self::create(lcfirst($relation), $alias);
}
/**
* Create with a sub-query.
*
* @param Select $subQuery A sub-query.
* @param string $alias An alias.
*/
public static function createWithSubQuery(Select $subQuery, string $alias): self
{
return new self($subQuery, $alias);
}
/**
* Clone with an alias.
*/
public function withAlias(?string $alias): self
{
$obj = clone $this;
$obj->alias = $alias;
return $obj;
}
/**
* Clone with join conditions.
*/
public function withConditions(?WhereItem $conditions): self
{
$obj = clone $this;
$obj->conditions = $conditions;
return $obj;
}
/**
* Join only middle table. For many-to-many relationships.
*/
public function withOnlyMiddle(bool $onlyMiddle = true): self
{
if (!$this->isRelation()) {
throw new LogicException("Only-middle is compatible only with relation joins.");
}
$obj = clone $this;
$obj->onlyMiddle = $onlyMiddle;
return $obj;
}
/**
* With LATERAL. Only for a sub-query join.
*
* @since 9.1.6
*/
public function withLateral(bool $isLateral = true): self
{
if (!$this->isSubQuery()) {
throw new LogicException("Lateral can be used only with sub-query joins.");
}
$obj = clone $this;
$obj->isLateral = $isLateral;
return $obj;
}
/**
* With LEFT type.
*
* @since 9.2.0.
*/
public function withLeft(): self
{
$obj = clone $this;
$obj->type = JoinType::left;
return $obj;
}
/**
* With INNER type.
*
* @since 9.2.0.
*/
public function withInner(): self
{
$obj = clone $this;
$obj->type = JoinType::inner;
return $obj;
}
/**
* With a join type.
*
* @since 9.2.0.
*/
public function withType(JoinType $type): self
{
$obj = clone $this;
$obj->type = $type;
return $obj;
}
}

View File

@@ -0,0 +1,46 @@
<?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\Query\Part\Join;
/**
* @since 9.2.0
*/
enum JoinType: string
{
/**
* An INNER join.
*/
case inner = 'inner';
/**
* A LEFT join.
*/
case left = 'left';
}

View File

@@ -0,0 +1,156 @@
<?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\Query\Part;
use RuntimeException;
/**
* An order item. Immutable.
*
* Immutable.
*/
class Order
{
public const ASC = 'ASC';
public const DESC = 'DESC';
private Expression $expression;
private bool $isDesc = false;
private function __construct(Expression $expression)
{
$this->expression = $expression;
}
/**
* Get an expression.
*/
public function getExpression(): Expression
{
return $this->expression;
}
public function isDesc(): bool
{
return $this->isDesc;
}
/**
* Get a direction.
*
* @return self::DESC|self::ASC
*/
public function getDirection(): string
{
return $this->isDesc ? self::DESC : self::ASC;
}
/**
* Create.
*/
public static function create(Expression $expression): self
{
return new self($expression);
}
/**
* Create from a string expression.
*/
public static function fromString(string $expression): self
{
return self::create(
Expression::create($expression)
);
}
/**
* Create an order by position in list.
* Note: Reverses the list and applies DESC order.
*
* @param string[]|int[]|float[] $list
*/
public static function createByPositionInList(Expression $expression, array $list): self
{
$orderExpression = Expression::positionInList($expression, array_reverse($list));
return self::create($orderExpression)->withDesc();
}
/**
* Clone with an ascending direction.
*/
public function withAsc(): self
{
$obj = clone $this;
$obj->isDesc = false;
return $obj;
}
/**
* Clone with a descending direction.
*/
public function withDesc(): self
{
$obj = clone $this;
$obj->isDesc = true;
return $obj;
}
/**
* Clone with a direction.
*
* @params self::ASC|self::DESC $direction
* @throws RuntimeException
*/
public function withDirection(string $direction): self
{
$obj = clone $this;
$obj->isDesc = strtoupper($direction) === self::DESC;
if (!in_array(strtoupper($direction), [self::DESC, self::ASC])) {
throw new RuntimeException("Bad order direction.");
}
return $obj;
}
/**
* Clone with a reverse direction.
*/
public function withReverseDirection(): self
{
$obj = clone $this;
$obj->isDesc = !$this->isDesc;
return $obj;
}
}

View File

@@ -0,0 +1,96 @@
<?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\Query\Part;
use InvalidArgumentException;
use Iterator;
/**
* A list of order items.
*
* Immutable.
*
* @implements Iterator<Order>
*/
class OrderList implements Iterator
{
private int $position = 0;
/** @var Order[] */
private array $list;
/**
* @param Order[] $list
*/
private function __construct(array $list)
{
foreach ($list as $item) {
if (!$item instanceof Order) {
throw new InvalidArgumentException();
}
}
$this->list = $list;
}
/**
* Create an instance.
*
* @param Order[] $list
*/
public static function create(array $list): self
{
return new self($list);
}
public function rewind(): void
{
$this->position = 0;
}
public function current(): Order
{
return $this->list[$this->position];
}
public function key(): int
{
return $this->position;
}
public function next(): void
{
++$this->position;
}
public function valid(): bool
{
return isset($this->list[$this->position]);
}
}

View File

@@ -0,0 +1,73 @@
<?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\Query\Part;
/**
* A select item. Immutable.
*
* Immutable.
*/
class Selection
{
private function __construct(
private Expression $expression,
private ?string $alias = null
) {}
public function getExpression(): Expression
{
return $this->expression;
}
public function getAlias(): ?string
{
return $this->alias;
}
public static function create(Expression $expression, ?string $alias = null): self
{
return new self($expression, $alias);
}
public static function fromString(string $expression): self
{
return self::create(
Expression::create($expression)
);
}
public function withAlias(?string $alias): self
{
$obj = clone $this;
$obj->alias = $alias;
return $obj;
}
}

View File

@@ -0,0 +1,108 @@
<?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\Query\Part\Where;
use Espo\ORM\Query\Part\WhereClause;
use Espo\ORM\Query\Part\WhereItem;
/**
* AND-group. Immutable.
*/
class AndGroup implements WhereItem
{
/** @var array<string|int, mixed> */
private $rawValue = [];
/**
* @return array<string|int, mixed>
*/
public function getRaw(): array
{
return ['AND' => $this->getRawValue()];
}
public function getRawKey(): string
{
return 'AND';
}
/**
* @return array<string|int, mixed>
*/
public function getRawValue(): array
{
return $this->rawValue;
}
/**
* Get a number of items.
*/
public function getItemCount(): int
{
return count($this->rawValue);
}
/**
* @param array<string|int, mixed> $whereClause
* @return self
*/
public static function fromRaw(array $whereClause): self
{
if (count($whereClause) === 1 && array_keys($whereClause)[0] === 0) {
$whereClause = $whereClause[0];
}
// Do not refactor.
$obj = static::class === WhereClause::class ?
new WhereClause() :
new self();
/** @phpstan-ignore-next-line */
$obj->rawValue = $whereClause;
return $obj;
}
public static function create(WhereItem ...$itemList): self
{
$builder = self::createBuilder();
foreach ($itemList as $item) {
$builder->add($item);
}
return $builder->build();
}
public static function createBuilder(): AndGroupBuilder
{
return new AndGroupBuilder();
}
}

View File

@@ -0,0 +1,95 @@
<?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\Query\Part\Where;
use Espo\ORM\Query\Part\WhereItem;
class AndGroupBuilder
{
/** @var array<string|int, mixed> */
private array $raw = [];
public function build(): AndGroup
{
return AndGroup::fromRaw($this->raw);
}
public function add(WhereItem $item): self
{
$key = $item->getRawKey();
$value = $item->getRawValue();
if ($item instanceof AndGroup) {
$this->raw = self::normalizeRaw($this->raw);
$this->raw[] = $item->getRawValue();
return $this;
}
if (count($this->raw) === 0) {
$this->raw[$key] = $value;
return $this;
}
$this->raw = self::normalizeRaw($this->raw);
$this->raw[] = [$key => $value];
return $this;
}
/**
* Merge with another AndGroup.
*/
public function merge(AndGroup $andGroup): self
{
$this->raw = array_merge(
self::normalizeRaw($this->raw),
self::normalizeRaw($andGroup->getRawValue())
);
return $this;
}
/**
* @param array<string|int, mixed> $raw
* @return array<string|int, mixed>
*/
private static function normalizeRaw(array $raw): array
{
if (count($raw) === 1 && array_keys($raw)[0] !== 0) {
return [$raw];
}
return $raw;
}
}

View File

@@ -0,0 +1,433 @@
<?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\Query\Part\Where;
use Espo\ORM\Query\Part\Expression;
use Espo\ORM\Query\Part\WhereItem;
use Espo\ORM\Query\Select;
use RuntimeException;
/**
* Compares an expression to a value or another expression. Immutable.
*/
class Comparison implements WhereItem
{
private const OPERATOR_EQUAL = '=';
private const OPERATOR_NOT_EQUAL = '!=';
private const OPERATOR_GREATER = '>';
private const OPERATOR_GREATER_OR_EQUAL = '>=';
private const OPERATOR_LESS = '<';
private const OPERATOR_LESS_OR_EQUAL = '<=';
private const OPERATOR_LIKE = '*';
private const OPERATOR_NOT_LIKE = '!*';
private const OPERATOR_IN_SUB_QUERY = '=s';
private const OPERATOR_NOT_IN_SUB_QUERY = '!=s';
private const OPERATOR_NOT_EQUAL_ANY = '!=any';
private const OPERATOR_GREATER_ANY = '>any';
private const OPERATOR_GREATER_OR_EQUAL_ANY = '>=any';
private const OPERATOR_LESS_ANY = '<any';
private const OPERATOR_LESS_OR_EQUAL_ANY = '<=any';
private const OPERATOR_EQUAL_ALL = '=all';
private const OPERATOR_GREATER_ALL = '>all';
private const OPERATOR_GREATER_OR_EQUAL_ALL = '>=all';
private const OPERATOR_LESS_ALL = '<all';
private const OPERATOR_LESS_OR_EQUAL_ALL = '<=all';
private string $rawKey;
private mixed $rawValue;
private function __construct(string $rawKey, mixed $rawValue)
{
$this->rawKey = $rawKey;
$this->rawValue = $rawValue;
}
public function getRaw(): array
{
return [$this->rawKey => $this->rawValue];
}
public function getRawKey(): string
{
return $this->rawKey;
}
public function getRawValue(): mixed
{
return $this->rawValue;
}
/**
* Create '=' comparison.
*
* @param Expression $argument1 An expression.
* @param Expression|Select|string|int|float|bool|null $argument2 A scalar, expression or sub-query.
* @return self
*/
public static function equal(
Expression $argument1,
Expression|Select|string|int|float|bool|null $argument2
): self {
return self::createComparison(self::OPERATOR_EQUAL, $argument1, $argument2);
}
/**
* Create '!=' comparison.
*
* @param Expression $argument1 An expression.
* @param Expression|Select|string|int|float|bool|null $argument2 A scalar, expression or sub-query.
* @return self
*/
public static function notEqual(
Expression $argument1,
Expression|Select|string|int|float|bool|null $argument2
): self {
return self::createComparison(self::OPERATOR_NOT_EQUAL, $argument1, $argument2);
}
/**
* Create 'LIKE' comparison.
*
* @param Expression $subject What to test.
* @param Expression|string $pattern A pattern.
* @return self
*/
public static function like(Expression $subject, Expression|string $pattern): self
{
return self::createComparison(self::OPERATOR_LIKE, $subject, $pattern);
}
/**
* Create 'NOT LIKE' comparison.
*
* @param Expression $subject What to test.
* @param Expression|string $pattern A pattern.
* @return self
*/
public static function notLike(Expression $subject, Expression|string $pattern): self
{
return self::createComparison(self::OPERATOR_NOT_LIKE, $subject, $pattern);
}
/**
* Create '>' comparison.
*
* @param Expression $argument1 An expression.
* @param Expression|Select|string|int|float $argument2 A scalar, expression or sub-query.
* @return self
*/
public static function greater(Expression $argument1, Expression|Select|string|int|float $argument2): self
{
return self::createComparison(self::OPERATOR_GREATER, $argument1, $argument2);
}
/**
* Create '>=' comparison.
*
* @param Expression $argument1 An expression.
* @param Expression|Select|string|int|float $argument2 A scalar, expression or sub-query.
* @return self
*/
public static function greaterOrEqual(Expression $argument1, Expression|Select|string|int|float $argument2): self
{
return self::createComparison(self::OPERATOR_GREATER_OR_EQUAL, $argument1, $argument2);
}
/**
* Create '<' comparison.
*
* @param Expression $argument1 An expression.
* @param Expression|Select|string|int|float $argument2 A scalar, expression or sub-query.
* @return self
*/
public static function less(Expression $argument1, Expression|Select|string|int|float $argument2): self
{
return self::createComparison(self::OPERATOR_LESS, $argument1, $argument2);
}
/**
* Create '<=' comparison.
*
* @param Expression $argument1 An expression.
* @param Expression|Select|string|int|float $argument2 A scalar, expression or sub-query.
* @return self
*/
public static function lessOrEqual(Expression $argument1, Expression|Select|string|int|float $argument2): self
{
return self::createComparison(self::OPERATOR_LESS_OR_EQUAL, $argument1, $argument2);
}
/**
* Create 'IN' comparison.
*
* @param Expression $subject What to test.
* @param Select|scalar[] $set A set of values. A select query or array of scalars.
* @return self
*/
public static function in(Expression $subject, Select|array $set): self
{
if ($set instanceof Select) {
return self::createInOrNotInSubQuery(self::OPERATOR_IN_SUB_QUERY, $subject, $set);
}
return self::createInOrNotInArray(self::OPERATOR_EQUAL, $subject, $set);
}
/**
* Create 'NOT IN' comparison.
*
* @param Expression $subject What to test.
* @param Select|scalar[] $set A set of values. A select query or array of scalars.
* @return self
*/
public static function notIn(Expression $subject, Select|array $set): self
{
if ($set instanceof Select) {
return self::createInOrNotInSubQuery(self::OPERATOR_NOT_IN_SUB_QUERY, $subject, $set);
}
return self::createInOrNotInArray(self::OPERATOR_NOT_EQUAL, $subject, $set);
}
/**
* Create '!= ANY' comparison.
*
* @param Expression $argument An expression.
* @param Select $subQuery A sub-query.
* @return self
*/
public static function notEqualAny(Expression $argument, Select $subQuery): self
{
return self::createComparison(self::OPERATOR_NOT_EQUAL_ANY, $argument, $subQuery);
}
/**
* Create '> ANY' comparison.
*
* @param Expression $argument An expression.
* @param Select $subQuery A sub-query.
* @return self
*/
public static function greaterAny(Expression $argument, Select $subQuery): self
{
return self::createComparison(self::OPERATOR_GREATER_ANY, $argument, $subQuery);
}
/**
* Create '< ANY' comparison.
*
* @param Expression $argument An expression.
* @param Select $subQuery A sub-query.
* @return self
*/
public static function lessAny(Expression $argument, Select $subQuery): self
{
return self::createComparison(self::OPERATOR_LESS_ANY, $argument, $subQuery);
}
/**
* Create '>= ANY' comparison.
*
* @param Expression $argument An expression.
* @param Select $subQuery A sub-query.
* @return self
*/
public static function greaterOrEqualAny(Expression $argument, Select $subQuery): self
{
return self::createComparison(self::OPERATOR_GREATER_OR_EQUAL_ANY, $argument, $subQuery);
}
/**
* Create '<= ANY' comparison.
*
* @param Expression $argument An expression.
* @param Select $subQuery A sub-query.
* @return self
*/
public static function lessOrEqualAny(Expression $argument, Select $subQuery): self
{
return self::createComparison(self::OPERATOR_LESS_OR_EQUAL_ANY, $argument, $subQuery);
}
/**
* Create '= ALL' comparison.
*
* @param Expression $argument An expression.
* @param Select $subQuery A sub-query.
* @return self
*/
public static function equalAll(Expression $argument, Select $subQuery): self
{
return self::createComparison(self::OPERATOR_EQUAL_ALL, $argument, $subQuery);
}
/**
* Create '> ALL' comparison.
*
* @param Expression $argument An expression.
* @param Select $subQuery A sub-query.
* @return self
*/
public static function greaterAll(Expression $argument, Select $subQuery): self
{
return self::createComparison(self::OPERATOR_GREATER_ALL, $argument, $subQuery);
}
/**
* Create '< ALL' comparison.
*
* @param Expression $argument An expression.
* @param Select $subQuery A sub-query.
* @return self
*/
public static function lessAll(Expression $argument, Select $subQuery): self
{
return self::createComparison(self::OPERATOR_LESS_ALL, $argument, $subQuery);
}
/**
* Create '>= ALL' comparison.
*
* @param Expression $argument An expression.
* @param Select $subQuery A sub-query.
* @return self
*/
public static function greaterOrEqualAll(Expression $argument, Select $subQuery): self
{
return self::createComparison(self::OPERATOR_GREATER_OR_EQUAL_ALL, $argument, $subQuery);
}
/**
* Create '<= ALL' comparison.
*
* @param Expression $argument An expression.
* @param Select $subQuery A sub-query.
* @return self
*/
public static function lessOrEqualAll(Expression $argument, Select $subQuery): self
{
return self::createComparison(self::OPERATOR_LESS_OR_EQUAL_ALL, $argument, $subQuery);
}
private static function createComparison(
string $operator,
Expression|string $argument1,
Expression|Select|string|int|float|bool|null $argument2
): self {
if (is_string($argument1)) {
$key = $argument1;
if ($key === '') {
throw new RuntimeException("Expression can't be empty.");
}
} else {
$key = $argument1->getValue();
}
if (str_ends_with($key, ':')) {
throw new RuntimeException("Expression should not end with `:`.");
}
$key .= $operator;
if ($argument2 instanceof Expression) {
$key .= ':';
$value = $argument2->getValue();
} else {
$value = $argument2;
}
return new self($key, $value);
}
/**
* @param scalar[] $valueList
*/
private static function createInOrNotInArray(
string $operator,
Expression|string $argument1,
array $valueList
): self {
foreach ($valueList as $item) {
if (!is_scalar($item)) {
throw new RuntimeException("Array items must be scalar.");
}
}
if (is_string($argument1)) {
$key = $argument1;
if ($key === '') {
throw new RuntimeException("Expression can't be empty.");
}
if (str_ends_with($key, ':')) {
throw new RuntimeException("Expression can't end with `:`.");
}
} else {
$key = $argument1->getValue();
}
$key .= $operator;
return new self($key, $valueList);
}
private static function createInOrNotInSubQuery(
string $operator,
Expression|string $argument1,
Select $query
): self {
if (is_string($argument1)) {
$key = $argument1;
if ($key === '') {
throw new RuntimeException("Expression can't be empty.");
}
if (str_ends_with($key, ':')) {
throw new RuntimeException("Expression can't end with `:`.");
}
} else {
$key = $argument1->getValue();
}
$key .= $operator;
return new self($key, $query);
}
}

View File

@@ -0,0 +1,61 @@
<?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\Query\Part\Where;
use Espo\ORM\Query\Part\WhereItem;
use Espo\ORM\Query\Select;
/**
* An EXISTS-operator. Immutable.
*/
class Exists implements WhereItem
{
private function __construct(private Select $rawValue) {}
public function getRaw(): array
{
return ['EXISTS' => $this->getRawValue()];
}
public function getRawKey(): string
{
return 'EXISTS';
}
public function getRawValue(): Select
{
return $this->rawValue;
}
public static function create(Select $subQuery): self
{
return new self($subQuery);
}
}

View File

@@ -0,0 +1,80 @@
<?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\Query\Part\Where;
use Espo\ORM\Query\Part\WhereItem;
/**
* A NOT-operator. Immutable.
*/
class Not implements WhereItem
{
/** @var array<string|int, mixed> */
private $rawValue = [];
public function getRaw(): array
{
return ['NOT' => $this->getRawValue()];
}
public function getRawKey(): string
{
return 'NOT';
}
/**
* @return array<string|int, mixed>
*/
public function getRawValue(): array
{
return $this->rawValue;
}
/**
* @param array<string|int, mixed> $whereClause
*/
public static function fromRaw(array $whereClause): self
{
if (count($whereClause) === 1 && array_keys($whereClause)[0] === 0) {
$whereClause = $whereClause[0];
}
$obj = new self();
$obj->rawValue = $whereClause;
return $obj;
}
public static function create(WhereItem $item): self
{
return self::fromRaw($item->getRaw());
}
}

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\Query\Part\Where;
use Espo\ORM\Query\Part\WhereItem;
/**
* OR-group. Immutable.
*/
class OrGroup implements WhereItem
{
/** @var array<string|int, mixed> */
private $rawValue = [];
public function __construct()
{
}
public function getRaw(): array
{
return ['OR' => $this->rawValue];
}
public function getRawKey(): string
{
return 'OR';
}
/**
* @return array<string|int, mixed>
*/
public function getRawValue(): array
{
return $this->rawValue;
}
/**
* Get a number of items.
*/
public function getItemCount(): int
{
return count($this->rawValue);
}
/**
* @param array<string|int, mixed> $whereClause
*/
public static function fromRaw(array $whereClause): self
{
$obj = new self();
$obj->rawValue = $whereClause;
return $obj;
}
public static function create(WhereItem ...$itemList): self
{
$builder = self::createBuilder();
foreach ($itemList as $item) {
$builder->add($item);
}
return $builder->build();
}
public static function createBuilder(): OrGroupBuilder
{
return new OrGroupBuilder();
}
}

View File

@@ -0,0 +1,95 @@
<?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\Query\Part\Where;
use Espo\ORM\Query\Part\WhereItem;
class OrGroupBuilder
{
/** @var array<string|int, mixed> */
private array $raw = [];
public function build(): OrGroup
{
return OrGroup::fromRaw($this->raw);
}
public function add(WhereItem $item): self
{
$key = $item->getRawKey();
$value = $item->getRawValue();
if ($item instanceof AndGroup) {
$this->raw = self::normalizeRaw($this->raw);
$this->raw[] = $value;
return $this;
}
if (count($this->raw) === 0) {
$this->raw[$key] = $value;
return $this;
}
$this->raw = self::normalizeRaw($this->raw);
$this->raw[] = [$key => $value];
return $this;
}
/**
* Merge with another OrGroup.
*/
public function merge(OrGroup $orGroup): self
{
$this->raw = array_merge(
self::normalizeRaw($this->raw),
self::normalizeRaw($orGroup->getRawValue())
);
return $this;
}
/**
* @param array<string|int, mixed> $raw
* @return array<string|int, mixed>
*/
private static function normalizeRaw(array $raw): array
{
if (count($raw) === 1 && array_keys($raw)[0] !== 0) {
return [$raw];
}
return $raw;
}
}

View File

@@ -0,0 +1,45 @@
<?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\Query\Part;
use Espo\ORM\Query\Part\Where\AndGroup;
/**
* A where-clause. Immutable.
*
* Immutable.
*/
class WhereClause extends AndGroup
{
public function getRaw(): array
{
return $this->getRawValue();
}
}

View File

@@ -0,0 +1,45 @@
<?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\Query\Part;
/**
* Can be used as a where-clause.
*/
interface WhereItem
{
/**
* @return array<string|int, mixed>
*/
public function getRaw(): array;
public function getRawKey(): string;
public function getRawValue(): mixed;
}

View File

@@ -0,0 +1,43 @@
<?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\Query;
/**
* Query parameters. Instances are immutable. Need to clone with a builder to get a copy for a further modification.
*/
interface Query
{
/**
* Get parameters in RAW format.
*
* @return array<string, mixed>
*/
public function getRaw(): array;
}

View File

@@ -0,0 +1,207 @@
<?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\Query;
use Espo\ORM\Query\Part\WhereClause;
use Espo\ORM\Query\Part\Selection;
use Espo\ORM\Query\Part\Order;
use Espo\ORM\Query\Part\Expression;
use RuntimeException;
/**
* Select parameters.
*
* Immutable.
*
* @todo Add validation and normalization.
*/
class Select implements SelectingQuery
{
use SelectingTrait;
use BaseTrait;
public const ORDER_ASC = Order::ASC;
public const ORDER_DESC = Order::DESC;
/**
* Get an entity type.
*/
public function getFrom(): ?string
{
return $this->params['from'] ?? null;
}
/**
* Get a from-alias
*/
public function getFromAlias(): ?string
{
return $this->params['fromAlias'] ?? null;
}
/**
* Get a from-query.
*/
public function getFromQuery(): ?SelectingQuery
{
return $this->params['fromQuery'] ?? null;
}
/**
* Get an OFFSET.
*/
public function getOffset(): ?int
{
return $this->params['offset'] ?? null;
}
/**
* Get a LIMIT.
*/
public function getLimit(): ?int
{
return $this->params['limit'] ?? null;
}
/**
* Get USE INDEX (list of indexes).
*
* @return string[]
*/
public function getUseIndex(): array
{
return $this->params['useIndex'] ?? [];
}
/**
* Get SELECT items.
*
* @return Selection[]
*/
public function getSelect(): array
{
return array_map(
function ($item) {
if (is_array($item) && count($item)) {
return Selection::fromString($item[0])
->withAlias($item[1] ?? null);
}
if (is_string($item)) {
return Selection::fromString($item);
}
throw new RuntimeException("Bad select item.");
},
$this->params['select'] ?? []
);
}
/**
* Whether DISTINCT is applied.
*/
public function isDistinct(): bool
{
return $this->params['distinct'] ?? false;
}
/**
* Whether a FOR SHARE lock mode is set.
*/
public function isForShare(): bool
{
return $this->params['forShare'] ?? false;
}
/**
* Whether a FOR UPDATE lock mode is set.
*/
public function isForUpdate(): bool
{
return $this->params['forUpdate'] ?? false;
}
/**
* Get GROUP BY items.
*
* @return Expression[]
*/
public function getGroup(): array
{
return array_map(
function (string $item) {
return Expression::create($item);
},
$this->params['groupBy'] ?? []
);
}
/**
* Get HAVING clause.
*/
public function getHaving(): ?WhereClause
{
$havingClause = $this->params['havingClause'] ?? null;
if ($havingClause === null || $havingClause === []) {
return null;
}
$having = WhereClause::fromRaw($havingClause);
if (!$having instanceof WhereClause) {
throw new RuntimeException();
}
return $having;
}
/**
* @param array<string, mixed> $params
*/
private function validateRawParams(array $params): void
{
$this->validateRawParamsSelecting($params);
if (
(
!empty($params['joins']) ||
!empty($params['leftJoins']) ||
!empty($params['whereClause']) ||
!empty($params['orderBy'])
)
&&
empty($params['from']) && empty($params['fromQuery'])
) {
throw new RuntimeException("Select params: Missing 'from'.");
}
}
}

View File

@@ -0,0 +1,335 @@
<?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\Query;
use Espo\ORM\Query\Part\Expression;
use Espo\ORM\Query\Part\Selection;
use Espo\ORM\Query\Part\WhereItem;
use InvalidArgumentException;
use RuntimeException;
class SelectBuilder implements Builder
{
use SelectingBuilderTrait;
/**
* Create an instance.
*/
public static function create(): self
{
return new self();
}
/**
* Build a SELECT query.
*/
public function build(): Select
{
return Select::fromRaw($this->params);
}
/**
* Clone an existing query for a subsequent modifying and building.
*/
public function clone(Select $query): self
{
$this->cloneInternal($query);
return $this;
}
/**
* Set FROM. For what entity type to build a query.
*/
public function from(string $entityType, ?string $alias = null): self
{
if (isset($this->params['from']) && $entityType !== $this->params['from']) {
throw new RuntimeException("Method 'from' can be called only once.");
}
if (isset($this->params['fromQuery'])) {
throw new RuntimeException("Method 'from' can't be if 'fromQuery' is set.");
}
$this->params['from'] = $entityType;
if ($alias) {
$this->params['fromAlias'] = $alias;
}
return $this;
}
/**
* Set FROM sub-query.
*/
public function fromQuery(SelectingQuery $query, string $alias): self
{
if (isset($this->params['from'])) {
throw new RuntimeException("Method 'fromQuery' can be called only once.");
}
if (isset($this->params['fromQuery'])) {
throw new RuntimeException("Method 'fromQuery' can't be if 'from' is set.");
}
if ($alias === '') {
throw new RuntimeException("Alias can't be empty.");
}
$this->params['fromQuery'] = $query;
$this->params['fromAlias'] = $alias;
return $this;
}
/**
* Set DISTINCT parameter.
*/
public function distinct(): self
{
$this->params['distinct'] = true;
return $this;
}
/**
* Apply OFFSET and LIMIT.
*/
public function limit(?int $offset = null, ?int $limit = null): self
{
$this->params['offset'] = $offset;
$this->params['limit'] = $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.
*/
public function select($select, ?string $alias = null): self
{
/** @phpstan-var mixed $select */
if (is_array($select)) {
$this->params['select'] = $this->normalizeSelectExpressionArray($select);
return $this;
}
if ($select instanceof Expression) {
$select = $select->getValue();
} else if ($select instanceof Selection) {
$alias = $alias ?? $select->getAlias();
$select = $select->getExpression()->getValue();
}
if (is_string($select)) {
$this->params['select'] = $this->params['select'] ?? [];
$this->params['select'][] = $alias ?
[$select, $alias] :
$select;
return $this;
}
throw new InvalidArgumentException();
}
/**
* 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
*/
public function group($groupBy): self
{
/** @phpstan-var mixed $groupBy */
if (is_array($groupBy)) {
$this->params['groupBy'] = $this->normalizeExpressionItemArray($groupBy);
return $this;
}
if ($groupBy instanceof Expression) {
$groupBy = $groupBy->getValue();
}
if (is_string($groupBy)) {
$this->params['groupBy'] = $this->params['groupBy'] ?? [];
$this->params['groupBy'][] = $groupBy;
return $this;
}
throw new InvalidArgumentException();
}
/**
* @deprecated Use `group` method.
* @param Expression|Expression[]|string|string[] $groupBy
*/
public function groupBy($groupBy): self
{
return $this->group($groupBy);
}
/**
* Use index.
*/
public function useIndex(string $index): self
{
$this->params['useIndex'] = $this->params['useIndex'] ?? [];
$this->params['useIndex'][] = $index;
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 mixed[]|scalar|null $value A value. Omitted if the first argument is not string.
*/
public function having($clause, $value = null): self
{
$this->applyWhereClause('havingClause', $clause, $value);
return $this;
}
/**
* Lock selected rows in shared mode. To be used within a transaction.
*/
public function forShare(): self
{
if (isset($this->params['forUpdate'])) {
throw new RuntimeException("Can't use two lock modes together.");
}
$this->params['forShare'] = true;
return $this;
}
/**
* Lock selected rows. To be used within a transaction.
*/
public function forUpdate(): self
{
if (isset($this->params['forShare'])) {
throw new RuntimeException("Can't use two lock modes together.");
}
$this->params['forUpdate'] = true;
return $this;
}
/**
* @todo Remove?
*/
public function withDeleted(): self
{
$this->params['withDeleted'] = true;
return $this;
}
/**
* @param array<Expression|Selection|mixed[]> $itemList
* @return array<array{0: string, 1?: string}|string>
*/
private function normalizeSelectExpressionArray(array $itemList): array
{
$resultList = [];
foreach ($itemList as $item) {
if ($item instanceof Expression) {
$resultList[] = $item->getValue();
continue;
}
if ($item instanceof Selection) {
$resultList[] = $item->getAlias() ?
[$item->getExpression()->getValue(), $item->getAlias()] :
[$item->getExpression()->getValue()];
continue;
}
if (!is_array($item) || !count($item) || !$item[0] instanceof Expression) {
/** @var array{0:string,1?:string} $item */
$resultList[] = $item;
continue;
}
$newItem = [$item[0]->getValue()];
if (count($item) > 1) {
$newItem[] = $item[1];
}
/** @var array{0: string, 1?: string} $newItem */
$resultList[] = $newItem;
}
return $resultList;
}
}

View File

@@ -0,0 +1,429 @@
<?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\Query;
use Espo\ORM\Query\Part\WhereItem;
use Espo\ORM\Query\Part\Expression;
use Espo\ORM\Query\Part\Order;
use Espo\ORM\Query\Part\Join;
use InvalidArgumentException;
use LogicException;
use RuntimeException;
trait SelectingBuilderTrait
{
use BaseBuilderTrait;
/**
* 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 mixed[]|scalar|null $value A value. Omitted if the first argument is not string.
*/
public function where($clause, $value = null): self
{
$this->applyWhereClause('whereClause', $clause, $value);
return $this;
}
/**
* @param WhereItem|array<string|int, mixed>|string $clause A key or where clause.
* @param mixed[]|scalar|null $value A value. Omitted if the first argument is not string.
*/
private function applyWhereClause(string $type, $clause, $value): void
{
if ($clause instanceof WhereItem) {
$clause = $clause->getRaw();
}
$this->params[$type] = $this->params[$type] ?? [];
$original = $this->params[$type];
if (!is_string($clause) && !is_array($clause)) {
throw new InvalidArgumentException("Bad where clause.");
}
if (is_array($clause)) {
$new = $clause;
}
if (is_string($clause)) {
$new = [$clause => $value];
}
$containsSameKeys = (bool) count(
array_intersect(
array_keys($new),
array_keys($original)
)
);
if ($containsSameKeys) {
$this->params[$type][] = $new;
return;
}
$this->params[$type] = $new + $original;
}
/**
* 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. True for DESC.
*/
public function order($orderBy, $direction = null): self
{
if (is_bool($direction)) {
$direction = $direction ? Order::DESC : Order::ASC;
}
if (is_array($orderBy)) {
$this->params['orderBy'] = $this->normalizeOrderExpressionItemArray(
$orderBy,
$direction ?? Order::ASC
);
return $this;
}
if (!$orderBy) {
throw new InvalidArgumentException();
}
$this->params['orderBy'] = $this->params['orderBy'] ?? [];
if ($orderBy instanceof Expression) {
$orderBy = $orderBy->getValue();
$direction = $direction ?? Order::ASC;
} else if ($orderBy instanceof Order) {
$direction = $direction ?? $orderBy->getDirection();
$orderBy = $orderBy->getExpression()->getValue();
} else {
$direction = $direction ?? Order::ASC;
}
$this->params['orderBy'][] = [$orderBy, $direction];
return $this;
}
/**
* Add JOIN.
*
* @param Join|string|Select $target A relation name, table or sub-query. A relation name should be in camelCase,
* a table in CamelCase.
* @param ?string $alias An alias.
* @param WhereItem|array<string|int, mixed>|null $conditions Join conditions.
*/
public function join(
$target,
?string $alias = null,
WhereItem|array|null $conditions = null
): self {
return $this->joinInternal('joins', $target, $alias, $conditions);
}
/**
* Add LEFT JOIN.
*
* @param Join|string|Select $target A relation name, table or sub-query. A relation name should be in camelCase,
* a table in CamelCase.
* @param ?string $alias An alias.
* @param WhereItem|array<string|int, mixed>|null $conditions Join conditions.
*/
public function leftJoin(
$target,
?string $alias = null,
WhereItem|array|null $conditions = null
): self {
return $this->joinInternal('leftJoins', $target, $alias, $conditions);
}
/**
* @param 'leftJoins'|'joins' $type
* @todo Support USE INDEX in Join.
* @param Join|string|Select $target $target
* @param WhereItem|array<string|int, mixed>|null $conditions
*/
private function joinInternal(
string $type,
$target,
?string $alias = null,
WhereItem|array|null $conditions = null
): self {
$onlyMiddle = false;
$isLateral = false;
/** @var string|Join|array<int, mixed> $target */
$joinType = null;
if ($target instanceof Join) {
$alias = $alias ?? $target->getAlias();
$conditions = $conditions ?? $target->getConditions();
$onlyMiddle = $target->isOnlyMiddle();
$isLateral = $target->isLateral();
$joinType = $target->getType();
$target = $target->getTarget();
}
if ($type === 'leftJoins') {
$joinType = Join\JoinType::left;
}
if ($target instanceof Select && !$alias) {
throw new LogicException("Sub-query join can't be used w/o alias.");
}
$noLeftAlias = false;
if ($conditions instanceof WhereItem) {
$conditions = $conditions->getRaw();
$noLeftAlias = true;
}
$this->params['joins'] ??= [];
// For bc.
// @todo Remove in v10.0.
if (is_array($target)) {
// @todo Log deprecation.
$joinList = $target;
$this->params[$type] ??= [];
foreach ($joinList as $item) {
$this->params[$type][] = $item;
}
return $this;
}
if (
is_null($alias) &&
is_null($conditions) &&
is_string($target) &&
$this->hasJoinAliasInternal('joins', $target)
) {
return $this;
}
$params = [];
if ($noLeftAlias) {
$params['noLeftAlias'] = true;
}
if ($onlyMiddle) {
$params['onlyMiddle'] = true;
}
if ($isLateral) {
$params['isLateral'] = true;
}
$params['type'] = $joinType;
$this->params['joins'][] = [$target, $alias, $conditions, $params];
return $this;
}
private function hasJoinAliasInternal(string $type, string $alias): bool
{
$joins = $this->params[$type] ?? [];
if (in_array($alias, $joins)) {
return true;
}
foreach ($joins as $item) {
if (is_array($item) && count($item) > 1) {
if ($item[1] === $alias) {
return true;
}
if (
$item[1] === null &&
$item[0] === $alias &&
lcfirst($item[0]) === $alias
) {
return true;
}
}
}
return false;
}
/**
* @deprecated As of v9.2.0. Use `hasJoinAlias`.
*/
public function hasLeftJoinAlias(string $alias): bool
{
return $this->hasJoinAlias($alias);
}
/**
* Whether an alias is in joins.
*/
public function hasJoinAlias(string $alias): bool
{
return $this->hasJoinAliasInternal('joins', $alias) ||
// For bc.
$this->hasJoinAliasInternal('leftJoins', $alias);
}
/**
* @param array<Expression|mixed[]> $itemList
* @return array<array{0: string, 1?: string}|string>
*/
private function normalizeExpressionItemArray(array $itemList): array
{
$resultList = [];
foreach ($itemList as $item) {
if ($item instanceof Expression) {
$resultList[] = $item->getValue();
continue;
}
if (!is_array($item) || !count($item) || !$item[0] instanceof Expression) {
/** @var array{0:string, 1?:string} $item */
$resultList[] = $item;
continue;
}
$newItem = [$item[0]->getValue()];
if (count($item) > 1) {
$newItem[] = $item[1];
}
/** @var array{0:string,1?:string} $newItem */
$resultList[] = $newItem;
}
return $resultList;
}
/**
* @param array<Order|mixed[]|string> $itemList
* @param string|bool|null $direction
* @return array<array{string, string|bool}>
*/
private function normalizeOrderExpressionItemArray(array $itemList, $direction): array
{
$resultList = [];
foreach ($itemList as $item) {
if (is_string($item)) {
$resultList[] = [$item, $direction];
continue;
}
if (is_int($item)) {
$resultList[] = [(string) $item, $direction];
continue;
}
if ($item instanceof Order) {
$resultList[] = [
$item->getExpression()->getValue(),
$item->getDirection()
];
continue;
}
if ($item instanceof Expression) {
$resultList[] = [
$item->getValue(),
$direction
];
continue;
}
if (!is_array($item) || !count($item)) {
throw new RuntimeException("Bad order item.");
}
$itemValue = $item[0] instanceof Expression ?
$item[0]->getValue() :
$item[0];
if (!is_string($itemValue) && !is_int($itemValue)) {
throw new RuntimeException("Bad order item.");
}
$itemDirection = count($item) > 1 ? $item[1] : $direction;
if (is_bool($itemDirection)) {
$itemDirection = $itemDirection ?
Order::DESC :
Order::ASC;
}
$resultList[] = [$itemValue, $itemDirection];
}
return $resultList;
}
}

View File

@@ -0,0 +1,33 @@
<?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\Query;
interface SelectingQuery extends Query
{}

View File

@@ -0,0 +1,146 @@
<?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\Query;
use Espo\ORM\Query\Part\Order;
use Espo\ORM\Query\Part\WhereClause;
use Espo\ORM\Query\Part\Join;
use RuntimeException;
trait SelectingTrait
{
/**
* Get ORDER items.
*
* @return Order[]
*/
public function getOrder(): array
{
return array_map(
function ($item) {
if (is_array($item) && count($item)) {
$itemValue = is_int($item[0]) ? (string) $item[0] : $item[0];
return Order::fromString($itemValue)
->withDirection($item[1] ?? Order::ASC);
}
if (is_string($item)) {
return Order::fromString($item);
}
throw new RuntimeException("Bad order item.");
},
$this->params['orderBy'] ?? []
);
}
/**
* Get WHERE clause.
*/
public function getWhere(): ?WhereClause
{
$whereClause = $this->params['whereClause'] ?? null;
if ($whereClause === null || $whereClause === []) {
return null;
}
$where = WhereClause::fromRaw($whereClause);
if (!$where instanceof WhereClause) {
throw new RuntimeException();
}
return $where;
}
/**
* Get JOIN items.
*
* @return Join[]
*/
public function getJoins(): array
{
return array_map(
function ($item) {
if (is_string($item)) {
$item = [$item];
}
$conditions = isset($item[2]) ?
WhereClause::fromRaw($item[2]) : null;
$params = $item[3] ?? [];
$type = $params['type'] ?? null;
$type ??= Join\JoinType::inner;
return Join::create($item[0])
->withAlias($item[1] ?? null)
->withConditions($conditions)
->withType($type);
},
$this->params['joins'] ?? []
);
}
/**
* @return Join[]
* @deprecated As of 9.2.0. Use getJoins and check join type.
*/
public function getLeftJoins(): array
{
return array_map(
function ($item) {
if (is_string($item)) {
$item = [$item];
}
$conditions = isset($item[2]) ?
WhereClause::fromRaw($item[2]) : null;
return Join::create($item[0])
->withAlias($item[1] ?? null)
->withConditions($conditions)
->withLeft();
},
$this->params['leftJoins'] ?? []
);
}
/**
* @param array<string, mixed> $params
*/
private static function validateRawParamsSelecting(array $params): void
{
}
}

View File

@@ -0,0 +1,52 @@
<?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\Query;
use RuntimeException;
/**
* Union parameters.
*
* Immutable.
*/
class Union implements SelectingQuery
{
use BaseTrait;
/**
* @param array<string, mixed> $params
*/
private function validateRawParams(array $params): void
{
if (empty($params['queries'])) {
throw new RuntimeException("Union params: No query were added.");
}
}
}

View File

@@ -0,0 +1,146 @@
<?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\Query;
use Espo\ORM\Query\Part\Order;
use InvalidArgumentException;
class UnionBuilder implements Builder
{
use BaseBuilderTrait;
/**
* Create an instance.
*/
public static function create(): self
{
return new self();
}
/**
* Build a UNION select query.
*/
public function build(): Union
{
return Union::fromRaw($this->params);
}
/**
* Clone an existing query for a subsequent modifying and building.
*/
public function clone(Union $query): self
{
$this->cloneInternal($query);
return $this;
}
/**
* Use UNION ALL.
*/
public function all(): self
{
$this->params['all'] = true;
return $this;
}
public function query(Select $query): self
{
$this->params['queries'] = $this->params['queries'] ?? [];
$this->params['queries'][] = $query;
return $this;
}
/**
* Apply OFFSET and LIMIT.
*/
public function limit(?int $offset = null, ?int $limit = null): self
{
$this->params['offset'] = $offset;
$this->params['limit'] = $limit;
return $this;
}
/**
* Apply ORDER.
*
* @param string|array<array{string, (Order::ASC|Order::DESC)|bool}|array{string}> $orderBy A select alias.
* @param (Order::ASC|Order::DESC)|bool $direction A direction. True for DESC.
*/
public function order($orderBy, string|bool $direction = Order::ASC): self
{
if (is_bool($direction)) {
$direction = $direction ? Order::DESC : Order::ASC;
}
if (!$orderBy) {
throw new InvalidArgumentException();
}
if (is_array($orderBy)) {
foreach ($orderBy as $item) {
/** @var mixed[] $item */
if (count($item) === 2) {
/** @var array{string, bool|(Order::ASC|Order::DESC)} $item */
$this->order($item[0], $item[1]);
continue;
}
if (count($item) === 1) {
/** @var array{string} $item */
$this->order($item[0]);
continue;
}
throw new InvalidArgumentException("Bad order.");
}
return $this;
}
/** @var object|scalar $orderBy */
if (!is_string($orderBy) && !is_int($orderBy)) {
throw new InvalidArgumentException("Bad order.");
}
$this->params['orderBy'] = $this->params['orderBy'] ?? [];
$this->params['orderBy'][] = [$orderBy, $direction];
return $this;
}
}

View File

@@ -0,0 +1,109 @@
<?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\Query;
use Espo\ORM\Query\Part\Expression;
use RuntimeException;
/**
* Update parameters.
*
* Immutable.
*/
class Update implements Query
{
use SelectingTrait;
use BaseTrait;
/**
* Get an entity type.
*/
public function getIn(): string
{
$in = $this->params['from'];
if ($in === null) {
throw new RuntimeException("Missing 'in'.");
}
return $in;
}
/**
* Get a LIMIT.
*/
public function getLimit(): ?int
{
return $this->params['limit'] ?? null;
}
/**
* Get SET values.
*
* @return array<string, scalar|Expression|null>
*/
public function getSet(): array
{
$set = [];
/** @var array<string, ?scalar> $raw */
$raw = $this->params['set'];
foreach ($raw as $key => $value) {
if (str_ends_with($key, ':')) {
$key = substr($key, 0, -1);
$value = Expression::create((string) $value);
}
$set[$key] = $value;
}
return $set;
}
/**
* @param array<string, mixed> $params
*/
private function validateRawParams(array $params): void
{
$this->validateRawParamsSelecting($params);
$from = $params['from'] ?? null;
if (!$from || !is_string($from)) {
throw new RuntimeException("Update params: Missing 'in'.");
}
$set = $params['set'] ?? null;
if (!$set || !is_array($set)) {
throw new RuntimeException("Update params: Bad or missing 'set' parameter.");
}
}
}

View File

@@ -0,0 +1,114 @@
<?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\Query;
use Espo\ORM\Query\Part\Expression;
use RuntimeException;
class UpdateBuilder implements Builder
{
use SelectingBuilderTrait;
/**
* Create an instance.
*/
public static function create(): self
{
return new self();
}
/**
* Build a UPDATE query.
*/
public function build(): Update
{
return Update::fromRaw($this->params);
}
/**
* Clone an existing query for a subsequent modifying and building.
*/
public function clone(Update $query): self
{
$this->cloneInternal($query);
return $this;
}
/**
* For what entity type to build a query.
*/
public function in(string $entityType): self
{
if (isset($this->params['from'])) {
throw new RuntimeException("Method 'in' can be called only once.");
}
$this->params['from'] = $entityType;
return $this;
}
/**
* Values to set. Column => Value map.
*
* @param array<string, scalar|Expression|null> $set
*/
public function set(array $set): self
{
$modified = [];
foreach ($set as $key => $value) {
if (!$value instanceof Expression) {
$modified[$key] = $value;
continue;
}
$newKey = rtrim($key, ':') . ':';
$modified[$newKey] = $value->getValue();
}
$this->params['set'] = $modified;
return $this;
}
/**
* Apply LIMIT.
*/
public function limit(?int $limit = null): self
{
$this->params['limit'] = $limit;
return $this;
}
}