Skip to content

Commit 4ce89e4

Browse files
authored
Ensure fresh DB connection for batch jobs
Added logic to ensure a fresh database connection for batch dispatch in multi-tenant environments.
1 parent 6000326 commit 4ce89e4

1 file changed

Lines changed: 19 additions & 0 deletions

File tree

src/Import/Jobs/BulkImportProcessor.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
use Illuminate\Queue\InteractsWithQueue;
1515
use Illuminate\Queue\SerializesModels;
1616
use Illuminate\Support\Facades\Bus;
17+
use Illuminate\Support\Facades\DB;
1718
use Illuminate\Support\Facades\Log;
1819
use Throwable;
1920

@@ -101,6 +102,24 @@ public function handle(): void
101102

102103
$import = $this->import;
103104

105+
// Ensure fresh database connection for batch dispatch
106+
// This is critical in multi-tenant environments where DB::purge() may have been called
107+
// during tenant switching, causing the Connection object in DatabaseBatchRepository
108+
// to have a null PDO. This fix is safe for non-multi-tenant apps as well.
109+
$batchConnection = config('queue.batching.database');
110+
111+
if ($batchConnection) {
112+
// Purge and reconnect to ensure clean connection state
113+
DB::purge($batchConnection);
114+
115+
// Forget both BatchRepository singletons so they get rebuilt with fresh connection
116+
app()->forgetInstance('Illuminate\Bus\BatchRepository');
117+
app()->forgetInstance('Illuminate\Bus\DatabaseBatchRepository');
118+
119+
// Force connection to be established
120+
DB::connection($batchConnection)->reconnect();
121+
}
122+
104123
Bus::batch($jobs)
105124
->then(function (Batch $batch) {
106125
Log::debug('[BulkImportProcessor] Batch finished');

0 commit comments

Comments
 (0)