snapshot of https://github.com/espocrm/espocrm.git (master, 2026-09-18; blobs > 131072B omitted)
Some checks failed
Test / Test on PHP 8.3 (push) Failing after 5s
Test / Test on PHP 8.4 (push) Failing after 4s
Test / Test on PHP 8.5 (push) Failing after 3s
TypeScript static analysis / TypeScript check (push) Failing after 14s
Test Integration on MySQL / Test on PHP 8.3 (push) Failing after 2s
Test Integration on MySQL / Test on PHP 8.5 (push) Failing after 0s
Test Integration on PostgreSQL / Test on PHP 8.4 fix (push) Failing after 1s
Test Integration on PostgreSQL / Test on PHP 8.4 master (push) Failing after 1s

This commit is contained in:
upstream-mirror
2026-09-18 04:19:15 +05:00
commit 7cc7e6b4f3
10077 changed files with 900756 additions and 0 deletions

View File

@@ -0,0 +1,136 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 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 tests\unit\Espo\ORM;
use Espo\ORM\EntityFactory;
use Espo\ORM\Locker\BaseLocker;
use Espo\ORM\Metadata;
use Espo\ORM\QueryComposer\MysqlQueryComposer;
use Espo\ORM\TransactionManager;
use PDO;
use PHPUnit\Framework\TestCase;
class BaseLockerTest extends TestCase
{
private $transactionManager;
private $locker;
private $pdo;
protected function setUp() : void
{
$this->pdo = $this->createMock(PDO::class);
$entityFactory = $this->createMock(EntityFactory::class);
$metadata = $this->getMockBuilder(Metadata::class)->disableOriginalConstructor()->getMock();
$this->transactionManager = $this->getMockBuilder(TransactionManager::class)
->disableOriginalConstructor()->getMock();
$composer = new MysqlQueryComposer($this->pdo, $entityFactory, $metadata);
$this->locker = new BaseLocker($this->pdo, $composer, $this->transactionManager);
}
public function testLockCommit()
{
$this->transactionManager
->expects($this->exactly(2))
->method('start');
$invokedCount = $this->exactly(2);
$this->pdo
->expects($invokedCount)
->method('exec')
->willReturnCallback(function ($sql) use ($invokedCount) {
if ($invokedCount->numberOfInvocations() === 1) {
$this->assertEquals('LOCK TABLES `account` WRITE', $sql);
}
if ($invokedCount->numberOfInvocations() === 2) {
$this->assertEquals('LOCK TABLES `contact` READ', $sql);
}
return 1;
});
$this->transactionManager
->expects($this->once())
->method('commit');
$this->locker->lockExclusive('Account');
$this->locker->lockShare('Contact');
$this->assertTrue($this->locker->isLocked());
$this->locker->commit();
$this->assertFalse($this->locker->isLocked());
}
public function testLockRollback()
{
$this->transactionManager
->expects($this->exactly(2))
->method('start');
$invokedCount = $this->exactly(2);
$this->pdo
->expects($invokedCount)
->method('exec')
->willReturnCallback(function ($sql) use ($invokedCount) {
if ($invokedCount->numberOfInvocations() === 1) {
$this->assertEquals('LOCK TABLES `account` WRITE', $sql);
}
if ($invokedCount->numberOfInvocations() === 2) {
$this->assertEquals('LOCK TABLES `contact` READ', $sql);
}
return 1;
});
$this->transactionManager
->expects($this->once())
->method('rollback');
$this->locker->lockExclusive('Account');
$this->locker->lockShare('Contact');
$this->assertTrue($this->locker->isLocked());
$this->locker->rollback();
$this->assertFalse($this->locker->isLocked());
}
}

View File

@@ -0,0 +1,199 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 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 tests\unit\Espo\ORM;
use Espo\ORM\BaseEntity;
use Espo\ORM\Defs;
use Espo\ORM\Defs\DefsData;
use Espo\ORM\Entity;
use Espo\ORM\EntityCollection;
use Espo\ORM\Metadata;
use Espo\ORM\MetadataDataProvider;
use Espo\Core\ORM\EntityManager;
use PHPUnit\Framework\TestCase;
use SplObjectStorage;
require_once 'tests/unit/testData/DB/Entities.php';
class CollectionTest extends TestCase
{
private $metadata;
private $entityManager;
protected function setUp(): void
{
$ormMetadata = include('tests/unit/testData/DB/ormMetadata.php');
$metadataDataProvider = $this->createMock(MetadataDataProvider::class);
$metadataDataProvider
->expects($this->any())
->method('get')
->willReturn($ormMetadata);
$this->metadata = new Metadata($metadataDataProvider);
$defsData = new DefsData($this->metadata);
$defs = new Defs($defsData);
$this->entityManager = $this->createMock(EntityManager::class);
$this->entityManager
->expects($this->any())
->method('getDefs')
->willReturn($defs);
}
/** @noinspection PhpSameParameterValueInspection */
private function createEntity(string $entityType): BaseEntity
{
$defs = $this->metadata->get($entityType);
return new BaseEntity($entityType, $defs, $this->entityManager);
}
public function testEntityCollectionAppend(): void
{
$entity1 = $this->createEntity('Account');
$entity2 = $this->createEntity('Account');
$entity3 = $this->createEntity('Account');
$collection = new EntityCollection([$entity1]);
$collection[] = $entity2;
$collection->append($entity3);
$this->assertEquals(3, $collection->count());
}
public function testEntityCollectionIteratorToArray(): void
{
$entity1 = $this->createEntity('Account');
$entity2 = $this->createEntity('Account');
$entity3 = $this->createEntity('Account');
$collection1 = new EntityCollection([$entity1]);
$collection2 = new EntityCollection([$entity2, $entity3]);
$collection = new EntityCollection([
...iterator_to_array($collection1),
...iterator_to_array($collection2),
]);
$this->assertEquals(3, $collection->count());
}
public function testEntityCollectionUnset(): void
{
$entity1 = $this->createEntity('Account');
$entity2 = $this->createEntity('Account');
$collection = new EntityCollection([$entity1]);
$collection[] = $entity2;
unset($collection[1]);
$this->assertEquals(1, $collection->count());
}
public function testFilter(): void
{
$e1 = $this->createMock(Entity::class);
$e2 = $this->createMock(Entity::class);
$e3 = $this->createMock(Entity::class);
$e4 = $this->createMock(Entity::class);
$collection = new EntityCollection([$e1, $e2, $e3, $e4], 'Account');
$filtered = $collection->filter(function ($e) use ($e2, $e3) {
return $e !== $e2 && $e !== $e3;
});
$this->assertEquals([$e1, $e2], [...$filtered]);
$this->assertEquals($collection->getEntityType(), $filtered->getEntityType());
}
public function testSort(): void
{
$e1 = $this->createMock(Entity::class);
$e2 = $this->createMock(Entity::class);
$e3 = $this->createMock(Entity::class);
$map = new SplObjectStorage();
$map[$e1] = 3;
$map[$e2] = 2;
$map[$e3] = 1;
$collection = new EntityCollection([$e1, $e2, $e3], 'Account');
$sorted = $collection->sort(function ($e1, $e2) use ($map) {
return $map[$e1] - $map[$e2];
});
$this->assertEquals([$e3, $e2, $e1], [...$sorted]);
$this->assertEquals($collection->getEntityType(), $sorted->getEntityType());
}
public function testFind(): void
{
$e1 = $this->createMock(Entity::class);
$e2 = $this->createMock(Entity::class);
$e3 = $this->createMock(Entity::class);
$collection = new EntityCollection([$e1, $e2, $e3]);
$e = $collection->find(function ($e) use ($e2) {
return $e === $e2;
});
$this->assertSame($e2, $e);
$e = $collection->find(function ($e) use ($e2) {
return $e === 0;
});
$this->assertNull($e);
}
public function testReverse(): void
{
$e1 = $this->createMock(Entity::class);
$e2 = $this->createMock(Entity::class);
$e3 = $this->createMock(Entity::class);
$collection = new EntityCollection([$e1, $e2, $e3], 'Account');
$reversed = $collection->reverse();
$this->assertEquals([$e3, $e2, $e1], [...$reversed]);
$this->assertEquals($collection->getEntityType(), $reversed->getEntityType());
}
}

View File

