| 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; |
| 39 | |
| 40 | use Std\Lib\Db\DbInterface; |
| 41 | use Std\Lib\Db\Mysql; |
| 42 | use Std\Lib\Db\Pgsql; |
| 43 | use Std\Lib\Db\Sqlite; |
| 44 | |
| 45 | /** |
| 46 | * データベース |
| 47 | * |
| 48 | * DBINFOの「driver」でドライバ(Std\Lib\Db\の中)を選ぶ。接続は最初のクエリの時に自動で行う。 |
| 49 | * |
| 50 | * 使い方: |
| 51 | * $db = new Db(); |
| 52 | * $users = $db->query('SELECT * FROM users WHERE role > ?', [0])['rows']; |
| 53 | * $id = $db->query('INSERT INTO users (name) VALUES (?)', ['諏訪子'])['insertId']; // MySQL・SQLite(PostgreSQLはRETURNINGを使う) |
| 54 | * $db->transaction(function(Db $db): void { |
| 55 | * $db->query('UPDATE users SET points = points - ? WHERE id = ?', [100, 1]); |
| 56 | * $db->query('UPDATE users SET points = points + ? WHERE id = ?', [100, 2]); |
| 57 | * }); |
| 58 | */ |
| 59 | class Db { |
| 60 | private const SUPPORTED = [ |
| 61 | 'mysql' => Mysql::class, |
| 62 | 'mariadb' => Mysql::class, |
| 63 | 'pgsql' => Pgsql::class, |
| 64 | 'postgres' => Pgsql::class, |
| 65 | 'postgresql' => Pgsql::class, |
| 66 | 'sqlite' => Sqlite::class, |
| 67 | 'sqlite3' => Sqlite::class, |
| 68 | ]; |
| 69 | |
| 70 | public string $driverName; |
| 71 | private DbInterface $driver; |
| 72 | |
| 73 | /** |
| 74 | * コンストラクタ |
| 75 | * |
| 76 | * @param array|null $info 設定(省略するとDBINFO)。driver(mysql等)、その他はドライバ毎 |
| 77 | * @throws \Exception $infoを省略し、DB_ENABLEDが無効な場合 |
| 78 | * @throws \RuntimeException 未対応のドライバの場合 |
| 79 | */ |
| 80 | public function __construct(?array $info = null) { |
| 81 | if ($info === null && !(defined('DB_ENABLED') && DB_ENABLED)) { |
| 82 | throw new \Exception('データベースは無効です。'); |
| 83 | } |
| 84 | |
| 85 | $info ??= DBINFO; |
| 86 | $this->driverName = strtolower((string)($info['driver'] ?? 'mysql')); |
| 87 | $class = self::SUPPORTED[$this->driverName] ?? null; |
| 88 | if (!$class) throw new \RuntimeException("未対応のデータベース: {$this->driverName}"); |
| 89 | $this->driver = new $class($info); |
| 90 | } |
| 91 | |
| 92 | /** |
| 93 | * ドライバに対応しているかどうか |
| 94 | * |
| 95 | * @param string $driver ドライバ名 |
| 96 | * @return bool |
| 97 | */ |
| 98 | public static function isSupported(string $driver): bool { |
| 99 | return isset(self::SUPPORTED[strtolower($driver)]); |
| 100 | } |
| 101 | |
| 102 | /** |
| 103 | * ドライバ(ドライバ毎の機能用、例:MysqlのsetDebug()) |
| 104 | * |
| 105 | * @return DbInterface |
| 106 | */ |
| 107 | public function driver(): DbInterface { |
| 108 | return $this->driver; |
| 109 | } |
| 110 | |
| 111 | public function connect(): bool { |
| 112 | return $this->driver->connect(); |
| 113 | } |
| 114 | |
| 115 | public function close(): void { |
| 116 | $this->driver->close(); |
| 117 | } |
| 118 | |
| 119 | public function isConnected(): bool { |
| 120 | return $this->driver->isConnected(); |
| 121 | } |
| 122 | |
| 123 | public function ping(): bool { |
| 124 | return $this->driver->ping(); |
| 125 | } |
| 126 | |
| 127 | /** |
| 128 | * SQLを実行する |
| 129 | * |
| 130 | * パラメータがある場合はプリペアドステートメント(プレースホルダは「?」)で実行するので、 |
| 131 | * 値をエスケープする必要はない。 |
| 132 | * |
| 133 | * @param string $sql SQL |
| 134 | * @param array $params パラメータ(順番通り) |
| 135 | * @return array 結果(fields、rows、affectedRows、insertId、warningCount等、DbInterfaceを参照) |
| 136 | * @throws Db\DbException 失敗した場合 |
| 137 | */ |
| 138 | public function query(string $sql, array $params = []): array { |
| 139 | $this->driver->connect(); |
| 140 | if (empty($params)) return $this->driver->query($sql); |
| 141 | |
| 142 | $id = $this->driver->prepare($sql); |
| 143 | try { |
| 144 | return $this->driver->execute($id, $params); |
| 145 | } finally { |
| 146 | $this->driver->demolish($id); |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | /** |
| 151 | * 何回も実行するSQLを準備する(終わったらdemolish()) |
| 152 | * |
| 153 | * @param string $sql SQL |
| 154 | * @return int ステートメントID |
| 155 | * @throws Db\DbException |
| 156 | */ |
| 157 | public function prepare(string $sql): int { |
| 158 | $this->driver->connect(); |
| 159 | return $this->driver->prepare($sql); |
| 160 | } |
| 161 | |
| 162 | public function execute(int $statementId, array $params = []): array { |
| 163 | return $this->driver->execute($statementId, $params); |
| 164 | } |
| 165 | |
| 166 | public function demolish(int $statementId): bool { |
| 167 | return $this->driver->demolish($statementId); |
| 168 | } |
| 169 | |
| 170 | /** |
| 171 | * トランザクションの中で実行する |
| 172 | * |
| 173 | * 例外が出たらロールバックして、その例外を投げ直す。それ以外はコミットする。 |
| 174 | * |
| 175 | * @param callable $fn function(Db $db): mixed |
| 176 | * @return mixed $fnの戻り値 |
| 177 | * @throws \Throwable $fnの例外 |
| 178 | */ |
| 179 | public function transaction(callable $fn): mixed { |
| 180 | $this->beginTransaction(); |
| 181 | |
| 182 | try { |
| 183 | $res = $fn($this); |
| 184 | } catch (\Throwable $e) { |
| 185 | if ($this->driver->isConnected()) { |
| 186 | try { |
| 187 | $this->driver->rollback(); |
| 188 | } catch (\Throwable $ignore) { |
| 189 | // 接続が切れた場合等:元の例外を優先する |
| 190 | } |
| 191 | } |
| 192 | throw $e; |
| 193 | } |
| 194 | |
| 195 | $this->driver->commit(); |
| 196 | return $res; |
| 197 | } |
| 198 | |
| 199 | public function beginTransaction(): bool { |
| 200 | $this->driver->connect(); |
| 201 | return $this->driver->beginTransaction(); |
| 202 | } |
| 203 | |
| 204 | public function commit(): bool { |
| 205 | return $this->driver->commit(); |
| 206 | } |
| 207 | |
| 208 | public function rollback(): bool { |
| 209 | return $this->driver->rollback(); |
| 210 | } |
| 211 | |
| 212 | public function inTransaction(): bool { |
| 213 | return $this->driver->inTransaction(); |
| 214 | } |
| 215 | |
| 216 | public function quoteIdentifier(string $name): string { |
| 217 | return $this->driver->quoteIdentifier($name); |
| 218 | } |
| 219 | } |