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 DatabaseTableSizeCheck #37

Merged
merged 4 commits into from
Oct 5, 2023
Merged
Changes from 2 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 src/Checks/DatabaseTableSizeCheck.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php

namespace Vormkracht10\LaravelOK\Checks;

use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\ConnectionResolverInterface;
use Illuminate\Database\MySqlConnection;
use Illuminate\Database\PostgresConnection;
use Vormkracht10\LaravelOK\Checks\Base\Check;
use Vormkracht10\LaravelOK\Checks\Base\Result;

class DatabaseTableSizeCheck extends Check
{
protected string $connectionName;

protected array $tableSizeThresholds = [];

public function onConnection(string $name): static
{
$this->connectionName = $name;

return $this;
}

public function setTableSizeThresholds(array $config): static
{
$this->tableSizeThresholds = $config;

return $this;
}

public function run(): Result
{
$result = Result::new();

$connectionName = $this->connectionName ?? config('database.default');

$connection = app(ConnectionResolverInterface::class)->connection($connectionName);

$config = array_map(
fn ($MB) => $MB * 1024 * 1024,
$this->tableSizeThresholds,
);

foreach ($config as $table => $max) {
$size = $this->getTableSize($connection, $table);

if ($size > $max) {
$mb = fn ($bytes) => round($bytes / 1024 / 1024, 2);

return $result->failed("Table [{$table}] size is {$mb($size)} megabytes, max is configured at {$mb($max)} megabytes");
}
}

return $result->ok();
}

protected function getTableSize(ConnectionInterface $connection, string $table): int
{
return match (true) {
$connection instanceof MySqlConnection => $connection->selectOne('SELECT (data_length + index_length) AS size FROM information_schema.TABLES WHERE table_schema = ? AND table_name = ?', [
$connection->getDatabaseName(),
$table,
])->size,
$connection instanceof PostgresConnection => $connection->selectOne('SELECT pg_total_relation_size(?) AS size;', [
$table,
])->size,
default => throw new \Exception('This database type is not supported'),
};
}
}