97 lines
2.7 KiB
PHP
97 lines
2.7 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\SourceDatabase;
|
|
use App\Models\TargetDatabase;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Exception;
|
|
|
|
class DatabaseConnectionService
|
|
{
|
|
/**
|
|
* Test connection to a source database
|
|
*/
|
|
public function testSourceConnection(SourceDatabase $database): array
|
|
{
|
|
return $this->testConnection($database->getConnectionConfig());
|
|
}
|
|
|
|
/**
|
|
* Test connection to a target database
|
|
*/
|
|
public function testTargetConnection(TargetDatabase $database): array
|
|
{
|
|
return $this->testConnection($database->getConnectionConfig());
|
|
}
|
|
|
|
/**
|
|
* Test connection with given config
|
|
*/
|
|
private function testConnection(array $config): array
|
|
{
|
|
$connectionName = 'temp_' . uniqid();
|
|
$driver = $config['driver'] ?? 'pgsql';
|
|
|
|
try {
|
|
config(["database.connections.{$connectionName}" => $config]);
|
|
|
|
$result = DB::connection($connectionName)->select('SELECT 1 as test');
|
|
|
|
// Get version based on driver
|
|
if ($driver === 'mssql') {
|
|
$version = DB::connection($connectionName)->select("SELECT @@VERSION as version")[0]->version;
|
|
} else {
|
|
$version = DB::connection($connectionName)->select('SELECT version()')[0]->version;
|
|
}
|
|
|
|
DB::purge($connectionName);
|
|
|
|
return [
|
|
'success' => true,
|
|
'message' => 'Connection successful',
|
|
'version' => $version,
|
|
];
|
|
} catch (Exception $e) {
|
|
DB::purge($connectionName);
|
|
|
|
return [
|
|
'success' => false,
|
|
'message' => $e->getMessage(),
|
|
];
|
|
} finally {
|
|
config(["database.connections.{$connectionName}" => null]);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get a temporary database connection
|
|
*/
|
|
public function getConnection(array $config): \Illuminate\Database\ConnectionInterface
|
|
{
|
|
$connectionName = 'temp_' . uniqid();
|
|
|
|
// Add driver-specific configuration
|
|
$driver = $config['driver'] ?? 'pgsql';
|
|
if ($driver === 'mssql') {
|
|
$config['driver'] = 'sqlsrv';
|
|
unset($config['search_path'], $config['sslmode']);
|
|
}
|
|
|
|
config(["database.connections.{$connectionName}" => $config]);
|
|
|
|
return DB::connection($connectionName);
|
|
}
|
|
|
|
/**
|
|
* Purge a temporary connection
|
|
*/
|
|
public function purgeConnection(string $connectionName): void
|
|
{
|
|
if (str_starts_with($connectionName, 'temp_')) {
|
|
DB::purge($connectionName);
|
|
config(["database.connections.{$connectionName}" => null]);
|
|
}
|
|
}
|
|
}
|