Completed
Push — master ( b33394...a92fd9 )
by
unknown
35:32 queued 20:04
created

DatabaseRowsUpdateWizard::updateNecessary()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the TYPO3 CMS project.
7
 *
8
 * It is free software; you can redistribute it and/or modify it under
9
 * the terms of the GNU General Public License, either version 2
10
 * of the License, or any later version.
11
 *
12
 * For the full copyright and license information, please read the
13
 * LICENSE.txt file that was distributed with this source code.
14
 *
15
 * The TYPO3 project - inspiring people to share!
16
 */
17
18
namespace TYPO3\CMS\Install\Updates;
19
20
use TYPO3\CMS\Core\Database\Connection;
21
use TYPO3\CMS\Core\Database\ConnectionPool;
22
use TYPO3\CMS\Core\Registry;
23
use TYPO3\CMS\Core\Utility\GeneralUtility;
24
use TYPO3\CMS\Install\Updates\RowUpdater\RowUpdaterInterface;
25
use TYPO3\CMS\Install\Updates\RowUpdater\WorkspaceVersionRecordsMigration;
26
27
/**
28
 * This is a generic updater to migrate content of TCA rows.
29
 *
30
 * Multiple classes implementing interface "RowUpdateInterface" can be
31
 * registered here, each for a specific update purpose.
32
 *
33
 * The updater fetches each row of all TCA registered tables and
34
 * visits the client classes who may modify the row content.
35
 *
36
 * The updater remembers for each class if it run through, so the updater
37
 * will be shown again if a new updater class is registered that has not
38
 * been run yet.
39
 *
40
 * A start position pointer is stored in the registry that is updated during
41
 * the run process, so if for instance the PHP process runs into a timeout,
42
 * the job can restart at the position it stopped.
43
 * @internal This class is only meant to be used within EXT:install and is not part of the TYPO3 Core API.
44
 */
