EspoCRM – Open Source CRM Application
PHP calendarcontactscrmcrm-platformcrm-systemcustomer-portalcustomer-supportcustomizabledocumentsemail-marketingkanbanleadsopen-sourcephpplatformsales-automationsingle-page-applicationsupport
Dbal: Update
Yurii2bd67bc84dab
diff --git a/application/Espo/Core/Upgrades/Migrations/V8_3/AfterUpgrade.php b/application/Espo/Core/Upgrades/Migrations/V8_3/AfterUpgrade.phpindex 60de0fd8b4..b155cb11f3 100644--- a/application/Espo/Core/Upgrades/Migrations/V8_3/AfterUpgrade.php+++ b/application/Espo/Core/Upgrades/Migrations/V8_3/AfterUpgrade.php@@ -130,11 +130,11 @@ class AfterUpgrade implements Script$connection = $this->helper->getDbalConnection();$schemaManager = $connection->createSchemaManager();- if (!$schemaManager->tablesExist('subscription')) {+ if (!$schemaManager->tablesExist(['subscription'])) {return;}- if ($schemaManager->tablesExist('stream_subscription')) {+ if ($schemaManager->tablesExist(['stream_subscription'])) {try {$schemaManager->dropTable('stream_subscription');} catch (DbalException) {diff --git a/application/Espo/Core/Utils/Database/Dbal/Platforms/Keywords/MariaDb102Keywords.php b/application/Espo/Core/Utils/Database/Dbal/Platforms/Keywords/MariaDb102Keywords.phpdeleted file mode 100644index 457a26a4f7..0000000000--- a/application/Espo/Core/Utils/Database/Dbal/Platforms/Keywords/MariaDb102Keywords.php+++ /dev/null@@ -1,52 +0,0 @@-<?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 Espo\Core\Utils\Database\Dbal\Platforms\Keywords;--use Doctrine\DBAL\Platforms\Keywords\MariaDBKeywords;--/**- * 'LEAD' happened to be a reserved words on some environments.- */-class MariaDb102Keywords extends MariaDBKeywords-{- /** @deprecated */- public function getName(): string- {- return 'MariaDb102';- }-- protected function getKeywords(): array- {- return [- ...parent::getKeywords(),- 'LEAD',- ];- }-}diff --git a/application/Espo/Core/Utils/Database/Dbal/Platforms/PostgreSQLSchemaManager.php b/application/Espo/Core/Utils/Database/Dbal/Platforms/PostgreSQLSchemaManager.phpindex f8f6f80df2..452d152328 100644--- a/application/Espo/Core/Utils/Database/Dbal/Platforms/PostgreSQLSchemaManager.php+++ b/application/Espo/Core/Utils/Database/Dbal/Platforms/PostgreSQLSchemaManager.php@@ -36,37 +36,47 @@ class PostgreSQLSchemaManager extends BasePostgreSQLSchemaManager{/*** DBAL does not add the 'fulltext' flag on reverse engineering.+ *+ * @todo Test.*/- protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)+ protected function _getPortableTableIndexesList(array $rows, string $tableName): array{- $indexes = parent::_getPortableTableIndexesList($tableIndexes, $tableName);+ $indexes = parent::_getPortableTableIndexesList($rows, $tableName);- foreach ($tableIndexes as $row) {- $key = $row['relname'];+ foreach ($rows as $row) {+ $key = $row['key_name'];- if (is_string($tableName) && str_starts_with($tableName, '"') && str_ends_with($tableName, '"')) {+ if (str_starts_with($tableName, '"') && str_ends_with($tableName, '"')) {$tableName = substr($tableName, 1, -1);}- if ($key === "idx_{$tableName}_system_full_text_search") {- $sql = "SELECT indexdef FROM pg_indexes WHERE indexname = '{$key}'";+ if ($key !== "idx_{$tableName}_system_full_text_search") {+ continue;+ }++ $sql = "SELECT indexdef FROM pg_indexes WHERE indexname = '$key'";- $rows = $this->_conn->fetchAllAssociative($sql);+ $items = $this->connection->fetchAllAssociative($sql);- if (!$rows) {- continue;- }+ if (!$items) {+ continue;+ }- $columns = self::parseColumnsIndexFromDeclaration($rows[0]['indexdef']);+ $columns = self::parseColumnsIndexFromDeclaration($items[0]['indexdef']);- $indexes[$key] = new Index(- $key,- $columns,- false,- false,- ['fulltext']- );+ if (!$columns) {+ unset($indexes[$key]);++ continue;}++ $indexes[$key] = new Index(+ name: $key,+ columns: array_values($columns),+ isUnique: false,+ isPrimary: false,+ flags: ['fulltext'],+ );}return $indexes;diff --git a/application/Espo/Core/Utils/Database/Dbal/Platforms/PostgresqlPlatform.php b/application/Espo/Core/Utils/Database/Dbal/Platforms/PostgresqlPlatform.phpindex f796a2173b..d762584bd9 100644--- a/application/Espo/Core/Utils/Database/Dbal/Platforms/PostgresqlPlatform.php+++ b/application/Espo/Core/Utils/Database/Dbal/Platforms/PostgresqlPlatform.php@@ -30,13 +30,12 @@namespace Espo\Core\Utils\Database\Dbal\Platforms;use Doctrine\DBAL\Connection;-use Doctrine\DBAL\Platforms\PostgreSQL100Platform;+use Doctrine\DBAL\Platforms\PostgreSQLPlatform as PostgreSQLPlatformDbal;use Doctrine\DBAL\Schema\Index;-use Doctrine\DBAL\Schema\Table;use InvalidArgumentException;-class PostgresqlPlatform extends PostgreSQL100Platform+class PostgresqlPlatform extends PostgreSQLPlatformDbal{private const string TEXT_SEARCH_CONFIG = 'pg_catalog.simple';@@ -52,16 +51,15 @@ class PostgresqlPlatform extends PostgreSQL100Platformreturn new PostgreSQLSchemaManager($connection, $this);}- public function getCreateIndexSQL(Index $index, $table)+ /**+ * @todo Test.+ */+ public function getCreateIndexSQL(Index $index, string $table): string{if (!$index->hasFlag('fulltext')) {return parent::getCreateIndexSQL($index, $table);}- if ($table instanceof Table) {- $table = $table->getQuotedName($this);- }-$name = $index->getQuotedName($this);$columns = $index->getColumns();diff --git a/application/Espo/Core/Utils/Database/Dbal/Types/LongtextType.php b/application/Espo/Core/Utils/Database/Dbal/Types/LongtextType.phpindex e3eeb93243..f428631601 100644--- a/application/Espo/Core/Utils/Database/Dbal/Types/LongtextType.php+++ b/application/Espo/Core/Utils/Database/Dbal/Types/LongtextType.php@@ -39,12 +39,12 @@ class LongtextType extends TextType{public const string NAME = 'longtext';- public function getName()+ public function getName(): string{return self::NAME;}- public function getSQLDeclaration(array $column, AbstractPlatform $platform)+ public function getSQLDeclaration(array $column, AbstractPlatform $platform): string{return 'LONGTEXT';}diff --git a/application/Espo/Core/Utils/Database/Dbal/Types/MediumtextType.php b/application/Espo/Core/Utils/Database/Dbal/Types/MediumtextType.phpindex 5cb2f0d95b..85487d2d31 100644--- a/application/Espo/Core/Utils/Database/Dbal/Types/MediumtextType.php+++ b/application/Espo/Core/Utils/Database/Dbal/Types/MediumtextType.php@@ -39,12 +39,12 @@ class MediumtextType extends TextType{public const string NAME = 'mediumtext';- public function getName()+ public function getName(): string{return self::NAME;}- public function getSQLDeclaration(array $column, AbstractPlatform $platform)+ public function getSQLDeclaration(array $column, AbstractPlatform $platform): string{return 'MEDIUMTEXT';}diff --git a/application/Espo/Core/Utils/Database/Dbal/Types/UuidType.php b/application/Espo/Core/Utils/Database/Dbal/Types/UuidType.phpindex 386f6ea274..526c44ea05 100644--- a/application/Espo/Core/Utils/Database/Dbal/Types/UuidType.php+++ b/application/Espo/Core/Utils/Database/Dbal/Types/UuidType.php@@ -39,12 +39,12 @@ class UuidType extends Type{public const string NAME = 'uuid';- public function getName()+ public function getName(): string{return self::NAME;}- public function getSQLDeclaration(array $column, AbstractPlatform $platform)+ public function getSQLDeclaration(array $column, AbstractPlatform $platform): string{return 'UUID';}diff --git a/application/Espo/Core/Utils/Database/Schema/Builder.php b/application/Espo/Core/Utils/Database/Schema/Builder.phpindex f982dadc32..b4b63b3903 100644--- a/application/Espo/Core/Utils/Database/Schema/Builder.php+++ b/application/Espo/Core/Utils/Database/Schema/Builder.php@@ -197,7 +197,9 @@ class Builder$this->addColumn($table, $column);}- $table->setPrimaryKey($primaryColumns);+ if ($primaryColumns) {+ $table->setPrimaryKey($primaryColumns);+ }$this->addIndexes($table, $entityDefs->getIndexList());}@@ -379,15 +381,17 @@ class Builder/*** @param IndexDefs[] $indexDefsList- * @throws SchemaException*/private function addIndexes(Table $table, array $indexDefsList): void{foreach ($indexDefsList as $indexDefs) {- $columns = array_map(- fn($item) => Util::toUnderScore($item),- $indexDefs->getColumnList()- );+ $columns = array_map(fn ($item) => Util::toUnderScore($item), $indexDefs->getColumnList());++ if (!$columns) {+ continue;+ }++ $columns = array_values($columns);if ($indexDefs->isUnique()) {$table->addUniqueIndex($columns, $indexDefs->getKey());diff --git a/application/Espo/Core/Utils/Database/Schema/ColumnPreparators/MysqlColumnPreparator.php b/application/Espo/Core/Utils/Database/Schema/ColumnPreparators/MysqlColumnPreparator.phpindex b6ba579823..e75a9faecf 100644--- a/application/Espo/Core/Utils/Database/Schema/ColumnPreparators/MysqlColumnPreparator.php+++ b/application/Espo/Core/Utils/Database/Schema/ColumnPreparators/MysqlColumnPreparator.php@@ -29,6 +29,7 @@namespace Espo\Core\Utils\Database\Schema\ColumnPreparators;+use Doctrine\DBAL\Types\StringType;use Doctrine\DBAL\Types\Types;use Espo\Core\Utils\Database\Dbal\Types\LongtextType;use Espo\Core\Utils\Database\Dbal\Types\MediumtextType;@@ -60,6 +61,10 @@ class MysqlColumnPreparator implements ColumnPreparatorprivate const int MB4_INDEX_LENGTH_LIMIT = 3072;private const int DEFAULT_INDEX_LIMIT = 1000;+ private const int DEFAULT_STRING_MAX_LENGTH = 255;+ private const int DEFAULT_PRECISION = 13;+ private const int DEFAULT_SCALE = 4;+/** @var string[] */private array $mediumTextTypeList = [Entity::TEXT,@@ -104,6 +109,10 @@ class MysqlColumnPreparator implements ColumnPreparator$column = Column::create($columnName, strtolower($columnType));+ if ($columnType === Types::STRING) {+ $length ??= self::DEFAULT_STRING_MAX_LENGTH;+ }+if ($length !== null) {$column = $column->withLength($length);}@@ -120,6 +129,11 @@ class MysqlColumnPreparator implements ColumnPreparator$column = $column->withAutoincrement($autoincrement);}+ if ($columnType === Types::DECIMAL) {+ $precision ??= self::DEFAULT_PRECISION;+ $scale ??= self::DEFAULT_SCALE;+ }+if ($precision !== null) {$column = $column->withPrecision($precision);}diff --git a/application/Espo/Core/Utils/Database/Schema/ColumnPreparators/PostgresqlColumnPreparator.php b/application/Espo/Core/Utils/Database/Schema/ColumnPreparators/PostgresqlColumnPreparator.phpindex b54293a1b7..53b4909057 100644--- a/application/Espo/Core/Utils/Database/Schema/ColumnPreparators/PostgresqlColumnPreparator.php+++ b/application/Espo/Core/Utils/Database/Schema/ColumnPreparators/PostgresqlColumnPreparator.php@@ -50,6 +50,10 @@ class PostgresqlColumnPreparator implements ColumnPreparatorprivate const string PARAM_SCALE = 'scale';private const string PARAM_STORE_ARRAY_VALUES = 'storeArrayValues';+ private const int DEFAULT_STRING_MAX_LENGTH = 255;+ private const int DEFAULT_PRECISION = 13;+ private const int DEFAULT_SCALE = 4;+/** @var string[] */private array $textTypeList = [Entity::TEXT,@@ -91,6 +95,10 @@ class PostgresqlColumnPreparator implements ColumnPreparator$column = Column::create($columnName, strtolower($columnType));+ if ($columnType === Types::STRING) {+ $length ??= self::DEFAULT_STRING_MAX_LENGTH;+ }+if ($length !== null) {$column = $column->withLength($length);}@@ -107,6 +115,11 @@ class PostgresqlColumnPreparator implements ColumnPreparator$column = $column->withAutoincrement($autoincrement);}+ if ($columnType === Types::DECIMAL) {+ $precision ??= self::DEFAULT_PRECISION;+ $scale ??= self::DEFAULT_SCALE;+ }+if ($precision !== null) {$column = $column->withPrecision($precision);}diff --git a/application/Espo/Core/Utils/Database/Schema/DiffModifier.php b/application/Espo/Core/Utils/Database/Schema/DiffModifier.phpindex 1d8161706f..1d06280719 100644--- a/application/Espo/Core/Utils/Database/Schema/DiffModifier.php+++ b/application/Espo/Core/Utils/Database/Schema/DiffModifier.php@@ -32,6 +32,7 @@ namespace Espo\Core\Utils\Database\Schema;use Doctrine\DBAL\Exception as DbalException;use Doctrine\DBAL\Schema\Column as Column;use Doctrine\DBAL\Schema\ColumnDiff;+use Doctrine\DBAL\Schema\Index;use Doctrine\DBAL\Schema\Schema;use Doctrine\DBAL\Schema\SchemaDiff;use Doctrine\DBAL\Schema\TableDiff;@@ -44,12 +45,14 @@ use Espo\ORM\Name\Attribute;class DiffModifier{+ private const int DEFAULT_VARCHAR_LENGTH = 255;+/*** @param RebuildMode::* $mode* @throws DbalException*/public function modify(- SchemaDiff $diff,+ SchemaDiff &$diff,Schema $schema,bool $secondRun = false,string $mode = RebuildMode::SOFT,@@ -58,87 +61,104 @@ class DiffModifier$reRun = false;$isHard = $mode === RebuildMode::HARD;+ // @todo Test.$diff = $this->handleRemovedSequences($diff, $schema);- $diff->removedTables = [];+ $alteredTables = [];++ foreach ($diff->getAlteredTables() as $tableDiff) {+ [$newTableDiff, $itemReRun] = $this->amendTableDiff($tableDiff, $secondRun, $isHard);- foreach ($diff->changedTables as $tableDiff) {- $reRun = $this->amendTableDiff($tableDiff, $secondRun, $isHard) || $reRun;+ if ($itemReRun) {+ $reRun = true;+ }++ $alteredTables[] = $newTableDiff;}+ $diff = new SchemaDiff(+ createdSchemas: $diff->getCreatedSchemas(),+ droppedSchemas: [],+ createdTables: $diff->getCreatedTables(),+ alteredTables: $alteredTables,+ droppedTables: [],+ createdSequences: $diff->getCreatedSequences(),+ alteredSequences: $diff->getAlteredSequences(),+ droppedSequences: $diff->getDroppedSequences(),+ );+return $reRun;}/**+ * @return array{TableDiff, bool}* @throws DbalException*/- private function amendTableDiff(TableDiff $tableDiff, bool $secondRun, bool $isHard): bool+ private function amendTableDiff(TableDiff $tableDiff, bool $secondRun, bool $isHard): array{$reRun = false;- foreach ($tableDiff->removedColumns as $name => $column) {- $reRun = $this->moveRemovedAutoincrementColumnToChanged($tableDiff, $column, $name) || $reRun;- }+ foreach ($tableDiff->getDroppedColumns() as $column) {+ $itemTableDiff = $this->moveRemovedAutoincrementColumnToChanged($tableDiff, $column);- if (!$isHard) {- // Prevent column removal to prevent data loss.- $tableDiff->removedColumns = [];+ if ($itemTableDiff) {+ $tableDiff = $itemTableDiff;- // @todo Recreate $tableDiff w/o dropped columns. Or config.+ $reRun = true;+ }}- // @todo Config.- // Prevent column renaming as a not desired behavior.- /*foreach ($tableDiff->getRenamedColumns() as $renamedColumn) {- $addedName = strtolower($renamedColumn->getName());-- $tableDiff->addedColumns[$addedName] = $renamedColumn;- }*/--- $tableDiff->renamedColumns = [];+ if (!$isHard) {+ $tableDiff = $this->cloneTableDiffWithoutDroppedColumns($tableDiff);+ }foreach ($tableDiff->getAddedColumns() as $column) {- // Suppress autoincrement as need having a unique index first.$reRun = $this->amendAddedColumnAutoincrement($column) || $reRun;}- foreach ($tableDiff->getModifiedColumns() as $columnDiff) {+ $changedColumns = [];++ foreach ($tableDiff->getChangedColumns() as $name => $columnDiff) {+ $newColumnDiff = $columnDiff;+if (!$isHard) {- // Prevent decreasing length for string columns to prevent data loss.$this->amendColumnDiffLength($columnDiff);- // Prevent longtext => mediumtext to prevent data loss.$this->amendColumnDiffTextType($columnDiff);- // Prevent changing collation.$this->amendColumnDiffCollation($columnDiff);- // Prevent changing charset.$this->amendColumnDiffCharset($columnDiff);}// Prevent setting autoincrement in first run.if (!$secondRun) {- $reRun = $this->amendColumnDiffAutoincrement($columnDiff) || $reRun;+ [$newColumnDiff, $itemReRun] = $this->amendColumnDiffAutoincrement($columnDiff);++ if ($itemReRun) {+ $reRun = $itemReRun;+ }}++ $changedColumns[$name] = $newColumnDiff;}- return $reRun;+ $tableDiff = $this->cloneTableDiffWithChangedColumns($tableDiff, $changedColumns);++ return [$tableDiff, $reRun];}+ /**+ * Prevent decreasing length for string columns to prevent data loss.+ */private function amendColumnDiffLength(ColumnDiff $columnDiff): void{$fromColumn = $columnDiff->getOldColumn();$column = $columnDiff->getNewColumn();- if (!$fromColumn) {- return;- }-if (!$columnDiff->hasLengthChanged()) {return;}- $fromLength = $fromColumn->getLength() ?? 255;- $length = $column->getLength() ?? 255;+ $fromLength = $fromColumn->getLength() ?? self::DEFAULT_VARCHAR_LENGTH;+ $length = $column->getLength() ?? self::DEFAULT_VARCHAR_LENGTH;if ($fromLength <= $length) {return;@@ -148,6 +168,8 @@ class DiffModifier}/**+ * Prevent longtext => mediumtext to prevent data loss.+ ** @throws DbalException*/private function amendColumnDiffTextType(ColumnDiff $columnDiff): void@@ -155,10 +177,6 @@ class DiffModifier$fromColumn = $columnDiff->getOldColumn();$column = $columnDiff->getNewColumn();- if (!$fromColumn) {- return;- }-if (!$columnDiff->hasTypeChanged()) {return;}@@ -192,17 +210,16 @@ class DiffModifier$column->setType(Type::getType($fromName));}+ /**+ * Prevent changing collation.+ */private function amendColumnDiffCollation(ColumnDiff $columnDiff): void{$fromColumn = $columnDiff->getOldColumn();$column = $columnDiff->getNewColumn();- if (!$fromColumn) {- return;- }-- $fromCollation = $fromColumn->getPlatformOption('collation');- $collation = $column->getPlatformOption('collation');+ $fromCollation = $fromColumn->getCollation();+ $collation = $column->getCollation();if (!$fromCollation || $fromCollation === $collation) {return;@@ -211,17 +228,16 @@ class DiffModifier$column->setPlatformOption('collation', $fromCollation);}+ /**+ * Prevent changing charset.+ */private function amendColumnDiffCharset(ColumnDiff $columnDiff): void{$fromColumn = $columnDiff->getOldColumn();$column = $columnDiff->getNewColumn();- if (!$fromColumn) {- return;- }-- $fromCharset = $fromColumn->getPlatformOption('charset');- $charset = $column->getPlatformOption('charset');+ $fromCharset = $fromColumn->getCharset();+ $charset = $column->getCharset();if (!$fromCharset || $fromCharset === $charset) {return;@@ -230,17 +246,17 @@ class DiffModifier$column->setPlatformOption('charset', $fromCharset);}- private function amendColumnDiffAutoincrement(ColumnDiff $columnDiff): bool+ /**+ * @param ColumnDiff $columnDiff+ * @return array{ColumnDiff, bool}+ */+ private function amendColumnDiffAutoincrement(ColumnDiff $columnDiff): array{$fromColumn = $columnDiff->getOldColumn();$column = $columnDiff->getNewColumn();- if (!$fromColumn) {- return false;- }-if (!$columnDiff->hasAutoIncrementChanged() || $fromColumn->getAutoincrement()) {- return false;+ return [$columnDiff, false];}$column@@ -248,13 +264,18 @@ class DiffModifier->setNotnull(false)->setDefault(null);- if ($column->getName() === Attribute::ID) {+ $name = $column->getObjectName()->getIdentifier()->getValue();++ if ($name === Attribute::ID) {$column->setNotnull(true);}- return true;+ return [$columnDiff, true];}+ /**+ * Suppress autoincrement as need having a unique index first.+ */private function amendAddedColumnAutoincrement(Column $column): bool{if (!$column->getAutoincrement()) {@@ -269,12 +290,14 @@ class DiffModifierreturn true;}- private function moveRemovedAutoincrementColumnToChanged(TableDiff $tableDiff, Column $column, string $name): bool+ private function moveRemovedAutoincrementColumnToChanged(TableDiff $tableDiff, Column $column): ?TableDiff{if (!$column->getAutoincrement()) {- return false;+ return null;}+ $name = $column->getObjectName()->getIdentifier()->getValue();+$newColumn = clone $column;$newColumn@@ -282,35 +305,29 @@ class DiffModifier->setNotnull(false)->setDefault(null);- $changedProperties = [- 'autoincrement',- 'notnull',- 'default',- ];+ $columnDiff = new ColumnDiff(+ oldColumn: $column,+ newColumn: $newColumn,+ );- $tableDiff->changedColumns[$name] = new ColumnDiff($name, $newColumn, $changedProperties, $column);+ $changedColumns = [...$tableDiff->getChangedColumns(), $name => $columnDiff];- foreach ($tableDiff->removedIndexes as $indexName => $index) {- if ($index->getColumns() === [$name]) {- unset($tableDiff->removedIndexes[$indexName]);- }- }+ $tableDiff = $this->cloneTableDiffWithChangedColumns($tableDiff, $changedColumns);- return true;- }+ $droppedIndexes = [];- private static function unsetChangedColumnProperty(- TableDiff $tableDiff,- ColumnDiff $columnDiff,- string $name,- string $property- ): void {+ foreach ($tableDiff->getDroppedIndexes() as $index) {+ if (+ count($index->getIndexedColumns()) === 1 &&+ $index->getIndexedColumns()[0]->getColumnName()->toString() === $name+ ) {+ continue;+ }- if (count($columnDiff->changedProperties) === 1) {- unset($tableDiff->changedColumns[$name]);+ $droppedIndexes[] = $index;}- $columnDiff->changedProperties = array_diff($columnDiff->changedProperties, [$property]);+ return $this->cloneTableDiffWithDroppedIndexes($tableDiff, $droppedIndexes);}/**@@ -350,8 +367,75 @@ class DiffModifier}}- $diff->removedSequences = array_values($droppedSequences);+ $droppedSequences = array_values($droppedSequences);++ return new SchemaDiff(+ createdSchemas: $diff->getCreatedSchemas(),+ droppedSchemas: $diff->getDroppedSchemas(),+ createdTables: $diff->getCreatedTables(),+ alteredTables: $diff->getAlteredTables(),+ droppedTables: $diff->getDroppedTables(),+ createdSequences: $diff->getCreatedSequences(),+ alteredSequences: $diff->getAlteredSequences(),+ droppedSequences: $droppedSequences,+ );+ }++ private function cloneTableDiffWithoutDroppedColumns(TableDiff $tableDiff): TableDiff+ {+ return new TableDiff(+ oldTable: $tableDiff->getOldTable(),+ addedColumns: $tableDiff->getAddedColumns(),+ changedColumns: $tableDiff->getChangedColumns(),+ // Prevents column removal to prevent data loss.+ droppedColumns: [],+ addedIndexes: $tableDiff->getAddedIndexes(),+ modifiedIndexes: $tableDiff->getModifiedIndexes(),+ droppedIndexes: $tableDiff->getDroppedIndexes(),+ renamedIndexes: $tableDiff->getRenamedIndexes(),+ addedForeignKeys: $tableDiff->getAddedForeignKeys(),+ modifiedForeignKeys: $tableDiff->getModifiedForeignKeys(),+ droppedForeignKeys: $tableDiff->getDroppedForeignKeys(),+ );+ }- return $diff;+ /**+ * @param array<string, ColumnDiff> $changedColumns+ */+ private function cloneTableDiffWithChangedColumns(TableDiff $tableDiff, array $changedColumns): TableDiff+ {+ return new TableDiff(+ oldTable: $tableDiff->getOldTable(),+ addedColumns: $tableDiff->getAddedColumns(),+ changedColumns: $changedColumns,+ droppedColumns: $tableDiff->getDroppedColumns(),+ addedIndexes: $tableDiff->getAddedIndexes(),+ modifiedIndexes: $tableDiff->getModifiedIndexes(),+ droppedIndexes: $tableDiff->getDroppedIndexes(),+ renamedIndexes: $tableDiff->getRenamedIndexes(),+ addedForeignKeys: $tableDiff->getAddedForeignKeys(),+ modifiedForeignKeys: $tableDiff->getModifiedForeignKeys(),+ droppedForeignKeys: $tableDiff->getDroppedForeignKeys(),+ );+ }++ /**+ * @param Index[] $droppedIndexes+ */+ private function cloneTableDiffWithDroppedIndexes(TableDiff $tableDiff, array $droppedIndexes): TableDiff+ {+ return new TableDiff(+ oldTable: $tableDiff->getOldTable(),+ addedColumns: $tableDiff->getAddedColumns(),+ changedColumns: $tableDiff->getChangedColumns(),+ droppedColumns: $tableDiff->getDroppedColumns(),+ addedIndexes: $tableDiff->getAddedIndexes(),+ modifiedIndexes: $tableDiff->getModifiedIndexes(),+ droppedIndexes: $droppedIndexes,+ renamedIndexes: $tableDiff->getRenamedIndexes(),+ addedForeignKeys: $tableDiff->getAddedForeignKeys(),+ modifiedForeignKeys: $tableDiff->getModifiedForeignKeys(),+ droppedForeignKeys: $tableDiff->getDroppedForeignKeys(),+ );}}diff --git a/application/Espo/Core/Utils/Database/Schema/RebuildActions/Postgresql/MigrateSequences.php b/application/Espo/Core/Utils/Database/Schema/RebuildActions/Postgresql/MigrateSequences.phpnew file mode 100644index 0000000000..20d7a5b875--- /dev/null+++ b/application/Espo/Core/Utils/Database/Schema/RebuildActions/Postgresql/MigrateSequences.php@@ -0,0 +1,153 @@+<?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 Espo\Core\Utils\Database\Schema\RebuildActions\Postgresql;++use Doctrine\DBAL\Exception;+use Doctrine\DBAL\Schema\Schema as DbalSchema;+use Espo\Core\Utils\Config;+use Espo\Core\Utils\Database\Helper;+use Espo\Core\Utils\Database\Schema\RebuildAction;+use RuntimeException;++/**+ * @noinspection PhpUnused+ */+class MigrateSequences implements RebuildAction+{+ public function __construct(+ private Config\SystemConfig $config,+ private Helper $helper,+ ) {}++ public function process(DbalSchema $oldSchema, DbalSchema $newSchema): void+ {+ $version = $this->config->getVersion();++ if ($version !== '@@version' && version_compare($version, '10.1.999') <= 0) {+ $this->runMigrationScript();+ }+ }++ private function runMigrationScript(): void+ {+ $sql = <<<'SQL'+ CREATE OR REPLACE FUNCTION upgrade_serial_to_identity(tbl regclass, col name)+ RETURNS void+ LANGUAGE plpgsql+ AS $$+ DECLARE+ colnum smallint;+ seqid oid;+ count int;+ BEGIN+ -- Find column number.+ SELECT attnum INTO colnum FROM pg_attribute WHERE attrelid = tbl AND attname = col;+ IF NOT FOUND THEN+ RAISE EXCEPTION 'column does not exist';+ END IF;++ -- Find sequence.+ SELECT INTO seqid objid+ FROM pg_depend+ WHERE+ (refclassid, refobjid, refobjsubid) = ('pg_class'::regclass, tbl, colnum) AND+ classid = 'pg_class'::regclass AND+ objsubid = 0 AND+ deptype = 'a';++ GET DIAGNOSTICS count = ROW_COUNT;+ IF count < 1 THEN+ RAISE EXCEPTION 'no linked sequence found';+ ELSIF count > 1 THEN+ RAISE EXCEPTION 'more than one linked sequence found';+ END IF;++ -- Drop the default.+ EXECUTE 'ALTER TABLE ' || tbl || ' ALTER COLUMN ' || quote_ident(col) || ' DROP DEFAULT';++ -- Change the dependency between column and sequence to internal.+ UPDATE pg_depend+ SET deptype = 'i'+ WHERE+ (classid, objid, objsubid) = ('pg_class'::regclass, seqid, 0) AND+ deptype = 'a';++ -- Mark the column as identity column.+ UPDATE pg_attribute+ SET attidentity = 'd'+ WHERE+ attrelid = tbl AND+ attname = col;+ END;+ $$;++ DO $$+ DECLARE+ r record;+ BEGIN+ FOR r IN+ SELECT+ a.attrelid::regclass AS table_name,+ a.attname AS column_name+ FROM pg_attribute a+ JOIN pg_depend d ON+ d.refclassid = 'pg_class'::regclass AND+ d.refobjid = a.attrelid AND+ d.refobjsubid = a.attnum+ WHERE+ a.attnum > 0 AND+ NOT a.attisdropped AND+ d.classid = 'pg_class'::regclass AND+ d.objsubid = 0 AND+ d.deptype = 'a' AND+ EXISTS (+ SELECT 1+ FROM pg_class s+ WHERE+ s.oid = d.objid AND+ s.relkind = 'S'+ )+ LOOP+ PERFORM+ upgrade_serial_to_identity(r.table_name, r.column_name);+ END LOOP;+ END;+ $$;+ SQL;++ $connection = $this->helper->getDbalConnection();++ try {+ $connection->executeQuery($sql);+ } catch (Exception $e) {+ throw new RuntimeException($e->getMessage(), previous: $e);+ }+ }+}diff --git a/application/Espo/Core/Utils/Database/Schema/RebuildActions/PrepareForFulltextIndex.php b/application/Espo/Core/Utils/Database/Schema/RebuildActions/PrepareForFulltextIndex.phpindex d689eb6bc4..cc2a60ecce 100644--- a/application/Espo/Core/Utils/Database/Schema/RebuildActions/PrepareForFulltextIndex.php+++ b/application/Espo/Core/Utils/Database/Schema/RebuildActions/PrepareForFulltextIndex.php@@ -30,6 +30,7 @@namespace Espo\Core\Utils\Database\Schema\RebuildActions;use Doctrine\DBAL\Exception as DbalException;+use Doctrine\DBAL\Schema\Index\IndexType;use Doctrine\DBAL\Schema\Schema as DbalSchema;use Espo\Core\Utils\Database\Helper;use Espo\Core\Utils\Database\Schema\RebuildAction;@@ -60,18 +61,21 @@ class PrepareForFulltextIndex implements RebuildAction$pdo = $this->helper->getPDO();foreach ($newSchema->getTables() as $table) {- $tableName = $table->getName();+ $tableName = $table->getObjectName()->getUnqualifiedName()->getValue();+$indexes = $table->getIndexes();foreach ($indexes as $index) {- if (!$index->hasFlag('fulltext')) {+ if ($index->getType() !== IndexType::FULLTEXT) {continue;}- $columns = $index->getColumns();+ foreach ($index->getIndexedColumns() as $column) {+ $columnName = $column->getColumnName()->toString();++ $quotedColumnName = $pdo->quote($columnName);- foreach ($columns as $columnName) {- $sql = "SHOW FULL COLUMNS FROM `" . $tableName . "` WHERE Field = " . $pdo->quote($columnName);+ $sql = "SHOW FULL COLUMNS FROM `$tableName` WHERE Field = $quotedColumnName";try {/** @var array{Type: string, Collation: string} $row */@@ -82,9 +86,12 @@ class PrepareForFulltextIndex implements RebuildActionswitch (strtoupper($row['Type'])) {case 'LONGTEXT':- $alterSql =- "ALTER TABLE `$tableName` " .- "MODIFY `$columnName` MEDIUMTEXT COLLATE " . $row['Collation'];+ $collationPart = $row['Collation'];++ $alterSql = <<<EOF+ ALTER TABLE `$tableName`+ MODIFY `$columnName` MEDIUMTEXT COLLATE $collationPart+ EOF;$this->log->info('SCHEMA, Execute Query: ' . $alterSql);diff --git a/application/Espo/Core/Utils/Database/Schema/SchemaManager.php b/application/Espo/Core/Utils/Database/Schema/SchemaManager.phpindex b490b45753..99dca1f4d5 100644--- a/application/Espo/Core/Utils/Database/Schema/SchemaManager.php+++ b/application/Espo/Core/Utils/Database/Schema/SchemaManager.php@@ -34,6 +34,7 @@ use Doctrine\DBAL\Exception as DbalException;use Doctrine\DBAL\Platforms\AbstractPlatform;use Doctrine\DBAL\Schema\AbstractSchemaManager;use Doctrine\DBAL\Schema\Comparator;+use Doctrine\DBAL\Schema\ComparatorConfig;use Doctrine\DBAL\Schema\Schema;use Doctrine\DBAL\Schema\SchemaDiff;use Doctrine\DBAL\Schema\SchemaException;@@ -72,10 +73,15 @@ class SchemaManager->getDatabasePlatform()->createSchemaManager($this->getDbalConnection());- // Not using a platform specific comparator as it unsets a collation and charset if- // they match a table default.- //$this->comparator = $this->schemaManager->createComparator();- $this->comparator = new Comparator($this->getPlatform());+ $comparatorConfig = new ComparatorConfig(+ // Column renaming as not a desired behavior.+ detectRenamedColumns: false,+ );++ // Not using a platform specific comparator as it unsets the collation and charset if+ // they match the table default.+ // `$this->schemaManager->createComparator()`+ $this->comparator = new Comparator($this->getPlatform(), $comparatorConfig);$this->initFieldTypes();@@ -145,7 +151,13 @@ class SchemaManager}$diff = $this->comparator->compareSchemas($fromSchema, $schema);- $needReRun = $this->diffModifier->modify($diff, $schema, false, $mode);++ $needReRun = $this->diffModifier->modify(+ diff: $diff,+ schema: $schema,+ mode: $mode,+ );+$sql = $this->composeDiffSql($diff);$result = $this->runSql($sql);@@ -163,8 +175,14 @@ class SchemaManager$diff = $this->comparator->compareSchemas($intermediateSchema, $schema);- $this->diffModifier->modify($diff, $schema, true);+ $this->diffModifier->modify(+ diff: $diff,+ schema: $schema,+ secondRun: true,+ );+$sql = $this->composeDiffSql($diff);+$result = $this->runSql($sql);}diff --git a/application/Espo/Core/Utils/Database/Schema/SchemaManagerProxy.php b/application/Espo/Core/Utils/Database/Schema/SchemaManagerProxy.phpindex 13c3afb47e..596a82aecf 100644--- a/application/Espo/Core/Utils/Database/Schema/SchemaManagerProxy.php+++ b/application/Espo/Core/Utils/Database/Schema/SchemaManagerProxy.php@@ -29,6 +29,7 @@namespace Espo\Core\Utils\Database\Schema;+use Doctrine\DBAL\Exception;use Espo\Core\InjectableFactory;use Espo\Core\Utils\Database\Helper;@@ -51,6 +52,7 @@ class SchemaManagerProxy* @param ?string[] $entityTypeList* @param RebuildMode::* $mode* @throws SchemaException+ * @throws Exception*/public function rebuild(?array $entityTypeList = null, string $mode = RebuildMode::SOFT): bool{diff --git a/application/Espo/Resources/defaults/class-aliases.php b/application/Espo/Resources/defaults/class-aliases.phpindex 9e4dd0cb93..6aa2b46277 100644--- a/application/Espo/Resources/defaults/class-aliases.php+++ b/application/Espo/Resources/defaults/class-aliases.php@@ -30,7 +30,6 @@// Aliases for backward compatibility or patches.$map = ['Espo\\Core\\ORM\\Repository\\Option\\SaveContext' => 'Espo\\ORM\\Repository\\Option\\SaveContext',- 'Doctrine\\DBAL\\Platforms\\Keywords\\MariaDb102Keywords' => 'Espo\\Core\\Utils\\Database\\Dbal\\Platforms\\Keywords\\MariaDb102Keywords',];/** @phpstan-ignore-next-line */diff --git a/application/Espo/Resources/metadata/app/databasePlatforms.json b/application/Espo/Resources/metadata/app/databasePlatforms.jsonindex 94b4d18dac..9b1fae5f87 100644--- a/application/Espo/Resources/metadata/app/databasePlatforms.json+++ b/application/Espo/Resources/metadata/app/databasePlatforms.json@@ -21,6 +21,9 @@"columnPreparatorClassName": "Espo\\Core\\Utils\\Database\\Schema\\ColumnPreparators\\PostgresqlColumnPreparator","dbalTypeClassNameMap": {"uuid": "Espo\\Core\\Utils\\Database\\Dbal\\Types\\UuidType"- }+ },+ "preRebuildActionClassNameList": [+ "Espo\\Core\\Utils\\Database\\Schema\\RebuildActions\\Postgresql\\MigrateSequences"+ ]}}diff --git a/composer.json b/composer.jsonindex 3ecaf94920..a7abbfe7aa 100644--- a/composer.json+++ b/composer.json@@ -36,7 +36,7 @@"michelf/php-markdown": "^1.9","robthree/twofactorauth": "^1.8","phpoffice/phpspreadsheet": "^5.7",- "doctrine/dbal": "^3.10",+ "doctrine/dbal": "^4.4","league/flysystem-async-aws-s3": "^3.0","johngrogg/ics-parser": "^3.0","phpseclib/phpseclib": "^3.0",diff --git a/composer.lock b/composer.lockindex dedc5d23f6..4ef4ff7a5b 100644--- a/composer.lock+++ b/composer.lock@@ -4,7 +4,7 @@"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies","This file is @generated automatically"],- "content-hash": "95e112e060c110a04829061ede857ce9",+ "content-hash": "c1f0cdefbb364e6f2ea6d2b69a9700c5","packages": [{"name": "async-aws/core",@@ -189,30 +189,35 @@},{"name": "carbonphp/carbon-doctrine-types",- "version": "2.1.1",+ "version": "3.2.1","source": {"type": "git","url": "https://github.com/CarbonPHP/carbon-doctrine-types.git",- "reference": "bf72f821b9952722ea9f9c3912f85946e1af9e3d"+ "reference": "5fa5eacafd9ef47c8c6ab9143fc901ba0194d3dc"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/CarbonPHP/carbon-doctrine-types/zipball/bf72f821b9952722ea9f9c3912f85946e1af9e3d",- "reference": "bf72f821b9952722ea9f9c3912f85946e1af9e3d",+ "url": "https://api.github.com/repos/CarbonPHP/carbon-doctrine-types/zipball/5fa5eacafd9ef47c8c6ab9143fc901ba0194d3dc",+ "reference": "5fa5eacafd9ef47c8c6ab9143fc901ba0194d3dc","shasum": ""},"require": {- "php": "^7.4 || ^8.0"+ "php": "^8.1"},"conflict": {- "doctrine/dbal": "<3.7.0 || >=4.0.0"+ "doctrine/dbal": "<4.0.0 || >=5.0.0"},"require-dev": {- "doctrine/dbal": "^3.7.0",+ "doctrine/dbal": "^4.0.0","nesbot/carbon": "^2.71.0 || ^3.0.0","phpunit/phpunit": "^10.3"},"type": "library",+ "extra": {+ "branch-alias": {+ "dev-main": "3.x-dev"+ }+ },"autoload": {"psr-4": {"Carbon\\Doctrine\\": "src/Carbon/Doctrine/"@@ -238,7 +243,7 @@],"support": {"issues": "https://github.com/CarbonPHP/carbon-doctrine-types/issues",- "source": "https://github.com/CarbonPHP/carbon-doctrine-types/tree/2.1.1"+ "source": "https://github.com/CarbonPHP/carbon-doctrine-types/tree/3.2.1"},"funding": [{@@ -254,7 +259,7 @@"type": "tidelift"}],- "time": "2026-09-06T14:11:23+00:00"+ "time": "2026-09-06T14:11:38+00:00"},{"name": "cboden/ratchet",@@ -874,48 +879,40 @@},{"name": "doctrine/dbal",- "version": "3.10.4",+ "version": "4.4.4","source": {"type": "git","url": "https://github.com/doctrine/dbal.git",- "reference": "63a46cb5aa6f60991186cc98c1d1b50c09311868"+ "reference": "fb9e0ffe15e1590e24dc61c0c0a23f9a33ee42ce"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/doctrine/dbal/zipball/63a46cb5aa6f60991186cc98c1d1b50c09311868",- "reference": "63a46cb5aa6f60991186cc98c1d1b50c09311868",+ "url": "https://api.github.com/repos/doctrine/dbal/zipball/fb9e0ffe15e1590e24dc61c0c0a23f9a33ee42ce",+ "reference": "fb9e0ffe15e1590e24dc61c0c0a23f9a33ee42ce","shasum": ""},"require": {- "composer-runtime-api": "^2",- "doctrine/deprecations": "^0.5.3|^1",- "doctrine/event-manager": "^1|^2",- "php": "^7.4 || ^8.0",+ "doctrine/deprecations": "^1.1.5",+ "php": "^8.2","psr/cache": "^1|^2|^3","psr/log": "^1|^2|^3"},- "conflict": {- "doctrine/cache": "< 1.11"- },"require-dev": {- "doctrine/cache": "^1.11|^2.0","doctrine/coding-standard": "14.0.0","fig/log-test": "^1",- "jetbrains/phpstorm-stubs": "2023.1",+ "jetbrains/phpstorm-stubs": "2023.2","phpstan/phpstan": "2.1.30",+ "phpstan/phpstan-phpunit": "2.0.7","phpstan/phpstan-strict-rules": "^2",- "phpunit/phpunit": "9.6.29",- "slevomat/coding-standard": "8.24.0",- "squizlabs/php_codesniffer": "4.0.0",- "symfony/cache": "^5.4|^6.0|^7.0|^8.0",- "symfony/console": "^4.4|^5.4|^6.0|^7.0|^8.0"+ "phpunit/phpunit": "11.5.50",+ "slevomat/coding-standard": "8.27.1",+ "squizlabs/php_codesniffer": "4.0.1",+ "symfony/cache": "^6.3.8|^7.0|^8.0",+ "symfony/console": "^5.4|^6.3|^7.0|^8.0"},"suggest": {"symfony/console": "For helpful console commands such as SQL execution and import of files."},- "bin": [- "bin/doctrine-dbal"- ],"type": "library","autoload": {"psr-4": {@@ -968,7 +965,7 @@],"support": {"issues": "https://github.com/doctrine/dbal/issues",- "source": "https://github.com/doctrine/dbal/tree/3.10.4"+ "source": "https://github.com/doctrine/dbal/tree/4.4.4"},"funding": [{@@ -984,7 +981,7 @@"type": "tidelift"}],- "time": "2025-11-29T10:46:08+00:00"+ "time": "2026-07-21T14:34:40+00:00"},{"name": "doctrine/deprecations",@@ -1034,97 +1031,6 @@},"time": "2026-02-07T07:09:04+00:00"},- {- "name": "doctrine/event-manager",- "version": "2.0.1",- "source": {- "type": "git",- "url": "https://github.com/doctrine/event-manager.git",- "reference": "b680156fa328f1dfd874fd48c7026c41570b9c6e"- },- "dist": {- "type": "zip",- "url": "https://api.github.com/repos/doctrine/event-manager/zipball/b680156fa328f1dfd874fd48c7026c41570b9c6e",- "reference": "b680156fa328f1dfd874fd48c7026c41570b9c6e",- "shasum": ""- },- "require": {- "php": "^8.1"- },- "conflict": {- "doctrine/common": "<2.9"- },- "require-dev": {- "doctrine/coding-standard": "^12",- "phpstan/phpstan": "^1.8.8",- "phpunit/phpunit": "^10.5",- "vimeo/psalm": "^5.24"- },- "type": "library",- "autoload": {- "psr-4": {- "Doctrine\\Common\\": "src"- }- },- "notification-url": "https://packagist.org/downloads/",- "license": [- "MIT"- ],- "authors": [- {- "name": "Guilherme Blanco",- "email": "[email protected]"- },- {- "name": "Roman Borschel",- "email": "[email protected]"- },- {- "name": "Benjamin Eberlei",- "email": "[email protected]"- },- {- "name": "Jonathan Wage",- "email": "[email protected]"- },- {- "name": "Johannes Schmitt",- "email": "[email protected]"- },- {- "name": "Marco Pivetta",- "email": "[email protected]"- }- ],- "description": "The Doctrine Event Manager is a simple PHP event system that was built to be used with the various Doctrine projects.",- "homepage": "https://www.doctrine-project.org/projects/event-manager.html",- "keywords": [- "event",- "event dispatcher",- "event manager",- "event system",- "events"- ],- "support": {- "issues": "https://github.com/doctrine/event-manager/issues",- "source": "https://github.com/doctrine/event-manager/tree/2.0.1"- },- "funding": [- {- "url": "https://www.doctrine-project.org/sponsorship.html",- "type": "custom"- },- {- "url": "https://www.patreon.com/phpdoctrine",- "type": "patreon"- },- {- "url": "https://tidelift.com/funding/github/packagist/doctrine%2Fevent-manager",- "type": "tidelift"- }- ],- "time": "2024-05-22T20:47:39+00:00"- },{"name": "doctrine/lexer","version": "3.0.1",diff --git a/tests/integration/Core/Tester.php b/tests/integration/Core/Tester.phpindex 079aa1ab7e..457fc44b20 100644--- a/tests/integration/Core/Tester.php+++ b/tests/integration/Core/Tester.php@@ -32,7 +32,6 @@ namespace tests\integration\Core;use Composer\Autoload\ClassLoader;use Doctrine\DBAL\Exception;use Doctrine\DBAL\Schema\SchemaException;-use Doctrine\DBAL\Schema\Table;use Espo\Core\Authentication\Authentication;use Espo\Core\Authentication\AuthenticationData;use Espo\Core\Application;@@ -406,7 +405,9 @@ class Tester$tables = $schemaManager->listTableNames();foreach ($tables as $table) {- $sql = $platform->getDropTableSQL(new Table($table));+ $tableQuoted = $platform->quoteIdentifier($table);++ $sql = $platform->getDropTableSQL($tableQuoted);$pdo->query($sql);}diff --git a/tests/integration/Espo/Core/Utils/Database/RebuildTest.php b/tests/integration/Espo/Core/Utils/Database/RebuildTest.phpnew file mode 100644index 0000000000..4a2787bf4d--- /dev/null+++ b/tests/integration/Espo/Core/Utils/Database/RebuildTest.php@@ -0,0 +1,284 @@+<?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\integration\Espo\Core\Utils\Database;++use Doctrine\DBAL\Schema\Column;+use Espo\Core\ORM\Type\FieldType;+use Espo\Core\Templates\Entities\Base;+use Espo\Core\Utils\Database\Helper;+use Espo\Core\Utils\Database\Schema\RebuildMode;+use Espo\ORM\Defs\Params\FieldParam;+use Espo\Tools\EntityManager\EntityManager as EntityTypeManager;+use Espo\Tools\FieldManager\FieldManager;+use integration\Core\NoTransaction;+use tests\integration\Core\BaseTestCase;++#[NoTransaction]+class RebuildTest extends BaseTestCase+{+ private const string ENTITY_TYPE_TEST = 'TestEntityType';++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ public function testTablesAndColumns(): void+ {+ // Create entity type.++ $emTool = $this->getInjectableFactory()->create(EntityTypeManager::class);++ $emTool->create(self::ENTITY_TYPE_TEST, Base::TEMPLATE_TYPE);++ $this->reCreateApplication();++ $table = 'c_test_entity_type';++ $this->assertTrue($this->tableExists($table));++ // Create field.++ $fm = $this->getInjectableFactory()->create(FieldManager::class);++ $column = 'test';++ $fm->create('C' . self::ENTITY_TYPE_TEST, 'test', [+ 'type' => FieldType::VARCHAR,+ ]);++ //++ $em = $this->getEntityManager();++ $em->createEntity('C' . self::ENTITY_TYPE_TEST);++ // Column exists.++ $this->reCreateApplication();+ $this->getDataManager()->rebuildDatabase();++ $this->assertTrue($this->columnExists($table, $column));++ // Increase column length on soft rebuild.++ $fm->update('C' . self::ENTITY_TYPE_TEST, 'test', [+ FieldParam::MAX_LENGTH => 300,+ ]);++ $this->reCreateApplication();+ $this->getDataManager()->rebuildDatabase();++ $this->assertEquals(300, $this->getColumn($table, $column)?->getLength());++ // Do not decrease column length on soft rebuild.++ $fm->update('C' . self::ENTITY_TYPE_TEST, 'test', [+ FieldParam::MAX_LENGTH => 100,+ ]);++ $this->reCreateApplication();+ $this->getDataManager()->rebuildDatabase();++ $this->assertEquals(300, $this->getColumn($table, $column)?->getLength());++ // Decrease column length on hard rebuild.++ $fm->update('C' . self::ENTITY_TYPE_TEST, 'test', [+ FieldParam::MAX_LENGTH => 100,+ ]);++ $this->reCreateApplication();+ $this->getDataManager()->rebuildDatabase(mode: RebuildMode::HARD);++ $this->assertEquals(100, $this->getColumn($table, $column)?->getLength());++ // Delete field.++ $fm->delete('C' . self::ENTITY_TYPE_TEST, 'test');++ // Column exists after soft rebuild.++ $this->reCreateApplication();+ $this->getDataManager()->rebuildDatabase();++ $this->assertTrue($this->columnExists($table, $column));++ // Column does not exist after hard rebuild.++ $this->reCreateApplication();+ $this->getDataManager()->rebuildDatabase(mode: RebuildMode::HARD);++ $this->assertFalse($this->columnExists($table, $column));++ // Add autoincrement field.++ $fm = $this->getInjectableFactory()->create(FieldManager::class);++ $fm->create('C' . self::ENTITY_TYPE_TEST, 'testSecond', [+ 'type' => FieldType::AUTOINCREMENT,+ ]);++ $this->reCreateApplication();+ $this->getDataManager()->rebuildDatabase();++ $em = $this->getEntityManager();++ $em->createEntity('C' . self::ENTITY_TYPE_TEST);+ $entity = $em->createEntity('C' . self::ENTITY_TYPE_TEST);+ $em->refreshEntity($entity);++ $this->assertEquals(3, $entity->get('testSecond'));++ // Disable autoincrement.++ $this->getMetadata()->set('entityDefs', 'C' . self::ENTITY_TYPE_TEST, [+ 'fields' => [+ 'testSecond' => [+ 'type' => FieldType::INT,+ 'autoincrement' => false,+ ],+ ],+ ]);+ $this->getMetadata()->save();++ $this->reCreateApplication();+ $this->getDataManager()->rebuildDatabase();++ //++ $entity = $em->createEntity('C' . self::ENTITY_TYPE_TEST);+ $em->refreshEntity($entity);++ $this->assertEquals(null, $entity->get('testSecond'));++ // Enable autoincrement back.++ $this->getMetadata()->set('entityDefs', 'C' . self::ENTITY_TYPE_TEST, [+ 'fields' => [+ 'testSecond' => [+ 'type' => FieldType::INT,+ 'autoincrement' => true,+ ],+ ],+ ]);+ $this->getMetadata()->save();++ $this->reCreateApplication();+ $this->getDataManager()->rebuildDatabase();++ $this->assertTrue($this->getColumn($table, 'test_second')?->getAutoincrement());++ //++ $em->refreshEntity($entity);+ $this->assertEquals(4, $entity->get('testSecond'));++ $entity = $em->createEntity('C' . self::ENTITY_TYPE_TEST);+ $em->refreshEntity($entity);++ // Sequence is not preserved in MariaDB for some reason.+ $this->assertIsInt($entity->get('testSecond'));++ // Delete autoincrement column.++ $fm->delete('C' . self::ENTITY_TYPE_TEST, 'testSecond');++ $this->reCreateApplication();+ $this->getDataManager()->rebuildDatabase();++ $this->assertFalse($this->getColumn($table, 'test_second')?->getAutoincrement());++ // Delete entity type.++ $emTool->delete('C' . self::ENTITY_TYPE_TEST);++ // Table exists after soft rebuild.++ $this->reCreateApplication();+ $this->getDataManager()->rebuildDatabase();++ $this->assertTrue($this->tableExists($table));++ // Table exists after hard rebuild.++ $this->reCreateApplication();+ $this->getDataManager()->rebuildDatabase(mode: RebuildMode::HARD);++ $this->assertTrue($this->tableExists($table));+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ private function tableExists(string $table): bool+ {+ $helper = $this->getInjectableFactory()->create(Helper::class);++ return $helper->getDbalConnection()+ ->createSchemaManager()+ ->tablesExist([$table]);+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ private function columnExists(string $table, string $column): bool+ {+ return $this->getColumn($table, $column) !== null;+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ private function getColumn(string $table, string $column): ?Column+ {+ $helper = $this->getInjectableFactory()->create(Helper::class);++ $tables = $helper->getDbalConnection()+ ->createSchemaManager()+ ->introspectTables();++ foreach ($tables as $tableObject) {+ if ($tableObject->getObjectName()->getUnqualifiedName()->getValue() !== $table) {+ continue;+ }++ foreach ($tableObject->getColumns() as $columnObject) {+ if ($columnObject->getObjectName()->getIdentifier()->getValue() !== $column) {+ continue;+ }++ return $columnObject;+ }++ }++ return null;+ }+}