Merge pull request #13709 from spencerrlongg/eol-migration

Speed up EOL Migration
This commit is contained in:
snipe 2023-10-05 14:26:47 +01:00 committed by GitHub
commit 05dd2b4008
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -4,6 +4,7 @@ use App\Models\Asset;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
@ -22,38 +23,33 @@ class DenormalizedEolAndAddColumnForExplicitDateToAssets extends Migration
// Update the eol_explicit column with the value from asset_eol_date if it exists and is different from the calculated value // Update the eol_explicit column with the value from asset_eol_date if it exists and is different from the calculated value
Asset::whereNotNull('asset_eol_date')->with('model')->chunkById(500, function ($assetsWithEolDates) { Asset::whereNotNull('asset_eol_date')->with('model')->chunkById(500, function ($assetsWithEolDates) {
foreach ($assetsWithEolDates as $asset) { foreach ($assetsWithEolDates as $asset) {
if ($asset->asset_eol_date && $asset->purchase_date) { if ($asset->asset_eol_date && $asset->purchase_date) {
try { try {
$months = CarbonImmutable::parse($asset->asset_eol_date)->diffInMonths($asset->purchase_date); $months = CarbonImmutable::parse($asset->asset_eol_date)->diffInMonths($asset->purchase_date);
} catch (\Exception $e) { } catch (\Exception $e) {
Log::info('asset_eol_date invalid for asset '.$asset->id); Log::info('asset_eol_date invalid for asset ' . $asset->id);
} }
if ($asset->model->eol) { if ($asset->model->eol) {
if ($months != $asset->model->eol) { if ($months != $asset->model->eol) {
$asset->update(['eol_explicit' => true]);
}
} else {
$asset->update(['eol_explicit' => true]); $asset->update(['eol_explicit' => true]);
} }
} else {
$asset->update(['eol_explicit' => true]);
} }
} }
} });
});
// Update the asset_eol_date column with the calculated value if it doesn't exist DB::table('assets')
Asset::whereNull('asset_eol_date')->with('model')->chunkById(500, function ($assets) { ->whereNull('asset_eol_date')
foreach ($assets as $asset) { ->whereNotNull('purchase_date')
if ($asset->model->eol && $asset->purchase_date) { ->whereNotNull('model_id')
try { ->join('models', 'assets.model_id', '=', 'models.id')
$asset_eol_date = CarbonImmutable::parse($asset->purchase_date)->addMonths($asset->model->eol)->format('Y-m-d'); ->update([
$asset->update(['asset_eol_date' => $asset_eol_date]); 'asset_eol_date' => DB::raw('DATE_ADD(purchase_date, INTERVAL models.eol MONTH)')
} catch (\Exception $e) { ]);
Log::info('purchase date invalid for asset '.$asset->id);
}
}
}
});
} }