perf(db): index transactions for the daily synced-email query

SendDailyBankTransactionsSyncedEmailJob filters transactions by
(user_id, source, created_at > ?). The only user_id-leading index is
idx_transactions_budget_lookup (user_id, transaction_date, category_id),
so MySQL narrows to the user's rows then scans them all to filter on
source + created_at — the slow query reported as PHP-LARAVEL-3X. Add a
(user_id, source, created_at) composite index matching the two
equalities and the range.

Fixes PHP-LARAVEL-3X
This commit is contained in:
Víctor Falcón 2026-07-02 15:34:55 +02:00
parent 0f8eca50d0
commit dae0f64aa1
2 changed files with 44 additions and 0 deletions

View File

@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Support the daily "transactions synced" email query, which filters
* transactions by (user_id = ?, source = ?, created_at > ?). The existing
* indexes only lead with user_id via transaction_date, so that query scans
* every one of the user's rows to filter on source + created_at
* (PHP-LARAVEL-3X). This composite index matches the two equalities and the
* range directly.
*/
public function up(): void
{
Schema::table('transactions', function (Blueprint $table) {
$table->index(['user_id', 'source', 'created_at'], 'idx_transactions_user_source_created');
});
}
public function down(): void
{
Schema::table('transactions', function (Blueprint $table) {
$table->dropIndex('idx_transactions_user_source_created');
});
}
};

View File

@ -0,0 +1,14 @@
<?php
use Illuminate\Support\Facades\Schema;
it('has a composite index supporting the daily synced-email transaction query', function () {
$indexes = collect(Schema::getIndexes('transactions'));
$match = $indexes->first(fn (array $index): bool => $index['columns'] === ['user_id', 'source', 'created_at']
);
expect($match)->not->toBeNull(
'Expected a (user_id, source, created_at) index on transactions for the daily email query.'
);
});