Add indexes to tables

This commit is contained in:
DariusIII
2025-12-22 13:22:31 +01:00
parent b9a071e947
commit 74857a3c72
2 changed files with 78 additions and 0 deletions
@@ -0,0 +1,37 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* This index optimizes queries that filter by passwordstatus + categories_id and order by postdate DESC,
* which is the common pattern for TV/Movie search APIs.
*
* Column order rationale:
* - passwordstatus first: low cardinality but always filtered with <= comparison
* - categories_id second: filtered with IN() clause
* - postdate third (DESC): used for ORDER BY, avoids filesort
*/
public function up(): void
{
// Use raw SQL to specify DESC for postdate which Laravel Blueprint doesn't support
DB::statement('CREATE INDEX ix_releases_password_categories_postdate ON releases (passwordstatus, categories_id, postdate DESC)');
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('releases', function (Blueprint $table) {
$table->dropIndex('ix_releases_password_categories_postdate');
});
}
};
@@ -0,0 +1,41 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* This index specifically optimizes the TV/Movie API search queries that:
* 1. Filter by passwordstatus (always <= 1 or = 0)
* 2. Filter by categories_id IN (...) for TV categories
* 3. Order by postdate DESC
*
* The index includes videos_id and tv_episodes_id as they are used in JOIN conditions,
* allowing the optimizer to evaluate join necessity directly from the index.
*/
public function up(): void
{
// Check if the index already exists
$indexExists = DB::select("SHOW INDEX FROM releases WHERE Key_name = 'ix_releases_tv_search_covering'");
if (empty($indexExists)) {
// Covering index for TV search - includes FK columns to help optimizer
DB::statement('CREATE INDEX ix_releases_tv_search_covering ON releases (passwordstatus, categories_id, postdate DESC, videos_id, tv_episodes_id, groups_id)');
}
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('releases', function ($table) {
$table->dropIndex('ix_releases_tv_search_covering');
});
}
};