vendor/doctrine/migrations/src/Metadata/Storage/TableMetadataStorage.php line 247

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Doctrine\Migrations\Metadata\Storage;
  4. use DateTimeImmutable;
  5. use Doctrine\DBAL\Connection;
  6. use Doctrine\DBAL\Connections\PrimaryReadReplicaConnection;
  7. use Doctrine\DBAL\Platforms\AbstractPlatform;
  8. use Doctrine\DBAL\Schema\AbstractSchemaManager;
  9. use Doctrine\DBAL\Schema\Column;
  10. use Doctrine\DBAL\Schema\ComparatorConfig;
  11. use Doctrine\DBAL\Schema\Name\OptionallyQualifiedName;
  12. use Doctrine\DBAL\Schema\Name\UnqualifiedName;
  13. use Doctrine\DBAL\Schema\PrimaryKeyConstraint;
  14. use Doctrine\DBAL\Schema\Table;
  15. use Doctrine\DBAL\Schema\TableDiff;
  16. use Doctrine\DBAL\Types\Types;
  17. use Doctrine\Migrations\Exception\MetadataStorageError;
  18. use Doctrine\Migrations\Metadata\AvailableMigration;
  19. use Doctrine\Migrations\Metadata\ExecutedMigration;
  20. use Doctrine\Migrations\Metadata\ExecutedMigrationsList;
  21. use Doctrine\Migrations\MigrationsRepository;
  22. use Doctrine\Migrations\Query\Query;
  23. use Doctrine\Migrations\Version\Comparator as MigrationsComparator;
  24. use Doctrine\Migrations\Version\Direction;
  25. use Doctrine\Migrations\Version\ExecutionResult;
  26. use Doctrine\Migrations\Version\Version;
  27. use InvalidArgumentException;
  28. use function array_change_key_case;
  29. use function assert;
  30. use function class_exists;
  31. use function explode;
  32. use function floatval;
  33. use function method_exists;
  34. use function round;
  35. use function sprintf;
  36. use function str_contains;
  37. use function strlen;
  38. use function strpos;
  39. use function strtolower;
  40. use function uasort;
  41. use const CASE_LOWER;
  42. final class TableMetadataStorage implements MetadataStorage
  43. {
  44. private bool $isInitialized = false;
  45. private bool $schemaUpToDate = false;
  46. /** @var AbstractSchemaManager<AbstractPlatform> */
  47. private readonly AbstractSchemaManager $schemaManager;
  48. private readonly AbstractPlatform $platform;
  49. private readonly TableMetadataStorageConfiguration $configuration;
  50. public function __construct(
  51. private readonly Connection $connection,
  52. private readonly MigrationsComparator $comparator,
  53. MetadataStorageConfiguration|null $configuration = null,
  54. private readonly MigrationsRepository|null $migrationRepository = null,
  55. ) {
  56. $this->schemaManager = $connection->createSchemaManager();
  57. $this->platform = $connection->getDatabasePlatform();
  58. if ($configuration !== null && ! ($configuration instanceof TableMetadataStorageConfiguration)) {
  59. throw new InvalidArgumentException(sprintf(
  60. '%s accepts only %s as configuration',
  61. self::class,
  62. TableMetadataStorageConfiguration::class,
  63. ));
  64. }
  65. $this->configuration = $configuration ?? new TableMetadataStorageConfiguration();
  66. }
  67. public function getExecutedMigrations(): ExecutedMigrationsList
  68. {
  69. if (! $this->isInitialized()) {
  70. return new ExecutedMigrationsList([]);
  71. }
  72. $this->checkInitialization();
  73. $rows = $this->connection->fetchAllAssociative(sprintf('SELECT * FROM %s', $this->configuration->getTableName()));
  74. $migrations = [];
  75. foreach ($rows as $row) {
  76. $row = array_change_key_case($row, CASE_LOWER);
  77. $version = new Version($row[strtolower($this->configuration->getVersionColumnName())]);
  78. $executedAt = $row[strtolower($this->configuration->getExecutedAtColumnName())] ?? '';
  79. $executedAt = $executedAt !== ''
  80. ? DateTimeImmutable::createFromFormat($this->platform->getDateTimeFormatString(), $executedAt)
  81. : null;
  82. $executionTime = isset($row[strtolower($this->configuration->getExecutionTimeColumnName())])
  83. ? floatval($row[strtolower($this->configuration->getExecutionTimeColumnName())] / 1000)
  84. : null;
  85. $migration = new ExecutedMigration(
  86. $version,
  87. $executedAt instanceof DateTimeImmutable ? $executedAt : null,
  88. $executionTime,
  89. );
  90. $migrations[(string) $version] = $migration;
  91. }
  92. uasort($migrations, fn (ExecutedMigration $a, ExecutedMigration $b): int => $this->comparator->compare($a->getVersion(), $b->getVersion()));
  93. return new ExecutedMigrationsList($migrations);
  94. }
  95. public function reset(): void
  96. {
  97. $this->checkInitialization();
  98. $this->connection->executeStatement(
  99. sprintf(
  100. 'DELETE FROM %s WHERE 1 = 1',
  101. $this->configuration->getTableName(),
  102. ),
  103. );
  104. }
  105. public function complete(ExecutionResult $result): void
  106. {
  107. $this->checkInitialization();
  108. if ($result->getDirection() === Direction::DOWN) {
  109. $this->connection->delete($this->configuration->getTableName(), [
  110. $this->configuration->getVersionColumnName() => (string) $result->getVersion(),
  111. ]);
  112. } else {
  113. $this->connection->insert($this->configuration->getTableName(), [
  114. $this->configuration->getVersionColumnName() => (string) $result->getVersion(),
  115. $this->configuration->getExecutedAtColumnName() => $result->getExecutedAt(),
  116. $this->configuration->getExecutionTimeColumnName() => $result->getTime() === null ? null : (int) round($result->getTime() * 1000),
  117. ], [
  118. Types::STRING,
  119. Types::DATETIME_IMMUTABLE,
  120. Types::INTEGER,
  121. ]);
  122. }
  123. }
  124. /** @return iterable<Query> */
  125. public function getSql(ExecutionResult $result): iterable
  126. {
  127. yield new Query('-- Version ' . (string) $result->getVersion() . ' update table metadata');
  128. if ($result->getDirection() === Direction::DOWN) {
  129. yield new Query(sprintf(
  130. 'DELETE FROM %s WHERE %s = %s',
  131. $this->configuration->getTableName(),
  132. $this->configuration->getVersionColumnName(),
  133. $this->connection->quote((string) $result->getVersion()),
  134. ));
  135. return;
  136. }
  137. yield new Query(sprintf(
  138. 'INSERT INTO %s (%s, %s, %s) VALUES (%s, %s, 0)',
  139. $this->configuration->getTableName(),
  140. $this->configuration->getVersionColumnName(),
  141. $this->configuration->getExecutedAtColumnName(),
  142. $this->configuration->getExecutionTimeColumnName(),
  143. $this->connection->quote((string) $result->getVersion()),
  144. $this->connection->quote(($result->getExecutedAt() ?? new DateTimeImmutable())->format('Y-m-d H:i:s')),
  145. ));
  146. }
  147. public function ensureInitialized(): void
  148. {
  149. if (! $this->isInitialized()) {
  150. $expectedSchemaChangelog = $this->getExpectedTable();
  151. $this->schemaManager->createTable($expectedSchemaChangelog);
  152. $this->schemaUpToDate = true;
  153. $this->isInitialized = true;
  154. return;
  155. }
  156. $this->isInitialized = true;
  157. $expectedSchemaChangelog = $this->getExpectedTable();
  158. $diff = $this->needsUpdate($expectedSchemaChangelog);
  159. if ($diff === null) {
  160. $this->schemaUpToDate = true;
  161. return;
  162. }
  163. $this->schemaUpToDate = true;
  164. $this->schemaManager->alterTable($diff);
  165. $this->updateMigratedVersionsFromV1orV2toV3();
  166. }
  167. private function needsUpdate(Table $expectedTable): TableDiff|null
  168. {
  169. if ($this->schemaUpToDate) {
  170. return null;
  171. }
  172. if (class_exists(ComparatorConfig::class)) {
  173. $comparator = $this->schemaManager->createComparator((new ComparatorConfig())->withReportModifiedIndexes(false));
  174. } else {
  175. $comparator = $this->schemaManager->createComparator();
  176. }
  177. /** @phpstan-ignore function.alreadyNarrowedType */
  178. if (method_exists($this->schemaManager, 'introspectTableByUnquotedName')) {
  179. if (str_contains($this->configuration->getTableName(), '.')) {
  180. [$namespace, $tableName] = explode('.', $this->configuration->getTableName(), 2);
  181. assert($namespace !== '' && $tableName !== '');
  182. $currentTable = $this->schemaManager->introspectTableByUnquotedName(
  183. $tableName,
  184. $namespace,
  185. );
  186. } else {
  187. $currentTable = $this->schemaManager->introspectTableByUnquotedName($this->configuration->getTableName());
  188. }
  189. } else {
  190. /** @phpstan-ignore method.deprecated */
  191. $currentTable = $this->schemaManager->introspectTable($this->configuration->getTableName());
  192. }
  193. $diff = $comparator->compareTables($currentTable, $expectedTable);
  194. return $diff->isEmpty() ? null : $diff;
  195. }
  196. private function isInitialized(): bool
  197. {
  198. if ($this->isInitialized) {
  199. return $this->isInitialized;
  200. }
  201. if ($this->connection instanceof PrimaryReadReplicaConnection) {
  202. $this->connection->ensureConnectedToPrimary();
  203. }
  204. return $this->schemaManager->tablesExist([$this->configuration->getTableName()]);
  205. }
  206. private function checkInitialization(): void
  207. {
  208. if (! $this->isInitialized()) {
  209. throw MetadataStorageError::notInitialized();
  210. }
  211. $expectedTable = $this->getExpectedTable();
  212. if ($this->needsUpdate($expectedTable) !== null) {
  213. throw MetadataStorageError::notUpToDate();
  214. }
  215. }
  216. private function getExpectedTable(): Table
  217. {
  218. // @phpstan-ignore-next-line function.alreadyNarrowedType
  219. if (method_exists(Table::class, 'editor')) { // doctrine/dbal >= 4.5
  220. $editor = Table::editor()
  221. ->setName(OptionallyQualifiedName::unquoted($this->configuration->getTableName()))
  222. ->addColumn(
  223. Column::editor()
  224. ->setName(UnqualifiedName::unquoted($this->configuration->getVersionColumnName()))
  225. ->setTypeName('string')
  226. ->setNotNull(true)
  227. ->setLength($this->configuration->getVersionColumnLength())
  228. ->create(),
  229. )
  230. ->addColumn(
  231. Column::editor()
  232. ->setName(UnqualifiedName::unquoted($this->configuration->getExecutedAtColumnName()))
  233. ->setTypeName('datetime')
  234. ->setNotNull(false)
  235. ->create(),
  236. )
  237. ->addColumn(
  238. Column::editor()
  239. ->setName(UnqualifiedName::unquoted($this->configuration->getExecutionTimeColumnName()))
  240. ->setTypeName('integer')
  241. ->setNotNull(false)
  242. ->create(),
  243. )
  244. ->addPrimaryKeyConstraint(
  245. PrimaryKeyConstraint::editor()
  246. ->setColumnNames(UnqualifiedName::unquoted($this->configuration->getVersionColumnName()))
  247. ->create(),
  248. );
  249. return $editor->create();
  250. }
  251. $schemaChangelog = new Table($this->configuration->getTableName());
  252. // @phpstan-ignore-next-line method.deprecated
  253. $schemaChangelog->addColumn(
  254. $this->configuration->getVersionColumnName(),
  255. 'string',
  256. ['notnull' => true, 'length' => $this->configuration->getVersionColumnLength()],
  257. );
  258. // @phpstan-ignore-next-line method.deprecated
  259. $schemaChangelog->addColumn($this->configuration->getExecutedAtColumnName(), 'datetime', ['notnull' => false]);
  260. // @phpstan-ignore-next-line method.deprecated
  261. $schemaChangelog->addColumn($this->configuration->getExecutionTimeColumnName(), 'integer', ['notnull' => false]);
  262. if (class_exists(PrimaryKeyConstraint::class)) { // doctrine/dbal >= 4.3
  263. $constraint = PrimaryKeyConstraint::editor()
  264. ->setColumnNames(UnqualifiedName::unquoted($this->configuration->getVersionColumnName()))
  265. ->create();
  266. // @phpstan-ignore-next-line method.deprecated
  267. $schemaChangelog->addPrimaryKeyConstraint($constraint);
  268. } else {
  269. // @phpstan-ignore-next-line method.deprecated
  270. $schemaChangelog->setPrimaryKey([$this->configuration->getVersionColumnName()]);
  271. }
  272. return $schemaChangelog;
  273. }
  274. private function updateMigratedVersionsFromV1orV2toV3(): void
  275. {
  276. if ($this->migrationRepository === null) {
  277. return;
  278. }
  279. $availableMigrations = $this->migrationRepository->getMigrations()->getItems();
  280. $executedMigrations = $this->getExecutedMigrations()->getItems();
  281. foreach ($availableMigrations as $availableMigration) {
  282. foreach ($executedMigrations as $k => $executedMigration) {
  283. if ($this->isAlreadyV3Format($availableMigration, $executedMigration)) {
  284. continue;
  285. }
  286. $this->connection->update(
  287. $this->configuration->getTableName(),
  288. [
  289. $this->configuration->getVersionColumnName() => (string) $availableMigration->getVersion(),
  290. ],
  291. [
  292. $this->configuration->getVersionColumnName() => (string) $executedMigration->getVersion(),
  293. ],
  294. );
  295. unset($executedMigrations[$k]);
  296. }
  297. }
  298. }
  299. private function isAlreadyV3Format(AvailableMigration $availableMigration, ExecutedMigration $executedMigration): bool
  300. {
  301. return (string) $availableMigration->getVersion() === (string) $executedMigration->getVersion()
  302. || strpos(
  303. (string) $availableMigration->getVersion(),
  304. (string) $executedMigration->getVersion(),
  305. ) !== strlen((string) $availableMigration->getVersion()) -
  306. strlen((string) $executedMigration->getVersion());
  307. }
  308. }