-
Notifications
You must be signed in to change notification settings - Fork 611
/
BaseContentRefactorMigration.php
336 lines (292 loc) · 11.2 KB
/
BaseContentRefactorMigration.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
<?php
namespace craft\migrations;
use craft\base\ElementInterface;
use craft\base\FieldInterface;
use craft\db\Migration;
use craft\db\Query;
use craft\db\Table;
use craft\fieldlayoutelements\CustomField;
use craft\fields\MissingField;
use craft\helpers\ArrayHelper;
use craft\helpers\Db;
use craft\helpers\Json;
use craft\models\FieldLayout;
use yii\base\InvalidArgumentException;
use yii\db\ColumnSchema;
use yii\db\Expression;
use yii\db\Query as YiiQuery;
use yii\db\Schema;
use yii\db\TableSchema;
/**
* Base content refactor migration class
*
* @since 5.0.0
*/
class BaseContentRefactorMigration extends Migration
{
/**
* @var bool Whether the old content table data should be preserved after it has been migrated to the
* `elements_sites` table.
*/
protected bool $preserveOldData = false;
/**
* Updates the `elements_sites.content` value for elements.
*
* @param int[]|YiiQuery $ids The element IDs to update, or a query that selects them.
* If a query is passed but `select` is not set, it will default to `'id'`.
* @param FieldLayout|null $fieldLayout The field layout that the elements use, if any
* @param string $contentTable The table that the elements stored their field values in.
* @param string $fieldColumnPrefix The column prefix that the content table used for these elements’ fields.
*/
protected function updateElements(
YiiQuery|array $ids,
?FieldLayout $fieldLayout,
string $contentTable = '{{%content}}',
string $fieldColumnPrefix = 'field_',
): void {
if (is_array($ids) && empty($ids)) {
return;
}
$contentTableSchema = $this->db->getSchema()->getTableSchema($contentTable);
// make sure the table hasn't already been deleted
if (!$contentTableSchema) {
return;
}
$fieldsByUid = [];
$fieldColumns = [];
$flatFieldColumns = [];
if ($fieldLayout) {
foreach ($fieldLayout->getCustomFieldElements() as $layoutElement) {
$field = $layoutElement->getField();
if ($this->findColumnsForField(
$fieldColumnPrefix,
$contentTableSchema,
$layoutElement,
$field,
$fieldColumns,
$flatFieldColumns,
)) {
$fieldsByUid[$layoutElement->uid] = $field;
}
}
}
if ($ids instanceof YiiQuery && !$ids->select) {
$ids->select('id');
}
$query = (new YiiQuery())
->select([
'es.id',
'es.elementId',
'es.siteId',
'e.draftId',
'e.revisionId',
'e.type',
...$flatFieldColumns,
])
->from(['es' => Table::ELEMENTS_SITES])
->innerJoin(['c' => $contentTable], '[[c.elementId]] = [[es.elementId]] and [[c.siteId]] = [[es.siteId]]')
->innerJoin(['e' => Table::ELEMENTS], '[[e.id]] = [[es.elementId]]')
->where(['in', 'es.elementId', $ids]);
if ($contentTableSchema->getColumn('title')) {
$query->addSelect('c.title');
}
$total = (string)$query->count();
$totalLen = strlen($total);
$i = 0;
foreach (Db::each($query) as $element) {
$i++;
echo sprintf(
' > [%s/%s] Updating %s ...',
str_pad((string)$i, $totalLen, '0', STR_PAD_LEFT),
$total,
$this->elementLabel($element),
);
$content = [];
foreach ($fieldColumns as $layoutElementUid => $column) {
$field = $fieldsByUid[$layoutElementUid];
if ($field instanceof MissingField) {
// Figure it out from the actual DB column
$dbType = $contentTableSchema->getColumn($column)?->dbType;
} else {
$dbType = $field::dbType();
}
if (is_array($column)) {
/** @var array $dbType */
$value = [];
foreach (array_keys($dbType) as $i => $key) {
if (!isset($column[$key])) {
continue;
}
$c = $column[$key];
$v = $this->decodeValue($element[$c], $dbType[$key], $contentTableSchema->getColumn($c));
if ($v !== null) {
$value[$key] = $v;
} elseif ($i === 0) {
// the primary column is null, so consider the whole value to be null
continue 2;
}
}
} else {
$value = $this->decodeValue($element[$column], $dbType, $contentTableSchema->getColumn($column));
if ($value === null) {
continue;
}
}
$content[$layoutElementUid] = $value;
}
// don't call $this->update() so it doesn't mess with the CLI output
Db::update(Table::ELEMENTS_SITES, [
'title' => $element['title'] ?? null,
'content' => !empty($content) ? Db::prepareForJsonColumn($content, $this->db) : null,
], ['id' => $element['id']], updateTimestamp: false, db: $this->db);
echo " done\n";
}
// make sure the elements’ fieldLayoutId values are accurate
if ($fieldLayout) {
$this->update(Table::ELEMENTS, [
'fieldLayoutId' => $fieldLayout->id,
], ['in', 'id', $ids], updateTimestamp: false);
}
if (!empty($fieldsByUid)) {
$caseSql = 'CASE ';
$params = [];
$i = 0;
foreach ($fieldsByUid as $uid => $field) {
$i++;
$caseSql .= "WHEN [[fieldId]] = :fieldId$i THEN :uid$i ";
$params += [
":fieldId$i" => $field->id,
":uid$i" => $uid,
];
}
$caseSql .= "ELSE '0' END";
$this->update(Table::CHANGEDFIELDS, [
'layoutElementUid' => new Expression($caseSql),
], ['in', 'elementId', $ids], $params, false);
}
if (!$this->preserveOldData) {
// drop these content rows completely
$this->delete($contentTable, ['in', 'elementId', $ids]);
// if the content table is totally empty now, drop it
$rowsExist = (new Query())
->select('id')
->from($contentTable)
->limit(1)
->exists($this->db);
if (!$rowsExist) {
$this->dropTable($contentTable);
}
}
}
private function elementLabel(array $element): string
{
$elementType = $element['type'];
if ($elementType && class_exists($elementType) && is_subclass_of($elementType, ElementInterface::class)) {
/** @var string|ElementInterface $elementType */
$label = $elementType::lowerDisplayName();
} else {
$label = 'element';
}
if ($element['draftId']) {
$label .= ' draft';
} elseif ($element['revisionId']) {
$label .= ' revision';
}
$label .= " {$element['elementId']}";
if (!empty($element['title'])) {
$label .= sprintf(' "%s"', $element['title']);
}
return $label;
}
private function findColumnsForField(
string $fieldColumnPrefix,
TableSchema $contentTableSchema,
CustomField $layoutElement,
FieldInterface $field,
array &$fieldColumns,
array &$flatFieldColumns,
): bool {
if ($field instanceof MissingField) {
$dbType = Schema::TYPE_TEXT;
} else {
$dbType = $field::dbType();
if ($dbType === null) {
return false;
}
}
$primaryColumn = sprintf(
'%s%s%s',
$fieldColumnPrefix,
$field->handle,
($field->columnSuffix ? "_$field->columnSuffix" : ''),
);
if (!$contentTableSchema->getColumn($primaryColumn)) {
return false;
}
// was this a multi-column field?
if (is_array($dbType) && count($dbType) > 1) {
$dbTypeKeys = array_keys($dbType);
$extraColumns = array_map(
fn(string $key) => sprintf('%s%s_%s_%s', $fieldColumnPrefix, $field->handle, $key, $field->columnSuffix),
array_slice($dbTypeKeys, 1),
);
if (ArrayHelper::contains($extraColumns, fn(string $column) => $contentTableSchema->getColumn($column))) {
$columns = [$primaryColumn, ...$extraColumns];
foreach ($columns as $i => $column) {
if ($contentTableSchema->getColumn($column)) {
$fieldColumns[$layoutElement->uid][$dbTypeKeys[$i]] = $column;
$flatFieldColumns[] = "c.$column";
}
}
return true;
}
}
$fieldColumns[$layoutElement->uid] = $primaryColumn;
$flatFieldColumns[] = "c.$primaryColumn";
return true;
}
private function decodeValue(mixed $value, string|array|null $dbType, ColumnSchema $column): mixed
{
if ($value === null || $value === '') {
return null;
}
// if dbType is null or text, the content column type may be more reliable
if (!$dbType || $dbType === Schema::TYPE_TEXT) {
$dbType = $column->type;
}
if (is_array($dbType)) {
// dbType() returned an array but there was only one field column,
// so see if the field was storing JSON
if (Json::isJsonObject($value)) {
try {
return Json::decode($value);
} catch (InvalidArgumentException) {
}
}
// if we're still here, go with the first type listed instead
$dbType = reset($dbType);
// special case for a datetime that was stored in a single column
// we need to do it here, cause if it was stored in 2 cols, the $dbType wouldn't have been an array
if ($dbType === Schema::TYPE_DATETIME && is_string($value)) {
return ['date' => $value];
}
}
switch ($dbType) {
case Schema::TYPE_TINYINT:
case Schema::TYPE_SMALLINT:
case Schema::TYPE_INTEGER:
case Schema::TYPE_BIGINT:
return (int)$value;
case Schema::TYPE_FLOAT:
case Schema::TYPE_DOUBLE:
case Schema::TYPE_DECIMAL:
case Schema::TYPE_MONEY:
return (float)$value;
case Schema::TYPE_BOOLEAN:
return (bool)$value;
case Schema::TYPE_JSON:
return Json::decodeIfJson($value);
}
return $value;
}
}