From b604da5d13f7eb4a20749f20e6e31c7e5670b7c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=9Cmit=20Tun=C3=A7?= Date: Fri, 24 Apr 2026 07:10:49 +0300 Subject: [PATCH] feat: implement MySqlDriver to handle dynamic database connections and schema discovery --- backend/app/Services/Database/MySqlDriver.php | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 backend/app/Services/Database/MySqlDriver.php diff --git a/backend/app/Services/Database/MySqlDriver.php b/backend/app/Services/Database/MySqlDriver.php new file mode 100644 index 0000000..18d2a9e --- /dev/null +++ b/backend/app/Services/Database/MySqlDriver.php @@ -0,0 +1,85 @@ +connectionName}", [ + 'driver' => 'mysql', + 'host' => $config['host'] ?? '127.0.0.1', + 'port' => $config['port'] ?? '3306', + 'database' => $config['database'] ?? null, + 'username' => $config['username'] ?? 'root', + 'password' => $config['password'] ?? '', + 'charset' => 'utf8mb4', + 'collation' => 'utf8mb4_unicode_ci', + 'prefix' => '', + 'strict' => true, + 'engine' => null, + ]); + + try { + DB::purge($this->connectionName); + DB::connection($this->connectionName)->getPdo(); + return true; + } catch (\Exception $e) { + return false; + } + } + + public function query(string $sql, array $bindings = []): array + { + return DB::connection($this->connectionName)->select($sql, $bindings); + } + + public function getConnection() + { + return DB::connection($this->connectionName); + } + + public function getDatabases(): array + { + $results = $this->query('SHOW DATABASES'); + return array_map(fn($db) => $db->Database, $results); + } + + public function getTables(): array + { + $results = $this->query('SHOW TABLES'); + $key = "Tables_in_" . DB::connection($this->connectionName)->getDatabaseName(); + return array_map(fn($table) => $table->$key, $results); + } + + public function getTableSchema(string $table): array + { + return $this->query("DESCRIBE `{$table}`"); + } + + public function getForeignKeys(string $table): array + { + $sql = " + SELECT + COLUMN_NAME, + REFERENCED_TABLE_NAME, + REFERENCED_COLUMN_NAME + FROM + INFORMATION_SCHEMA.KEY_COLUMN_USAGE + WHERE + TABLE_NAME = ? AND + REFERENCED_TABLE_NAME IS NOT NULL AND + TABLE_SCHEMA = ? + "; + + $dbName = DB::connection($this->connectionName)->getDatabaseName(); + return $this->query($sql, [$table, $dbName]); + } +}