Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TM-1400] Do bulk inserts for a faster script execution. #614

Merged
merged 3 commits into from
Dec 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/Console/Commands/ImportTreeSpeciesAssociations.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public function handle()

TreeSpecies::isUuid($treeSpeciesUuid)->update([
'taxon_id' => $taxonId,
'name' => $research->name,
'name' => $research->scientific_name,
]);
} catch (AbortException $e) {
$abortExceptions[] = $e;
Expand Down
14 changes: 13 additions & 1 deletion app/Console/Commands/OneOff/PopulateTreeSpeciesResearch.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use App\Console\Commands\Traits\ExceptionLevel;
use App\Models\V2\TreeSpecies\TreeSpeciesResearch;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Symfony\Component\Process\Process;

class PopulateTreeSpeciesResearch extends Command
Expand Down Expand Up @@ -59,10 +60,15 @@ public function handle()

$this->withProgressBar($lines, function ($progressBar) use ($fileHandle) {
$abortExceptions = [];
$bulkInsert = [];
while ($csvRow = fgetcsv($fileHandle)) {
$data = [];
$now = Carbon::now();
foreach ($this->columns as $column => $index) {
$data[$column] = $csvRow[$index];
// These don't get set automatically with bulk insert
$data['created_at'] = $now;
$data['updated_at'] = $now;
}

try {
Expand All @@ -73,10 +79,16 @@ public function handle()
'existing_id' => $existing?->taxon_id,
'new_id' => $data['taxon_id'],
'scientific_name' => $data['scientific_name'],
'infraspecific_epithet' => $data['infraspecific_epithet'],
], JSON_PRETTY_PRINT),
ExceptionLevel::Warning
);
TreeSpeciesResearch::create($data);

$bulkInsert[] = $data;
if (count($bulkInsert) >= 1000) {
TreeSpeciesResearch::insert($bulkInsert);
$bulkInsert = [];
}
} catch (AbortException $e) {
$abortExceptions[] = $e;
}
Expand Down
Loading