| 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; |
| 41 | use Std\Lib\Db\Convert; |
| 42 | use Std\Lib\Db\DbException; |
| 43 | use Std\Lib\Db\Sqlite\Blob; |
| 44 | |
| 45 | /** |
| 46 | * データベース(MySQL・PostgreSQL・SQLite)に書く |
| 47 | * |
| 48 | * テーブルを作って、行を入れてから、インデックスを作る。PostgreSQLの自動の番号(SERIAL)は最後に続きの番号にする。 |
| 49 | */ |
| 50 | final class DbTarget implements Target { |
| 51 | public string $dialect; |
| 52 | private array $warnings = []; |
| 53 | private array $stmts = []; |
| 54 | private bool $inTx = false; |
| 55 | private int $pending = 0; |
| 56 | |
| 57 | public function __construct(private Db $db) { |
| 58 | $this->dialect = DbSource::dialectOf($db); |
| 59 | } |
| 60 | |
| 61 | public function warnings(): array { |
| 62 | return array_values(array_unique($this->warnings)); |
| 63 | } |
| 64 | |
| 65 | private function q(string $n): string { |
| 66 | return Convert::quote($this->dialect, $n); |
| 67 | } |
| 68 | |
| 69 | public function begin(bool $drop): void { |
| 70 | $this->drop = $drop; |
| 71 | $this->existing = array_map('strtolower', DbSource::tableNames($this->db)); |
| 72 | if ($this->dialect === 'mysql') $this->db->query('SET FOREIGN_KEY_CHECKS = 0'); |
| 73 | } |
| 74 | |
| 75 | private bool $drop = false; |
| 76 | private array $existing = []; |
| 77 | |
| 78 | public function createTable(array $t): void { |
| 79 | if (in_array(strtolower($t['name']), $this->existing, true)) { |
| 80 | if (!$this->drop) throw new DbException("テーブル{$t['name']}は既に有ります(消す場合は「drop」)", 0, 'HY000'); |
| 81 | $this->db->query('DROP TABLE '.$this->q($t['name']).($this->dialect === 'pgsql' ? ' CASCADE' : '')); |
| 82 | } |
| 83 | $this->db->query(Convert::createTable($this->dialect, $t, $this->warnings)); |
| 84 | } |
| 85 | |
| 86 | public function insertRows(array $t, array $rows): void { |
| 87 | $nc = count($t['columns']); |
| 88 | $per = max(1, min(500, intdiv(30000, max(1, $nc)))); |
| 89 | $drv = $this->db->driver(); |
| 90 | $drv->connect(); |
| 91 | if (!$this->inTx) { |
| 92 | $drv->beginTransaction(); |
| 93 | $this->inTx = true; |
| 94 | } |
| 95 | foreach (array_chunk($rows, $per) as $chunk) { |
| 96 | $n = count($chunk); |
| 97 | $key = $t['name']."\0".$n; |
| 98 | if (!isset($this->stmts[$key])) { |
| 99 | $ph = '('.implode(', ', array_fill(0, $nc, '?')).')'; |
| 100 | $sql = 'INSERT INTO '.$this->q($t['name']).' ('.implode(', ', array_map(fn($c) => $this->q($c['name']), $t['columns'])).') VALUES ' |
| 101 | .implode(', ', array_fill(0, $n, $ph)); |
| 102 | if (count($this->stmts) > 20) { |
| 103 | foreach ($this->stmts as $id) $drv->demolish($id); |
| 104 | $this->stmts = []; |
| 105 | } |
| 106 | $this->stmts[$key] = $drv->prepare($sql); |
| 107 | } |
| 108 | $params = []; |
| 109 | foreach ($chunk as $r) { |
| 110 | foreach ($t['columns'] as $i => $c) $params[] = $this->param($r[$i], $c, $t); |
| 111 | } |
| 112 | $drv->execute($this->stmts[$key], $params); |
| 113 | $this->pending += $n; |
| 114 | if ($this->pending >= 20000) { |
| 115 | $drv->commit(); |
| 116 | $drv->beginTransaction(); |
| 117 | $this->pending = 0; |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | private function param(mixed $v, array $c, array $t): mixed { |
| 123 | if ($v === null) return null; |
| 124 | if ($v instanceof Blob) return $this->dialect === 'sqlite' ? $v : $v->data; |
| 125 | if (is_bool($v)) return $this->dialect === 'pgsql' ? $v : (int)$v; |
| 126 | if (is_float($v) && (is_nan($v) || is_infinite($v)) && $this->dialect !== 'pgsql') { |
| 127 | if ($this->dialect === 'mysql' || is_nan($v)) { |
| 128 | $this->warnings[] = "NaN・無限はNULLにしました:{$t['name']}.{$c['name']}"; |
| 129 | return null; |
| 130 | } |
| 131 | } |
| 132 | if (is_string($v) && $this->dialect === 'pgsql' && str_contains($v, "\0")) { |
| 133 | $this->warnings[] = "PostgreSQLの文字列に0のバイトは入れられないので、消しました:{$t['name']}.{$c['name']}"; |
| 134 | return str_replace("\0", '', $v); |
| 135 | } |
| 136 | return $v; |
| 137 | } |
| 138 | |
| 139 | public function finishTable(array $t): void { |
| 140 | $drv = $this->db->driver(); |
| 141 | if ($this->inTx) { |
| 142 | $drv->commit(); |
| 143 | $this->inTx = false; |
| 144 | $this->pending = 0; |
| 145 | } |
| 146 | foreach ($t['indexes'] as $idx) $this->db->query(Convert::createIndex($this->dialect, $t, $idx)); |
| 147 | if ($this->dialect === 'pgsql') { |
| 148 | foreach ($t['columns'] as $c) { |
| 149 | if (!$c['autoinc'] || count($t['pk']) !== 1 || strcasecmp($t['pk'][0], $c['name']) !== 0) continue; |
| 150 | $this->db->query("SELECT setval(pg_get_serial_sequence(?, ?), COALESCE(MAX({$this->q($c['name'])}), 1), MAX({$this->q($c['name'])}) IS NOT NULL) FROM {$this->q($t['name'])}", |
| 151 | [$this->q($t['name']), $c['name']]); |
| 152 | } |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | public function abort(): void { |
| 157 | $drv = $this->db->driver(); |
| 158 | try { |
| 159 | if ($this->inTx && $drv->inTransaction()) $drv->rollback(); |
| 160 | } catch (\Throwable $e) { |
| 161 | // 接続が切れた等 |
| 162 | } |
| 163 | $this->inTx = false; |
| 164 | $this->stmts = []; |
| 165 | } |
| 166 | |
| 167 | public function end(): void { |
| 168 | $drv = $this->db->driver(); |
| 169 | foreach ($this->stmts as $id) $drv->demolish($id); |
| 170 | $this->stmts = []; |
| 171 | if ($this->inTx) { |
| 172 | $drv->commit(); |
| 173 | $this->inTx = false; |
| 174 | } |
| 175 | if ($this->dialect === 'mysql') $this->db->query('SET FOREIGN_KEY_CHECKS = 1'); |
| 176 | } |
| 177 | } |