資料滙出時 DB 連線 回收調整

初建資料留下User 資料 備用
20250528
This commit is contained in:
allen.yan 2025-05-28 09:15:52 +08:00
parent cd099bce76
commit 144aa499b6
5 changed files with 27 additions and 9 deletions

View File

@ -35,16 +35,16 @@ class ExportSqliteBranchJob implements ShouldQueue
if (!file_exists($sqlitePath)) {
file_put_contents($sqlitePath, '');
}
config(['database.connections.tempsqlite' => [
$connectionName = 'tempsqlite_' . md5($sqlitePath . microtime());
config(["database.connections.{$connectionName}" => [
'driver' => 'sqlite',
'database' => $sqlitePath,
'prefix' => '',
]]);
$exportService = new SqliteExportService();
$exporter = new SqliteExportService($connectionName);
$exportService->exportMultiple([
$exporter->exportMultiple([
'branches' => [
'modelClass' => Branch::class,
'query' => fn () => Branch::where('id', $this->branchId)->get(),
@ -98,7 +98,6 @@ class ExportSqliteBranchJob implements ShouldQueue
],
]
]);
SendSqliteFileJob::dispatch($sqlitePath, $this->branchId);
}
}

View File

@ -57,7 +57,6 @@ class ExportSqliteFavoriteJob implements ShouldQueue
],
],
]);
DB::purge($connectionName);
SendSqliteFileJob::dispatch($sqlitePath);
}
}

View File

@ -21,10 +21,19 @@ class ExportSqliteUserJob implements ShouldQueue
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $timeout = 600; // 可依資料量調整 timeout 秒數
public bool $isSend;
public function __construct(bool $isSend = true){
$this->isSend =$isSend ;
}
public function handle()
{
$sqlitePath = storage_path('app/database/tempUser.sqlite');
if($this->isSend){
$sqlitePath = storage_path('app/database/tempUser.sqlite');
}else{
$sqlitePath = 'database/tempUser.sqlite';
}
// 確保資料夾存在
if (!file_exists(dirname($sqlitePath))) {
@ -199,8 +208,8 @@ class ExportSqliteUserJob implements ShouldQueue
],
],
]);
DB::purge($connectionName);
SendSqliteFileJob::dispatch($sqlitePath);
if($this->isSend)
SendSqliteFileJob::dispatch($sqlitePath);
}
}

View File

@ -42,6 +42,7 @@ class SqliteExportService
$rows = $chunk->map($transformer)->toArray();
$this->insertData($tableName, $rows);
});
$this->purge();
}
/**
@ -83,6 +84,7 @@ class SqliteExportService
throw new \InvalidArgumentException("Each table config must define either 'modelClass' or 'query'.");
}
}
$this->purge();
}
protected function dropAndCreateTable(string $table, Closure $schema): void
@ -96,4 +98,10 @@ class SqliteExportService
if (empty($rows)) return;
DB::connection($this->connection)->table($table)->insert($rows);
}
protected function purge(): void
{
DB::purge($this->connection);
}
}

View File

@ -5,6 +5,7 @@ namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\User;
use App\Jobs\ExportSqliteUserJob;
class CreateAdminUserSeeder extends Seeder
{
@ -45,5 +46,7 @@ class CreateAdminUserSeeder extends Seeder
'password' => bcrypt('aa1234')
]);
$user->assignRole('User');
(new ExportSqliteUserJob(false))->handle();
}
}