driver = Settings::get('IAM_DB_DRIVER', 'sqlite'); if ($this->driver === 'sqlite') { $path = Settings::sqlitePath(); if (!$initialize && !is_file($path)) { throw new \RuntimeException('请先初始化独立数据库'); } if ($initialize && !is_dir(dirname($path)) && !mkdir(dirname($path), 0700, true) && !is_dir(dirname($path))) { throw new \RuntimeException('无法创建数据库目录'); } $this->pdo = new PDO('sqlite:' . $path); $this->pdo->exec('PRAGMA foreign_keys = ON'); $this->pdo->exec('PRAGMA busy_timeout = 5000'); } elseif ($this->driver === 'mysql') { $database = Settings::get('IAM_DB_DATABASE'); $port = Settings::get('IAM_DB_PORT', '3306'); $host = Settings::get('IAM_DB_HOST', '127.0.0.1'); if (!preg_match('/^[A-Za-z0-9_]+$/D', $database) || !ctype_digit($port) || preg_match('/[;\x00-\x20]/', $host)) { throw new \RuntimeException('MySQL 配置无效'); } $this->pdo = new PDO("mysql:host={$host};port={$port};dbname={$database};charset=utf8mb4", Settings::get('IAM_DB_USERNAME'), Settings::get('IAM_DB_PASSWORD')); } else { throw new \RuntimeException('仅支持 sqlite/mysql'); } $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); } public function all(string $sql, array $params = []): array { $statement = $this->pdo->prepare($sql); $statement->execute($params); return $statement->fetchAll(); } public function one(string $sql, array $params = []): ?array { return $this->all($sql, $params)[0] ?? null; } public function execute(string $sql, array $params = []): int { $statement = $this->pdo->prepare($sql); $statement->execute($params); return $statement->rowCount(); } public function transaction(callable $work): mixed { // Serialize writes on MySQL too: concurrent reparenting must not create a tree cycle. $lock = $this->driver === 'mysql' ? 'iam-write-' . sha1(Settings::get('IAM_DB_DATABASE')) : ''; if ($lock !== '' && (int) ($this->one('SELECT GET_LOCK(?,10) AS acquired', [$lock])['acquired'] ?? 0) !== 1) { throw new \RuntimeException('无法取得数据库写入锁'); } try { $this->pdo->beginTransaction(); $result = $work(); $this->pdo->commit(); return $result; } catch (\Throwable $error) { if ($this->pdo->inTransaction()) { $this->pdo->rollBack(); } throw $error; } finally { if ($lock !== '') { $this->one('SELECT RELEASE_LOCK(?)', [$lock]); } } } }