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

add migration to enforce optimization of tables #1199

Merged
merged 2 commits into from
Jan 16, 2022
Merged
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
71 changes: 71 additions & 0 deletions database/migrations/2022_01_16_181337_optimize_tables.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\ConsoleSectionOutput;

class OptimizeTables extends Migration
{
private ConsoleOutput $output;
private ConsoleSectionOutput $msgSection;

public function __construct()
{
$this->output = new ConsoleOutput();
$this->msgSection = $this->output->section();
}

/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$connection = Schema::connection(null)->getConnection();
$tables = $connection->getDoctrineSchemaManager()->listTableNames();

$driverName = $connection->getDriverName();

switch ($driverName) {
case 'mysql':
$this->msgSection->writeln('<info>Info:</info> MySql/MariaDB detected.');
$sql = 'ANALYZE TABLE ';
break;
case 'posgresql':
$this->msgSection->writeln('<info>Info:</info> PostgreSQL detected.');
$sql = 'ANALYZE ';
break;
case 'sqlite':
$this->msgSection->writeln('<info>Info:</info> SQLite detected.');
$sql = 'ANALYZE ';
break;
default:
$this->msgSection->writeln('<comment>Warning:</comment> Unknown DBMS; doing nothing.');

return;
}

foreach ($tables as $table) {
try {
DB::statement($sql . $table);
$this->msgSection->writeln('<info>Info:</info> ' . $table . ' optimized.');
} catch (\Throwable $th) {
$this->msgSection->writeln('<error>Error:</error> could not optimize ' . $table . '.');
$this->msgSection->writeln('<error>Error:</error> ' . $th->getMessage());
}
}
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
// Nothing do to here.
}
}