@@ -0,0 +1,352 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 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 tests\unit\Espo\ORM;
use Espo\ORM\Defs\Defs;
use Espo\ORM\Metadata;
use Espo\ORM\MetadataDataProvider;
use RuntimeException;
class DefsTest extends \PHPUnit\Framework\TestCase
{
protected ?MetadataDataProvider $metadataDataProvider = null;
protected ?Metadata $metadata = null;
protected ?Defs $defs = null;
protected function setUp() : void
{}
protected function initMetadata(array $data)
{
$this->metadataDataProvider = $this->createMock(MetadataDataProvider::class);
$this->metadataDataProvider
->expects($this->any())
->method('get')
->willReturn($data);
$this->metadata = new Metadata($this->metadataDataProvider);
$this->defs = $this->metadata->getDefs();
}
public function testEntity1()
{
$data = [
'Test1' => [
'attributes' => [
],
'test' => '1',
],
];
$this->initMetadata($data);
$this->assertEquals(['Test1'], $this->defs->getEntityTypeList());
$this->assertEquals('Test1', $this->defs->getEntityList()[0]->getName());
$this->assertEquals('Test1', $this->defs->getEntity('Test1')->getName());
$this->assertEquals('1', $this->defs->getEntity('Test1')->getParam('test'));
$this->assertTrue($this->defs->hasEntity('Test1'));
$this->assertFalse($this->defs->hasEntity('Test2'));
$this->assertNotNull($this->defs->tryGetEntity('Test1'));
$this->assertNull($this->defs->tryGetEntity('Test2'));
}
public function testEntityNotExisting()
{
$data = [
'Test1' => [
'attributes' => [
],
],
];
$this->initMetadata($data);
$this->expectException(RuntimeException::class);
$this->defs->getEntity('Test2');
}
public function testAttribute1()
{
$data = [
'Test' => [
'attributes' => [
'a1' => [
'type' => 'varchar',
],
'a2' => [
'type' => 'int',
'notStorable' => true,
'len' => 20,
],
],
],
];
$this->initMetadata($data);
$entityDefs = $this->defs->getEntity('Test');
$this->assertTrue($entityDefs->hasAttribute('a1'));
$this->assertFalse($entityDefs->hasAttribute('aNotExisting'));
$this->assertNotNull($entityDefs->tryGetAttribute('a1'));
$this->assertNull($entityDefs->tryGetAttribute('aNotExisting'));
$this->assertEquals(['a1', 'a2'], $entityDefs->getAttributeNameList());
$this->assertEquals('a1', $entityDefs->getAttributeList()[0]->getName());
$this->assertEquals('a1', $entityDefs->getAttribute('a1')->getName());
$this->assertEquals('a2', $entityDefs->getAttribute('a2')->getName());
$this->assertEquals('varchar', $entityDefs->getAttribute('a1')->getType());
$this->assertEquals('int', $entityDefs->getAttribute('a2')->getType());
$this->assertEquals(false, $entityDefs->getAttribute('a1')->isNotStorable());
$this->assertEquals(true, $entityDefs->getAttribute('a2')->isNotStorable());
$this->assertEquals(null, $entityDefs->getAttribute('a1')->getLength());
$this->assertEquals(20, $entityDefs->getAttribute('a2')->getLength());
$this->assertTrue($entityDefs->getAttribute('a1')->hasParam('type'));
$this->assertEquals('varchar', $entityDefs->getAttribute('a1')->getParam('type'));
$this->assertFalse($entityDefs->getAttribute('a1')->hasParam('len'));
}
public function testAttributeNotExisting()
{
$data = [
'Test' => [
'attributes' => [
],
],
];
$this->initMetadata($data);
$this->expectException(RuntimeException::class);
$this->defs->getEntity('Test1')->getAttribute('a1');
}
public function testRelation1()
{
$data = [
'Test' => [
'relations' => [
'r1' => [
'type' => 'belongsTo',
'foreign' => 'f1',
'entity' => 'Foreign1',
'key' => 'r1Id',
'foreignKey' => 'id',
],
'r2' => [
'type' => 'manyMany',
'relationName' => 'r2Name',
'midKeys' => ['k1', 'k2'],
'foreign' => 'f2',
'conditions' => ['type' => 'Test'],
],
],
],
];
$this->initMetadata($data);
$entityDefs = $this->defs->getEntity('Test');
$this->assertNotNull($entityDefs->tryGetRelation('r1'));
$this->assertEquals(['r1', 'r2'], $entityDefs->getRelationNameList());
$this->assertEquals('r1', $entityDefs->getRelation('r1')->getName());
$this->assertEquals('manyMany', $entityDefs->getRelation('r2')->getType());
$this->assertTrue($entityDefs->getRelation('r2')->isManyToMany());
$this->assertTrue($entityDefs->getRelation('r1')->hasForeignRelationName());
$this->assertEquals('f1', $entityDefs->getRelation('r1')->getForeignRelationName());
$this->assertFalse($entityDefs->getRelation('r1')->hasRelationshipName());
$this->assertEquals('r2Name', $entityDefs->getRelation('r2')->getRelationshipName());
$this->assertEquals('Foreign1', $entityDefs->getRelation('r1')->getForeignEntityType());
$this->assertEquals('r1Id', $entityDefs->getRelation('r1')->getKey());
$this->assertEquals('id', $entityDefs->getRelation('r1')->getForeignKey());
$this->assertEquals('k1', $entityDefs->getRelation('r2')->getMidKey());
$this->assertEquals('k2', $entityDefs->getRelation('r2')->getForeignMidKey());
$this->assertEquals(['type' => 'Test'], $entityDefs->getRelation('r2')->getConditions());
}
public function testRelationNotExisting()
{
$data = [
'Test' => [
'attributes' => [],
],
];
$this->initMetadata($data);
$this->assertNull($this->defs->getEntity('Test')->tryGetRelation('r1'));
$this->expectException(RuntimeException::class);
$this->defs->getEntity('Test')->getRelation('r1');
}
public function testGetIndex1()
{
$data = [
'Test' => [
'indexes' => [
'i1' => [
'type' => 'unique',
'columns' => ['c1'],
'key' => 'I_1',
],
'i2' => [
'type' => 'index',
'columns' => ['c1', 'c2'],
'key' => 'I_2',
],
],
],
];
$this->initMetadata($data);
$entityDefs = $this->defs->getEntity('Test');
$this->assertEquals(['i1', 'i2'], $entityDefs->getIndexNameList());
$this->assertEquals('i1', $entityDefs->getIndex('i1')->getName());
$this->assertTrue($entityDefs->getIndex('i1')->isUnique());
$this->assertFalse($entityDefs->getIndex('i2')->isUnique());
$this->assertEquals(['c1'], $entityDefs->getIndex('i1')->getColumnList());
$this->assertEquals('I_1', $entityDefs->getIndex('i1')->getKey());
}
public function testIndexNotExisting()
{
$data = [
'Test' => [
'attributes' => [],
],
];
$this->initMetadata($data);
$this->assertNull($this->defs->getEntity('Test')->tryGetIndex('i1'));
$this->expectException(RuntimeException::class);
$this->defs->getEntity('Test')->getIndex('i1');
}
public function testGetField1()
{
$data = [
'Test' => [
'fields' => [
'f1' => [
'type' => 'varchar',
'length' => 100,
],
'f2' => [
'type' => 'enum',
'notStorable' => true,
],
],
],
];
$this->initMetadata($data);
$entityDefs = $this->defs->getEntity('Test');
$this->assertEquals(['f1', 'f2'], $entityDefs->getFieldNameList());
$this->assertNotNull($entityDefs->tryGetField('f1'));
$this->assertNull($entityDefs->tryGetField('fBad'));
$this->assertTrue($entityDefs->hasField('f1'));
$this->assertFalse($entityDefs->hasField('fBad'));
$this->assertEquals('varchar', $entityDefs->getField('f1')->getType());
$this->assertEquals('f1', $entityDefs->getField('f1')->getName());
$this->assertEquals(100, $entityDefs->getField('f1')->getParam('length'));
$this->assertTrue($entityDefs->getField('f2')->isNotStorable());
}
public function testFieldNotExisting()
{
$data = [
'Test' => [
'attributes' => [],
],
];
$this->initMetadata($data);
$this->expectException(RuntimeException::class);
$this->defs->getEntity('Test')->getField('f1');
}
public function testClearCache()
{
$data = [
'Test' => [
'attributes' => [
'a1' => [
'type' => 'varchar',
],
'a2' => [
'type' => 'int',
'notStorable' => true,
'len' => 20,
],
],
],
];
$this->initMetadata($data);
$entityDefs = $this->defs->getEntity('Test');
$this->assertEquals('varchar', $entityDefs->getAttribute('a1')->getType());
$attribute = $entityDefs->getAttribute('a1');
$this->metadata->updateData();
$entityDefsAfter = $this->defs->getEntity('Test');
$this->assertEquals('varchar', $entityDefsAfter->getAttribute('a1')->getType());
$attributeAfter = $entityDefsAfter->getAttribute('a1');
$this->assertNotSame($entityDefs, $entityDefsAfter);
$this->assertNotSame($attribute, $attributeAfter);
}
}

View File

@@ -0,0 +1,77 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 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 tests\unit\Espo\ORM;
use Espo\ORM\EventDispatcher;
use PHPUnit\Framework\TestCase;
class EntityDispatcherTest extends TestCase
{
public function testSubscribe(): void
{
$eventDispatcher = new EventDispatcher();
$dispatched = false;
$eventDispatcher->subscribeToMetadataUpdate(function () use (&$dispatched) {
$dispatched = true;
});
$eventDispatcher->dispatchMetadataUpdate();
$this->assertTrue($dispatched);
}
public function testUnsubscribe(): void
{
$eventDispatcher = new EventDispatcher();
$dispatched1 = false;
$closure1 = function () use (&$dispatched1) {
$dispatched1 = true;
};
$dispatched2 = false;
$closure2 = function () use (&$dispatched2) {
$dispatched2 = true;
};
$eventDispatcher->subscribeToMetadataUpdate($closure1);
$eventDispatcher->subscribeToMetadataUpdate($closure2);
$eventDispatcher->unsubscribeFromMetadataUpdate($closure1);
$eventDispatcher->dispatchMetadataUpdate();
$this->assertFalse($dispatched1);
$this->assertTrue($dispatched2);
}
}

View File

