215 lines
8.7 KiB
Swift
215 lines
8.7 KiB
Swift
import Foundation
|
|
|
|
/// The prompt that asks an agent to write `HelderSchemaCommand` in a Laravel project.
|
|
public enum SchemaCommandPrompt {
|
|
/// The JSON contract in this text is what `SchemaDump` decodes; change both together.
|
|
public static let text = #"""
|
|
Build an Artisan command that dumps this app's database schema for Helder, the IDE that draws it as a diagram.
|
|
|
|
File: app/Console/Commands/HelderSchemaCommand.php
|
|
Class: App\Console\Commands\HelderSchemaCommand, extends Illuminate\Console\Command
|
|
Signature: helder:schema {--connection= : Database connection to read (default: the default connection)}
|
|
Description: Dump the database schema for Helder to visualise.
|
|
|
|
What the command does:
|
|
1. Read the structure with Laravel's schema builder only: Schema::connection($connection)->getTables(), getColumns($table), getIndexes($table) and getForeignKeys($table). Write no raw SQL for the structure. If this Laravel version has no Schema::getTables(), stop and tell me.
|
|
2. Skip these tables: migrations, jobs, job_batches, failed_jobs, cache, cache_locks, sessions, password_reset_tokens.
|
|
3. Count the rows of each table with DB::connection($connection)->table($table)->count(). When one count fails, write null for that table and go on.
|
|
4. Write the JSON below to database/helder/schema.json. Create database/helder when it is missing. Write to a temporary file in that folder first, then rename it, so Helder never reads a half-written file.
|
|
5. Make sure database/helder/.gitignore exists with the two lines `*` and `!.gitignore`, so the dump stays out of git.
|
|
6. Print the counts with $this->components->twoColumnDetail(): Connection (`<connection> · <database>`), Tables, Columns, Foreign keys. Then print `Wrote database/helder/schema.json (<size> KB)` with $this->components->info() and return self::SUCCESS. On an error, print it with $this->components->error() and return self::FAILURE.
|
|
|
|
The JSON contract. Helder reads exactly these keys. Keep the arrays from the schema builder as they come, unchanged:
|
|
|
|
{
|
|
"version": 1,
|
|
"connection": "<connection name>",
|
|
"driver": "<DB::connection($connection)->getDriverName()>",
|
|
"database": "<DB::connection($connection)->getDatabaseName()>",
|
|
"generated_at": "<now()->toIso8601String()>",
|
|
"tables": [
|
|
{
|
|
"name": "<table name>",
|
|
"rows": <int or null>,
|
|
"columns": [ <Schema::getColumns($table), unchanged> ],
|
|
"indexes": [ <Schema::getIndexes($table), unchanged> ],
|
|
"foreign_keys": [ <Schema::getForeignKeys($table), unchanged> ]
|
|
}
|
|
]
|
|
}
|
|
|
|
Sort the tables by name. Encode with JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR.
|
|
|
|
Follow the code style of this project. Add no migration, no route and no package. When the command is done, run `php artisan helder:schema` once and show me the output.
|
|
|
|
A working example follows. Use it as the starting point and adapt it to this project's conventions. Schema::getCurrentSchemaListing() keeps MySQL to this connection's own database; if this Laravel version does not have that method, filter the result of getTables() by the connection's database instead.
|
|
|
|
```php
|
|
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
use Illuminate\Console\Command;
|
|
use Illuminate\Support\Arr;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\File;
|
|
use Illuminate\Support\Facades\Schema;
|
|
use RuntimeException;
|
|
use Throwable;
|
|
|
|
final class HelderSchemaCommand extends Command
|
|
{
|
|
private const SKIPPED_TABLES = [
|
|
'migrations',
|
|
'jobs',
|
|
'job_batches',
|
|
'failed_jobs',
|
|
'cache',
|
|
'cache_locks',
|
|
'sessions',
|
|
'password_reset_tokens',
|
|
];
|
|
|
|
/**
|
|
* The name and signature of the console command.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $signature = 'helder:schema
|
|
{--connection= : Database connection to read (default: the default connection)}';
|
|
|
|
/**
|
|
* The console command description.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $description = 'Dump the database schema for Helder to visualise.';
|
|
|
|
/**
|
|
* Execute the console command.
|
|
*/
|
|
public function handle(): int
|
|
{
|
|
try {
|
|
$connection = (string) ($this->option('connection') ?: config('database.default'));
|
|
$payload = $this->buildPayload($connection);
|
|
$path = $this->writeAtomically($payload);
|
|
|
|
$tables = Arr::get($payload, 'tables', []);
|
|
|
|
$this->components->twoColumnDetail('Connection', $connection.' · '.Arr::get($payload, 'database'));
|
|
$this->components->twoColumnDetail('Tables', (string) count($tables));
|
|
$this->components->twoColumnDetail('Columns', (string) $this->countOf($tables, 'columns'));
|
|
$this->components->twoColumnDetail('Foreign keys', (string) $this->countOf($tables, 'foreign_keys'));
|
|
|
|
$size = number_format(filesize($path) / 1024, 1);
|
|
$this->components->info("Wrote database/helder/schema.json ({$size} KB)");
|
|
|
|
return self::SUCCESS;
|
|
} catch (Throwable $exception) {
|
|
$this->components->error($exception->getMessage());
|
|
|
|
return self::FAILURE;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Build the schema payload for one connection.
|
|
*
|
|
* @return array<string, mixed>
|
|
*/
|
|
private function buildPayload(string $connection): array
|
|
{
|
|
$schema = Schema::connection($connection);
|
|
|
|
// On MySQL, getTables() without an argument lists the tables of every database on the server; the listing limits it to this connection's database.
|
|
$names = Arr::pluck($schema->getTables($schema->getCurrentSchemaListing()), 'name');
|
|
$names = array_values(array_diff($names, self::SKIPPED_TABLES));
|
|
sort($names);
|
|
|
|
$tables = [];
|
|
|
|
foreach ($names as $name) {
|
|
$tables[] = [
|
|
'name' => $name,
|
|
'rows' => $this->countRows($connection, $name),
|
|
'columns' => $schema->getColumns($name),
|
|
'indexes' => $schema->getIndexes($name),
|
|
'foreign_keys' => $schema->getForeignKeys($name),
|
|
];
|
|
}
|
|
|
|
return [
|
|
'version' => 1,
|
|
'connection' => $connection,
|
|
'driver' => DB::connection($connection)->getDriverName(),
|
|
'database' => DB::connection($connection)->getDatabaseName(),
|
|
'generated_at' => now()->toIso8601String(),
|
|
'tables' => $tables,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Count the rows of a table, or return null when the count fails.
|
|
*/
|
|
private function countRows(string $connection, string $table): ?int
|
|
{
|
|
try {
|
|
return DB::connection($connection)->table($table)->count();
|
|
} catch (Throwable) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Sum the size of one list key over all tables.
|
|
*
|
|
* @param array<int, array<string, mixed>> $tables
|
|
*/
|
|
private function countOf(array $tables, string $key): int
|
|
{
|
|
return array_sum(array_map(fn (array $table): int => count(Arr::get($table, $key, [])), $tables));
|
|
}
|
|
|
|
/**
|
|
* Write the payload to schema.json through a temp file and a rename, and return the path.
|
|
*
|
|
* @param array<string, mixed> $payload
|
|
*/
|
|
private function writeAtomically(array $payload): string
|
|
{
|
|
$directory = database_path('helder');
|
|
$target = $directory.'/schema.json';
|
|
$gitignore = $directory.'/.gitignore';
|
|
|
|
File::ensureDirectoryExists($directory);
|
|
|
|
if (! File::exists($gitignore)) {
|
|
File::put($gitignore, "*\n!.gitignore\n");
|
|
}
|
|
|
|
$json = json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
|
|
$temporary = tempnam($directory, 'schema.json.');
|
|
|
|
try {
|
|
File::put($temporary, $json);
|
|
File::chmod($temporary, 0644);
|
|
|
|
if (! rename($temporary, $target)) {
|
|
throw new RuntimeException('Could not move the temp file onto schema.json.');
|
|
}
|
|
} catch (Throwable $exception) {
|
|
File::delete($temporary);
|
|
|
|
throw $exception;
|
|
}
|
|
|
|
return $target;
|
|
}
|
|
}
|
|
```
|
|
"""#
|
|
}
|