|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * Text in every script, under mixed collations, diffed and applied on MySQL. |
| 5 | + * |
| 6 | + * DBDiff connected to MySQL as `utf8` — MySQL's utf8mb3, three bytes a |
| 7 | + * character at most — and compared rows through CAST/CONVERT to the same. |
| 8 | + * Anything needing four bytes (emoji, scripts outside the Basic Multilingual |
| 9 | + * Plane such as Brahmi) was read as '?', so a change from one such value to |
| 10 | + * another was not seen at all, on either data path. |
| 11 | + * |
| 12 | + * And the schema pre-scan hashed each column's type, default and nullability |
| 13 | + * but not its character set, collation, comment or generated expression, so |
| 14 | + * a table that differed only there was skipped as unchanged. |
| 15 | + * |
| 16 | + * Verdicts are byte for byte: after the generated UP the target must hold |
| 17 | + * exactly the source's bytes, and the source's collations. Runs in the MySQL |
| 18 | + * jobs (DB_HOST); skips without a server. |
| 19 | + */ |
| 20 | + |
| 21 | +use DBDiff\DB\Data\StreamingMergeDiff; |
| 22 | +use DBDiff\Params\DefaultParams; |
| 23 | +use DBDiff\Params\ParamsFactory; |
| 24 | +use DBDiff\SQLGen\Dialect\MySQLDialect; |
| 25 | +use DBDiff\SQLGen\DiffToSQL\DeleteDataSQL; |
| 26 | +use DBDiff\SQLGen\DiffToSQL\InsertDataSQL; |
| 27 | +use DBDiff\SQLGen\DiffToSQL\UpdateDataSQL; |
| 28 | +use DBDiff\Diff\InsertData; |
| 29 | +use DBDiff\Diff\DeleteData; |
| 30 | +use Illuminate\Database\Capsule\Manager as Capsule; |
| 31 | +use Illuminate\Database\Events\StatementPrepared; |
| 32 | +use Illuminate\Events\Dispatcher; |
| 33 | +use PHPUnit\Framework\TestCase; |
| 34 | + |
| 35 | +class UnicodeMySQLTest extends TestCase |
| 36 | +{ |
| 37 | + private ?PDO $admin = null; |
| 38 | + private string $host = ''; |
| 39 | + private string $port = ''; |
| 40 | + private string $password = ''; |
| 41 | + private array $created = []; |
| 42 | + |
| 43 | + /** Gurmukhi, transliteration, translation, other scripts, and four-byte characters. */ |
| 44 | + private const TABLE = "CREATE TABLE gurbani ( |
| 45 | + id int PRIMARY KEY, |
| 46 | + gurmukhi text COLLATE utf8mb4_unicode_ci, |
| 47 | + translit varchar(200) COLLATE utf8mb4_0900_ai_ci, |
| 48 | + english text COLLATE utf8mb4_bin, |
| 49 | + other varchar(200), |
| 50 | + emoji varchar(40) COLLATE utf8mb4_bin, |
| 51 | + legacy varchar(50) CHARACTER SET latin1 |
| 52 | + ) DEFAULT CHARSET=utf8mb4"; |
| 53 | + |
| 54 | + private const WORDS = "CREATE TABLE words (word varchar(100) COLLATE utf8mb4_0900_ai_ci PRIMARY KEY, meaning varchar(100)) DEFAULT CHARSET=utf8mb4"; |
| 55 | + |
| 56 | + protected function setUp(): void |
| 57 | + { |
| 58 | + $host = getenv('DB_HOST'); |
| 59 | + if (!$host || !extension_loaded('pdo_mysql')) { |
| 60 | + $this->markTestSkipped('DB_HOST not set.'); |
| 61 | + } |
| 62 | + $this->host = $host; |
| 63 | + $this->port = getenv('DB_PORT') ?: '3306'; |
| 64 | + $this->password = getenv('DB_ROOT_PASSWORD') ?: 'rootpass'; |
| 65 | + $this->admin = new PDO("mysql:host={$this->host};port={$this->port};charset=utf8mb4", 'root', $this->password, |
| 66 | + [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); |
| 67 | + ParamsFactory::set(new DefaultParams); |
| 68 | + } |
| 69 | + |
| 70 | + protected function tearDown(): void |
| 71 | + { |
| 72 | + foreach ($this->created as $db) { |
| 73 | + $this->admin?->exec("DROP DATABASE IF EXISTS `$db`"); |
| 74 | + } |
| 75 | + ParamsFactory::reset(); |
| 76 | + } |
| 77 | + |
| 78 | + public function testSameServerDiffCarriesEveryScriptByteForByte(): void |
| 79 | + { |
| 80 | + [$source, $target] = $this->fixture('same'); |
| 81 | + |
| 82 | + $up = $this->cliUp($source, $target, 'all'); |
| 83 | + if ($this->onDolt()) { |
| 84 | + $this->assertCaseOnlyChangesPlanned($up); |
| 85 | + return; |
| 86 | + } |
| 87 | + $this->apply($target, $up); |
| 88 | + |
| 89 | + $this->assertSame($this->snapshot($source), $this->snapshot($target)); |
| 90 | + } |
| 91 | + |
| 92 | + /** The streaming merge — the cross-server path — on the same rows. */ |
| 93 | + public function testStreamingMergeSeesFourByteChanges(): void |
| 94 | + { |
| 95 | + [$source, $target] = $this->fixture('stream'); |
| 96 | + $capsule = new Capsule; |
| 97 | + $dispatcher = new Dispatcher(); |
| 98 | + $dispatcher->listen(StatementPrepared::class, fn($e) => $e->statement->setFetchMode(PDO::FETCH_ASSOC)); |
| 99 | + $capsule->setEventDispatcher($dispatcher); |
| 100 | + $conn = []; |
| 101 | + foreach ([$source, $target] as $db) { |
| 102 | + $capsule->addConnection(['driver' => 'mysql', 'host' => $this->host, 'port' => $this->port, 'database' => $db, |
| 103 | + 'username' => 'root', 'password' => $this->password, 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci'], $db); |
| 104 | + $conn[] = $capsule->getConnection($db); |
| 105 | + } |
| 106 | + $merge = new StreamingMergeDiff($conn[0], $conn[1], 'mysql'); |
| 107 | + $dialect = new MySQLDialect(); |
| 108 | + $up = []; |
| 109 | + foreach (['gurbani' => ['id'], 'words' => ['word']] as $table => $key) { |
| 110 | + $cols = array_column($this->pdo($source)->query("SHOW COLUMNS FROM `$table`")->fetchAll(PDO::FETCH_ASSOC), 'Field'); |
| 111 | + foreach ($merge->getDiff($table, $key, $cols, $cols) as $d) { |
| 112 | + $sql = match (true) { |
| 113 | + $d instanceof InsertData => new InsertDataSQL($d, $dialect), |
| 114 | + $d instanceof DeleteData => new DeleteDataSQL($d, $dialect), |
| 115 | + default => new UpdateDataSQL($d, $dialect), |
| 116 | + }; |
| 117 | + $up[] = $sql->getUp(); |
| 118 | + } |
| 119 | + } |
| 120 | + // Deletes first: a key can come back under another normalisation. |
| 121 | + usort($up, fn($a, $b) => str_starts_with($b, 'DELETE') <=> str_starts_with($a, 'DELETE')); |
| 122 | + |
| 123 | + if ($this->onDolt()) { |
| 124 | + $this->assertCaseOnlyChangesPlanned(implode("\n", $up)); |
| 125 | + return; |
| 126 | + } |
| 127 | + $this->apply($target, implode("\n", $up)); |
| 128 | + |
| 129 | + $this->assertSame($this->rows($source), $this->rows($target)); |
| 130 | + } |
| 131 | + |
| 132 | + public function testThePreScanSeesCollationCommentAndGeneratedChanges(): void |
| 133 | + { |
| 134 | + $source = $this->db('prescan_s'); |
| 135 | + $target = $this->db('prescan_t'); |
| 136 | + $this->pdo($source)->exec("CREATE TABLE c1 (id int PRIMARY KEY, v text COLLATE utf8mb4_unicode_ci); |
| 137 | + CREATE TABLE c2 (id int PRIMARY KEY, v int COMMENT 'ਮੂਲ ਮੰਤਰ'); |
| 138 | + CREATE TABLE c3 (id int PRIMARY KEY, a int, g int GENERATED ALWAYS AS (a * 2) STORED)"); |
| 139 | + $this->pdo($target)->exec("CREATE TABLE c1 (id int PRIMARY KEY, v text COLLATE utf8mb4_0900_ai_ci); |
| 140 | + CREATE TABLE c2 (id int PRIMARY KEY, v int COMMENT 'old'); |
| 141 | + CREATE TABLE c3 (id int PRIMARY KEY, a int, g int GENERATED ALWAYS AS (a * 3) STORED)"); |
| 142 | + |
| 143 | + $up = $this->cliUp($source, $target, 'schema'); |
| 144 | + |
| 145 | + $this->assertMatchesRegularExpression('/ALTER TABLE `c1` CHANGE `v` `v` text .*COLLATE utf8mb4_unicode_ci/', $up); |
| 146 | + $this->assertStringContainsString("COMMENT 'ਮੂਲ ਮੰਤਰ'", $up); |
| 147 | + // Dolt leaves information_schema's GENERATION_EXPRESSION empty, so |
| 148 | + // the pre-scan cannot see this one there; MySQL fills it in. |
| 149 | + if (!$this->onDolt()) { |
| 150 | + $this->assertMatchesRegularExpression('/ALTER TABLE `c3` CHANGE `g` `g` int GENERATED ALWAYS AS \(\(`a` \* 2\)\)/', $up); |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + // ── helpers ────────────────────────────────────────────────────────────── |
| 155 | + |
| 156 | + /** |
| 157 | + * Dolt does not apply an UPDATE whose new value equals the old one under |
| 158 | + * the column's collation ("0 rows affected" for 'akaal' → 'Akaal' in a |
| 159 | + * _ci column), where MySQL writes the new bytes. DBDiff plans it all the |
| 160 | + * same; on Dolt that is what is checked, instead of the applied bytes. |
| 161 | + */ |
| 162 | + private function onDolt(): bool |
| 163 | + { |
| 164 | + try { |
| 165 | + $this->admin->query('SELECT dolt_version()'); |
| 166 | + return true; |
| 167 | + } catch (PDOException) { |
| 168 | + return false; |
| 169 | + } |
| 170 | + } |
| 171 | + |
| 172 | + private function assertCaseOnlyChangesPlanned(string $up): void |
| 173 | + { |
| 174 | + $this->assertStringContainsString("`translit` = 'Akaal Moorat'", $up); |
| 175 | + $this->assertStringContainsString("`meaning` = 'wondrous'", $up); |
| 176 | + $this->assertStringContainsString("`emoji` = '🎵'", $up); |
| 177 | + $this->assertStringContainsString("`emoji` = '𑀅𑀓'", $up); |
| 178 | + } |
| 179 | + |
| 180 | + /** Two databases, the target differing in ways only exact bytes reveal. @return string[] */ |
| 181 | + private function fixture(string $case): array |
| 182 | + { |
| 183 | + $source = $this->db("uni_{$case}_s"); |
| 184 | + $target = $this->db("uni_{$case}_t"); |
| 185 | + $nfd = "cafe\u{0301}"; // é as e + combining acute: looks the same, different bytes |
| 186 | + $this->pdo($source)->exec(self::TABLE . ';' . self::WORDS . "; |
| 187 | + INSERT INTO gurbani VALUES |
| 188 | + (1, 'ੴ ਸਤਿ ਨਾਮੁ ਕਰਤਾ ਪੁਰਖੁ', 'Ik Oankaar Sat Naam', 'One Universal Creator', 'एक ओंकार सत नाम', '🙏', 'café'), |
| 189 | + (2, 'ਅਕਾਲ ਮੂਰਤਿ ਅਜੂਨੀ ਸੈਭੰ', 'Akaal Moorat', 'Image Of The Undying', 'اک اونکار', '🪯', 'naïve'), |
| 190 | + (3, '॥ ਜਪੁ ॥', 'Jap', 'Chant', '唯一神', '𑀅𑀓', 'Ångström'), |
| 191 | + (4, 'ਆਦਿ ਸਚੁ', 'Aad Sach', 'Waheguru', 'café', '👳🏽♂️', 'resume'), |
| 192 | + (5, 'ਸੋ ਦਰੁ', 'So Dar', 'That Door', 'सो दर', '🎵', 'x'); |
| 193 | + INSERT INTO words VALUES ('ਸਤਿ','truth'),('ਨਾਮੁ','name'),('Waheguru','wondrous'),('10','ten'),('9','nine'),('é','NFC');"); |
| 194 | + $this->pdo($target)->exec(self::TABLE . ';' . self::WORDS . "; |
| 195 | + INSERT INTO gurbani VALUES |
| 196 | + (1, 'ੴ ਸਤ ਨਾਮੁ ਕਰਤਾ ਪੁਰਖੁ', 'Ik Oankaar Sat Naam', 'One Universal Creator', 'एक ओंकार सत नाम', '🙂', 'café'), |
| 197 | + (2, 'ਅਕਾਲ ਮੂਰਤਿ ਅਜੂਨੀ ਸੈਭੰ', 'akaal moorat', 'Image Of The Undying', 'اک اونکار', '🪯', 'naive'), |
| 198 | + (3, '॥ ਜਪੁ ॥', 'Jap', 'Chant', '唯一神', '𑀅𑀔', 'Angstrom'), |
| 199 | + (4, 'ਆਦਿ ਸਚੁ', 'Aad Sach', 'waheguru', '$nfd', '👳🏽♂️', 'resume'), |
| 200 | + -- Differs only in a four-byte character, so nothing else flags the row. |
| 201 | + (5, 'ਸੋ ਦਰੁ', 'So Dar', 'That Door', 'सो दर', '🎶', 'x'); |
| 202 | + INSERT INTO words VALUES ('ਸਤਿ','truth'),('Waheguru','Wondrous'),('9','nine'),('e\u{0301}','NFD'),('ਗੁਰੂ','guru');"); |
| 203 | + return [$source, $target]; |
| 204 | + } |
| 205 | + |
| 206 | + private function db(string $name): string |
| 207 | + { |
| 208 | + $db = "dbdiff_$name"; |
| 209 | + $this->admin->exec("DROP DATABASE IF EXISTS `$db`"); |
| 210 | + $this->admin->exec("CREATE DATABASE `$db` CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci"); |
| 211 | + $this->created[] = $db; |
| 212 | + return $db; |
| 213 | + } |
| 214 | + |
| 215 | + private function pdo(string $db): PDO |
| 216 | + { |
| 217 | + return new PDO("mysql:host={$this->host};port={$this->port};dbname=$db;charset=utf8mb4", 'root', $this->password, |
| 218 | + [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); |
| 219 | + } |
| 220 | + |
| 221 | + /** The CLI's UP from `$source` to `$target`. */ |
| 222 | + private function cliUp(string $source, string $target, string $type): string |
| 223 | + { |
| 224 | + $out = tempnam(sys_get_temp_dir(), 'dbdiff_uni_') . '.sql'; |
| 225 | + $url = fn($db) => "mysql://root:" . rawurlencode($this->password) . "@{$this->host}:{$this->port}/$db"; |
| 226 | + exec(escapeshellarg(PHP_BINARY) . ' ' . escapeshellarg(dirname(__DIR__, 2) . '/dbdiff.php') |
| 227 | + . " diff --type=$type --include=up --nocomments --allow-destructive" |
| 228 | + . ' --server1-url=' . escapeshellarg($url($source)) . ' --server2-url=' . escapeshellarg($url($target)) |
| 229 | + . ' --output=' . escapeshellarg($out) . ' 2>&1', $log, $status); |
| 230 | + $this->assertSame(0, $status, implode("\n", $log)); |
| 231 | + $sql = file_exists($out) ? file_get_contents($out) : ''; |
| 232 | + @unlink($out); |
| 233 | + return $sql; |
| 234 | + } |
| 235 | + |
| 236 | + private function apply(string $db, string $sql): void |
| 237 | + { |
| 238 | + $pdo = $this->pdo($db); |
| 239 | + foreach (preg_split('/;\s*$/m', preg_replace('/^--.*$/m', '', $sql)) as $statement) { |
| 240 | + if (trim($statement) !== '') { |
| 241 | + $pdo->exec($statement); |
| 242 | + } |
| 243 | + } |
| 244 | + } |
| 245 | + |
| 246 | + /** Every value as hex, so a byte that changed cannot hide behind a collation. */ |
| 247 | + private function rows(string $db): array |
| 248 | + { |
| 249 | + $pdo = $this->pdo($db); |
| 250 | + return [ |
| 251 | + $pdo->query("SELECT CONCAT_WS('|', id, HEX(gurmukhi), HEX(translit), HEX(english), HEX(other), HEX(emoji), HEX(legacy)) FROM gurbani ORDER BY id")->fetchAll(PDO::FETCH_COLUMN), |
| 252 | + $pdo->query("SELECT CONCAT_WS('|', HEX(word), HEX(meaning)) FROM words ORDER BY HEX(word)")->fetchAll(PDO::FETCH_COLUMN), |
| 253 | + ]; |
| 254 | + } |
| 255 | + |
| 256 | + private function snapshot(string $db): array |
| 257 | + { |
| 258 | + $collations = $this->admin->query("SELECT CONCAT_WS(' ', TABLE_NAME, COLUMN_NAME, IFNULL(COLLATION_NAME, '')) |
| 259 | + FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = '$db' ORDER BY 1")->fetchAll(PDO::FETCH_COLUMN); |
| 260 | + return [$this->rows($db), $collations]; |
| 261 | + } |
| 262 | +} |
0 commit comments