@@ -0,0 +1,442 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 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 tests\unit\Espo\ORM;
use Espo\ORM\BaseEntity;
use Espo\ORM\Defs;
use Espo\ORM\Defs\DefsData;
use Espo\ORM\Metadata;
use Espo\ORM\MetadataDataProvider;
use PHPUnit\Framework\TestCase;
use RuntimeException;
use tests\unit\testData\DB\Job;
use Espo\Core\ORM\EntityManager;
require_once 'tests/unit/testData/DB/Entities.php';
class EntityTest extends TestCase
{
private $entityManager;
private $metadata;
protected function setUp() : void
{
$ormMetadata = include('tests/unit/testData/DB/ormMetadata.php');
$metadataDataProvider = $this->createMock(MetadataDataProvider::class);
$metadataDataProvider
->expects($this->any())
->method('get')
->willReturn($ormMetadata);
$this->metadata = new Metadata($metadataDataProvider);
$defsData = new DefsData($this->metadata);
$defs = new Defs($defsData);
$this->entityManager = $this->createMock(EntityManager::class);
$this->entityManager
->expects($this->any())
->method('getDefs')
->willReturn($defs);
}
/**
* @return BaseEntity
*/
protected function createEntity(string $entityType, ?string $className = null)
{
$defs = $this->metadata->get($entityType);
$classNameToUse = $className ?? BaseEntity::class;
return new $classNameToUse($entityType, $defs, $this->entityManager);
}
public function testIsAttributeChanged()
{
$job = $this->createEntity('Job', Job::class);
$job->setFetched('string', 'test');
$this->assertFalse($job->isAttributeChanged('string'));
$job = $this->createEntity('Job', Job::class);
$job->setFetched('string', 'test');
$job->set('string', 'hello');
$this->assertTrue($job->isAttributeChanged('string'));
$job = $this->createEntity('Job', Job::class);
$job->set('string', 'hello');
$this->assertTrue($job->isAttributeChanged('string'));
$job = $this->createEntity('Job', Job::class);
$job->set('string', null);
$this->assertTrue($job->isAttributeChanged('string'));
$job = $this->createEntity('Job', Job::class);
$job->setFetched('array', ['1', '2']);
$job->set('array', ['2', '1']);
$this->assertTrue($job->isAttributeChanged('array'));
$job = $this->createEntity('Job', Job::class);
$job->setFetched('array', ['1', '2']);
$job->set('array', ['1', '2']);
$this->assertFalse($job->isAttributeChanged('array'));
$job = $this->createEntity('Job', Job::class);
$job->setFetched('array', ['1', '2']);
$job->set('array', ['1', 2]);
$this->assertTrue($job->isAttributeChanged('array'));
$job = $this->createEntity('Job', Job::class);
$job->setFetched('array', [
(object) ['1' => 'v1']
]);
$job->set('array', [
(object) ['1' => 'v1']
]);
$this->assertFalse($job->isAttributeChanged('array'));
$job = $this->createEntity('Job', Job::class);
$job->setFetched('array', [
(object) ['k1' => 'v1']
]);
$job->set('array', [
(object) ['k1' => 'v2']
]);
$this->assertTrue($job->isAttributeChanged('array'));
$job = $this->createEntity('Job', Job::class);
$job->set('array', [
(object) ['k1' => 'v1']
]);
$job->setAsFetched();
$job->set('array', [
(object) ['k1' => 'v1', 'k2' => 'v2'],
]);
$this->assertTrue($job->isAttributeChanged('array'));
$job = $this->createEntity('Job', Job::class);
$v = [
(object) ['k1' => 'v1']
];
$job->setFetched('array', $v);
$v[0]->k2 = 'v2';
$job->set('array', $v);
$this->assertTrue($job->isAttributeChanged('array'));
$job = $this->createEntity('Job', Job::class);
$job->setFetched('array', ['1', '2']);
$job->set('array', ['1', '2', '3']);
$this->assertTrue($job->isAttributeChanged('array'));
$job = $this->createEntity('Job', Job::class);
$job->set('array', ['1', '2', '3']);
$this->assertTrue($job->isAttributeChanged('array'));
$job = $this->createEntity('Job', Job::class);
$job->set('array', null);
$this->assertTrue($job->isAttributeChanged('array'));
$job = $this->createEntity('Job', Job::class);
$job->setFetched('array', null);
$this->assertFalse($job->isAttributeChanged('array'));
$job = $this->createEntity('Job', Job::class);
$job->setFetched('arrayUnordered', ['1', '2']);
$job->set('arrayUnordered', ['2', '1']);
$this->assertFalse($job->isAttributeChanged('arrayUnordered'));
$job = $this->createEntity('Job', Job::class);
$job->setFetched('arrayUnordered', ['1', '2']);
$job->set('arrayUnordered', ['1', '2']);
$this->assertFalse($job->isAttributeChanged('arrayUnordered'));
$job = $this->createEntity('Job', Job::class);
$job->setFetched('arrayUnordered', ['1', '2']);
$job->set('arrayUnordered', ['1', '2', '3']);
$this->assertTrue($job->isAttributeChanged('arrayUnordered'));
$job = $this->createEntity('Job', Job::class);
$job->setFetched('arrayUnordered', ['1', '2']);
$job->set('arrayUnordered', null);
$this->assertTrue($job->isAttributeChanged('arrayUnordered'));
$job = $this->createEntity('Job', Job::class);
$job->setFetched('object', (object) ['a1' => 'value-1']);
$job->set('object', (object) ['a1' => 'value-1']);
$this->assertFalse($job->isAttributeChanged('object'));
$job = $this->createEntity('Job', Job::class);
$job->setFetched('object', (object) ['a1' => 'value-1']);
$job->set('object', ['a1' => 'value-1']);
$this->assertFalse($job->isAttributeChanged('object'));
$job = $this->createEntity('Job', Job::class);
$job->setFetched('object', (object) ['1' => '1']);
$job->set('object', (object) ['1' => 1]);
$this->assertTrue($job->isAttributeChanged('object'));
$job = $this->createEntity('Job', Job::class);
$job->setFetched('object', (object) [
'k1' => (object) [
'k11' => 'v1'
]
]);
$job->set('object', (object) [
'k1' => (object) [
'k11' => 'v2'
]
]);
$this->assertTrue($job->isAttributeChanged('object'));
$job = $this->createEntity('Job', Job::class);
$job->setFetched('object', (object) [
'k1' => [
'k11' => 'v1'
]
]);
$job->set('object', (object) [
'k1' => (object) [
'k11' => 'v1'
]
]);
$this->assertTrue($job->isAttributeChanged('object'));
$job = $this->createEntity('Job', Job::class);
$job->setFetched('object', [
'k1' => [
'k11' => 'v1'
]
]);
$job->set('object', (object) [
'k1' => (object) [
'k11' => 'v1'
]
]);
$this->assertFalse($job->isAttributeChanged('object'));
}
public function testCloningObject() : void
{
$original = (object) [
'k1' => (object) [
'k11' => 'v1'
]
];
/** @var Job $job */
$job = $this->createEntity('Job', Job::class);
$job->set('object', $original);
$gotten = $job->get('object');
$this->assertEquals($gotten, $original);
$this->assertNotSame($gotten, $original);
$this->assertNotSame($gotten->k1, $original->k1);
$this->assertEquals($job->getFromContainerOriginal('object'), $original);
$this->assertNotSame($job->getFromContainerOriginal('object'), $original);
}
public function testEmptyArray() : void
{
$job = $this->createEntity('Job', Job::class);
$job->set('array', []);
$this->assertEquals([], $job->get('array'));
}
public function testEmptyObject() : void
{
$job = $this->createEntity('Job', Job::class);
$job->set('object', (object) []);
$this->assertEquals((object) [], $job->get('object'));
}
public function testCloningArray() : void
{
$original = [
(object) [
'k1' => 'v1',
]
];
/** @var Job $job */
$job = $this->createEntity('Job', Job::class);
$job->set('array', $original);
$gotten = $job->get('array');
$this->assertEquals($gotten, $original);
$this->assertNotSame($gotten[0], $original[0]);
$this->assertEquals($job->getFromContainerOriginal('array'), $original);
$this->assertNotSame($job->getFromContainerOriginal('array'), $original);
}
public function testSetForeign()
{
$entity = $this->createEntity('Comment');
$entity->set([
'postName' => 'test',
]);
$this->assertEquals('test', $entity->get('postName'));
}
public function testSetJsonObject()
{
$entity = $this->createEntity('Test');
$value = '{"test": "1"}';
$entity->set([
'object' => '{"test": "1"}',
]);
$this->assertEquals(json_decode($value), $entity->get('object'));
}
public function testGetJsonArray(): void
{
$entity = $this->createEntity('Job');
$entity->set('array', [0, 1]);
$this->assertEquals([0, 1], $entity->get('array'));
$entity->set('array', [[0], [1]]);
$this->assertEquals([[0], [1]], $entity->get('array'));
$entity->set('array', [
(object) ['test' => 0],
(object) ['test' => 1],
]);
$this->assertEquals([
(object) ['test' => 0],
(object) ['test' => 1],
], $entity->get('array'));
$entity->set('array', [
['test' => 0],
['test' => 1],
]);
$this->assertEquals([
(object) ['test' => 0],
(object) ['test' => 1],
], $entity->get('array'));
}
public function testSetWrongType()
{
$entity = $this->createEntity('Test');
$entity->set([
'int' => '1',
]);
$this->assertEquals(1, $entity->get('int'));
$entity->set('int', '1');
$this->assertEquals(1, $entity->get('int'));
}
public function testHasId(): void
{
$entity = $this->createEntity('Test');
$this->assertFalse($entity->hasId());
$entity->set('id', '1');
$this->assertTrue($entity->hasId());
}
public function testGetId1(): void
{
$entity = $this->createEntity('Test');
$entity->set('id', '1');
$this->assertEquals('1', $entity->getId());
}
public function testGetIdEmpty(): void
{
$entity = $this->createEntity('Test');
$this->expectException(RuntimeException::class);
$entity->getId();
}
public function testIsAttributeWritten1(): void
{
$entity = $this->createEntity('Test');
$entity->set([
'int' => '1',
'object' => (object) [],
]);
$entity->setAsFetched();
$this->assertFalse($entity->isAttributeWritten('int'));
$entity->set('int', '1');
$this->assertTrue($entity->isAttributeWritten('int'));
$this->assertFalse($entity->isAttributeWritten('object'));
}
public function testSetMultiple(): void
{
$entity = $this->createEntity('Test');
$entity->setMultiple(['int' => 2]);
$this->assertEquals(2, $entity->get('int'));
$entity->setMultiple((object) ['int' => 3]);
$this->assertEquals(3, $entity->get('int'));
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,114 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 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 tests\unit\Espo\ORM;
use Espo\ORM\{
Metadata,
MetadataDataProvider,
};
class MetadataTest extends \PHPUnit\Framework\TestCase
{
protected function setUp() : void
{
}
public function testHas1()
{
$metadata = $this->createMetadata([
'Test' => [],
]);
$this->assertTrue($metadata->has('Test'));
}
public function testHas2()
{
$metadata = $this->createMetadata([
'Test' => [],
]);
$this->assertFalse($metadata->has('Hello'));
}
public function testGet1()
{
$metadata = $this->createMetadata([
'Test' => [
'indexes' => [],
],
]);
$this->assertEquals([], $metadata->get('Test', 'indexes'));
}
public function testGet2()
{
$metadata = $this->createMetadata([
'Test' => [
'relations' => [
'test' => [
'type' => 'hasMany',
],
],
],
]);
$this->assertEquals('hasMany', $metadata->get('Test', 'relations.test.type'));
}
public function testGet3()
{
$metadata = $this->createMetadata([
'Test' => [
'relations' => [
'test' => [
'type' => 'hasMany',
],
],
],
]);
$this->assertEquals('hasMany', $metadata->get('Test', ['relations', 'test', 'type']));
}
protected function createMetadata(array $data) : Metadata
{
$metadataDataProvider = $this->createMock(MetadataDataProvider::class);
$metadataDataProvider
->expects($this->any())
->method('get')
->willReturn($data);
return new Metadata($metadataDataProvider);
}
}

View File

@@ -0,0 +1,122 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 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 tests\unit\Espo\ORM;
use Espo\ORM\EntityFactory;
use Espo\ORM\Locker\MysqlLocker;
use Espo\ORM\Metadata;
use Espo\ORM\QueryComposer\MysqlQueryComposer;
use Espo\ORM\TransactionManager;
use PDO;
use PHPUnit\Framework\TestCase;
class MysqlLockerTest extends TestCase
{
private $locker;
private $pdo;
protected function setUp() : void
{
$this->pdo = $this->createMock(PDO::class);
$entityFactory = $this->createMock(EntityFactory::class);
$metadata = $this->createMock(Metadata::class);
$transactionManager = $this->createMock(TransactionManager::class);
$composer = new MysqlQueryComposer($this->pdo, $entityFactory, $metadata);
$this->locker = new MysqlLocker($this->pdo, $composer, $transactionManager);
}
public function testLockCommit()
{
$invokedCount = $this->exactly(3);
$this->pdo
->expects($invokedCount)
->method('exec')
->willReturnCallback(function ($sql) use ($invokedCount) {
if ($invokedCount->numberOfInvocations() === 1) {
$this->assertEquals('LOCK TABLES `account` WRITE', $sql);
}
if ($invokedCount->numberOfInvocations() === 2) {
$this->assertEquals('LOCK TABLES `contact` READ', $sql);
}
if ($invokedCount->numberOfInvocations() === 3) {
$this->assertEquals('UNLOCK TABLES', $sql);
}
return 1;
});
$this->locker->lockExclusive('Account');
$this->locker->lockShare('Contact');
$this->assertTrue($this->locker->isLocked());
$this->locker->commit();
$this->assertFalse($this->locker->isLocked());
}
public function testLockRollback()
{
$invokedCount = $this->exactly(3);
$this->pdo
->expects($invokedCount)
->method('exec')
->willReturnCallback(function ($sql) use ($invokedCount) {
if ($invokedCount->numberOfInvocations() === 1) {
$this->assertEquals('LOCK TABLES `account` WRITE', $sql);
}
if ($invokedCount->numberOfInvocations() === 2) {
$this->assertEquals('LOCK TABLES `contact` READ', $sql);
}
if ($invokedCount->numberOfInvocations() === 3) {
$this->assertEquals('UNLOCK TABLES', $sql);
}
return 1;
});
$this->locker->lockExclusive('Account');
$this->locker->lockShare('Contact');
$this->assertTrue($this->locker->isLocked());
$this->locker->commit();
$this->assertFalse($this->locker->isLocked());
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,382 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 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 tests\unit\Espo\ORM;
use Espo\ORM\EntityFactory;
use Espo\ORM\EntityManager;
use Espo\ORM\Metadata;
use Espo\ORM\MetadataDataProvider;
use Espo\ORM\Query\DeleteBuilder;
use Espo\ORM\Query\InsertBuilder;
use Espo\ORM\Query\Part\Condition;
use Espo\ORM\Query\Part\Expression;
use Espo\ORM\Query\Part\Join;
use Espo\ORM\Query\SelectBuilder;
use Espo\ORM\Query\UpdateBuilder;
use Espo\ORM\QueryBuilder;
use Espo\ORM\QueryComposer\PostgresqlQueryComposer as QueryComposer;
use PHPUnit\Framework\TestCase;
require_once 'tests/unit/testData/DB/Entities.php';
require_once 'tests/unit/testData/DB/MockPDO.php';
require_once 'tests/unit/testData/DB/MockDBResult.php';
class PostgresqlQueryComposerTest extends TestCase
{
private ?QueryComposer $queryComposer;
private ?EntityManager $entityManager;
private $queryBuilder;
protected function setUp(): void
{
$ormMetadata = include('tests/unit/testData/DB/ormMetadata.php');
$metadataDataProvider = $this->createMock(MetadataDataProvider::class);
$metadataDataProvider
->expects($this->any())
->method('get')
->willReturn($ormMetadata);
$metadata = new Metadata($metadataDataProvider);
$this->queryBuilder = new QueryBuilder();
$pdo = $this->createMock('MockPDO');
$pdo
->expects($this->any())
->method('quote')
->willReturnCallback(function() {
$args = func_get_args();
return "'" . $args[0] . "'";
});
$this->entityManager = $this->createMock(EntityManager::class);
$entityFactory = $this->createMock(EntityFactory::class);
$entityFactory
->expects($this->any())
->method('create')
->willReturnCallback(
function () use ($metadata) {
$args = func_get_args();
$className = "tests\\unit\\testData\\DB\\" . $args[0];
$defs = $metadata->get($args[0]) ?? [];
return new $className($args[0], $defs, $this->entityManager);
}
);
$this->queryComposer = new QueryComposer($pdo, $entityFactory, $metadata);
}
public function testUpdate1(): void
{
$query = UpdateBuilder::create()
->in('Comment')
->set(['name' => '1'])
->where(['name' => 'post.name'])
->join('post')
->limit(1)
->order('name')
->build();
$sql = $this->queryComposer->composeUpdate($query);
$expectedSql =
'UPDATE "comment" SET "name" = \'1\' WHERE "comment"."id" IN ' .
'(SELECT "comment"."id" AS "id" FROM "comment" ' .
'JOIN "post" AS "post" ON "comment"."post_id" = "post"."id" AND "post"."deleted" = false ' .
'WHERE "comment"."name" = \'post.name\' AND "comment"."deleted" = false ' .
'ORDER BY "comment"."name" ASC LIMIT 1 OFFSET 0 FOR UPDATE)';
$this->assertEquals($expectedSql, $sql);
}
public function testSelect1()
{
$query = SelectBuilder::create()
->from('Comment')
->select(['name', 'postId', 'postName'])
->build();
$sql = $this->queryComposer->composeSelect($query);
$expectedSql =
'SELECT "comment"."name" AS "name", "comment"."post_id" AS "postId", "post"."name" AS "postName" ' .
'FROM "comment" LEFT JOIN "post" AS "post" ON "comment"."post_id" = "post"."id" ' .
'AND "post"."deleted" = false ' .
'WHERE "comment"."deleted" = false';
$this->assertEquals($expectedSql, $sql);
}
public function testSelectForUpdate1()
{
$query = SelectBuilder::create()
->from('Comment')
->select(['name', 'postId', 'postName'])
->forUpdate()
->build();
$sql = $this->queryComposer->composeSelect($query);
$expectedSql =
'SELECT "comment"."name" AS "name", "comment"."post_id" AS "postId" ' .
'FROM "comment" WHERE "comment"."deleted" = false FOR UPDATE';
$this->assertEquals($expectedSql, $sql);
}
public function testSelectForShare()
{
$query = SelectBuilder::create()
->from('Comment')
->select(['name', 'postId', 'postName'])
->forShare()
->build();
$sql = $this->queryComposer->composeSelect($query);
$expectedSql =
'SELECT "comment"."name" AS "name", "comment"."post_id" AS "postId" ' .
'FROM "comment" WHERE "comment"."deleted" = false FOR SHARE';
$this->assertEquals($expectedSql, $sql);
}
public function testDelete1(): void
{
$query = DeleteBuilder::create()
->from('Account')
->where(['name' => 'test'])
->build();
$sql = $this->queryComposer->composeDelete($query);
$expectedSql =
"DELETE FROM \"account\" " .
"WHERE \"account\".\"name\" = 'test'";
$this->assertEquals($expectedSql, $sql);
}
public function testDelete2(): void
{
$query = DeleteBuilder::create()
->from('Comment')
->join('post')
->where(['name' => 'post.name'])
->limit(1)
->order('name')
->build();
$sql = $this->queryComposer->composeDelete($query);
$expectedSql =
'DELETE FROM "comment" WHERE "comment"."id" IN ' .
'(SELECT "comment"."id" AS "id" FROM "comment" ' .
'JOIN "post" AS "post" ON "comment"."post_id" = "post"."id" AND "post"."deleted" = false ' .
'WHERE "comment"."name" = \'post.name\' AND "comment"."deleted" = false ' .
'ORDER BY "comment"."name" ASC LIMIT 1 OFFSET 0)';
$this->assertEquals($expectedSql, $sql);
}
public function testInsertUpdate1(): void
{
$query = InsertBuilder::create()
->into('PostTag')
->columns(['id', 'postId', 'tagId'])
->values([
'id' => '1',
'postId' => 'post-id',
'tagId' => 'tag-id',
])
->updateSet([
'deleted' => 0
])
->build();
$sql = $this->queryComposer->composeInsert($query);
$expectedSql =
"INSERT INTO \"post_tag\" (\"id\", \"post_id\", \"tag_id\") VALUES ('1', 'post-id', 'tag-id') " .
"ON CONFLICT(\"post_id\", \"tag_id\") DO UPDATE SET \"deleted\" = 0";
$this->assertEquals($expectedSql, $sql);
}
public function testInsertUpdate2(): void
{
$query = InsertBuilder::create()
->into('Account')
->columns(['id', 'name'])
->values([
'id' => '1',
'name' => 'name',
])
->updateSet([
'deleted' => 0
])
->build();
$sql = $this->queryComposer->composeInsert($query);
$expectedSql =
"INSERT INTO \"account\" (\"id\", \"name\") VALUES ('1', 'name') " .
"ON CONFLICT(\"id\") DO UPDATE SET \"deleted\" = 0";
$this->assertEquals($expectedSql, $sql);
}
public function testAlias4(): void
{
$subQuery =
SelectBuilder::create()
->select('id', 'someId')
->from('Test')
->withDeleted()
->build();
$query = SelectBuilder::create()
->select('id')
->from('Post')
->leftJoin(
Join::createWithSubQuery($subQuery, 'sqAlias')
->withConditions(
Condition::equal(
Expression::alias('sqAlias.someId'),
Expression::column('id')
)
)
)
->withDeleted()
->build();
$expectedSql =
"SELECT \"post\".\"id\" AS \"id\" FROM \"post\" LEFT JOIN " .
"(SELECT \"test\".\"id\" AS \"someId\" FROM \"test\") AS \"sqAlias\" ON \"sqAlias\".\"someId\" = \"post\".\"id\"";
$sql = $this->queryComposer->composeSelect($query);
$this->assertEquals($expectedSql, $sql);
}
public function testSelectFunctionTz1()
{
$query = SelectBuilder::create()
->from('Comment')
->select(
Expression::convertTimezone(
Expression::column('createdAt'),
5.5
),
'createdAt'
)
->withDeleted()
->build();
$sql = $this->queryComposer->composeSelect($query);
$expectedSql =
'SELECT "comment"."created_at" + INTERVAL \'330 MINUTE\' AS "createdAt" ' .
'FROM "comment"';
$this->assertEquals($expectedSql, $sql);
}
public function testSelectFunctionTz2()
{
$query = SelectBuilder::create()
->from('Comment')
->select(
Expression::convertTimezone(
Expression::column('createdAt'),
-5.5
),
'createdAt'
)
->withDeleted()
->build();
$sql = $this->queryComposer->composeSelect($query);
$expectedSql =
'SELECT "comment"."created_at" + INTERVAL \'-330 MINUTE\' AS "createdAt" ' .
'FROM "comment"';
$this->assertEquals($expectedSql, $sql);
}
public function testSelectFunctionTz3()
{
$query = SelectBuilder::create()
->from('Comment')
->select(
Expression::convertTimezone(
Expression::column('createdAt'),
5
),
'createdAt'
)
->withDeleted()
->build();
$sql = $this->queryComposer->composeSelect($query);
$expectedSql =
'SELECT "comment"."created_at" + INTERVAL \'5 HOUR\' AS "createdAt" ' .
'FROM "comment"';
$this->assertEquals($expectedSql, $sql);
}
public function testDeleteWithAlias()
{
$query = $this->queryBuilder
->delete()
->from('Account', 'a')
->where([
'a.name' => 'test',
])
->build();
$sql = $this->queryComposer->compose($query);
$expectedSql =
"DELETE FROM \"account\" AS \"a\" " .
"WHERE \"a\".\"name\" = 'test'";
$this->assertEquals($expectedSql, $sql);
}
}

View File

@@ -0,0 +1,450 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 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 tests\unit\Espo\ORM\Query\Part;
use Espo\ORM\Query\Part\Expression as Expr;
use RuntimeException;
class ExpressionTest extends \PHPUnit\Framework\TestCase
{
protected function setUp(): void
{
}
public function testAlias1(): void
{
$actual = Expr::alias('test')->getValue();
$expected = '#test';
$this->assertEquals($expected, $actual);
}
public function testAlias2(): void
{
$actual = Expr::alias('test.someAlias')->getValue();
$expected = 'test.#someAlias';
$this->assertEquals($expected, $actual);
}
public function testColumn1(): void
{
$actual = Expr::column('test')->getValue();
$expected = 'test';
$this->assertEquals($expected, $actual);
}
public function testColumn2(): void
{
$actual = Expr::column('alias.test')->getValue();
$expected = 'alias.test';
$this->assertEquals($expected, $actual);
}
public function testColumn3(): void
{
$actual = Expr::column('@alias1.test')->getValue();
$expected = '@alias1.test';
$this->assertEquals($expected, $actual);
}
public function testColumn4(): void
{
$this->expectException(RuntimeException::class);
Expr::column('@alias@test');
}
public function testColumn5(): void
{
$this->expectException(RuntimeException::class);
Expr::column('^test');
}
public function testValue1(): void
{
$actual = Expr::value('"test"')->getValue();
$expected = "'" . '"test"' . "'";
$this->assertEquals($expected, $actual);
}
public function testValue2(): void
{
$actual = Expr::value("'test'")->getValue();
$expected = "'" . "\\'test\\'" . "'";
$this->assertEquals($expected, $actual);
}
public function testValue3(): void
{
$actual = Expr::value(10)->getValue();
$expected = '10';
$this->assertEquals($expected, $actual);
}
public function testValue4(): void
{
$actual = Expr::value(10.5)->getValue();
$expected = '10.5';
$this->assertEquals($expected, $actual);
}
public function testValue6(): void
{
$actual = Expr::value(true)->getValue();
$expected = 'TRUE';
$this->assertEquals($expected, $actual);
}
public function testValue7(): void
{
$actual = Expr::value(false)->getValue();
$expected = 'FALSE';
$this->assertEquals($expected, $actual);
}
public function testValue8(): void
{
$actual = Expr::value(null)->getValue();
$expected = 'NULL';
$this->assertEquals($expected, $actual);
}
public function testFuncIf1(): void
{
$actual = Expr::if(
Expr::column('test'),
'1',
2
)->getValue();
$expected = "IF:(test, '1', 2)";
$this->assertEquals($expected, $actual);
}
public function testFuncIf2(): void
{
$actual = Expr::if(
Expr::column('test'),
Expr::column('hello.man'),
true
)->getValue();
$expected = "IF:(test, hello.man, TRUE)";
$this->assertEquals($expected, $actual);
}
public function testFuncLike(): void
{
$actual = Expr::like(
Expr::column('test'),
'test%'
)->getValue();
$expected = "LIKE:(test, 'test%')";
$this->assertEquals($expected, $actual);
}
public function testFuncEqual(): void
{
$actual = Expr::equal(
Expr::column('test'),
1
)->getValue();
$expected = "EQUAL:(test, 1)";
$this->assertEquals($expected, $actual);
}
public function testFuncNotEqual(): void
{
$actual = Expr::notEqual(
Expr::column('test'),
1
)->getValue();
$expected = "NOT_EQUAL:(test, 1)";
$this->assertEquals($expected, $actual);
}
public function testIn(): void
{
$actual = Expr::in(
Expr::column('test'),
[
Expr::value(1),
2
]
)->getValue();
$expected = "IN:(test, 1, 2)";
$this->assertEquals($expected, $actual);
}
public function testCoalesce(): void
{
$actual = Expr::coalesce(
Expr::column('test1'),
Expr::column('test2')
)->getValue();
$expected = "COALESCE:(test1, test2)";
$this->assertEquals($expected, $actual);
}
public function testIfNull(): void
{
$actual = Expr::ifNull(
Expr::column('test1'),
''
)->getValue();
$expected = "IFNULL:(test1, '')";
$this->assertEquals($expected, $actual);
}
public function testMonth(): void
{
$actual = Expr::month(
Expr::column('test')
)->getValue();
$expected = "MONTH_NUMBER:(test)";
$this->assertEquals($expected, $actual);
}
public function testWeek0(): void
{
$actual = Expr::week(
Expr::column('test')
)->getValue();
$expected = "WEEK_NUMBER:(test)";
$this->assertEquals($expected, $actual);
}
public function testWeek1(): void
{
$actual = Expr::week(
Expr::column('test'),
1
)->getValue();
$expected = "WEEK_NUMBER_1:(test)";
$this->assertEquals($expected, $actual);
}
public function testDayOfWeek(): void
{
$actual = Expr::dayOfWeek(
Expr::column('test')
)->getValue();
$expected = "DAYOFWEEK:(test)";
$this->assertEquals($expected, $actual);
}
public function testDayOfMonth(): void
{
$actual = Expr::dayOfMonth(
Expr::column('test')
)->getValue();
$expected = "DAYOFMONTH:(test)";
$this->assertEquals($expected, $actual);
}
public function testYear(): void
{
$actual = Expr::year(
Expr::column('test')
)->getValue();
$expected = "YEAR:(test)";
$this->assertEquals($expected, $actual);
}
public function testYearFiscsal(): void
{
$actual = Expr::yearFiscal(
Expr::column('test'),
10
)->getValue();
$expected = "YEAR_10:(test)";
$this->assertEquals($expected, $actual);
}
public function testNow(): void
{
$actual = Expr::now(
)->getValue();
$expected = "NOW:()";
$this->assertEquals($expected, $actual);
}
public function testConvertTimezone(): void
{
$actual = Expr::convertTimezone(
Expr::column('test'),
-10.5
)->getValue();
$expected = "TZ:(test, -10.5)";
$this->assertEquals($expected, $actual);
}
public function testConcat(): void
{
$actual = Expr::concat(
Expr::column('test'),
' ',
'test'
)->getValue();
$expected = "CONCAT:(test, ' ', 'test')";
$this->assertEquals($expected, $actual);
}
public function testReplace(): void
{
$actual = Expr::replace(
Expr::column('test'),
'test',
'hello'
)->getValue();
$expected = "REPLACE:(test, 'test', 'hello')";
$this->assertEquals($expected, $actual);
}
public function testAdd(): void
{
$actual = Expr::add(
Expr::column('test'),
1
)->getValue();
$expected = "ADD:(test, 1)";
$this->assertEquals($expected, $actual);
}
public function testRound(): void
{
$actual = Expr::round(
Expr::column('test'),
1
)->getValue();
$expected = "ROUND:(test, 1)";
$this->assertEquals($expected, $actual);
}
public function testAnd(): void
{
$actual = Expr::and(
Expr::column('test1'),
Expr::column('test2')
)->getValue();
$expected = "AND:(test1, test2)";
$this->assertEquals($expected, $actual);
}
public function testOr(): void
{
$actual = Expr::or(
Expr::column('test1'),
Expr::column('test2')
)->getValue();
$expected = "OR:(test1, test2)";
$this->assertEquals($expected, $actual);
}
public function testNot(): void
{
$actual = Expr::not(
Expr::column('test')
)->getValue();
$expected = "NOT:(test)";
$this->assertEquals($expected, $actual);
}
}

View File

@@ -0,0 +1,100 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 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 tests\unit\Espo\ORM\Query\Part;
use Espo\ORM\Query\Part\Expression;
use Espo\ORM\Query\Part\Join;
use Espo\ORM\Query\Part\Expression as Expr;
use Espo\ORM\Query\SelectBuilder;
class JoinTest extends \PHPUnit\Framework\TestCase
{
public function testCreate1(): void
{
$conditions = Expr::isNull(
Expr::column('test')
);
$join = Join::createWithRelationTarget('test')
->withAlias('testAlias')
->withConditions($conditions);
$this->assertEquals('test', $join->getTarget());
$this->assertEquals('testAlias', $join->getAlias());
$this->assertEquals($conditions, $join->getConditions());
$this->assertTrue($join->isRelation());
$this->assertFalse($join->isTable());
$this->assertEquals(Join::MODE_RELATION, $join->getMode());
}
public function testCreate2(): void
{
$conditions = Expr::isNull(
Expr::column('test')
);
$join = Join::createWithTableTarget('Test')
->withAlias('testAlias')
->withConditions($conditions);
$this->assertEquals('Test', $join->getTarget());
$this->assertEquals('testAlias', $join->getAlias());
$this->assertEquals($conditions, $join->getConditions());
$this->assertTrue($join->isTable());
$this->assertFalse($join->isRelation());
$this->assertEquals(Join::MODE_TABLE, $join->getMode());
}
public function testCreate3(): void
{
$join = Join::create('Test', 'testAlias');
$this->assertEquals('Test', $join->getTarget());
$this->assertEquals('testAlias', $join->getAlias());
}
public function testCreate4(): void
{
$join = Join::createWithSubQuery(
SelectBuilder::create()
->select(Expression::value(true))
->build()
,
'a'
);
$this->assertTrue($join->isSubQuery());
$this->assertEquals(Join::MODE_SUB_QUERY, $join->getMode());
}
}

View File

@@ -0,0 +1,78 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 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 tests\unit\Espo\ORM\Query\Part;
use Espo\ORM\Query\Part\Order as OrderExpr;
use Espo\ORM\Query\Part\Expression as Expr;
class OrderExpressionTest extends \PHPUnit\Framework\TestCase
{
public function testCreate1(): void
{
$order = OrderExpr::fromString('test')->withDesc();
$this->assertEquals(Expr::create('test'), $order->getExpression());
$this->assertEquals(OrderExpr::DESC, $order->getDirection());
$this->assertEquals(true, $order->isDesc());
}
public function testCreate2(): void
{
$order = OrderExpr::fromString('test');
$this->assertEquals(OrderExpr::ASC, $order->getDirection());
$this->assertEquals(false, $order->isDesc());
}
public function testCreate3(): void
{
$order = OrderExpr::fromString('test')->withAsc();
$this->assertEquals(Expr::create('test'), $order->getExpression());
$this->assertEquals(OrderExpr::ASC, $order->getDirection());
$this->assertEquals(false, $order->isDesc());
}
public function testCreate4(): void
{
$order = OrderExpr::fromString('test')->withDirection(OrderExpr::DESC);
$this->assertEquals(OrderExpr::DESC, $order->getDirection());
}
public function testReverseOrder(): void
{
$order = OrderExpr::fromString('test')
->withDirection(OrderExpr::DESC)
->withReverseDirection();
$this->assertEquals(OrderExpr::ASC, $order->getDirection());
}
}

View File

@@ -0,0 +1,489 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 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 tests\unit\Espo\ORM\Query\Part;
use Espo\ORM\{
Query\Part\Where\AndGroup,
Query\Part\Where\OrGroup,
Query\Part\WhereClause,
Query\Part\Where\Comparison as Comp,
Query\Part\Expression as Expr,
Query\Part\Condition as Cond,
Query\SelectBuilder,
};
class WhereTest extends \PHPUnit\Framework\TestCase
{
protected function setUp(): void
{
}
public function testAndGroup1(): void
{
$raw =
AndGroup::createBuilder()
->add(
WhereClause::fromRaw([
'test1' => '1',
])
)
->build()
->getRaw();
$expextedRaw = [
'AND' => [
'test1' => '1',
]
];
$this->assertEquals($expextedRaw, $raw);
}
public function testAndGroup2(): void
{
$raw =
AndGroup::createBuilder()
->add(
WhereClause::fromRaw([
'test1' => '1',
'test1a' => '1a',
])
)
->add(
WhereClause::fromRaw([
'test2' => '2',
])
)
->build()
->getRaw();
$expextedRaw = [
'AND' => [
['test1' => '1', 'test1a' => '1a'],
['test2' => '2'],
]
];
$this->assertEquals($expextedRaw, $raw);
}
public function testAndGroup3(): void
{
$raw =
AndGroup::createBuilder()
->add(
WhereClause::fromRaw([
'test1' => '1',
])
)
->add(
OrGroup::createBuilder()
->add(
WhereClause::fromRaw([
'o1' => '1',
])
)
->add(
WhereClause::fromRaw([
'o2' => '2',
])
)
->build()
)
->build()
->getRaw();
$expextedRaw = [
'AND' => [
['test1' => '1'],
[
'OR' => [
['o1' => '1'],
['o2' => '2'],
],
],
]
];
$this->assertEquals($expextedRaw, $raw);
}
public function testOrGroup1(): void
{
$raw =
OrGroup::createBuilder()
->add(
WhereClause::fromRaw([
'test1' => '1',
])
)
->build()
->getRaw();
$expextedRaw = [
'OR' => [
['test1' => '1'],
]
];
$this->assertEquals($expextedRaw, $raw);
}
public function testOrGroup2(): void
{
$raw =
OrGroup::createBuilder()
->add(
WhereClause::fromRaw([
'test1' => '1',
'test2' => '2',
])
)
->build()
->getRaw();
$expextedRaw = [
'OR' => [
[
'test1' => '1',
'test2' => '2',
],
]
];
$this->assertEquals($expextedRaw, $raw);
}
public function testAndGroupMerge1(): void
{
$group1 =
AndGroup::createBuilder()
->add(
WhereClause::fromRaw([
'test1' => '1',
])
)
->build();
$group =
AndGroup::createBuilder()
->merge($group1)
->add(
WhereClause::fromRaw([
'test2' => '2',
])
)
->build();
$raw = $group->getRaw();
$expextedRaw = [
'AND' => [
['test1' => '1'],
['test2' => '2'],
]
];
$this->assertEquals($expextedRaw, $raw);
}
public function testOrGroupMerge1(): void
{
$orGroup1 =
OrGroup::createBuilder()
->add(
WhereClause::fromRaw([
'test1' => '1',
])
)
->build();
$orGroup =
OrGroup::createBuilder()
->merge($orGroup1)
->add(
WhereClause::fromRaw([
'test2' => '2',
])
)
->build();
$raw = $orGroup->getRaw();
$expextedRaw = [
'OR' => [
['test1' => '1'],
['test2' => '2'],
]
];
$this->assertEquals($expextedRaw, $raw);
}
public function testOrGroupMerge2(): void
{
$orGroup1 =
OrGroup::createBuilder()
->add(
WhereClause::fromRaw([
'test1' => '1',
])
)
->build();
$orGroup =
OrGroup::createBuilder()
->add(
WhereClause::fromRaw([
'test2' => '2',
])
)
->merge($orGroup1)
->build();
$raw = $orGroup->getRaw();
$expextedRaw = [
'OR' => [
['test2' => '2'],
['test1' => '1'],
]
];
$this->assertEquals($expextedRaw, $raw);
}
public function testAndGroupCreate1(): void
{
$raw = AndGroup
::create(
WhereClause::fromRaw(['test1' => '1']),
WhereClause::fromRaw(['test2' => '2'])
)
->getRaw();
$expextedRaw = [
'AND' => [
['test1' => '1'],
['test2' => '2'],
]
];
$this->assertEquals($expextedRaw, $raw);
}
public function testOrGroupCreate1(): void
{
$raw = OrGroup
::create(
WhereClause::fromRaw(['test1' => '1']),
WhereClause::fromRaw(['test2' => '2'])
)
->getRaw();
$expextedRaw = [
'OR' => [
['test1' => '1'],
['test2' => '2'],
]
];
$this->assertEquals($expextedRaw, $raw);
}
public function testAndGroupCreateWithCmp(): void
{
$raw = AndGroup
::create(
Comp::equal(Expr::column('test1'), '1'),
Comp::equal(Expr::column('test2'), '2')
)
->getRaw();
$expextedRaw = [
'AND' => [
['test1=' => '1'],
['test2=' => '2'],
]
];
$this->assertEquals($expextedRaw, $raw);
}
public function testAll(): void
{
$raw =
Cond::and(
Cond::equal(Cond::column('test1'), '1'),
Cond::notEqual(Expr::column('test2'), '2'),
Cond::greater(Expr::column('test3'), 3),
Expr::greater(Expr::column('test4'), 4),
Cond::equal(Expr::column('test5'), Expr::column('hello5')),
Comp::equal(Expr::column('test6'), Expr::column('hello6')),
Cond::equal(Expr::column('test9'), Expr::column('hello9')),
Comp::greaterOrEqual(Expr::column('test10'), Expr::column('hello10'))
)
->getRaw();
$expextedRaw = [
'AND' => [
['test1=' => '1'],
['test2!=' => '2'],
['test3>' => 3],
['GREATER_THAN:(test4, 4):' => null],
['test5=:' => 'hello5'],
['test6=:' => 'hello6'],
['test9=:' => 'hello9'],
['test10>=:' => 'hello10'],
]
];
$this->assertEquals($expextedRaw, $raw);
}
public function testAny(): void
{
$raw =
Cond::or(
Cond::equal(Expr::column('test1'), '1'),
Cond::equal(Expr::column('test2'), '2')
)
->getRaw();
$expextedRaw = [
'OR' => [
['test1=' => '1'],
['test2=' => '2'],
]
];
$this->assertEquals($expextedRaw, $raw);
}
public function testNot1(): void
{
$raw =
Cond::not(
Cond::or(
Cond::equal(Expr::column('test1'), '1'),
Cond::equal(Expr::column('test2'), '2')
)
)
->getRaw();
$expextedRaw = [
'NOT' => [
'OR' => [
['test1=' => '1'],
['test2=' => '2'],
]
]
];
$this->assertEquals($expextedRaw, $raw);
}
public function testNot2(): void
{
$raw =
Cond::not(
Cond::equal(Expr::column('test1'), '1')
)
->getRaw();
$expextedRaw = [
'NOT' => [
'test1=' => '1',
]
];
$this->assertEquals($expextedRaw, $raw);
}
public function testInQuery(): void
{
$query = (new SelectBuilder)->from('Test')->build();
$raw =
Cond::in(Expr::column('id'), $query)
->getRaw();
$expectedRaw = [
'id=s' => $query
];
$this->assertEquals($expectedRaw, $raw);
}
public function testNotInQuery(): void
{
$query = (new SelectBuilder)->from('Test')->build();
$raw =
Cond::notIn(Expr::column('id'), $query)
->getRaw();
$expectedRaw = [
'id!=s' => $query
];
$this->assertEquals($expectedRaw, $raw);
}
public function testInList(): void
{
$raw =
Cond::in(Expr::column('status'), ['1', '2'])
->getRaw();
$expectedRaw = [
'status=' => ['1', '2']
];
$this->assertEquals($expectedRaw, $raw);
}
public function testNotInList(): void
{
$raw =
Cond::notIn(Expr::column('status'), ['1', '2'])
->getRaw();
$expectedRaw = [
'status!=' => ['1', '2']
];
$this->assertEquals($expectedRaw, $raw);
}
}

View File

@@ -0,0 +1,698 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 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 tests\unit\Espo\ORM\Query;
use PHPUnit\Framework\TestCase;
use Espo\ORM\Query\Part\Condition as Cond;
use Espo\ORM\Query\Part\Expression as Expr;
use Espo\ORM\Query\Part\Join;
use Espo\ORM\Query\Part\Order;
use Espo\ORM\Query\Part\Selection;
use Espo\ORM\Query\Part\WhereClause;
use Espo\ORM\Query\SelectBuilder;
use RuntimeException;
class SelectBuilderTest extends TestCase
{
/**
* @var SelectBuilder
*/
private $builder;
protected function setUp(): void
{
$this->builder = new SelectBuilder();
}
public function testFrom()
{
$params = $this->builder
->from('Test')
->build()
->getRaw();
$this->assertEquals('Test', $params['from']);
}
public function testSelect1()
{
$select = $this->builder
->from('Test')
->select(['id', 'name'])
->select('test')
->build();
$this->assertEquals(
[
Selection::fromString('id'),
Selection::fromString('name'),
Selection::fromString('test'),
],
$select->getSelect()
);
}
public function testSelect2()
{
$select = $this->builder
->from('Test')
->select('test')
->select(['id', 'name'])
->build();
$this->assertEquals(
[
Selection::fromString('id'),
Selection::fromString('name'),
],
$select->getSelect()
);
}
public function testSelect3()
{
$select = $this->builder
->from('Test')
->select('test', 'hello')
->build();
$this->assertEquals(
[
Selection::fromString('test')->withAlias('hello'),
],
$select->getSelect()
);
}
public function testSelect4()
{
$select = $this->builder
->from('Test')
->select(Expr::create('test'), 'hello')
->build();
$this->assertEquals(
[
Selection::fromString('test')->withAlias('hello'),
],
$select->getSelect()
);
}
public function testSelect5()
{
$select = $this->builder
->from('Test')
->select('test')
->select([Expr::create('id'), Expr::create('name')])
->build();
$this->assertEquals(
[
Selection::fromString('id'),
Selection::fromString('name'),
],
$select->getSelect()
);
}
public function testSelect6()
{
$select = $this->builder
->from('Test')
->select('test')
->select([
[Expr::create('id'), 'id'],
[Expr::create('name'), 'name'],
])
->build();
$this->assertEquals(
[
Selection::fromString('id')->withAlias('id'),
Selection::fromString('name')->withAlias('name'),
],
$select->getSelect()
);
}
public function testSelect7()
{
$select = $this->builder
->from('Test')
->select([
'id',
Selection::create(Expr::create('name'))
])
->select(Selection::fromString('test')->withAlias('testAlias'))
->build();
$this->assertEquals(
[
Selection::fromString('id'),
Selection::fromString('name'),
Selection::fromString('test')->withAlias('testAlias'),
],
$select->getSelect()
);
}
public function testCloneNotSame()
{
$builder = new SelectBuilder();
$select = $builder
->from('Test')
->build();
$builder = new SelectBuilder();
$selectCloned = $builder
->clone($select)
->build();
$this->assertNotSame($selectCloned, $select);
}
public function testWhereNull1()
{
$select = $this->builder
->from('Test')
->where(['test' => null])
->build();
$raw = $select->getRaw();
$this->assertEquals(['test' => null], $raw['whereClause']);
}
public function testWhereNull2()
{
$select = $this->builder
->from('Test')
->where('test', null)
->build();
$raw = $select->getRaw();
$this->assertEquals(['test' => null], $raw['whereClause']);
}
public function testGroupBy1()
{
$select = $this->builder
->from('Test')
->having(['test' => null])
->group(['test'])
->build();
$raw = $select->getRaw();
$this->assertEquals(['test' => null], $raw['havingClause']);
$this->assertEquals(['test'], $raw['groupBy']);
}
public function testGroupBy2()
{
$select = $this->builder
->from('Test')
->having(Cond::equal(Expr::column('test'), null))
->group(Expr::create('test'))
->build();
$raw = $select->getRaw();
$this->assertEquals(['test'], $raw['groupBy']);
}
public function testGroupBy3()
{
$select = $this->builder
->from('Test')
->group([
Expr::create('test1'),
Expr::create('test2'),
])
->build();
$this->assertEquals(
[
Expr::create('test1'),
Expr::create('test2'),
],
$select->getGroup()
);
}
public function testHaving1()
{
$select = $this->builder
->from('Test')
->having(Cond::equal(Expr::column('test'), null))
->group(Expr::create('test'))
->build();
$this->assertEquals(
Cond::equal(Expr::column('test'), null)->getRaw(),
$select->getHaving()->getRaw()
);
}
public function testOrder1()
{
$select = $this->builder
->from('Test')
->order(Expr::create('test'))
->build();
$raw = $select->getRaw();
$this->assertEquals([['test', 'ASC']], $raw['orderBy']);
}
public function testOrder2()
{
$select = $this->builder
->from('Test')
->order(Expr::create('test'))
->build();
$raw = $select->getRaw();
$this->assertEquals([['test', 'ASC']], $raw['orderBy']);
}
public function testOrder3()
{
$select = $this->builder
->from('Test')
->order([Expr::create('test')], 'DESC')
->build();
$raw = $select->getRaw();
$this->assertEquals([['test', 'DESC']], $raw['orderBy']);
}
public function testOrder4()
{
$select = $this->builder
->from('Test')
->order([[Expr::create('test'), 'DESC']], 'ASC')
->build();
$raw = $select->getRaw();
$this->assertEquals([['test', 'DESC']], $raw['orderBy']);
}
public function testOrder5()
{
$select = $this->builder
->from('Test')
->order(Order::fromString('test')->withDesc())
->order('hello', true)
->build();
$this->assertEquals(
[
Order::fromString('test')->withDesc(),
Order::fromString('hello')->withDesc(),
],
$select->getOrder()
);
}
public function testOrder6()
{
$select = $this->builder
->from('Test')
->order([
Order::fromString('test')->withDesc(),
['hello', true],
])
->build();
$this->assertEquals(
[
Order::fromString('test')->withDesc(),
Order::fromString('hello')->withDesc(),
],
$select->getOrder()
);
}
public function testClone()
{
$builder = new SelectBuilder();
$select = $builder
->from('Test')
->where('test1', '1')
->build();
$builder = new SelectBuilder();
$selectCloned = $builder
->clone($select)
->distinct()
->where('test2', '2')
->build();
$params = $select->getRaw();
$paramsCloned = $selectCloned->getRaw();
$this->assertTrue($paramsCloned['distinct']);
$this->assertFalse($params['distinct'] ?? false);
$this->assertEquals(['test1' =>'1'], $params['whereClause']);
$this->assertEquals(['test1' => '1', 'test2' => '2'], $paramsCloned['whereClause']);
}
public function testCloneException()
{
$builder = new SelectBuilder();
$select = $builder
->from('Test')
->where('test1', '1')
->build();
$builder = new SelectBuilder();
$this->expectException(RuntimeException::class);
$builder
->from('Test')
->clone($select);
}
public function testWhereSameKeys1()
{
$builder = new SelectBuilder();
$select = $builder
->from('Test')
->where(['test' => '1'])
->where(['test' => '2'])
->build();
$raw = $select->getRaw();
$expected = [
'test' => '1',
['test' => '2'],
];
$this->assertEquals($expected, $raw['whereClause']);
}
public function testWhereSameKeys2()
{
$builder = new SelectBuilder();
$select = $builder
->from('Test')
->where([
'OR' => [
'test' => '1'
],
])
->where([
'OR' => [
'test' => '2'
],
])
->build();
$raw = $select->getRaw();
$expected = [
'OR' => [
'test' => '1'
],
[
'OR' => [
'test' => '2'
],
]
];
$this->assertEquals($expected, $raw['whereClause']);
}
public function testLeftJoin1()
{
$params = $this->builder
->from('Test')
->leftJoin('link1')
->leftJoin('link1')
->leftJoin('link2')
->build();
$this->assertEquals(
[
Join::create('link1')
->withLeft(),
Join::create('link2')
->withLeft()
],
$params->getJoins()
);
}
public function testLeftJoin2()
{
$query = $this->builder
->from('Test')
->leftJoin('link1', 'alias1', ['name' => 'test'])
->leftJoin('link2', 'alias2')
->build();
$this->assertEquals(
[
Join::create('link1', 'alias1')
->withConditions(WhereClause::fromRaw(['name' => 'test']))
->withLeft(),
Join::create('link2', 'alias2')
->withLeft(),
],
$query->getJoins()
);
}
public function testLeftJoin3()
{
$query = $this->builder
->from('Test')
->leftJoin(
Join::create('link1', 'alias1')
->withConditions(
WhereClause::fromRaw(['name' => 'test'])
)
)
->leftJoin(
Join::create('link2', 'alias2')
)
->build();
$this->assertEquals(
[
Join::create('link1', 'alias1')
->withConditions(WhereClause::fromRaw(['name' => 'test']))
->withLeft(),
Join::create('link2', 'alias2')
->withLeft(),
],
$query->getJoins()
);
}
public function testJoin1()
{
$params = $this->builder
->from('Test')
->join('link1')
->join('link1')
->join('link2')
->build()
->getRaw();
$this->assertEquals(
[
['link1', null, null, ['type' => null]],
['link2', null, null, ['type' => null]],
],
$params['joins']
);
}
public function testJoin2()
{
$query = $this->builder
->from('Test')
->join('link1', 'alias1', ['name' => 'test'])
->join('link2', 'alias2')
->build();
$this->assertEquals(
[
Join::create('link1', 'alias1')
->withConditions(WhereClause::fromRaw(['name' => 'test']))
->withInner(),
Join::create('link2', 'alias2')
->withInner(),
],
$query->getJoins()
);
}
public function testJoin3()
{
$query = $this->builder
->from('Test')
->join(
Join::create('link1', 'alias1')
->withConditions(WhereClause::fromRaw(['name' => 'test']))
)
->join(Join::create('link2', 'alias2'))
->build();
$this->assertEquals(
[
Join::create('link1', 'alias1')
->withConditions(WhereClause::fromRaw(['name' => 'test']))
->withInner(),
Join::create('link2', 'alias2')
->withInner(),
],
$query->getJoins()
);
}
public function testWhereItemUsage1()
{
$query = $this->builder
->from('Test')
->where(
Cond::or(
Cond::equal(Expr::column('test'), '1'),
Cond::equal(Expr::column('test'), '2')
)
)
->join(
'Table1',
'table1',
Cond::equal(Expr::column('table1.testId'), Expr::column('id'))
)
->leftJoin(
'Table2',
'table2',
Cond::equal(Expr::column('table2.testId'), Expr::column('id'))
)
->build();
$raw = $query->getRaw();
$expectedWhere = [
'OR' => [
['test=' => '1'],
['test=' => '2'],
]
];
$expectedJoins = [
[
'Table1',
'table1',
[
'table1.testId=:' => 'id'
],
['noLeftAlias' => true, 'type' => null]
],
[
'Table2',
'table2',
[
'table2.testId=:' => 'id'
],
['noLeftAlias' => true, 'type' => Join\JoinType::left]
]
];
$this->assertEquals($expectedWhere, $raw['whereClause']);
$this->assertEquals($expectedJoins, $raw['joins']);
}
public function testExists1(): void
{
$query = (new SelectBuilder())
->select('id')
->from('Test', 'test')
->where(
Cond::exists(
(new SelectBuilder())
->select('id')
->from('Test', 'sq')
->where(
Cond::equal(
Cond::column('test.id'),
Cond::column('sq.id')
)
)
->build()
)
)
->build();
$expected = [
'select' => ['id'],
'from' => 'Test',
'fromAlias' => 'test',
'whereClause' => [
'EXISTS' => (new SelectBuilder())
->select('id')
->from('Test', 'sq')
->where(
Cond::equal(
Cond::column('test.id'),
Cond::column('sq.id')
)
)
->build()
],
];
$this->assertEquals($expected, $query->getRaw());
}
}

View File

@@ -0,0 +1,73 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 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 tests\unit\Espo\ORM\Query;
use Espo\ORM\Query\SelectBuilder;
class SelectTest extends \PHPUnit\Framework\TestCase
{
/**
* @var SelectBuilder
*/
private $builder;
protected function setUp(): void
{
$this->builder = new SelectBuilder();
}
public function testGetWhere1(): void
{
$query = $this->builder
->from('Test')
->where([
'test' => 'hello'
])
->build();
$this->assertEquals(
[
'test' => 'hello'
],
$query->getWhere()->getRaw()
);
}
public function testGetWhere2(): void
{
$query = $this->builder
->from('Test')
->build();
$this->assertNull(
$query->getWhere()
);
}
}

View File

@@ -0,0 +1,272 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 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 tests\unit\Espo\ORM;
use Espo\ORM\Query\Delete;
use Espo\ORM\Query\Insert;
use Espo\ORM\Query\Part\Expression;
use Espo\ORM\Query\Part\Selection;
use Espo\ORM\Query\Select;
use Espo\ORM\Query\Union;
use Espo\ORM\Query\Update;
use Espo\ORM\QueryBuilder;
use RuntimeException;
class QueryBuilderTest extends \PHPUnit\Framework\TestCase
{
/**
* @var QueryBuilder
*/
private $queryBuilder;
protected function setUp() : void
{
$this->queryBuilder = new QueryBuilder();
}
public function testClone1()
{
$select = $this->queryBuilder
->select()
->from('Test')
->build();
$clonedSelect = $this->queryBuilder
->clone($select)
->distinct()
->build();
$this->assertNotSame($clonedSelect, $select);
$this->assertInstanceOf(Select::class, $clonedSelect);
}
public function testSelectNoFrom1()
{
$select = $this->queryBuilder
->select()
->select(['col1'])
->build();
$this->assertNull($select->getFrom());
}
public function testSelectNoFrom2()
{
$this->expectException(RuntimeException::class);
$this->queryBuilder
->select()
->select(['col1'])
->join('test')
->build();
}
public function testSelectFrom1()
{
$select = $this->queryBuilder
->select(['col1', 'col2'])
->from('Test')
->build();
$this->assertEquals(
[
Selection::fromString('col1'),
Selection::fromString('col2'),
],
$select->getSelect()
);
}
public function testSelectFrom2()
{
$select = $this->queryBuilder
->select('col1', 'alias1')
->from('Test')
->build();
$this->assertEquals(
[
Selection::fromString('col1')->withAlias('alias1')
],
$select->getSelect()
);
}
public function testInsert1()
{
$insert = $this->queryBuilder
->insert()
->into('Test')
->columns(['col1'])
->values(['col1' => '1'])
->build();
$this->assertInstanceOf(Insert::class, $insert);
}
public function testInsert2()
{
$select = $this->queryBuilder
->select()
->from('Test')
->build();
$insert = $this->queryBuilder
->insert()
->into('Test')
->columns(['col1'])
->valuesQuery($select)
->build();
$this->assertInstanceOf(Insert::class, $insert);
}
public function testInsertNoInto()
{
$this->expectException(RuntimeException::class);
$this->queryBuilder
->insert()
->columns(['col1'])
->values(['col1' => '1'])
->build();
}
public function testDelete1()
{
$delete = $this->queryBuilder
->delete()
->from('Test')
->where(['col1' => '1'])
->limit(1)
->build();
$this->assertInstanceOf(Delete::class, $delete);
}
public function testDeleteNoFrom()
{
$this->expectException(RuntimeException::class);
$this->queryBuilder
->delete()
->where(['col1' => '1'])
->build();
}
public function testUpdateNoIn()
{
$this->expectException(RuntimeException::class);
$this->queryBuilder
->update()
->set(['col1' => '2'])
->where(['col1' => '1'])
->build();
}
public function testUpdate1()
{
$update = $this->queryBuilder
->update()
->in('Test')
->set(['col1' => '2'])
->where(['col1' => '1'])
->limit(1)
->build();
$this->assertInstanceOf(Update::class, $update);
}
public function testUpdateNoSet()
{
$this->expectException(RuntimeException::class);
$this->queryBuilder
->update()
->in('Test')
->where(['col1' => '1'])
->limit(1)
->build();
}
public function testUpdate2()
{
$update = $this->queryBuilder
->update()
->in('Test')
->set(['col' => Expression::add(1, 2)])
->build();
$this->assertInstanceOf(Update::class, $update);
$this->assertEquals(
['col:' => 'ADD:(1, 2)'],
$update->getRaw()['set']
);
$set = $update->getSet();
$this->assertEquals('ADD:(1, 2)', $set['col']->getValue());
}
public function testUnion1()
{
$q1 = $this->queryBuilder
->select()
->select(['col1'])
->build();
$q2 = $this->queryBuilder
->select()
->select(['col1'])
->build();
$union = $this->queryBuilder
->union()
->query($q1)
->query($q2)
->all()
->limit(0, 5)
->order(1, 'DESC')
->build();
$this->assertInstanceOf(Union::class, $union);
}
public function testUnionNoQuery()
{
$this->expectException(RuntimeException::class);
$this->queryBuilder
->union()
->build();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,99 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 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 tests\unit\Espo\ORM\Repository;
require_once 'tests/unit/testData/DB/Entities.php';
use Espo\ORM\Repository\RDBTransactionManager;
use Espo\ORM\TransactionManager;
use PHPUnit\Framework\TestCase;
use RuntimeException;
class RDBTransactionManagerTest extends TestCase
{
private $wrappee;
private $manager;
protected function setUp(): void
{
$this->wrappee = $this->createMock(TransactionManager::class);
$this->manager = new RDBTransactionManager($this->wrappee);
}
public function testStartOnce()
{
$this->wrappee
->expects($this->once())
->method('start');
$this->manager->start();
}
public function testException()
{
$this->wrappee
->expects($this->once())
->method('start');
$this->wrappee
->expects($this->once())
->method('getLevel')
->willReturn(1);
$this->expectException(RuntimeException::class);
$this->manager->start();
$this->manager->start();
}
public function testCommit()
{
$this->wrappee
->expects($this->once())
->method('start');
$this->wrappee
->expects($this->exactly(4))
->method('getLevel')
->willReturnOnConsecutiveCalls(1, 2, 1, 0);
$this->wrappee
->expects($this->exactly(2))
->method('commit');
$this->manager->start();
$this->manager->commit();
}
}

View File

@@ -0,0 +1,55 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 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 tests\unit\Espo\ORM\Repository;
use Espo\Modules\Crm\Entities\CaseObj;
use Espo\Modules\Crm\Entities\Lead;
use PHPUnit\Framework\TestCase;
use tests\unit\testData\Entities\TestEntity;
use Espo\ORM\Repository\Util;
class UtilTest extends TestCase
{
public function testGetRDBRepositoryByClass(): void
{
$this->assertEquals('Lead', Util::getEntityTypeByClass(Lead::class));
$this->assertEquals('Case', Util::getEntityTypeByClass(CaseObj::class));
$this->assertEquals('TestEntity', Util::getEntityTypeByClass(TestEntity::class));
}
public function testGetRDBRepositoryByClassException(): void
{
$this->expectException(\InvalidArgumentException::class);
Util::getEntityTypeByClass(\stdClass::class);
}
}

View File

@@ -0,0 +1,164 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 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 tests\unit\Espo\ORM;
use Espo\ORM\Executor\DefaultSqlExecutor;
use Espo\ORM\PDO\PDOProvider;
use PDO;
use PDOStatement;
use PDOException;
use PHPUnit\Framework\TestCase;
use RuntimeException;
class SqlExecutorTest extends TestCase
{
private $pdo;
private $sth;
private $executor;
protected function setUp() : void
{
$this->pdo = $this->createMock(PDO::class);
$pdoProvider = $this->createMock(PDOProvider::class);
$pdoProvider
->expects($this->any())
->method('get')
->willReturn($this->pdo);
$this->sth = $this->getMockBuilder(PDOStatement::class)->disableOriginalConstructor()->getMock();
$this->executor = new DefaultSqlExecutor($pdoProvider);
}
public function testExecute1()
{
$sql = "SOME QUERY";
$this->pdo
->expects($this->once())
->method('query')
->willReturn($this->sth)
->with($sql);
$sth = $this->executor->execute($sql);
$this->assertInstanceOf(PDOStatement::class, $sth);
}
public function testExecuteException1()
{
$sql = "SOME QUERY";
$e = new PDOException;
$e->errorInfo = [100, 1001];
$this->pdo
->expects($this->once())
->method('query')
->will($this->throwException($e));
try {
$this->executor->execute($sql);
} catch (PDOException $e) {
}
}
public function testExecuteException2()
{
$sql = "SOME QUERY";
$e = new PDOException;
$e->errorInfo = [100, 1001];
$this->pdo
->expects($this->once())
->method('query')
->will($this->throwException($e));
try {
$this->executor->execute($sql, true);
} catch (PDOException $e) {
}
}
public function testExecuteDeadlock1()
{
$sql = "SOME QUERY";
$e = new PDOException;
$e->errorInfo = [100, 1001];
$this->pdo
->expects($this->once())
->method('query')
->will($this->throwException($e));
try {
$this->executor->execute($sql);
} catch (PDOException) {}
}
public function testExecuteDeadlock2()
{
$sql = "SOME QUERY";
$e = new PDOException;
$e->errorInfo = [40001, 1213];
$invokedCount = $this->exactly(2);
$this->pdo
->expects($invokedCount)
->method('query')
->willReturnCallback(function () use ($invokedCount, $e) {
if ($invokedCount->numberOfInvocations() === 1) {
throw $e;
}
if ($invokedCount->numberOfInvocations() === 2) {
return $this->sth;
}
throw new RuntimeException();
});
$sth = $this->executor->execute($sql, true);
$this->assertInstanceOf(PDOStatement::class, $sth);
}
}

View File

@@ -0,0 +1,276 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 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 tests\unit\Espo\ORM;
use Espo\ORM\QueryComposer\MysqlQueryComposer;
use Espo\ORM\TransactionManager;
use PDO;
use PHPUnit\Framework\TestCase;
use RuntimeException;
class TransactionManagerTest extends TestCase
{
private $pdo;
private $manager;
protected function setUp() : void
{
$this->pdo = $this->createMock(PDO::class);
$composer = $this->createMock(MysqlQueryComposer::class);
$composer
->expects($this->any())
->method('composeCreateSavepoint')
->willReturnCallback(
function ($name) {
return 'SAVEPOINT ' . $name;
}
);
$composer
->expects($this->any())
->method('composeReleaseSavepoint')
->willReturnCallback(
function ($name) {
return 'RELEASE SAVEPOINT ' . $name;
}
);
$composer
->expects($this->any())
->method('composeRollbackToSavepoint')
->willReturnCallback(
function ($name) {
return 'ROLLBACK TO SAVEPOINT ' . $name;
}
);
$this->manager = new TransactionManager($this->pdo, $composer);
}
public function testStartOnce()
{
$this->pdo
->expects($this->once())
->method('beginTransaction');
$this->manager->start();
}
public function testNested()
{
$this->pdo
->expects($this->exactly(1))
->method('beginTransaction');
$invokedCount = $this->exactly(4);
$this->pdo
->expects($invokedCount)
->method('exec')
->willReturnCallback(function ($sql) use ($invokedCount) {
if ($invokedCount->numberOfInvocations() === 1) {
$this->assertEquals('SAVEPOINT POINT_1', $sql);
}
if ($invokedCount->numberOfInvocations() === 2) {
$this->assertEquals('SAVEPOINT POINT_2', $sql);
}
if ($invokedCount->numberOfInvocations() === 3) {
$this->assertEquals('RELEASE SAVEPOINT POINT_2', $sql);
}
if ($invokedCount->numberOfInvocations() === 4) {
$this->assertEquals('ROLLBACK TO SAVEPOINT POINT_1', $sql);
}
return 1;
});
$this->pdo
->expects($this->exactly(1))
->method('commit');
$this->manager->start();
$this->manager->start();
$this->manager->start();
$this->manager->commit();
$this->manager->rollback();
$this->manager->commit();
}
public function testNestedRollback()
{
$invokedCount = $this->exactly(2);
$this->pdo
->expects($invokedCount)
->method('exec')
->willReturnCallback(function ($sql) use ($invokedCount) {
if ($invokedCount->numberOfInvocations() === 1) {
$this->assertEquals('SAVEPOINT POINT_1', $sql);
}
if ($invokedCount->numberOfInvocations() === 2) {
$this->assertEquals('ROLLBACK TO SAVEPOINT POINT_1', $sql);
}
return 1;
});
$this->pdo
->expects($this->once())
->method('rollBack');
$this->manager->start();
$this->manager->start();
$this->manager->rollback();
$this->manager->rollback();
}
public function testLevel()
{
$this->assertEquals(0, $this->manager->getLevel());
$this->assertFalse($this->manager->isStarted());
$this->manager->start();
$this->assertEquals(1, $this->manager->getLevel());
$this->assertTrue($this->manager->isStarted());
$this->manager->start();
$this->assertEquals(2, $this->manager->getLevel());
$this->manager->commit();
$this->assertEquals(1, $this->manager->getLevel());
$this->manager->rollback();
$this->assertEquals(0, $this->manager->getLevel());
$this->assertFalse($this->manager->isStarted());
}
public function testError1()
{
$this->expectException(RuntimeException::class);
$this->manager->commit();
}
public function testError2()
{
$this->expectException(RuntimeException::class);
$this->manager->start();
$this->assertTrue($this->manager->isStarted());
$this->manager->commit();
$this->manager->rollback();
}
public function testRunOnce()
{
$this->pdo
->expects($this->once())
->method('beginTransaction');
$this->pdo
->expects($this->once())
->method('commit');
$this->manager->run(
function () {}
);
}
public function testRunNested()
{
$this->pdo
->expects($this->once())
->method('beginTransaction');
$invokedCount = $this->exactly(2);
$this->pdo
->expects($invokedCount)
->method('exec')
->willReturnCallback(function ($sql) use ($invokedCount) {
if ($invokedCount->numberOfInvocations() === 1) {
$this->assertEquals('SAVEPOINT POINT_1', $sql);
}
if ($invokedCount->numberOfInvocations() === 2) {
$this->assertEquals('RELEASE SAVEPOINT POINT_1', $sql);
}
return 1;
});
$this->pdo
->expects($this->once())
->method('commit');
$this->manager->run(
function () {
$this->manager->run(
function () {}
);
}
);
}
public function testRunException()
{
$this->pdo
->expects($this->once())
->method('beginTransaction');
$this->pdo
->expects($this->once())
->method('rollback');
try {
$this->manager->run(
function () {
throw new RuntimeException();
}
);
} catch (RuntimeException $e) {}
}
}

View File

@@ -0,0 +1,201 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 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 tests\unit\Espo\ORM;
use Espo\ORM\Type\AttributeType;
use Espo\ORM\Util;
use PHPUnit\Framework\TestCase;
class UtilTest extends TestCase
{
public function testAreValuesEqualScalar(): void
{
$this->assertTrue(
Util::areValuesEqual(
AttributeType::VARCHAR,
'a1',
'a1'
)
);
$this->assertTrue(
Util::areValuesEqual(
AttributeType::VARCHAR,
1,
1
)
);
$this->assertTrue(
Util::areValuesEqual(
AttributeType::VARCHAR,
1.1,
1.1
)
);
$this->assertFalse(
Util::areValuesEqual(
AttributeType::VARCHAR,
'a1',
'a2'
)
);
}
public function testAreValuesEqualArray(): void
{
$this->assertTrue(
Util::areValuesEqual(
AttributeType::JSON_ARRAY,
['a1', 'a2'],
['a1', 'a2'],
)
);
$this->assertFalse(
Util::areValuesEqual(
AttributeType::JSON_ARRAY,
['a1', 'a2'],
['a2', 'a1'],
)
);
$this->assertTrue(
Util::areValuesEqual(
AttributeType::JSON_ARRAY,
['a1', 'a2'],
['a1', 'a2'],
isUnordered: true,
)
);
$this->assertTrue(
Util::areValuesEqual(
AttributeType::JSON_ARRAY,
['a1', 'a2'],
['a2', 'a1'],
isUnordered: true,
)
);
$this->assertTrue(
Util::areValuesEqual(
AttributeType::JSON_ARRAY,
['a1', 'a2'],
['a2', 'a1'],
isUnordered: true,
)
);
$this->assertTrue(
Util::areValuesEqual(
AttributeType::JSON_ARRAY,
[['a1'], ['a2']],
[['a1'], ['a2']],
)
);
$this->assertTrue(
Util::areValuesEqual(
AttributeType::JSON_ARRAY,
[(object) ['a1' => 1], (object) ['a2' => 1]],
[(object) ['a1' => 1], (object) ['a2' => 1]],
)
);
$this->assertFalse(
Util::areValuesEqual(
AttributeType::JSON_ARRAY,
[(object) ['a1' => 1], (object) ['a2' => 1]],
[(object) ['a1' => 2], (object) ['a2' => 1]],
)
);
$this->assertTrue(
Util::areValuesEqual(
AttributeType::JSON_ARRAY,
[[(object) ['a1' => 1], (object) ['a2' => 1]]],
[[(object) ['a1' => 1], (object) ['a2' => 1]]],
)
);
$this->assertFalse(
Util::areValuesEqual(
AttributeType::JSON_ARRAY,
[[(object) ['a1' => 1], (object) ['a2' => 1]]],
[[(object) ['a1' => 2], (object) ['a2' => 1]]],
)
);
}
public function testAreValuesEqualObject(): void
{
$this->assertTrue(
Util::areValuesEqual(
AttributeType::JSON_OBJECT,
(object) ['a1' => 1],
(object) ['a1' => 1],
)
);
$this->assertFalse(
Util::areValuesEqual(
AttributeType::JSON_OBJECT,
(object) ['a1' => 1],
(object) ['a1' => 2],
)
);
$this->assertFalse(
Util::areValuesEqual(
AttributeType::JSON_OBJECT,
(object) ['a1' => 1],
(object) ['a2' => 2],
)
);
$this->assertTrue(
Util::areValuesEqual(
AttributeType::JSON_OBJECT,
(object) ['a1' => 1, 'a2' => 2],
(object) ['a2' => 2, 'a1' => 1],
)
);
$this->assertTrue(
Util::areValuesEqual(
AttributeType::JSON_OBJECT,
(object) ['a1' => [1, 2], 'a2' => [3, 4]],
(object) ['a1' => [1, 2], 'a2' => [3, 4]],
)
);
}
}