1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Wabel\Zoho\CRM\Copy; |
4
|
|
|
|
5
|
|
|
use Doctrine\DBAL\Connection; |
6
|
|
|
use Doctrine\DBAL\Schema\Comparator; |
7
|
|
|
use Doctrine\DBAL\Schema\SchemaDiff; |
8
|
|
|
use Doctrine\DBAL\Schema\Table; |
9
|
|
|
use Psr\Log\LoggerInterface; |
10
|
|
|
|
11
|
|
|
class DbalTableDiffService |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var Connection |
15
|
|
|
*/ |
16
|
|
|
private $connection; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var LoggerInterface |
20
|
|
|
*/ |
21
|
|
|
private $logger; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @param Connection $connection |
25
|
|
|
*/ |
26
|
|
|
public function __construct(Connection $connection, LoggerInterface $logger) |
27
|
|
|
{ |
28
|
|
|
$this->connection = $connection; |
29
|
|
|
$this->logger = $logger; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param Table $table |
34
|
|
|
* |
35
|
|
|
* @return bool Returns true if changes where applied. False otherwise. |
36
|
|
|
*/ |
37
|
|
|
public function createOrUpdateTable(Table $table) |
38
|
|
|
{ |
39
|
|
|
$tableName = $table->getName(); |
40
|
|
|
$dbSchema = $this->connection->getSchemaManager()->createSchema(); |
41
|
|
|
if ($this->connection->getSchemaManager()->tablesExist($tableName)) { |
42
|
|
|
$dbTable = $dbSchema->getTable($tableName); |
43
|
|
|
|
44
|
|
|
$comparator = new Comparator(); |
45
|
|
|
$tableDiff = $comparator->diffTable($dbTable, $table); |
46
|
|
|
|
47
|
|
|
if ($tableDiff !== false) { |
48
|
|
|
$this->logger->notice('Changes detected in table structure for '.$tableName.'. Applying patch.'); |
49
|
|
|
$diff = new SchemaDiff(); |
50
|
|
|
$diff->fromSchema = $dbSchema; |
51
|
|
|
$diff->changedTables[$tableName] = $tableDiff; |
52
|
|
|
$statements = $diff->toSaveSql($this->connection->getDatabasePlatform()); |
53
|
|
|
foreach ($statements as $sql) { |
54
|
|
|
$this->connection->exec($sql); |
55
|
|
|
} |
56
|
|
|
return true; |
57
|
|
|
} |
58
|
|
|
$this->logger->info('No changes detected in table structure for '.$tableName); |
59
|
|
|
return false; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
$this->logger->notice("Creating new table '$tableName'."); |
63
|
|
|
$diff = new SchemaDiff(); |
64
|
|
|
$diff->fromSchema = $dbSchema; |
65
|
|
|
$diff->newTables[$tableName] = $table; |
66
|
|
|
$statements = $diff->toSaveSql($this->connection->getDatabasePlatform()); |
67
|
|
|
foreach ($statements as $sql) { |
68
|
|
|
$this->connection->exec($sql); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
return true; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|