| 1 | <?php |
| 2 | /************************************************************* |
| 3 | # 076 License |
| 4 | |
| 5 | Copyright (c) テクニカル諏訪子 |
| 6 | |
| 7 | Permission is hereby granted to any person obtaining a copy of the software |
| 8 | Little Beast (the "Software") to use, modify, merge, copy, publish, distribute, |
| 9 | sublicense, and/or sell copies of the Software, subject to the following conditions: |
| 10 | |
| 11 | 1. **Origin Attribution**: |
| 12 | - You must not misrepresent the origin of the Software; you must not claim |
| 13 | you created the original Software. |
| 14 | - If the Software is used in a product, you must either: |
| 15 | a. Provide clear attribution in the product's documentation, user interface, |
| 16 | or other visible areas, **OR** |
| 17 | b. Pay the original developers a fee they specify in writing. |
| 18 | 2. **Usage Restriction**: |
| 19 | - The Software, or any derivative works, dependencies, or libraries |
| 20 | incorporating it, must not be used for censorship or to suppress freedom of |
| 21 | speech, expression, or creativity. Prohibited uses include, but are not |
| 22 | limited to: |
| 23 | - Censorship of so-called "hate speech", visuals, non-mainstream opinions, |
| 24 | ideas, or objective reality. |
| 25 | - Tools or systems designed to restrict access to information or |
| 26 | artistic works. |
| 27 | 3. **Notice Preservation**: |
| 28 | - This license and the above copyright notice must remain intact in all copies |
| 29 | of the source code. |
| 30 | |
| 31 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, |
| 32 | INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A |
| 33 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT |
| 34 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF |
| 35 | CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE |
| 36 | OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 37 | */ |
| 38 | namespace Std\Lib\Db\Convert; |
| 39 | |
| 40 | use Std\Lib\Db\Convert; |
| 41 | use Std\Lib\Db\DbException; |
| 42 | |
| 43 | /** |
| 44 | * SQLのダンプのファイルに書く(MySQL、PostgreSQL、SQLiteの方言) |
| 45 | * |
| 46 | * mysql・psql・sqlite3のコマンド、又はDumpSourceで読める。 |
| 47 | */ |
| 48 | final class DumpTarget implements Target { |
| 49 | /** @var resource|null */ |
| 50 | private $fh = null; |
| 51 | private array $warnings = []; |
| 52 | private bool $drop = false; |
| 53 | private int $perInsert = 200; |
| 54 | |
| 55 | /** |
| 56 | * @param string $path 書くファイル(.gzなら圧縮) |
| 57 | * @param string $dialect mysql、pgsql、sqlite |
| 58 | */ |
| 59 | public function __construct(private string $path, public readonly string $dialect) { |
| 60 | if (!in_array($dialect, ['mysql', 'pgsql', 'sqlite'], true)) throw new \InvalidArgumentException("未対応の方言:{$dialect}"); |
| 61 | } |
| 62 | |
| 63 | public function warnings(): array { |
| 64 | return array_values(array_unique($this->warnings)); |
| 65 | } |
| 66 | |
| 67 | private function out(string $s): void { |
| 68 | $n = str_ends_with(strtolower($this->path), '.gz') ? gzwrite($this->fh, $s) : fwrite($this->fh, $s); |
| 69 | if ($n === false) throw new DbException("ダンプのファイルに書けません:{$this->path}", 0, 'HY000'); |
| 70 | } |
| 71 | |
| 72 | public function begin(bool $drop): void { |
| 73 | $this->drop = $drop; |
| 74 | $gz = str_ends_with(strtolower($this->path), '.gz'); |
| 75 | if ($gz && !function_exists('gzopen')) throw new DbException("圧縮したダンプにはzlibが必要です:{$this->path}", 0, 'HY000'); |
| 76 | $fh = $gz ? @gzopen($this->path, 'wb6') : @fopen($this->path, 'wb'); |
| 77 | if ($fh === false) throw new DbException("ダンプのファイルを作れません:{$this->path}", 0, 'HY000'); |
| 78 | $this->fh = $fh; |
| 79 | $this->out("-- LittleBeastのデータベースの変換({$this->dialect})\n-- ".gmdate('Y-m-d H:i:s')." UTC\n"); |
| 80 | if ($this->dialect === 'mysql') { |
| 81 | $this->out("SET NAMES utf8mb4;\nSET FOREIGN_KEY_CHECKS = 0;\nSET SQL_MODE = 'NO_AUTO_VALUE_ON_ZERO';\nSET time_zone = '+00:00';\n"); |
| 82 | } else if ($this->dialect === 'pgsql') { |
| 83 | $this->out("SET client_encoding = 'UTF8';\nSET standard_conforming_strings = on;\nSET TimeZone = 'UTC';\n"); |
| 84 | } |
| 85 | $this->out("BEGIN;\n\n"); |
| 86 | } |
| 87 | |
| 88 | public function createTable(array $t): void { |
| 89 | $q = fn(string $n) => Convert::quote($this->dialect, $n); |
| 90 | if ($this->drop) $this->out('DROP TABLE IF EXISTS '.$q($t['name']).($this->dialect === 'pgsql' ? ' CASCADE' : '').";\n"); |
| 91 | $this->out(Convert::createTable($this->dialect, $t, $this->warnings).";\n\n"); |
| 92 | } |
| 93 | |
| 94 | public function insertRows(array $t, array $rows): void { |
| 95 | $q = fn(string $n) => Convert::quote($this->dialect, $n); |
| 96 | $head = 'INSERT INTO '.$q($t['name']).' ('.implode(', ', array_map(fn($c) => $q($c['name']), $t['columns'])).') VALUES'; |
| 97 | foreach (array_chunk($rows, $this->perInsert) as $chunk) { |
| 98 | $vals = []; |
| 99 | foreach ($chunk as $r) { |
| 100 | $parts = []; |
| 101 | foreach ($t['columns'] as $i => $c) $parts[] = $this->value($r[$i], $c, $t); |
| 102 | $vals[] = '('.implode(', ', $parts).')'; |
| 103 | } |
| 104 | $this->out($head."\n".implode(",\n", $vals).";\n"); |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | private function value(mixed $v, array $c, array $t): string { |
| 109 | if ($v === null) return 'NULL'; |
| 110 | if (is_string($v) && $this->dialect === 'pgsql' && str_contains($v, "\0")) { |
| 111 | $this->warnings[] = "PostgreSQLの文字列に0のバイトは入れられないので、消しました:{$t['name']}.{$c['name']}"; |
| 112 | $v = str_replace("\0", '', $v); |
| 113 | } |
| 114 | if (is_float($v) && $this->dialect !== 'pgsql' && (is_nan($v) || is_infinite($v))) { |
| 115 | $this->warnings[] = "NaN・無限はNULLにしました:{$t['name']}.{$c['name']}"; |
| 116 | } |
| 117 | return Convert::literal($this->dialect, $v, $c); |
| 118 | } |
| 119 | |
| 120 | public function finishTable(array $t): void { |
| 121 | $q = fn(string $n) => Convert::quote($this->dialect, $n); |
| 122 | foreach ($t['indexes'] as $idx) $this->out(Convert::createIndex($this->dialect, $t, $idx).";\n"); |
| 123 | // 自動の番号の続き |
| 124 | foreach ($t['columns'] as $c) { |
| 125 | if (!$c['autoinc'] || count($t['pk']) !== 1 || strcasecmp($t['pk'][0], $c['name']) !== 0) continue; |
| 126 | if ($this->dialect === 'pgsql') { |
| 127 | $this->out("SELECT setval(pg_get_serial_sequence('".str_replace("'", "''", $q($t['name']))."', '".str_replace("'", "''", $c['name'])."'), " |
| 128 | ."COALESCE(MAX({$q($c['name'])}), 1), MAX({$q($c['name'])}) IS NOT NULL) FROM {$q($t['name'])};\n"); |
| 129 | } |
| 130 | } |
| 131 | $this->out("\n"); |
| 132 | } |
| 133 | |
| 134 | public function abort(): void { |
| 135 | if ($this->fh) { |
| 136 | str_ends_with(strtolower($this->path), '.gz') ? @gzclose($this->fh) : @fclose($this->fh); |
| 137 | $this->fh = null; |
| 138 | @unlink($this->path); |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | public function end(): void { |
| 143 | $this->out("COMMIT;\n"); |
| 144 | if ($this->dialect === 'mysql') $this->out("SET FOREIGN_KEY_CHECKS = 1;\n"); |
| 145 | str_ends_with(strtolower($this->path), '.gz') ? gzclose($this->fh) : fclose($this->fh); |
| 146 | $this->fh = null; |
| 147 | } |
| 148 | } |