File size: 2,380 Bytes
d2897cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<?php

declare(strict_types=1);

namespace Mautic\Migrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Schema\Table;
use Mautic\CoreBundle\Doctrine\PreUpAssertionMigration;

class Version20220429091934 extends PreUpAssertionMigration
{
    private const SIGNED   = 'SIGNED';

    private const UNSIGNED = 'UNSIGNED';

    protected function preUpAssertions(): void
    {
        $this->skipAssertion(function (Schema $schema) {
            return $schema->hasTable("{$this->prefix}contact_export_scheduler");
        }, sprintf('Table %s already exists', "{$this->prefix}contact_export_scheduler"));
    }

    public function up(Schema $schema): void
    {
        $userIdFK = $this->generatePropertyName('users', 'fk', ['user_id']);

        $contactExportSchedulerTableName = "{$this->prefix}contact_export_scheduler";
        $usersTableName                  = "{$this->prefix}users";

        $usersIdDataType = $this->getColumnDataType($schema->getTable($usersTableName), 'id');

        $this->addSql(
            "# Creating table {$this->prefix}contact_export_scheduler
            # ------------------------------------------------------------
            CREATE TABLE {$contactExportSchedulerTableName} (
                id INT AUTO_INCREMENT NOT NULL,
                user_id INT {$usersIdDataType} NOT NULL,
                scheduled_datetime DATETIME NOT NULL COMMENT '(DC2Type:datetime_immutable)',
                data LONGTEXT DEFAULT NULL COMMENT '(DC2Type:array)',
                PRIMARY KEY(id)
            ) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB;"
        );

        $this->addSql("ALTER TABLE {$contactExportSchedulerTableName} ADD CONSTRAINT {$userIdFK} FOREIGN KEY (user_id) REFERENCES $usersTableName (id)");
    }

    public function down(Schema $schema): void
    {
        $this->addSql(
            "# Dropping table {$this->prefix}contact_export_scheduler
            # ------------------------------------------------------------
            DROP TABLE {$this->prefix}contact_export_scheduler"
        );
    }

    /**
     * @throws \Doctrine\DBAL\Schema\SchemaException
     */
    private function getColumnDataType(Table $table, string $columnName): string
    {
        $column = $table->getColumn($columnName);

        return $column->getUnsigned() ? self::UNSIGNED : self::SIGNED;
    }
}