blob: 9a6f3e938a0f751144715245ad0eca4f89e88f7c (
plain) (
blame)
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
|
<?php
namespace Application\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Changed tags to lowercase.
*/
class Version20170719231144 extends AbstractMigration implements ContainerAwareInterface
{
/**
* @var ContainerInterface
*/
private $container;
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
/**
* @param Schema $schema
*/
public function up(Schema $schema)
{
$this->skipIf('sqlite' === $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'mysql\' or \'postgresql\'.');
// Find tags which need to be merged
$dupTags = $this->connection->query('
SELECT LOWER(label) AS lower_label
FROM ' . $this->getTable('tag') . '
GROUP BY LOWER(label)
HAVING COUNT(*) > 1'
);
$dupTags->execute();
foreach ($dupTags->fetchAll() as $duplicates) {
$label = $duplicates['lower_label'];
// Retrieve all duplicate tags for a given tag
$tags = $this->connection->executeQuery('
SELECT id
FROM ' . $this->getTable('tag') . '
WHERE LOWER(label) = :label
ORDER BY id ASC',
[
'label' => $label,
]
);
$first = true;
$newId = null;
$ids = [];
foreach ($tags->fetchAll() as $tag) {
// Ignore the first tag as we use it as the new reference tag
if ($first) {
$first = false;
$newId = $tag['id'];
} else {
$ids[] = $tag['id'];
}
}
// Just in case...
if (count($ids) > 0) {
// Merge tags
$this->addSql('
UPDATE ' . $this->getTable('entry_tag') . '
SET tag_id = ' . $newId . '
WHERE tag_id IN (' . implode(',', $ids) . ')
AND entry_id NOT IN (
SELECT entry_id
FROM ' . $this->getTable('entry_tag') . '
WHERE tag_id = ' . $newId . '
)'
);
// Delete links to unused tags
$this->addSql('
DELETE FROM ' . $this->getTable('entry_tag') . '
WHERE tag_id IN (' . implode(',', $ids) . ')'
);
// Delete unused tags
$this->addSql('
DELETE FROM ' . $this->getTable('tag') . '
WHERE id IN (' . implode(',', $ids) . ')'
);
}
}
// Iterate over all tags to lowercase them
$this->addSql('
UPDATE ' . $this->getTable('tag') . '
SET label = LOWER(label)'
);
}
/**
* @param Schema $schema
*/
public function down(Schema $schema)
{
throw new SkipMigrationException('Too complex ...');
}
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
}
}
|