summaryrefslogtreecommitdiff
path: root/db/migrations/2019_07_21_000000_fix_old_character_set.php
blob: f72e26aecc78d3494e5e965318e9a941216535c7 (plain)
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
<?php

namespace Engelsystem\Migrations;

use Engelsystem\Database\Migration\Migration;
use stdClass;

class FixOldCharacterSet extends Migration
{
    /**
     * Run the migration
     */
    public function up()
    {
        $connection = $this->schema->getConnection();
        $targetCharset = $connection->getConfig('charset');
        $targetCollation = $connection->getConfig('collation');

        if (!$targetCharset || !$targetCharset) {
            return;
        }

        $connection
            ->unprepared(sprintf(
                'ALTER DATABASE %s CHARACTER SET %s COLLATE %s',
                $connection->getDatabaseName(),
                $targetCharset,
                $targetCollation
            ));

        /** @var stdClass[] $databases */
        $tables = $this->getTablesToChange($targetCollation);
        foreach ($tables as $table) {
            $connection
                ->unprepared(sprintf(
                    'ALTER TABLE %s CONVERT TO CHARACTER SET %s COLLATE %s',
                    $table->table,
                    $targetCharset,
                    $targetCollation
                ));
        }
    }

    /**
     * Reverse the migration
     */
    public function down()
    {
        // Nothing to do
    }

    /**
     * @param $target
     * @return array
     */
    protected function getTablesToChange($target)
    {
        $connection = $this->schema->getConnection();

        return $connection
            ->select(
                '
                    SELECT
                        `TABLE_NAME` AS "table"
                    FROM information_schema.TABLES
                    WHERE TABLE_SCHEMA = ?
                    AND TABLE_COLLATION != ?
                ',
                [
                    $connection->getDatabaseName(),
                    $target
                ]
            );
    }
}