config = $config; $this->connect(); } /** * Establish database connection */ private function connect(): void { try { $dsn = $this->buildDsn(); if ($this->config['driver'] === 'sqlite') { $this->pdo = new PDO($dsn); } else { $this->pdo = new PDO( $dsn, $this->config['username'], $this->config['password'], $this->config['options'] ?? [] ); } } catch (PDOException $e) { throw new \Exception("Database connection failed: " . $e->getMessage()); } } /** * Build DSN string */ private function buildDsn(): string { $driver = $this->config['driver']; switch ($driver) { case 'mysql': $host = $this->config['host']; $port = $this->config['port'] ?? null; $database = $this->config['database']; $charset = $this->config['charset'] ?? 'utf8'; return "mysql:host={$host};port={$port};dbname={$database};charset={$charset}"; case 'pgsql': $host = $this->config['host']; $port = $this->config['port'] ?? null; $database = $this->config['database']; return "pgsql:host={$host};port={$port};dbname={$database}"; case 'sqlite': $database = $this->config['database']; return "sqlite:{$database}"; default: throw new \Exception("Unsupported database driver: {$driver}"); } } /** * Get PDO instance */ public function getPdo(): PDO { return $this->pdo; } /** * Execute query */ public function query(string $sql, array $params = []): \PDOStatement { $stmt = $this->pdo->prepare($sql); $stmt->execute($params); return $stmt; } /** * Execute query and return all results */ public function fetchAll(string $sql, array $params = []): array { $stmt = $this->query($sql, $params); return $stmt->fetchAll(); } /** * Execute query and return single result */ public function fetch(string $sql, array $params = []): ?array { $stmt = $this->query($sql, $params); $result = $stmt->fetch(); return $result ?: null; } /** * Execute query and return single value */ public function fetchColumn(string $sql, array $params = []) { $stmt = $this->query($sql, $params); return $stmt->fetchColumn(); } /** * Execute query and return affected rows */ public function execute(string $sql, array $params = []): int { $stmt = $this->query($sql, $params); return $stmt->rowCount(); } /** * Begin transaction */ public function beginTransaction(): bool { return $this->pdo->beginTransaction(); } /** * Commit transaction */ public function commit(): bool { return $this->pdo->commit(); } /** * Rollback transaction */ public function rollback(): bool { return $this->pdo->rollBack(); } /** * Get last insert ID */ public function lastInsertId(): string { return $this->pdo->lastInsertId(); } /** * Check if connected */ public function isConnected(): bool { try { $this->pdo->query('SELECT 1'); return true; } catch (PDOException $e) { return false; } } }