adds schema view and schema generating command
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
import Foundation
|
||||
|
||||
/// How a line in the Schema view's artisan console is painted.
|
||||
public enum ArtisanLineKind: String, Sendable, Equatable {
|
||||
case command
|
||||
case output
|
||||
case error
|
||||
case success
|
||||
}
|
||||
|
||||
public struct ArtisanConsoleLine: Sendable, Equatable {
|
||||
public var text: String
|
||||
public var kind: ArtisanLineKind
|
||||
|
||||
public init(text: String, kind: ArtisanLineKind) {
|
||||
self.text = text
|
||||
self.kind = kind
|
||||
}
|
||||
}
|
||||
|
||||
public enum ArtisanOutputClassifier {
|
||||
/// `$ php artisan helder:schema`, the echo before a run.
|
||||
public static let commandEcho = "$ " + SchemaPaths.commandLine
|
||||
|
||||
/// Stderr and `ERROR`/`Exception` lines are errors; Laravel's `INFO`/`DONE` blocks and `Wrote …` are successes.
|
||||
///
|
||||
/// PHP writes warnings to stderr too, but there they still mean the run went wrong for the user.
|
||||
public static func classify(_ line: String, isError: Bool) -> ArtisanLineKind {
|
||||
if isError { return .error }
|
||||
let trimmed = line.trimmingCharacters(in: .whitespaces)
|
||||
if trimmed.hasPrefix("ERROR") || trimmed.hasPrefix("FAIL") || line.contains("Exception") { return .error }
|
||||
if trimmed.hasPrefix("INFO") || trimmed.hasPrefix("DONE") || trimmed.hasPrefix("Wrote ") || trimmed.hasPrefix("Schema dumped") {
|
||||
return .success
|
||||
}
|
||||
return .output
|
||||
}
|
||||
|
||||
public static func line(_ text: String, isError: Bool) -> ArtisanConsoleLine {
|
||||
ArtisanConsoleLine(text: text, kind: classify(text, isError: isError))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
```
|
||||
"""#
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
import Foundation
|
||||
|
||||
public enum SchemaDumpError: Error, Equatable, LocalizedError {
|
||||
/// The file is not a JSON object; `reason` is the decoder's message.
|
||||
case corrupt(reason: String)
|
||||
|
||||
public var errorDescription: String? {
|
||||
switch self {
|
||||
case let .corrupt(reason): "\(SchemaPaths.dumpFile) is not a valid schema dump: \(reason)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `database/helder/schema.json` as the `helder:schema` command writes it (contract version 1).
|
||||
///
|
||||
/// Decoding is tolerant: a missing or mistyped key gets its default and a table without a name is skipped,
|
||||
/// so the older prototype dump (no version, driver, database or rows) still loads.
|
||||
public struct SchemaDump: Sendable, Equatable, Decodable {
|
||||
public var version: Int?
|
||||
public var connection: String?
|
||||
public var driver: String?
|
||||
public var database: String?
|
||||
public var generatedAt: String?
|
||||
public var tables: [Table]
|
||||
|
||||
public init(version: Int? = 1, connection: String? = nil, driver: String? = nil, database: String? = nil,
|
||||
generatedAt: String? = nil, tables: [Table] = []) {
|
||||
self.version = version
|
||||
self.connection = connection
|
||||
self.driver = driver
|
||||
self.database = database
|
||||
self.generatedAt = generatedAt
|
||||
self.tables = tables
|
||||
}
|
||||
|
||||
/// Throws `SchemaDumpError.corrupt` when the data is not a JSON object.
|
||||
public static func decode(_ data: Data) throws -> SchemaDump {
|
||||
do {
|
||||
return try JSONDecoder().decode(SchemaDump.self, from: data)
|
||||
} catch let error as DecodingError {
|
||||
throw SchemaDumpError.corrupt(reason: Self.describe(error))
|
||||
} catch {
|
||||
throw SchemaDumpError.corrupt(reason: error.localizedDescription)
|
||||
}
|
||||
}
|
||||
|
||||
private static func describe(_ error: DecodingError) -> String {
|
||||
switch error {
|
||||
case let .dataCorrupted(context):
|
||||
let underlying = (context.underlyingError as NSError?)?.userInfo[NSDebugDescriptionErrorKey] as? String
|
||||
return underlying ?? context.debugDescription
|
||||
case let .typeMismatch(_, context), let .valueNotFound(_, context), let .keyNotFound(_, context):
|
||||
return context.debugDescription
|
||||
@unknown default:
|
||||
return "\(error)"
|
||||
}
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case version, connection, driver, database, generatedAt = "generated_at", tables
|
||||
}
|
||||
|
||||
public init(from decoder: Decoder) throws {
|
||||
let c = try decoder.container(keyedBy: CodingKeys.self)
|
||||
version = c.lenientInt(.version)
|
||||
connection = c.lenientString(.connection)
|
||||
driver = c.lenientString(.driver)
|
||||
database = c.lenientString(.database)
|
||||
generatedAt = c.lenientString(.generatedAt)
|
||||
tables = c.lenientList(Table.self, .tables)
|
||||
}
|
||||
|
||||
public struct Table: Sendable, Equatable, Decodable {
|
||||
public var name: String
|
||||
public var rows: Int?
|
||||
public var columns: [Column]
|
||||
public var indexes: [Index]
|
||||
public var foreignKeys: [ForeignKey]
|
||||
|
||||
public init(name: String, rows: Int? = nil, columns: [Column] = [], indexes: [Index] = [], foreignKeys: [ForeignKey] = []) {
|
||||
self.name = name
|
||||
self.rows = rows
|
||||
self.columns = columns
|
||||
self.indexes = indexes
|
||||
self.foreignKeys = foreignKeys
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case name, rows, columns, indexes, foreignKeys = "foreign_keys"
|
||||
}
|
||||
|
||||
public init(from decoder: Decoder) throws {
|
||||
let c = try decoder.container(keyedBy: CodingKeys.self)
|
||||
guard let name = c.lenientString(.name), !name.isEmpty else {
|
||||
throw DecodingError.keyNotFound(CodingKeys.name, .init(codingPath: decoder.codingPath, debugDescription: "table without a name"))
|
||||
}
|
||||
self.name = name
|
||||
rows = c.lenientInt(.rows)
|
||||
columns = c.lenientList(Column.self, .columns)
|
||||
indexes = c.lenientList(Index.self, .indexes)
|
||||
foreignKeys = c.lenientList(ForeignKey.self, .foreignKeys)
|
||||
}
|
||||
}
|
||||
|
||||
/// One item of Laravel's `Schema::getColumns()`.
|
||||
public struct Column: Sendable, Equatable, Decodable {
|
||||
public var name: String
|
||||
public var typeName: String?
|
||||
/// The full type, such as `varchar(255)`.
|
||||
public var type: String?
|
||||
public var nullable: Bool
|
||||
/// Numbers and booleans are kept as their text.
|
||||
public var defaultValue: String?
|
||||
public var autoIncrement: Bool
|
||||
public var comment: String?
|
||||
|
||||
public init(name: String, typeName: String? = nil, type: String? = nil, nullable: Bool = false,
|
||||
defaultValue: String? = nil, autoIncrement: Bool = false, comment: String? = nil) {
|
||||
self.name = name
|
||||
self.typeName = typeName
|
||||
self.type = type
|
||||
self.nullable = nullable
|
||||
self.defaultValue = defaultValue
|
||||
self.autoIncrement = autoIncrement
|
||||
self.comment = comment
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case name, typeName = "type_name", type, nullable, defaultValue = "default", autoIncrement = "auto_increment", comment
|
||||
}
|
||||
|
||||
public init(from decoder: Decoder) throws {
|
||||
let c = try decoder.container(keyedBy: CodingKeys.self)
|
||||
guard let name = c.lenientString(.name), !name.isEmpty else {
|
||||
throw DecodingError.keyNotFound(CodingKeys.name, .init(codingPath: decoder.codingPath, debugDescription: "column without a name"))
|
||||
}
|
||||
self.name = name
|
||||
typeName = c.lenientString(.typeName)
|
||||
type = c.lenientString(.type)
|
||||
nullable = c.lenientBool(.nullable) ?? false
|
||||
defaultValue = c.lenientString(.defaultValue)
|
||||
autoIncrement = c.lenientBool(.autoIncrement) ?? false
|
||||
comment = c.lenientString(.comment)
|
||||
}
|
||||
}
|
||||
|
||||
/// One item of Laravel's `Schema::getIndexes()`.
|
||||
public struct Index: Sendable, Equatable, Decodable {
|
||||
public var name: String?
|
||||
public var columns: [String]
|
||||
public var type: String?
|
||||
public var unique: Bool
|
||||
public var primary: Bool
|
||||
|
||||
public init(name: String? = nil, columns: [String], type: String? = nil, unique: Bool = false, primary: Bool = false) {
|
||||
self.name = name
|
||||
self.columns = columns
|
||||
self.type = type
|
||||
self.unique = unique
|
||||
self.primary = primary
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case name, columns, type, unique, primary
|
||||
}
|
||||
|
||||
public init(from decoder: Decoder) throws {
|
||||
let c = try decoder.container(keyedBy: CodingKeys.self)
|
||||
name = c.lenientString(.name)
|
||||
columns = c.lenientStrings(.columns)
|
||||
type = c.lenientString(.type)
|
||||
primary = c.lenientBool(.primary) ?? false
|
||||
unique = c.lenientBool(.unique) ?? primary
|
||||
}
|
||||
}
|
||||
|
||||
/// One item of Laravel's `Schema::getForeignKeys()`.
|
||||
public struct ForeignKey: Sendable, Equatable, Decodable {
|
||||
public var name: String?
|
||||
public var columns: [String]
|
||||
public var foreignSchema: String?
|
||||
public var foreignTable: String
|
||||
public var foreignColumns: [String]
|
||||
public var onUpdate: String?
|
||||
public var onDelete: String?
|
||||
|
||||
public init(name: String? = nil, columns: [String], foreignSchema: String? = nil, foreignTable: String,
|
||||
foreignColumns: [String] = [], onUpdate: String? = nil, onDelete: String? = nil) {
|
||||
self.name = name
|
||||
self.columns = columns
|
||||
self.foreignSchema = foreignSchema
|
||||
self.foreignTable = foreignTable
|
||||
self.foreignColumns = foreignColumns
|
||||
self.onUpdate = onUpdate
|
||||
self.onDelete = onDelete
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case name, columns, foreignSchema = "foreign_schema", foreignTable = "foreign_table",
|
||||
foreignColumns = "foreign_columns", onUpdate = "on_update", onDelete = "on_delete"
|
||||
}
|
||||
|
||||
public init(from decoder: Decoder) throws {
|
||||
let c = try decoder.container(keyedBy: CodingKeys.self)
|
||||
guard let table = c.lenientString(.foreignTable), !table.isEmpty else {
|
||||
throw DecodingError.keyNotFound(CodingKeys.foreignTable, .init(codingPath: decoder.codingPath, debugDescription: "foreign key without a table"))
|
||||
}
|
||||
name = c.lenientString(.name)
|
||||
columns = c.lenientStrings(.columns)
|
||||
foreignSchema = c.lenientString(.foreignSchema)
|
||||
foreignTable = table
|
||||
foreignColumns = c.lenientStrings(.foreignColumns)
|
||||
onUpdate = c.lenientString(.onUpdate)
|
||||
onDelete = c.lenientString(.onDelete)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads that never throw: a missing or mistyped value is nil, and a list keeps only the items that decode.
|
||||
private extension KeyedDecodingContainer {
|
||||
func lenientString(_ key: Key) -> String? {
|
||||
if let value = try? decodeIfPresent(String.self, forKey: key) { return value }
|
||||
if let value = try? decodeIfPresent(Int.self, forKey: key) { return String(value) }
|
||||
if let value = try? decodeIfPresent(Double.self, forKey: key) { return String(value) }
|
||||
if let value = try? decodeIfPresent(Bool.self, forKey: key) { return value ? "true" : "false" }
|
||||
return nil
|
||||
}
|
||||
|
||||
func lenientInt(_ key: Key) -> Int? {
|
||||
if let value = try? decodeIfPresent(Int.self, forKey: key) { return value }
|
||||
if let value = try? decodeIfPresent(Double.self, forKey: key), value.isFinite { return Int(value) }
|
||||
if let value = try? decodeIfPresent(String.self, forKey: key) { return Int(value) }
|
||||
return nil
|
||||
}
|
||||
|
||||
/// PDO drivers may hand booleans over as 0/1 or "1".
|
||||
func lenientBool(_ key: Key) -> Bool? {
|
||||
if let value = try? decodeIfPresent(Bool.self, forKey: key) { return value }
|
||||
if let value = try? decodeIfPresent(Int.self, forKey: key) { return value != 0 }
|
||||
if let value = try? decodeIfPresent(String.self, forKey: key) {
|
||||
return ["1", "true", "yes"].contains(value.lowercased())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func lenientStrings(_ key: Key) -> [String] {
|
||||
lenientList(LenientString.self, key).compactMap(\.value)
|
||||
}
|
||||
|
||||
func lenientList<T: Decodable>(_ type: T.Type, _ key: Key) -> [T] {
|
||||
guard let items = try? decodeIfPresent([Failable<T>].self, forKey: key) else { return [] }
|
||||
return items.compactMap(\.value)
|
||||
}
|
||||
}
|
||||
|
||||
private struct Failable<T: Decodable>: Decodable {
|
||||
let value: T?
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
value = try? T(from: decoder)
|
||||
}
|
||||
}
|
||||
|
||||
private struct LenientString: Decodable {
|
||||
let value: String?
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
let c = try decoder.singleValueContainer()
|
||||
if let text = try? c.decode(String.self) {
|
||||
value = text
|
||||
} else if let number = try? c.decode(Int.self) {
|
||||
value = String(number)
|
||||
} else {
|
||||
value = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
import Foundation
|
||||
|
||||
/// A point on the schema canvas, in canvas units (before pan and zoom).
|
||||
public struct SchemaPoint: Sendable, Hashable, Codable {
|
||||
public var x: Double
|
||||
public var y: Double
|
||||
|
||||
public init(x: Double, y: Double) {
|
||||
self.x = x
|
||||
self.y = y
|
||||
}
|
||||
}
|
||||
|
||||
public struct SchemaSize: Sendable, Hashable {
|
||||
public var width: Double
|
||||
public var height: Double
|
||||
|
||||
public init(width: Double, height: Double) {
|
||||
self.width = width
|
||||
self.height = height
|
||||
}
|
||||
}
|
||||
|
||||
public struct SchemaRect: Sendable, Hashable {
|
||||
public var x: Double
|
||||
public var y: Double
|
||||
public var width: Double
|
||||
public var height: Double
|
||||
|
||||
public init(x: Double, y: Double, width: Double, height: Double) {
|
||||
self.x = x
|
||||
self.y = y
|
||||
self.width = width
|
||||
self.height = height
|
||||
}
|
||||
|
||||
public var maxX: Double { x + width }
|
||||
public var maxY: Double { y + height }
|
||||
}
|
||||
|
||||
/// Pan and zoom: a canvas point `p` shows at `p * scale + (x, y)` in the viewport.
|
||||
public struct SchemaViewport: Sendable, Hashable {
|
||||
public var x: Double
|
||||
public var y: Double
|
||||
public var scale: Double
|
||||
|
||||
public init(x: Double = 0, y: Double = 0, scale: Double = 1) {
|
||||
self.x = x
|
||||
self.y = y
|
||||
self.scale = scale
|
||||
}
|
||||
|
||||
/// `100%` style label for the zoom control.
|
||||
public var percentLabel: String { "\(Int((scale * 100).rounded()))%" }
|
||||
}
|
||||
|
||||
/// The fixed sizes of the Schema canvas; the line geometry depends on the card sizes.
|
||||
public enum SchemaMetrics {
|
||||
public static let cardWidth = 240.0
|
||||
/// The header, including its bottom border.
|
||||
public static let headerHeight = 33.0
|
||||
public static let rowHeight = 22.0
|
||||
/// Card top to the centre of column 0: 1px border + 33 header + half a row.
|
||||
public static let firstRowCentre = 45.0
|
||||
/// Header plus the card's top and bottom border.
|
||||
public static let cardChrome = 35.0
|
||||
public static let laneSpacing = 340.0
|
||||
public static let cardGap = 48.0
|
||||
/// Where the default layout starts.
|
||||
public static let layoutOrigin = SchemaPoint(x: 40, y: 40)
|
||||
public static let fitMargin = 48.0
|
||||
public static let fitMaxScale = 1.1
|
||||
/// Room right of the rightmost card for same-lane loops, as the prototype's fit.
|
||||
public static let fitExtraWidth = 60.0
|
||||
public static let minScale = 0.3
|
||||
public static let maxScale = 2.0
|
||||
public static let zoomStep = 1.2
|
||||
/// Card centres closer than this count as one lane: the line loops out on the right.
|
||||
public static let sameLaneDistance = 240.0
|
||||
public static let loopBase = 46.0
|
||||
public static let loopFactor = 0.12
|
||||
public static let minCurve = 40.0
|
||||
public static let endRadius = 3.0
|
||||
}
|
||||
|
||||
/// A cubic Bézier with horizontal tangents, from the foreign-key row to the referenced row.
|
||||
public struct SchemaEdgePath: Sendable, Hashable {
|
||||
public var start: SchemaPoint
|
||||
public var control1: SchemaPoint
|
||||
public var control2: SchemaPoint
|
||||
public var end: SchemaPoint
|
||||
|
||||
public init(start: SchemaPoint, control1: SchemaPoint, control2: SchemaPoint, end: SchemaPoint) {
|
||||
self.start = start
|
||||
self.control1 = control1
|
||||
self.control2 = control2
|
||||
self.end = end
|
||||
}
|
||||
}
|
||||
|
||||
public enum SchemaGeometry {
|
||||
public static func cardHeight(columns: Int) -> Double {
|
||||
SchemaMetrics.cardChrome + Double(columns) * SchemaMetrics.rowHeight
|
||||
}
|
||||
|
||||
/// The vertical centre of column `index` in a card whose top is `top`.
|
||||
public static func columnCentreY(top: Double, index: Int) -> Double {
|
||||
top + SchemaMetrics.firstRowCentre + Double(index) * SchemaMetrics.rowHeight
|
||||
}
|
||||
|
||||
/// Right edge to left edge when the target is right, the mirror when left, a loop off the right edges in one lane.
|
||||
public static func edgePath(from source: SchemaPoint, columnIndex: Int, to target: SchemaPoint, targetColumnIndex: Int) -> SchemaEdgePath {
|
||||
let width = SchemaMetrics.cardWidth
|
||||
let y1 = columnCentreY(top: source.y, index: columnIndex)
|
||||
let y2 = columnCentreY(top: target.y, index: targetColumnIndex)
|
||||
let sourceCentre = source.x + width / 2
|
||||
let targetCentre = target.x + width / 2
|
||||
let x1: Double, x2: Double, c1: Double, c2: Double
|
||||
if abs(sourceCentre - targetCentre) < SchemaMetrics.sameLaneDistance {
|
||||
x1 = source.x + width
|
||||
x2 = target.x + width
|
||||
let loop = SchemaMetrics.loopBase + abs(y2 - y1) * SchemaMetrics.loopFactor
|
||||
c1 = x1 + loop
|
||||
c2 = x2 + loop
|
||||
} else if targetCentre > sourceCentre {
|
||||
x1 = source.x + width
|
||||
x2 = target.x
|
||||
let d = max(SchemaMetrics.minCurve, (x2 - x1) / 2)
|
||||
c1 = x1 + d
|
||||
c2 = x2 - d
|
||||
} else {
|
||||
x1 = source.x
|
||||
x2 = target.x + width
|
||||
let d = max(SchemaMetrics.minCurve, (x1 - x2) / 2)
|
||||
c1 = x1 - d
|
||||
c2 = x2 + d
|
||||
}
|
||||
return SchemaEdgePath(start: SchemaPoint(x: x1, y: y1), control1: SchemaPoint(x: c1, y: y1),
|
||||
control2: SchemaPoint(x: c2, y: y2), end: SchemaPoint(x: x2, y: y2))
|
||||
}
|
||||
|
||||
/// Nil when either table has no position.
|
||||
public static func edgePath(_ edge: SchemaEdge, positions: [String: SchemaPoint]) -> SchemaEdgePath? {
|
||||
guard let source = positions[edge.from], let target = positions[edge.to] else { return nil }
|
||||
return edgePath(from: source, columnIndex: edge.columnIndex, to: target, targetColumnIndex: edge.targetColumnIndex)
|
||||
}
|
||||
|
||||
public static func cardRect(_ table: SchemaTable, at position: SchemaPoint) -> SchemaRect {
|
||||
SchemaRect(x: position.x, y: position.y, width: SchemaMetrics.cardWidth, height: table.cardHeight)
|
||||
}
|
||||
|
||||
/// The box around every placed card; nil when none is placed.
|
||||
public static func bounds(_ model: SchemaModel, positions: [String: SchemaPoint]) -> SchemaRect? {
|
||||
var x0 = Double.infinity, y0 = Double.infinity, x1 = -Double.infinity, y1 = -Double.infinity
|
||||
for table in model.tables {
|
||||
guard let p = positions[table.name] else { continue }
|
||||
let rect = cardRect(table, at: p)
|
||||
x0 = min(x0, rect.x)
|
||||
y0 = min(y0, rect.y)
|
||||
x1 = max(x1, rect.maxX)
|
||||
y1 = max(y1, rect.maxY)
|
||||
}
|
||||
guard x0.isFinite else { return nil }
|
||||
return SchemaRect(x: x0, y: y0, width: x1 - x0, height: y1 - y0)
|
||||
}
|
||||
|
||||
public static func clampScale(_ scale: Double) -> Double {
|
||||
min(SchemaMetrics.maxScale, max(SchemaMetrics.minScale, scale))
|
||||
}
|
||||
|
||||
/// Frames `bounds` in `viewport` with a 48px margin, never above 110% nor below 30%.
|
||||
public static func fit(bounds: SchemaRect, in viewport: SchemaSize) -> SchemaViewport {
|
||||
let margin = SchemaMetrics.fitMargin * 2
|
||||
let width = bounds.width + SchemaMetrics.fitExtraWidth
|
||||
let height = bounds.height
|
||||
let fitting = min((viewport.width - margin) / max(width, 1), (viewport.height - margin) / max(height, 1))
|
||||
let scale = min(SchemaMetrics.fitMaxScale, max(SchemaMetrics.minScale, fitting))
|
||||
return SchemaViewport(x: (viewport.width - width * scale) / 2 - bounds.x * scale,
|
||||
y: (viewport.height - height * scale) / 2 - bounds.y * scale,
|
||||
scale: scale)
|
||||
}
|
||||
|
||||
/// Scales by `factor` (clamped to 30–200%) keeping the canvas point under `anchor` (viewport coordinates) in place.
|
||||
public static func zoom(_ view: SchemaViewport, by factor: Double, around anchor: SchemaPoint) -> SchemaViewport {
|
||||
let scale = clampScale(view.scale * factor)
|
||||
let ratio = scale / view.scale
|
||||
return SchemaViewport(x: anchor.x - (anchor.x - view.x) * ratio,
|
||||
y: anchor.y - (anchor.y - view.y) * ratio,
|
||||
scale: scale)
|
||||
}
|
||||
|
||||
/// Zooms around the viewport's centre, as the `−` and `+` buttons do.
|
||||
public static func zoom(_ view: SchemaViewport, by factor: Double, in viewport: SchemaSize) -> SchemaViewport {
|
||||
zoom(view, by: factor, around: SchemaPoint(x: viewport.width / 2, y: viewport.height / 2))
|
||||
}
|
||||
|
||||
/// Pans so the card sits in the middle of `viewport`, keeping the scale; values are rounded to whole points.
|
||||
///
|
||||
/// Pass the width left of the detail panel when it is about to open, as the prototype does.
|
||||
public static func centre(_ table: SchemaTable, at position: SchemaPoint, in viewport: SchemaSize, view: SchemaViewport) -> SchemaViewport {
|
||||
let k = view.scale
|
||||
let midX = position.x + SchemaMetrics.cardWidth / 2
|
||||
let midY = position.y + table.cardHeight / 2
|
||||
return SchemaViewport(x: (viewport.width / 2 - midX * k).rounded(),
|
||||
y: (viewport.height / 2 - midY * k).rounded(),
|
||||
scale: k)
|
||||
}
|
||||
|
||||
/// The canvas point under a viewport point.
|
||||
public static func canvasPoint(_ point: SchemaPoint, in view: SchemaViewport) -> SchemaPoint {
|
||||
SchemaPoint(x: (point.x - view.x) / view.scale, y: (point.y - view.y) / view.scale)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import Foundation
|
||||
|
||||
/// Which lines, cards and rows light up for the current hover, selection and search.
|
||||
public struct SchemaHighlight: Sendable, Equatable {
|
||||
/// The hovered table, else the selected one.
|
||||
public var focus: String?
|
||||
/// Ids (`table.column`) of the edges drawn in amber.
|
||||
public var activeEdges: Set<String>
|
||||
/// Both ends of every active edge, plus the focus.
|
||||
public var relatedTables: Set<String>
|
||||
/// Cards drawn at 30% opacity.
|
||||
public var dimmedTables: Set<String>
|
||||
/// Cards whose name holds the search query; empty without a query.
|
||||
public var searchMatches: Set<String>
|
||||
/// The foreign-key rows and the rows they reference, of every active edge.
|
||||
public var highlightedColumns: Set<SchemaColumnRef>
|
||||
/// True when inactive lines take the receded colour (a focus, a hovered key, or a query).
|
||||
public var linesRecede: Bool
|
||||
|
||||
/// A hovered foreign key (`table.column`) narrows the highlight to its one edge and wins over the focus.
|
||||
///
|
||||
/// The search only dims cards while nothing is focused.
|
||||
public init(model: SchemaModel, hovered: String?, selected: String?, hoveredColumn: String?, query: String) {
|
||||
let focus = hovered ?? selected
|
||||
let needle = query.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
|
||||
let active = model.edges.filter { edge in
|
||||
if let hoveredColumn { return edge.id == hoveredColumn }
|
||||
guard let focus else { return false }
|
||||
return edge.from == focus || edge.to == focus
|
||||
}
|
||||
var related = Set(active.flatMap { [$0.from, $0.to] })
|
||||
if let focus { related.insert(focus) }
|
||||
|
||||
var columns = Set<SchemaColumnRef>()
|
||||
for edge in active {
|
||||
columns.insert(SchemaColumnRef(table: edge.from, column: edge.column))
|
||||
if let target = model.table(named: edge.to), edge.targetColumnIndex < target.columns.count {
|
||||
columns.insert(SchemaColumnRef(table: edge.to, column: target.columns[edge.targetColumnIndex].name))
|
||||
}
|
||||
}
|
||||
|
||||
let names = model.tables.map(\.name)
|
||||
let matches = needle.isEmpty ? Set<String>() : Set(names.filter { $0.lowercased().contains(needle) })
|
||||
let dimsAll = focus != nil || hoveredColumn != nil
|
||||
let dimmed: Set<String> = if dimsAll {
|
||||
Set(names.filter { !related.contains($0) })
|
||||
} else if !needle.isEmpty {
|
||||
Set(names.filter { !matches.contains($0) })
|
||||
} else {
|
||||
[]
|
||||
}
|
||||
|
||||
self.focus = focus
|
||||
activeEdges = Set(active.map(\.id))
|
||||
relatedTables = related
|
||||
dimmedTables = dimmed
|
||||
searchMatches = matches
|
||||
highlightedColumns = columns
|
||||
linesRecede = dimsAll || !needle.isEmpty
|
||||
}
|
||||
|
||||
public func isActive(_ edge: SchemaEdge) -> Bool {
|
||||
activeEdges.contains(edge.id)
|
||||
}
|
||||
|
||||
public func isHighlighted(table: String, column: String) -> Bool {
|
||||
highlightedColumns.contains(SchemaColumnRef(table: table, column: column))
|
||||
}
|
||||
|
||||
/// 1 or 0.3.
|
||||
public func opacity(of table: String) -> Double {
|
||||
dimmedTables.contains(table) ? 0.3 : 1
|
||||
}
|
||||
|
||||
/// The edges in drawing order: inactive first, so active lines sit on top.
|
||||
public func drawingOrder(_ edges: [SchemaEdge]) -> [SchemaEdge] {
|
||||
edges.filter { !isActive($0) } + edges.filter(isActive)
|
||||
}
|
||||
}
|
||||
|
||||
public enum SchemaSearch {
|
||||
/// The tables whose name holds `query` (case-insensitive), in name order; all of them for an empty query.
|
||||
public static func filter(_ model: SchemaModel, query: String) -> [SchemaTable] {
|
||||
let needle = query.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
|
||||
guard !needle.isEmpty else { return model.tables }
|
||||
return model.tables.filter { $0.name.lowercased().contains(needle) }
|
||||
}
|
||||
|
||||
/// `[ TABLES ] 16`, or `[ TABLES ] 3 of 16` while filtering.
|
||||
public static func listLabel(_ model: SchemaModel, query: String) -> String {
|
||||
let total = model.tables.count
|
||||
let isFiltering = !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
return isFiltering ? "[ TABLES ] \(filter(model, query: query).count) of \(total)" : "[ TABLES ] \(total)"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import Foundation
|
||||
|
||||
/// The default placement of the cards: lanes by foreign-key depth, left to right.
|
||||
public enum SchemaLayout {
|
||||
/// Lane 0 holds tables that point at nothing; every other table sits one lane right of the deepest table it points at.
|
||||
///
|
||||
/// Self-references are ignored and a cycle is broken at the edge that closes it, visiting tables by name, so the result is deterministic.
|
||||
public static func lanes(_ model: SchemaModel) -> [String: Int] {
|
||||
var targets: [String: [String]] = [:]
|
||||
for edge in model.edges where edge.from != edge.to {
|
||||
targets[edge.from, default: []].append(edge.to)
|
||||
}
|
||||
var lane: [String: Int] = [:]
|
||||
var visiting = Set<String>()
|
||||
|
||||
func visit(_ name: String) -> Int? {
|
||||
if let known = lane[name] { return known }
|
||||
guard visiting.insert(name).inserted else { return nil }
|
||||
var deepest = -1
|
||||
for target in Set(targets[name] ?? []).sorted() {
|
||||
if let value = visit(target) { deepest = max(deepest, value) }
|
||||
}
|
||||
visiting.remove(name)
|
||||
lane[name] = deepest + 1
|
||||
return deepest + 1
|
||||
}
|
||||
|
||||
for table in model.tables.map(\.name).sorted() { _ = visit(table) }
|
||||
return lane
|
||||
}
|
||||
|
||||
/// Lanes 340px apart, cards 48px apart, each lane centred against the tallest.
|
||||
///
|
||||
/// Lane 0 is in name order; later lanes follow the average height of the tables they point at, to limit crossings.
|
||||
public static func defaultPositions(_ model: SchemaModel) -> [String: SchemaPoint] {
|
||||
let lanes = lanes(model)
|
||||
let tables = Dictionary(uniqueKeysWithValues: model.tables.map { ($0.name, $0) })
|
||||
let laneCount = (lanes.values.max() ?? -1) + 1
|
||||
var members = Array(repeating: [String](), count: laneCount)
|
||||
for (name, lane) in lanes { members[lane].append(name) }
|
||||
|
||||
var offset: [String: Double] = [:]
|
||||
var laneHeight = Array(repeating: 0.0, count: laneCount)
|
||||
// Card centre as a share of its lane's height, which compares across lanes of different heights.
|
||||
var relative: [String: Double] = [:]
|
||||
|
||||
for lane in 0..<laneCount {
|
||||
let ordered: [String]
|
||||
if lane == 0 {
|
||||
ordered = members[lane].sorted()
|
||||
} else {
|
||||
let keys = Dictionary(uniqueKeysWithValues: members[lane].map { name in
|
||||
let shares = model.edges
|
||||
.filter { $0.from == name && $0.to != name && (lanes[$0.to] ?? lane) < lane }
|
||||
.compactMap { relative[$0.to] }
|
||||
return (name, shares.isEmpty ? 0.5 : shares.reduce(0, +) / Double(shares.count))
|
||||
})
|
||||
ordered = members[lane].sorted { a, b in
|
||||
keys[a]! == keys[b]! ? a < b : keys[a]! < keys[b]!
|
||||
}
|
||||
}
|
||||
var y = 0.0
|
||||
var centres: [(String, Double)] = []
|
||||
for name in ordered {
|
||||
let height = tables[name]?.cardHeight ?? SchemaGeometry.cardHeight(columns: 0)
|
||||
offset[name] = y
|
||||
centres.append((name, y + height / 2))
|
||||
y += height + SchemaMetrics.cardGap
|
||||
}
|
||||
laneHeight[lane] = y
|
||||
for (name, centre) in centres { relative[name] = y > 0 ? centre / y : 0.5 }
|
||||
}
|
||||
|
||||
let tallest = laneHeight.max() ?? 0
|
||||
let origin = SchemaMetrics.layoutOrigin
|
||||
var positions: [String: SchemaPoint] = [:]
|
||||
for (name, lane) in lanes {
|
||||
let shift = ((tallest - laneHeight[lane]) / 2).rounded()
|
||||
positions[name] = SchemaPoint(x: origin.x + Double(lane) * SchemaMetrics.laneSpacing,
|
||||
y: origin.y + shift + (offset[name] ?? 0))
|
||||
}
|
||||
return positions
|
||||
}
|
||||
|
||||
/// Saved positions for the tables that still exist, default ones for the rest.
|
||||
public static func positions(_ model: SchemaModel, saved: [String: SchemaPoint]) -> [String: SchemaPoint] {
|
||||
var result = defaultPositions(model)
|
||||
for table in model.tables {
|
||||
if let point = saved[table.name] { result[table.name] = point }
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/// The UserDefaults key that holds a project's card positions.
|
||||
public static func defaultsKey(root: String) -> String { "helder.schemaLayout:" + root }
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import Foundation
|
||||
|
||||
/// A column another column points at.
|
||||
public struct SchemaColumnRef: Sendable, Hashable, Codable {
|
||||
public var table: String
|
||||
public var column: String
|
||||
|
||||
public init(table: String, column: String) {
|
||||
self.table = table
|
||||
self.column = column
|
||||
}
|
||||
|
||||
/// `table.column`, the form the view uses for a hovered foreign key.
|
||||
public var id: String { table + "." + column }
|
||||
}
|
||||
|
||||
public struct SchemaColumn: Sendable, Equatable {
|
||||
public var name: String
|
||||
/// The full type such as `varchar(255)`, else the bare type name.
|
||||
public var type: String
|
||||
public var isPrimary: Bool
|
||||
public var isForeign: Bool
|
||||
/// Alone in a unique index that is not the primary key.
|
||||
public var isUnique: Bool
|
||||
public var isNullable: Bool
|
||||
public var foreignTarget: SchemaColumnRef?
|
||||
|
||||
public init(name: String, type: String, isPrimary: Bool = false, isForeign: Bool = false, isUnique: Bool = false,
|
||||
isNullable: Bool = false, foreignTarget: SchemaColumnRef? = nil) {
|
||||
self.name = name
|
||||
self.type = type
|
||||
self.isPrimary = isPrimary
|
||||
self.isForeign = isForeign
|
||||
self.isUnique = isUnique
|
||||
self.isNullable = isNullable
|
||||
self.foreignTarget = foreignTarget
|
||||
}
|
||||
|
||||
/// `PK`, `FK`, `UQ` or empty, in that order of precedence.
|
||||
public var keyLabel: String {
|
||||
isPrimary ? "PK" : isForeign ? "FK" : isUnique ? "UQ" : ""
|
||||
}
|
||||
|
||||
/// The type with `?` for a nullable column, as the card shows it.
|
||||
public var displayType: String {
|
||||
isNullable ? type + "?" : type
|
||||
}
|
||||
|
||||
/// The detail panel's flags line, such as `FK → users.id · NULL`.
|
||||
public var flags: String {
|
||||
var parts: [String] = []
|
||||
if isPrimary { parts.append("PRIMARY") }
|
||||
if isForeign { parts.append("FK → " + (foreignTarget?.id ?? "?")) }
|
||||
if isUnique { parts.append("UNIQUE") }
|
||||
parts.append(isNullable ? "NULL" : "NOT NULL")
|
||||
return parts.joined(separator: " · ")
|
||||
}
|
||||
}
|
||||
|
||||
public struct SchemaTable: Sendable, Equatable {
|
||||
public var name: String
|
||||
public var rows: Int?
|
||||
public var columns: [SchemaColumn]
|
||||
|
||||
public init(name: String, rows: Int? = nil, columns: [SchemaColumn]) {
|
||||
self.name = name
|
||||
self.rows = rows
|
||||
self.columns = columns
|
||||
}
|
||||
|
||||
/// The row count with en-US thousands separators, or empty when unknown.
|
||||
public var rowsLabel: String {
|
||||
SchemaFormat.count(rows)
|
||||
}
|
||||
|
||||
public var cardHeight: Double {
|
||||
SchemaGeometry.cardHeight(columns: columns.count)
|
||||
}
|
||||
}
|
||||
|
||||
/// One relationship line: from a foreign-key column to the column it references.
|
||||
public struct SchemaEdge: Sendable, Hashable {
|
||||
public var from: String
|
||||
public var column: String
|
||||
public var columnIndex: Int
|
||||
public var to: String
|
||||
public var targetColumnIndex: Int
|
||||
|
||||
public init(from: String, column: String, columnIndex: Int, to: String, targetColumnIndex: Int) {
|
||||
self.from = from
|
||||
self.column = column
|
||||
self.columnIndex = columnIndex
|
||||
self.to = to
|
||||
self.targetColumnIndex = targetColumnIndex
|
||||
}
|
||||
|
||||
/// `table.column` of the foreign-key end; unique within a model.
|
||||
public var id: String { from + "." + column }
|
||||
}
|
||||
|
||||
/// What the Schema view draws, derived from a dump.
|
||||
public struct SchemaModel: Sendable, Equatable {
|
||||
/// `mysql · odynt`: the driver (else the connection name) and the database.
|
||||
public var connectionLabel: String
|
||||
/// The dump's `generated_at` as written.
|
||||
public var generatedAt: String?
|
||||
/// Sorted by name.
|
||||
public var tables: [SchemaTable]
|
||||
public var edges: [SchemaEdge]
|
||||
|
||||
public init(connectionLabel: String, generatedAt: String? = nil, tables: [SchemaTable], edges: [SchemaEdge]) {
|
||||
self.connectionLabel = connectionLabel
|
||||
self.generatedAt = generatedAt
|
||||
self.tables = tables
|
||||
self.edges = edges
|
||||
}
|
||||
|
||||
/// Edges whose target table is not in the dump are dropped; a multi-column key draws one line from its first column.
|
||||
public init(dump: SchemaDump) {
|
||||
let sortedTables = dump.tables.sorted { $0.name < $1.name }
|
||||
var seen = Set<String>()
|
||||
let unique = sortedTables.filter { seen.insert($0.name).inserted }
|
||||
let raw = Dictionary(uniqueKeysWithValues: unique.map { ($0.name, $0) })
|
||||
let tables = unique.map(Self.table)
|
||||
let byName = Dictionary(uniqueKeysWithValues: tables.map { ($0.name, $0) })
|
||||
|
||||
var edges: [SchemaEdge] = []
|
||||
var edgeIDs = Set<String>()
|
||||
for table in tables {
|
||||
for key in raw[table.name]?.foreignKeys ?? [] {
|
||||
guard let first = key.columns.first,
|
||||
let columnIndex = table.columns.firstIndex(where: { $0.name == first }),
|
||||
let target = byName[key.foreignTable] else { continue }
|
||||
let edge = SchemaEdge(from: table.name, column: first, columnIndex: columnIndex, to: target.name,
|
||||
targetColumnIndex: Self.targetIndex(in: target, column: key.foreignColumns.first))
|
||||
if edgeIDs.insert(edge.id).inserted { edges.append(edge) }
|
||||
}
|
||||
}
|
||||
|
||||
self.init(connectionLabel: Self.connectionLabel(dump), generatedAt: dump.generatedAt, tables: tables, edges: edges)
|
||||
}
|
||||
|
||||
public var tableCount: Int { tables.count }
|
||||
public var columnCount: Int { tables.reduce(0) { $0 + $1.columns.count } }
|
||||
public var relationCount: Int { edges.count }
|
||||
|
||||
public func table(named name: String) -> SchemaTable? {
|
||||
tables.first { $0.name == name }
|
||||
}
|
||||
|
||||
/// Belongs to: the edges leaving `table`.
|
||||
public func outgoing(from table: String) -> [SchemaEdge] {
|
||||
edges.filter { $0.from == table }
|
||||
}
|
||||
|
||||
/// Has many: the edges arriving at `table`.
|
||||
public func incoming(to table: String) -> [SchemaEdge] {
|
||||
edges.filter { $0.to == table }
|
||||
}
|
||||
|
||||
/// `generatedAt` parsed as ISO 8601, with or without fractional seconds.
|
||||
public var generatedDate: Date? {
|
||||
guard let generatedAt else { return nil }
|
||||
let plain = ISO8601DateFormatter()
|
||||
if let date = plain.date(from: generatedAt) { return date }
|
||||
let fractional = ISO8601DateFormatter()
|
||||
fractional.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
||||
return fractional.date(from: generatedAt)
|
||||
}
|
||||
|
||||
private static func connectionLabel(_ dump: SchemaDump) -> String {
|
||||
let engine = nonEmpty(dump.driver) ?? nonEmpty(dump.connection)
|
||||
switch (engine, nonEmpty(dump.database)) {
|
||||
case let (engine?, database?): return engine + " · " + database
|
||||
case let (engine?, nil): return engine
|
||||
case let (nil, database?): return database
|
||||
case (nil, nil): return "database"
|
||||
}
|
||||
}
|
||||
|
||||
private static func nonEmpty(_ text: String?) -> String? {
|
||||
guard let text, !text.isEmpty else { return nil }
|
||||
return text
|
||||
}
|
||||
|
||||
private static func table(_ raw: SchemaDump.Table) -> SchemaTable {
|
||||
var primary = Set(raw.indexes.filter(\.primary).flatMap(\.columns))
|
||||
if primary.isEmpty, let auto = raw.columns.first(where: \.autoIncrement) { primary.insert(auto.name) }
|
||||
let unique = Set(raw.indexes.filter { $0.unique && !$0.primary && $0.columns.count == 1 }.flatMap(\.columns))
|
||||
var targets: [String: SchemaColumnRef] = [:]
|
||||
for key in raw.foreignKeys {
|
||||
for (offset, column) in key.columns.enumerated() where targets[column] == nil {
|
||||
let foreign = offset < key.foreignColumns.count ? key.foreignColumns[offset] : (key.foreignColumns.first ?? "id")
|
||||
targets[column] = SchemaColumnRef(table: key.foreignTable, column: foreign)
|
||||
}
|
||||
}
|
||||
let columns = raw.columns.map { column in
|
||||
let isPrimary = primary.contains(column.name)
|
||||
return SchemaColumn(
|
||||
name: column.name,
|
||||
type: nonEmpty(column.type) ?? nonEmpty(column.typeName) ?? "",
|
||||
isPrimary: isPrimary,
|
||||
isForeign: targets[column.name] != nil,
|
||||
isUnique: !isPrimary && unique.contains(column.name),
|
||||
isNullable: column.nullable,
|
||||
foreignTarget: targets[column.name]
|
||||
)
|
||||
}
|
||||
return SchemaTable(name: raw.name, rows: raw.rows, columns: columns)
|
||||
}
|
||||
|
||||
/// The referenced column, else the first primary column, else the first row.
|
||||
private static func targetIndex(in table: SchemaTable, column: String?) -> Int {
|
||||
if let column, let index = table.columns.firstIndex(where: { $0.name == column }) { return index }
|
||||
return table.columns.firstIndex(where: \.isPrimary) ?? 0
|
||||
}
|
||||
}
|
||||
|
||||
public enum SchemaFormat {
|
||||
/// `214,330`; empty for nil.
|
||||
public static func count(_ value: Int?) -> String {
|
||||
guard let value else { return "" }
|
||||
let formatter = NumberFormatter()
|
||||
formatter.locale = Locale(identifier: "en_US")
|
||||
formatter.numberStyle = .decimal
|
||||
return formatter.string(from: NSNumber(value: value)) ?? String(value)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import Foundation
|
||||
|
||||
/// Where the Schema view looks in a Laravel project, relative to the project root.
|
||||
public enum SchemaPaths {
|
||||
/// The command whose presence turns the Schema view on.
|
||||
public static let commandFile = "app/Console/Commands/HelderSchemaCommand.php"
|
||||
public static let dumpFile = "database/helder/schema.json"
|
||||
public static let artisanFile = "artisan"
|
||||
/// What the console echoes before a run.
|
||||
public static let commandLine = "php artisan helder:schema"
|
||||
}
|
||||
Reference in New Issue
Block a user