-
Notifications
You must be signed in to change notification settings - Fork 159
Expand file tree
/
Copy pathTableData.php
More file actions
83 lines (72 loc) · 2.88 KB
/
TableData.php
File metadata and controls
83 lines (72 loc) · 2.88 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
<?php namespace DBDiff\DB\Data;
use DBDiff\Diff\InsertData;
use DBDiff\Diff\UpdateData;
use DBDiff\Diff\DeleteData;
use DBDiff\Exceptions\DataException;
use DBDiff\Logger;
use Illuminate\Support\Arr;
class TableData {
function __construct($manager) {
$this->manager = $manager;
$this->source = $this->manager->getDB('source');
$this->target = $this->manager->getDB('target');
$this->distTableData = new DistTableData($manager);
$this->localTableData = new LocalTableData($manager);
}
public function getIterator($connection, $table) {
return new TableIterator($this->{$connection}, $table);
}
public function getNewData($table) {
Logger::info("Now getting new data from table `$table`");
$diffSequence = [];
$iterator = $this->getIterator('source', $table);
$key = $this->manager->getKey('source', $table);
while ($iterator->hasNext()) {
$data = $iterator->next(ArrayDiff::$size);
foreach ($data as $entry) {
$diffSequence[] = new InsertData($table, [
'keys' => Arr::only($entry, $key),
'diff' => new \Diff\DiffOp\DiffOpAdd($entry)
]);
}
}
return $diffSequence;
}
public function getOldData($table) {
Logger::info("Now getting old data from table `$table`");
$diffSequence = [];
$iterator = $this->getIterator('target', $table);
$key = $this->manager->getKey('target', $table);
while ($iterator->hasNext()) {
$data = $iterator->next(ArrayDiff::$size);
foreach ($data as $entry) {
$diffSequence[] = new DeleteData($table, [
'keys' => Arr::only($entry, $key),
'diff' => new \Diff\DiffOp\DiffOpRemove($entry)
]);
}
}
return $diffSequence;
}
public function getDiff($table) {
$server1 = $this->source->getConfig('host').':'.$this->source->getConfig('port');
$server2 = $this->target->getConfig('host').':'.$this->target->getConfig('port');
$sourceKey = $this->manager->getKey('source', $table);
$targetKey = $this->manager->getKey('target', $table);
$this->checkKeys($table, $sourceKey, $targetKey);
if ($server1 == $server2) {
return $this->localTableData->getDiff($table, $sourceKey);
} else {
return $this->distTableData->getDiff($table, $sourceKey);
}
}
private function checkKeys($table, $sourceKey, $targetKey) {
if (empty($sourceKey) || empty($targetKey)) {
throw new DataException("No primary key found in table `$table`");
}
if ($sourceKey != $targetKey) {
throw new DataException("Unmatched primary keys in table `$table`");
}
return true;
}
}