-
Notifications
You must be signed in to change notification settings - Fork 158
Expand file tree
/
Copy pathLocalTableData.php
More file actions
517 lines (445 loc) · 19.5 KB
/
Copy pathLocalTableData.php
File metadata and controls
517 lines (445 loc) · 19.5 KB
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
<?php namespace DBDiff\DB\Data;
use DBDiff\Params\ParamsFactory;
use DBDiff\Params\TableFilter;
use DBDiff\Diff\InsertData;
use DBDiff\Diff\UpdateData;
use DBDiff\Diff\DeleteData;
use DBDiff\DB\Data\BinaryValue;
use DBDiff\Exceptions\DataException;
use DBDiff\Logger;
use Illuminate\Database\Events\StatementPrepared;
use Illuminate\Events\Dispatcher;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
class LocalTableData {
private const SQL_AND = ' AND ';
function __construct($manager) {
$this->manager = $manager;
$this->source = $this->manager->getDB('source');
$this->target = $this->manager->getDB('target');
$this->driver = $this->manager->getDriver();
}
public function getDiff($table, $key) {
Logger::info("Now calculating data diff for table `$table`");
if ($this->driver === 'sqlite') {
return $this->getDiffSQLite($table, $key);
}
if ($this->driver === 'pgsql') {
return $this->getDiffPgsql($table, $key);
}
return $this->getDiffMySQL($table, $key);
}
private function getDiffMySQL($table, $key): array
{
if ($this->skipIfIdentical($table)) {
Logger::info("Table `$table` is identical (CHECKSUM match) — skipping data diff");
return [];
}
return array_merge($this->getOldNewDiff($table, $key), $this->getChangeDiff($table, $key));
}
/**
* MySQL CHECKSUM TABLE pre-scan.
*
* Issues CHECKSUM TABLE for both databases and compares. If both
* checksums match and are non-null, the table data is identical and
* the full diff can be skipped. This is only useful for same-server
* comparisons (which is always the case in LocalTableData).
*/
private function skipIfIdentical(string $table): bool
{
$db1 = $this->source->getDatabaseName();
$db2 = $this->target->getDatabaseName();
try {
$result = $this->source->select(
"CHECKSUM TABLE `$db1`.`$table`, `$db2`.`$table`"
);
if (count($result) === 2) {
$cs1 = $result[0]['Checksum'] ?? null;
$cs2 = $result[1]['Checksum'] ?? null;
return $cs1 !== null && $cs2 !== null && $cs1 === $cs2;
}
} catch (\Throwable $e) {
// CHECKSUM TABLE may not be supported (e.g. certain storage engines).
// Fall through to the full diff.
Logger::info("CHECKSUM TABLE not available for `$table`: " . $e->getMessage());
}
return false;
}
// ── SQLite path ───────────────────────────────────────────────────────
/**
* SQLite data diff via ATTACH DATABASE.
*
* SQLite only supports cross-database queries when the second file is
* attached to the same connection. MySQL-specific functions
* (CONVERT … USING utf8, CAST … AS CHAR CHARACTER SET utf8, SHA2) are
* replaced with SQLite-compatible equivalents.
*/
private function getDiffSQLite(string $table, array $key): array
{
$db2 = $this->target->getDatabaseName(); // absolute file path
// Attach target file to source connection under a unique alias.
$alias = '_dbdiff_target';
$this->source->unprepared("ATTACH DATABASE '$db2' AS \"$alias\"");
try {
return $this->runSQLiteDiff($table, $key, $alias);
} finally {
try {
$this->source->unprepared("DETACH DATABASE \"$alias\"");
} catch (\Throwable $e) {
// Ignore detach errors (e.g. connection already closed).
}
}
}
private function runSQLiteDiff(string $table, array $key, string $alias): array
{
$columns1 = $this->manager->getColumns('source', $table);
$columns2 = $this->manager->getColumns('target', $table);
$keyCols = implode(self::SQL_AND, array_map(
fn($el) => "\"a\".\"$el\" = \"b\".\"$el\"",
$key
));
$keyNullsSrc = implode(self::SQL_AND, array_map(fn($el) => "\"a\".\"$el\" IS NULL", $key));
$keyNullsTgt = implode(self::SQL_AND, array_map(fn($el) => "\"b\".\"$el\" IS NULL", $key));
// ── Rows only in source (→ INSERT in UP) ─────────────────────────
$colsA = implode(',', array_map(fn($el) => "\"a\".\"$el\" AS \"$el\"", $columns1));
$result1 = $this->source->select(
"SELECT $colsA FROM \"main\".\"$table\" AS a
LEFT JOIN \"$alias\".\"$table\" AS b ON $keyCols
WHERE $keyNullsTgt"
);
// ── Rows only in target (→ DELETE in UP) ─────────────────────────
$colsB = implode(',', array_map(fn($el) => "\"b\".\"$el\" AS \"$el\"", $columns2));
$result2 = $this->source->select(
"SELECT $colsB FROM \"$alias\".\"$table\" AS b
LEFT JOIN \"main\".\"$table\" AS a ON $keyCols
WHERE $keyNullsSrc"
);
// ── Changed rows (→ UPDATE in UP) ─────────────────────────────────
$params = ParamsFactory::get();
$commonCols = array_values(array_intersect($columns1, $columns2));
$ignoredFields = TableFilter::getFieldsToIgnore($table, $params);
if (!empty($ignoredFields)) {
$commonCols = array_values(array_diff($commonCols, $ignoredFields));
}
$result3 = [];
if (!empty($commonCols)) {
$changeConds = $this->buildSQLiteChangeConds($commonCols);
$allCols = implode(',', array_merge(
array_map(fn($el) => "\"a\".\"$el\" AS \"s_$el\"", $commonCols),
array_map(fn($el) => "\"b\".\"$el\" AS \"t_$el\"", $commonCols)
));
$result3 = $this->source->select(
"SELECT $allCols FROM \"main\".\"$table\" AS a
INNER JOIN \"$alias\".\"$table\" AS b ON $keyCols
WHERE $changeConds"
);
}
return $this->buildDiffSequence($table, $result1, $result2, $result3, $key);
}
/**
* Build the WHERE condition for detecting changed rows in SQLite.
*
* If sha3() is available (bundled into many libsqlite3 builds), use a
* single hash comparison — one condition per row rather than N per column.
* Otherwise, fall back to the NULL-safe field-by-field IS NOT comparison.
*/
private function buildSQLiteChangeConds(array $commonCols): string
{
if ($this->sqliteSha3Available()) {
$hashA = $this->buildSQLiteSha3Expr($commonCols, 'a');
$hashB = $this->buildSQLiteSha3Expr($commonCols, 'b');
return "$hashA <> $hashB";
}
// Fallback: NULL-safe inequality per column
return implode(
' OR ',
array_map(fn($el) => "CAST(\"a\".\"$el\" AS TEXT) IS NOT CAST(\"b\".\"$el\" AS TEXT)", $commonCols)
);
}
/**
* Build a sha3() hash expression over the given columns for a table alias.
* Example: sha3(COALESCE(CAST("a"."col1" AS TEXT), '') || X'1f' || ..., 256)
*/
private function buildSQLiteSha3Expr(array $columns, string $alias): string
{
$parts = array_map(
fn($c) => "COALESCE(CAST(\"$alias\".\"$c\" AS TEXT), '')",
$columns
);
return "sha3(" . implode(" || X'1f' || ", $parts) . ", 256)";
}
/**
* Probe whether sha3() is available in this SQLite build.
* Caches the result per-process.
*/
private function sqliteSha3Available(): bool
{
static $available = null;
if ($available !== null) {
return $available;
}
try {
$this->source->select("SELECT sha3('test', 256) AS h");
$available = true;
} catch (\Throwable $e) {
$available = false;
}
return $available;
}
/** Turn the three raw result sets into Diff objects. */
private function buildDiffSequence(string $table, array $result1, array $result2, array $result3, array $key): array
{
// Apply rowsToIgnore filtering
$params = ParamsFactory::get();
$rowRules = TableFilter::getRowIgnoreRules($table, $params);
if (!empty($rowRules)) {
$result1 = TableFilter::filterRows($result1, $rowRules);
$result2 = TableFilter::filterRows($result2, $rowRules);
}
$diffSequence = [];
foreach ($result1 as $row) {
$diffSequence[] = new InsertData($table, [
'keys' => Arr::only($row, $key),
'diff' => new \Diff\DiffOp\DiffOpAdd(Arr::except($row, '_connection')),
]);
}
foreach ($result2 as $row) {
$diffSequence[] = new DeleteData($table, [
'keys' => Arr::only($row, $key),
'diff' => new \Diff\DiffOp\DiffOpRemove(Arr::except($row, '_connection')),
]);
}
foreach ($result3 as $row) {
$update = $this->buildUpdateFromRow($table, $row, $key);
if ($update !== null) {
$diffSequence[] = $update;
}
}
return $diffSequence;
}
private function buildUpdateFromRow(string $table, array $row, array $key): ?UpdateData
{
$diff = [];
$keys = [];
foreach ($row as $k => $value) {
if (!Str::startsWith($k, 's_')) {
continue;
}
$theKey = substr($k, 2);
$targetKey = 't_' . $theKey;
$sourceValue = $value;
if (in_array($theKey, $key)) {
$keys[$theKey] = $value;
}
$targetValue = $row[$targetKey] ?? null;
if ((string) $sourceValue !== (string) $targetValue) {
$diff[$theKey] = new \Diff\DiffOp\DiffOpChange($targetValue, $sourceValue);
}
}
return empty($diff) ? null : new UpdateData($table, ['keys' => $keys, 'diff' => $diff]);
}
// ── PostgreSQL path ───────────────────────────────────────────────────
//
// PostgreSQL does not support cross-database queries. Instead of loading
// both full tables into PHP memory (the old approach), we use a streaming
// sorted-merge with md5() row hashing:
//
// Phase 1: Stream PK + md5(row::text) from both databases in PK order.
// A merge-sort pass identifies inserts, deletes, and changed PKs
// without transferring full row data.
//
// Phase 2: Batch-fetch full rows only for the differing PKs.
//
// This scales to millions of rows and transfers only O(pk + 32 byte hash)
// per row in Phase 1.
private function getDiffPgsql(string $table, array $key): array
{
$params = ParamsFactory::get();
$columns1 = $this->manager->getColumns('source', $table);
$columns2 = $this->manager->getColumns('target', $table);
$fieldsToIgnore = TableFilter::getFieldsToIgnore($table, $params);
$merge = new StreamingMergeDiff($this->source, $this->target, 'pgsql');
return $merge->getDiff($table, $key, $columns1, $columns2, $fieldsToIgnore);
}
// ── MySQL / PostgreSQL path ───────────────────────────────────────────
public function getOldNewDiff($table, $key) {
$diffSequence = [];
$db1 = $this->source->getDatabaseName();
$db2 = $this->target->getDatabaseName();
$columns1 = $this->manager->getColumns('source', $table);
$columns2 = $this->manager->getColumns('target', $table);
$binaryCols = $this->manager->getBinaryColumns('source', $table);
$wrapConvert = function($arr, $p) use ($binaryCols) {
return array_map(function($el) use ($p, $binaryCols) {
if (in_array($el, $binaryCols)) {
return "HEX(`{$p}`.`{$el}`) as `{$el}`";
}
return "CONVERT(`{$p}`.`{$el}` USING utf8) as `{$el}`";
}, $arr);
};
$columnsAUtf = implode(',', $wrapConvert($columns1, 'a'));
$columnsBUtf = implode(',', $wrapConvert($columns2, 'b'));
$keyCols = implode(self::SQL_AND, array_map(function($el) {
return "`a`.`{$el}` = `b`.`{$el}`";
}, $key));
$keyNull = function($arr, $p) {
return array_map(function($el) use ($p) {
return "`{$p}`.`{$el}` IS NULL";
}, $arr);
};
$keyNulls1 = implode(self::SQL_AND, $keyNull($key, 'a'));
$keyNulls2 = implode(self::SQL_AND, $keyNull($key, 'b'));
$this->setFetchMode(\PDO::FETCH_NAMED);
$result1 = $this->source->select(
"SELECT $columnsAUtf FROM `{$db1}`.`{$table}` as a
LEFT JOIN `{$db2}`.`{$table}` as b ON $keyCols WHERE $keyNulls2
");
$result2 = $this->source->select(
"SELECT $columnsBUtf FROM `{$db2}`.`{$table}` as b
LEFT JOIN `{$db1}`.`{$table}` as a ON $keyCols WHERE $keyNulls1
");
$this->setFetchMode(\PDO::FETCH_ASSOC);
$this->wrapBinaryValues($result1, $binaryCols);
$this->wrapBinaryValues($result2, $binaryCols);
// Apply rowsToIgnore filtering
$params = ParamsFactory::get();
$rowRules = TableFilter::getRowIgnoreRules($table, $params);
if (!empty($rowRules)) {
$result1 = TableFilter::filterRows($result1, $rowRules);
$result2 = TableFilter::filterRows($result2, $rowRules);
}
foreach ($result1 as $row) {
$diffSequence[] = new InsertData($table, [
'keys' => Arr::only($row, $key),
'diff' => new \Diff\DiffOp\DiffOpAdd(Arr::except($row, '_connection'))
]);
}
foreach ($result2 as $row) {
$diffSequence[] = new DeleteData($table, [
'keys' => Arr::only($row, $key),
'diff' => new \Diff\DiffOp\DiffOpRemove(Arr::except($row, '_connection'))
]);
}
return $diffSequence;
}
public function getChangeDiff($table, $key) {
$params = ParamsFactory::get();
$diffSequence = [];
$db1 = $this->source->getDatabaseName();
$db2 = $this->target->getDatabaseName();
$columns1 = $this->manager->getColumns('source', $table);
$columns2 = $this->manager->getColumns('target', $table);
$ignoredFields = TableFilter::getFieldsToIgnore($table, $params);
if (!empty($ignoredFields)) {
$columns1 = array_diff($columns1, $ignoredFields);
$columns2 = array_diff($columns2, $ignoredFields);
}
$binaryCols = $this->manager->getBinaryColumns('source', $table);
$wrapAs = function($arr, $p1, $p2) use ($binaryCols) {
return array_map(function($el) use ($p1, $p2, $binaryCols) {
if (in_array($el, $binaryCols)) {
return "HEX(`{$p1}`.`{$el}`) as `{$p2}{$el}`";
}
return "`{$p1}`.`{$el}` as `{$p2}{$el}`";
}, $arr);
};
$wrapCast = function($arr, $p) use ($binaryCols) {
return array_map(function($el) use ($p, $binaryCols) {
if (in_array($el, $binaryCols)) {
return "HEX(IFNULL(`{$p}`.`{$el}`, ''))";
}
return "CAST(IFNULL(`{$p}`.`{$el}`, '\\0') AS CHAR CHARACTER SET utf8)";
}, $arr);
};
// NULL-presence bitmap: distinguishes NULL from empty string
$wrapNullCheck = function($arr, $p) {
return array_map(function($el) use ($p) {
return "IF(`{$p}`.`{$el}` IS NULL, '1', '0')";
}, $arr);
};
$columnsAas = implode(',', $wrapAs($columns1, 'a', 's_'));
$columnsA = implode(',', $wrapCast($columns1, 'a'));
$columnsA0 = implode(',', $wrapNullCheck($columns1, 'a'));
$columnsBas = implode(',', $wrapAs($columns2, 'b', 't_'));
$columnsB = implode(',', $wrapCast($columns2, 'b'));
$columnsB0 = implode(',', $wrapNullCheck($columns2, 'b'));
$keyCols = implode(self::SQL_AND, array_map(function($el) {
return "`a`.`{$el}` = `b`.`{$el}`";
}, $key));
$this->setFetchMode(\PDO::FETCH_NAMED);
$result = $this->source->select(
"SELECT * FROM (
SELECT $columnsAas, $columnsBas, SHA2(concat($columnsA), 256) AS hash1,
SHA2(concat($columnsB), 256) AS hash2,
CONCAT($columnsA0) AS nullmap1, CONCAT($columnsB0) AS nullmap2
FROM `{$db1}`.`{$table}` as a
INNER JOIN `{$db2}`.`{$table}` as b
ON $keyCols
) t WHERE hash1 <> hash2 OR nullmap1 <> nullmap2");
$this->setFetchMode(\PDO::FETCH_ASSOC);
$this->wrapBinaryValuesChangeDiff($result, $binaryCols);
foreach ($result as $row) {
$diff = []; $keys = [];
foreach ($row as $k => $value) {
if (Str::startsWith($k, 's_')) {
$theKey = substr($k, 2);
$targetKey = 't_'.$theKey;
$sourceValue = $value;
if (in_array($theKey, $key)) $keys[$theKey] = $value;
if (isset($row[$targetKey])) {
$targetValue = $row[$targetKey];
if ($sourceValue != $targetValue) {
$diff[$theKey] = new \Diff\DiffOp\DiffOpChange($targetValue, $sourceValue);
}
} else {
$diff[$theKey] = new \Diff\DiffOp\DiffOpChange(NULL, $sourceValue);
}
}
}
$diffSequence[] = new UpdateData($table, [
'keys' => $keys,
'diff' => $diff
]);
}
return $diffSequence;
}
private function wrapBinaryValues(array &$rows, array $binaryCols): void
{
if (empty($binaryCols)) {
return;
}
foreach ($rows as &$row) {
foreach ($binaryCols as $col) {
if (isset($row[$col]) && $row[$col] !== null) {
$row[$col] = new BinaryValue($row[$col]);
}
}
}
}
private function wrapBinaryValuesChangeDiff(array &$rows, array $binaryCols): void
{
if (empty($binaryCols)) {
return;
}
foreach ($rows as &$row) {
foreach ($binaryCols as $col) {
$sKey = 's_' . $col;
$tKey = 't_' . $col;
if (isset($row[$sKey]) && $row[$sKey] !== null) {
$row[$sKey] = new BinaryValue($row[$sKey]);
}
if (isset($row[$tKey]) && $row[$tKey] !== null) {
$row[$tKey] = new BinaryValue($row[$tKey]);
}
}
}
}
private function setFetchMode($fetchMode = \PDO::FETCH_ASSOC)
{
$dispatcher = new Dispatcher();
$dispatcher->listen(StatementPrepared::class, function ($event) use ($fetchMode) {
$event->statement->setFetchMode($fetchMode);
});
$this->source->setEventDispatcher($dispatcher);
}
}