45
class DatabaseRowsUpdateWizard implements UpgradeWizardInterface, RepeatableInterface
46
{
47
    /**
48
     * @var array Single classes that may update rows
49
     */
50
    protected $rowUpdater = [
51
        WorkspaceVersionRecordsMigration::class,
52
    ];
53
54
    /**
55
     * @return string Unique identifier of this updater
56
     */
57
    public function getIdentifier(): string
58
    {
59
        return 'databaseRowsUpdateWizard';
60
    }
61
62
    /**
63
     * @return string Title of this updater
64
     */
65
    public function getTitle(): string
66
    {
67
        return 'Execute database migrations on single rows';
68
    }
69
70
    /**
71
     * @return string Longer description of this updater
72
     * @throws \RuntimeException
73
     */
74
    public function getDescription(): string
75
    {
76
        $rowUpdaterNotExecuted = $this->getRowUpdatersToExecute();
77
        $description = 'Row updaters that have not been executed:';
78
        foreach ($rowUpdaterNotExecuted as $rowUpdateClassName) {
79
            $rowUpdater = GeneralUtility::makeInstance($rowUpdateClassName);
80
            if (!$rowUpdater instanceof RowUpdaterInterface) {
81
                throw new \RuntimeException(
82
                    'Row updater must implement RowUpdaterInterface',
83
                    1484066647
84
                );
85
            }
86
            $description .= LF . $rowUpdater->getTitle();
87
        }
88
        return $description;
89
    }
90
91
    /**
92
     * @return bool True if at least one row updater is not marked done
93
     */
94
    public function updateNecessary(): bool
95
    {
96
        return !empty($this->getRowUpdatersToExecute());
97
    }
98
99
    /**
100
     * @return string[] All new fields and tables must exist
101
     */
102
    public function getPrerequisites(): array
103
    {
104
        return [
105
            DatabaseUpdatedPrerequisite::class
106
        ];
107
    }
108
109
    /**
110
     * Performs the configuration update.
111
     *
112
     * @return bool
113
     * @throws \Doctrine\DBAL\ConnectionException
114
     * @throws \Exception
115
     */
116
    public function executeUpdate(): bool
117
    {
118
        $registry = GeneralUtility::makeInstance(Registry::class);
119
120
        // If rows from the target table that is updated and the sys_registry table are on the
121
        // same connection, the row update statement and sys_registry position update will be
122
        // handled in a transaction to have an atomic operation in case of errors during execution.
123
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
124
        $connectionForSysRegistry = $connectionPool->getConnectionForTable('sys_registry');
125
126
        /** @var RowUpdaterInterface[] $rowUpdaterInstances */
127
        $rowUpdaterInstances = [];
128
        // Single row updater instances are created only once for this method giving
129
        // them a chance to set up local properties during hasPotentialUpdateForTable()
130
        // and using that in updateTableRow()
131
        foreach ($this->getRowUpdatersToExecute() as $rowUpdater) {
132
            $rowUpdaterInstance = GeneralUtility::makeInstance($rowUpdater);
133
            if (!$rowUpdaterInstance instanceof RowUpdaterInterface) {
134
                throw new \RuntimeException(
135
                    'Row updater must implement RowUpdaterInterface',
136
                    1484071612
137
                );
138
            }
139
            $rowUpdaterInstances[] = $rowUpdaterInstance;
140
        }
141
142
        // Scope of the row updater is to update all rows that have TCA,
143
        // our list of tables is just the list of loaded TCA tables.
144
        $listOfAllTables = array_keys($GLOBALS['TCA']);
145
146
        // In case the PHP ended for whatever reason, fetch the last position from registry
147
        // and throw away all tables before that start point.
148
        sort($listOfAllTables);
149
        reset($listOfAllTables);
150
        $firstTable = current($listOfAllTables);
151
        $startPosition = $this->getStartPosition($firstTable);
152
        foreach ($listOfAllTables as $key => $table) {
153
            if ($table === $startPosition['table']) {
154
                break;
155
            }
156
            unset($listOfAllTables[$key]);
157
        }
158
159
        // Ask each row updater if it potentially has field updates for rows of a table
160
        $tableToUpdaterList = [];
161
        foreach ($listOfAllTables as $table) {
162
            foreach ($rowUpdaterInstances as $updater) {
163
                if ($updater->hasPotentialUpdateForTable($table)) {
164
                    if (!is_array($tableToUpdaterList[$table])) {
165
                        $tableToUpdaterList[$table] = [];
166
                    }
167
                    $tableToUpdaterList[$table][] = $updater;
168
                }
169
            }
170
        }
171
172
        // Iterate through all rows of all tables that have potential row updaters attached,
173
        // feed each single row to each updater and finally update each row in database if
174
        // a row updater changed a fields
175
        foreach ($tableToUpdaterList as $table => $updaters) {
176
            /** @var RowUpdaterInterface[] $updaters */
177
            $connectionForTable = $connectionPool->getConnectionForTable($table);
178
            $queryBuilder = $connectionPool->getQueryBuilderForTable($table);
179
            $queryBuilder->getRestrictions()->removeAll();
180
            $queryBuilder->select('*')
181
                ->from($table)
182
                ->orderBy('uid');
183
            if ($table === $startPosition['table']) {
184
                $queryBuilder->where(
185
                    $queryBuilder->expr()->gt('uid', $queryBuilder->createNamedParameter($startPosition['uid']))
186
                );
187
            }
188
            $statement = $queryBuilder->execute();
189
            $rowCountWithoutUpdate = 0;
190
            while ($row = $rowBefore = $statement->fetch()) {
191
                foreach ($updaters as $updater) {
192
                    $row = $updater->updateTableRow($table, $row);
193
                }
194
                $updatedFields = array_diff_assoc($row, $rowBefore);
195
                if (empty($updatedFields)) {
196
                    // Updaters changed no field of that row
197
                    $rowCountWithoutUpdate++;
198
                    if ($rowCountWithoutUpdate >= 200) {
199
                        // Update startPosition if there were many rows without data change
200
                        $startPosition = [
201
                            'table' => $table,
202
                            'uid' => $row['uid'],
203
                        ];
204
                        $registry->set('installUpdateRows', 'rowUpdatePosition', $startPosition);
205
                        $rowCountWithoutUpdate = 0;
206
                    }
207
                } else {
208
                    $rowCountWithoutUpdate = 0;
209
                    $startPosition = [
210
                        'table' => $table,
211
                        'uid' => $rowBefore['uid'],
212
                    ];
213
                    if ($connectionForSysRegistry === $connectionForTable) {
214
                        // Target table and sys_registry table are on the same connection, use a transaction
215
                        $connectionForTable->beginTransaction();
216
                        try {
217
                            $this->updateOrDeleteRow(
218
                                $connectionForTable,
219
                                $connectionForTable,
220
                                $table,
221
                                (int)$rowBefore['uid'],
222
                                $updatedFields,
223
                                $startPosition
224
                            );
225
                            $connectionForTable->commit();
226
                        } catch (\Exception $up) {
227
                            $connectionForTable->rollBack();
228
                            throw $up;
229
                        }
230
                    } else {
231
                        // Different connections for table and sys_registry -> execute two
232
                        // distinct queries and hope for the best.
233
                        $this->updateOrDeleteRow(
234
                            $connectionForTable,
235
                            $connectionForSysRegistry,
236
                            $table,
237
                            (int)$rowBefore['uid'],
238
                            $updatedFields,
239
                            $startPosition
240
                        );
241
                    }
242
                }
243
            }
244
        }
245
246
        // Ready with updates, remove position information from sys_registry
247
        $registry->remove('installUpdateRows', 'rowUpdatePosition');
248
        // Mark row updaters that were executed as done
249
        foreach ($rowUpdaterInstances as $updater) {
250
            $this->setRowUpdaterExecuted($updater);
251
        }
252
253
        return true;
254
    }
255
256
    /**
257
     * Return an array of class names that are not yet marked as done.
258
     *
259
     * @return array Class names
260
     */
261
    protected function getRowUpdatersToExecute(): array
262
    {
263
        $doneRowUpdater = GeneralUtility::makeInstance(Registry::class)->get('installUpdateRows', 'rowUpdatersDone', []);
264
        return array_diff($this->rowUpdater, $doneRowUpdater);
265
    }
266
267
    /**
268
     * Mark a single updater as done
269
     *
270
     * @param RowUpdaterInterface $updater
271
     */
272
    protected function setRowUpdaterExecuted(RowUpdaterInterface $updater)
273
    {
274
        $registry = GeneralUtility::makeInstance(Registry::class);
275
        $doneRowUpdater = $registry->get('installUpdateRows', 'rowUpdatersDone', []);
276
        $doneRowUpdater[] = get_class($updater);
277
        $registry->set('installUpdateRows', 'rowUpdatersDone', $doneRowUpdater);
278
    }
279
280
    /**
281
     * Return an array with table / uid combination that specifies the start position the
282
     * update row process should start with.
283
     *
284
     * @param string $firstTable Table name of the first TCA in case the start position needs to be initialized
285
     * @return array New start position
286
     */
287
    protected function getStartPosition(string $firstTable): array
288
    {
289
        $registry = GeneralUtility::makeInstance(Registry::class);
290
        $startPosition = $registry->get('installUpdateRows', 'rowUpdatePosition', []);
291
        if (empty($startPosition)) {
292
            $startPosition = [
293
                'table' => $firstTable,
294
                'uid' => 0,
295
            ];
296
            $registry->set('installUpdateRows', 'rowUpdatePosition', $startPosition);
297
        }
298
        return $startPosition;
299
    }
300
301
    /**
302
     * @param Connection $connectionForTable
303
     * @param string $table
304
     * @param array $updatedFields
305
     * @param int $uid
306
     * @param Connection $connectionForSysRegistry
307
     * @param array $startPosition
308
     */
309
    protected function updateOrDeleteRow(Connection $connectionForTable, Connection $connectionForSysRegistry, string $table, int $uid, array $updatedFields, array $startPosition): void
310
    {
311
        $deleteField = $GLOBALS['TCA'][$table]['ctrl']['delete'] ?? null;
312
        if ($deleteField === null && $updatedFields['deleted'] === 1) {
313
            $connectionForTable->delete(
314
                $table,
315
                [
316
                    'uid' => $uid,
317
                ]
318
            );
319
        } else {
320
            $connectionForTable->update(
321
                $table,
322
                $updatedFields,
323
                [
324
                    'uid' => $uid,
325
                ]
326
            );
327
        }
328
        $connectionForSysRegistry->update(
329
            'sys_registry',
330
            [
331
                'entry_value' => serialize($startPosition),
332
            ],
333
            [
334
                'entry_namespace' => 'installUpdateRows',
335
                'entry_key' => 'rowUpdatePosition',
336
            ]
337
        );
338
    }
339
}
340