]> git.immae.eu Git - github/wallabag/wallabag.git/blob - app/DoctrineMigrations/Version20160410190541.php
Added hasColumn() in migration to check column existence
[github/wallabag/wallabag.git] / app / DoctrineMigrations / Version20160410190541.php
1 <?php
2
3 namespace Application\Migrations;
4
5 use Doctrine\DBAL\Migrations\AbstractMigration;
6 use Doctrine\DBAL\Schema\Schema;
7 use Symfony\Component\DependencyInjection\ContainerAwareInterface;
8 use Symfony\Component\DependencyInjection\ContainerInterface;
9
10 class Version20160410190541 extends AbstractMigration implements ContainerAwareInterface
11 {
12 /**
13 * @var ContainerInterface
14 */
15 private $container;
16
17 public function setContainer(ContainerInterface $container = null)
18 {
19 $this->container = $container;
20 }
21
22 private function getTable($tableName)
23 {
24 return $this->container->getParameter('database_table_prefix').$tableName;
25 }
26
27 private function hasColumn($tableName, $columnName)
28 {
29 switch ($this->connection->getDatabasePlatform()->getName()) {
30 case 'sqlite':
31 $rows = $this->connection->executeQuery('pragma table_info('.$tableName.')')->fetchAll();
32 foreach ($rows as $column) {
33 if (strcasecmp($column['name'], $columnName) === 0) {
34 return true;
35 }
36 }
37
38 return false;
39 case 'mysql':
40 $rows = $this->connection->executeQuery('SHOW COLUMNS FROM '.$tableName)->fetchAll();
41 foreach ($rows as $column) {
42 if (strcasecmp($column['Field'], $columnName) === 0) {
43 return true;
44 }
45 }
46
47 return false;
48 case 'postgresql':
49 $sql = sprintf("SELECT count(*)
50 FROM information_schema.columns
51 WHERE table_schema = 'public' AND table_name = '%s' AND column_name = '%s'",
52 $tableName,
53 $columnName
54 );
55 $result = $this->connection->executeQuery($sql)->fetch();
56
57 return $result['count'] > 0;
58 }
59 }
60
61 /**
62 * @param Schema $schema
63 */
64 public function up(Schema $schema)
65 {
66 $this->skipIf($this->hasColumn($this->getTable('entry'), 'uuid'), 'It seems that you already played this migration.');
67
68 if ($this->connection->getDatabasePlatform()->getName() == 'postgresql') {
69 $this->addSql('ALTER TABLE "'.$this->getTable('entry').'" ADD uuid UUID DEFAULT NULL');
70 } else {
71 $this->addSql('ALTER TABLE "'.$this->getTable('entry').'" ADD uuid LONGTEXT DEFAULT NULL');
72 }
73
74 $this->addSql('INSERT INTO "'.$this->getTable('craue_config_setting')."\" (name, value, section) VALUES ('share_public', '1', 'entry')");
75 }
76
77 /**
78 * @param Schema $schema
79 */
80 public function down(Schema $schema)
81 {
82 $this->skipIf($this->connection->getDatabasePlatform()->getName() != 'sqlite', 'This down migration can\'t be executed on SQLite databases, because SQLite don\'t support DROP COLUMN.');
83
84 $this->addSql('ALTER TABLE "'.$this->getTable('entry').'" DROP uuid');
85 $this->addSql('DELETE FROM "'.$this->getTable('craue_config_setting')."\" WHERE name = 'share_public'");
86 }
87 }