adds schema view and schema generating command

This commit is contained in:
2026-11-03 09:35:41 +01:00
parent cc41decccb
commit 600d4874d2
62 changed files with 4416 additions and 105 deletions
@@ -0,0 +1,42 @@
import Foundation
import HelderCore
import Testing
@Suite struct ArtisanConsoleTests {
@Test("stdout lines are classified", arguments: [
(" Connection ............................ mysql · odynt", ArtisanLineKind.output),
(" Tables ................................ 16", .output),
(" INFO Wrote database/helder/schema.json (18.4 KB).", .success),
(" Wrote database/helder/schema.json (18.4 KB)", .success),
(" DONE Schema dumped in 0.41s.", .success),
(" ERROR SQLSTATE[HY000] [2002] Connection refused.", .error),
(" Illuminate\\Database\\QueryException", .error),
("", .output),
])
func classify(line: String, expected: ArtisanLineKind) {
#expect(ArtisanOutputClassifier.classify(line, isError: false) == expected)
}
@Test func everyStderrLineIsAnError() {
#expect(ArtisanOutputClassifier.classify("PHP Warning: something", isError: true) == .error)
#expect(ArtisanOutputClassifier.line(" DONE x", isError: true) == ArtisanConsoleLine(text: " DONE x", kind: .error))
}
@Test func theEchoAndPathsMatchTheCommand() {
#expect(ArtisanOutputClassifier.commandEcho == "$ php artisan helder:schema")
#expect(SchemaPaths.commandFile == "app/Console/Commands/HelderSchemaCommand.php")
#expect(SchemaPaths.dumpFile == "database/helder/schema.json")
#expect(SchemaPaths.artisanFile == "artisan")
}
@Test func thePromptNamesTheFileTheContractAndTheIgnoreFile() {
let text = SchemaCommandPrompt.text
#expect(text.hasPrefix("Build an Artisan command that dumps this app's database schema for Helder"))
#expect(text.contains("Class: App\\Console\\Commands\\HelderSchemaCommand, extends Illuminate\\Console\\Command"))
#expect(text.contains("File: " + SchemaPaths.commandFile))
#expect(text.contains("\"foreign_keys\": [ <Schema::getForeignKeys($table), unchanged> ]"))
#expect(text.contains("`*` and `!.gitignore`"))
#expect(text.hasSuffix("run `php artisan helder:schema` once and show me the output."))
#expect(text.contains("\n{\n \"version\": 1,\n"))
}
}
@@ -0,0 +1,85 @@
import Foundation
import HelderCore
import Testing
@Suite struct SchemaDumpTests {
private func decode(_ json: String) throws -> SchemaDump {
try SchemaDump.decode(Data(json.utf8))
}
// MARK: decoding
@Test func theFullContractDecodes() throws {
let dump = try decode(SchemaFixtures.contract)
#expect(dump.version == 1)
#expect(dump.connection == "mysql")
#expect(dump.driver == "mysql")
#expect(dump.database == "odynt")
#expect(dump.generatedAt == "2026-11-02T14:32:05+01:00")
#expect(dump.tables.map(\.name) == ["users", "messages", "conversations"])
let users = try #require(dump.tables.first)
#expect(users.rows == 1284)
#expect(users.columns[0] == SchemaDump.Column(name: "id", typeName: "bigint", type: "bigint unsigned", autoIncrement: true))
#expect(users.indexes[1] == SchemaDump.Index(name: "users_email_unique", columns: ["email"], type: "btree", unique: true))
let messages = dump.tables[1]
#expect(messages.columns[2].comment == "the body")
#expect(messages.foreignKeys == [SchemaDump.ForeignKey(
name: "messages_conversation_id_foreign", columns: ["conversation_id"], foreignSchema: "odynt",
foreignTable: "conversations", foreignColumns: ["id"], onUpdate: "no action", onDelete: "cascade")])
#expect(dump.tables[2].rows == nil)
#expect(dump.tables[2].columns[2].defaultValue == "0")
}
@Test func theOlderPrototypeShapeDecodes() throws {
let dump = try decode("""
{"connection": "mysql", "generated_at": "2026-10-01T09:00:00+00:00",
"tables": [{"name": "users", "columns": [{"name": "id", "type_name": "bigint", "type": "bigint", "nullable": false}],
"indexes": [{"name": "primary", "columns": ["id"], "unique": true, "primary": true}], "foreign_keys": []}]}
""")
#expect(dump.version == nil)
#expect(dump.driver == nil)
#expect(dump.database == nil)
#expect(dump.tables.count == 1)
#expect(dump.tables[0].rows == nil)
#expect(SchemaModel(dump: dump).connectionLabel == "mysql")
}
@Test func missingKeysGetTheirDefaults() throws {
let dump = try decode(#"{"tables": [{"name": "t", "columns": [{"name": "a"}], "indexes": [{"columns": ["a"], "primary": true}]}]}"#)
let table = try #require(dump.tables.first)
#expect(table.foreignKeys == [])
#expect(table.columns == [SchemaDump.Column(name: "a")])
#expect(table.indexes[0].unique)
#expect(try decode("{}") == SchemaDump(version: nil))
}
@Test func unknownKeysAndBrokenItemsAreSkipped() throws {
let dump = try decode("""
{"version": "1", "extra": {"x": 1}, "tables": [
{"columns": []},
"not a table",
{"name": "t", "rows": "12", "columns": [{"type": "int"}, {"name": "a", "nullable": 1, "default": 5, "auto_increment": "1"}],
"foreign_keys": [{"columns": ["a"]}, {"columns": ["a"], "foreign_table": "u"}]}
]}
""")
#expect(dump.version == 1)
#expect(dump.tables.map(\.name) == ["t"])
let table = dump.tables[0]
#expect(table.rows == 12)
#expect(table.columns == [SchemaDump.Column(name: "a", nullable: true, defaultValue: "5", autoIncrement: true)])
#expect(table.foreignKeys == [SchemaDump.ForeignKey(columns: ["a"], foreignTable: "u")])
}
@Test("corrupt data throws a readable error", arguments: ["", "{\"tables\": [", "[1, 2]", "not json"])
func corrupt(json: String) {
#expect {
try decode(json)
} throws: { error in
guard let error = error as? SchemaDumpError, case .corrupt = error else { return false }
return error.localizedDescription.hasPrefix("database/helder/schema.json is not a valid schema dump:")
}
}
}
@@ -0,0 +1,80 @@
import Foundation
import HelderCore
enum SchemaFixtures {
/// A version 1 dump as the command writes it: users ← conversations ← messages, plus a unique email.
static let contract = #"""
{
"version": 1,
"connection": "mysql",
"driver": "mysql",
"database": "odynt",
"generated_at": "2026-11-02T14:32:05+01:00",
"tables": [
{
"name": "users",
"rows": 1284,
"columns": [
{"name": "id", "type_name": "bigint", "type": "bigint unsigned", "collation": null, "nullable": false, "default": null, "auto_increment": true, "comment": null, "generation": null},
{"name": "email", "type_name": "varchar", "type": "varchar(255)", "nullable": false, "default": null, "auto_increment": false, "comment": null},
{"name": "email_verified_at", "type_name": "timestamp", "type": "timestamp", "nullable": true, "default": null, "auto_increment": false, "comment": null}
],
"indexes": [
{"name": "primary", "columns": ["id"], "type": "btree", "unique": true, "primary": true},
{"name": "users_email_unique", "columns": ["email"], "type": "btree", "unique": true, "primary": false}
],
"foreign_keys": []
},
{
"name": "messages",
"rows": 214330,
"columns": [
{"name": "id", "type_name": "bigint", "type": "bigint unsigned", "nullable": false, "default": null, "auto_increment": true, "comment": null},
{"name": "conversation_id", "type_name": "bigint", "type": "bigint unsigned", "nullable": false, "default": null, "auto_increment": false, "comment": null},
{"name": "content", "type_name": "longtext", "type": "longtext", "nullable": false, "default": null, "auto_increment": false, "comment": "the body"}
],
"indexes": [
{"name": "primary", "columns": ["id"], "type": "btree", "unique": true, "primary": true}
],
"foreign_keys": [
{"name": "messages_conversation_id_foreign", "columns": ["conversation_id"], "foreign_schema": "odynt", "foreign_table": "conversations", "foreign_columns": ["id"], "on_update": "no action", "on_delete": "cascade"}
]
},
{
"name": "conversations",
"rows": null,
"columns": [
{"name": "id", "type_name": "bigint", "type": "bigint unsigned", "nullable": false, "default": null, "auto_increment": true, "comment": null},
{"name": "user_id", "type_name": "bigint", "type": "bigint unsigned", "nullable": true, "default": null, "auto_increment": false, "comment": null},
{"name": "archived", "type_name": "tinyint", "type": "tinyint(1)", "nullable": false, "default": "0", "auto_increment": false, "comment": null},
{"name": "ghost_id", "type_name": "bigint", "type": "bigint", "nullable": true, "default": null, "auto_increment": false, "comment": null}
],
"indexes": [
{"name": "primary", "columns": ["id"], "type": "btree", "unique": true, "primary": true}
],
"foreign_keys": [
{"name": "conversations_user_id_foreign", "columns": ["user_id"], "foreign_schema": "odynt", "foreign_table": "users", "foreign_columns": ["id"], "on_update": "no action", "on_delete": "set null"},
{"name": "conversations_ghost_id_foreign", "columns": ["ghost_id"], "foreign_schema": "odynt", "foreign_table": "ghosts", "foreign_columns": ["id"], "on_update": "no action", "on_delete": "cascade"}
]
}
]
}
"""#
static var contractModel: SchemaModel {
SchemaModel(dump: try! SchemaDump.decode(Data(contract.utf8)))
}
/// A table with `count` plain columns, the first one primary.
static func table(_ name: String, columns count: Int = 2) -> SchemaTable {
SchemaTable(name: name, columns: (0..<count).map { SchemaColumn(name: "c\($0)", type: "int", isPrimary: $0 == 0) })
}
static func edge(_ from: String, _ to: String, column: String = "c1", index: Int = 1) -> SchemaEdge {
SchemaEdge(from: from, column: column, columnIndex: index, to: to, targetColumnIndex: 0)
}
static func model(_ names: [String], edges: [SchemaEdge], columns: Int = 2) -> SchemaModel {
SchemaModel(connectionLabel: "test", tables: names.sorted().map { table($0, columns: columns) }, edges: edges)
}
}
@@ -0,0 +1,95 @@
import Foundation
import HelderCore
import Testing
@Suite struct SchemaGeometryTests {
private func p(_ x: Double, _ y: Double) -> SchemaPoint { SchemaPoint(x: x, y: y) }
@Test func cardSizesMatchTheCard() {
#expect(SchemaGeometry.cardHeight(columns: 0) == 35)
#expect(SchemaGeometry.cardHeight(columns: 3) == 101)
#expect(SchemaGeometry.columnCentreY(top: 100, index: 0) == 145)
#expect(SchemaGeometry.columnCentreY(top: 100, index: 2) == 189)
}
@Test func aTargetToTheRightLeavesTheRightEdgeAndEntersTheLeft() {
let path = SchemaGeometry.edgePath(from: p(40, 40), columnIndex: 1, to: p(380, 40), targetColumnIndex: 0)
#expect(path == SchemaEdgePath(start: p(280, 107), control1: p(330, 107), control2: p(330, 85), end: p(380, 85)))
}
@Test func aTargetToTheLeftIsTheMirror() {
let path = SchemaGeometry.edgePath(from: p(380, 40), columnIndex: 0, to: p(40, 100), targetColumnIndex: 0)
#expect(path == SchemaEdgePath(start: p(380, 85), control1: p(330, 85), control2: p(330, 145), end: p(280, 145)))
}
@Test func aNearTargetStillCurvesAtLeastFortyPoints() {
let path = SchemaGeometry.edgePath(from: p(0, 0), columnIndex: 0, to: p(250, 0), targetColumnIndex: 0)
#expect(path.control1.x == 280)
#expect(path.control2.x == 210)
}
@Test func theSameLaneLoopsOutOnTheRight() {
let path = SchemaGeometry.edgePath(from: p(40, 40), columnIndex: 2, to: p(100, 300), targetColumnIndex: 0)
let loop = 46 + 216 * 0.12
#expect(path == SchemaEdgePath(start: p(280, 129), control1: p(280 + loop, 129), control2: p(340 + loop, 345), end: p(340, 345)))
}
@Test func centresExactlyOneCardApartAreNotTheSameLane() {
let path = SchemaGeometry.edgePath(from: p(0, 0), columnIndex: 0, to: p(240, 0), targetColumnIndex: 0)
#expect(path.end.x == 240)
}
@Test func anEdgeWithAnUnplacedTableHasNoPath() {
let edge = SchemaFixtures.edge("a", "b")
#expect(SchemaGeometry.edgePath(edge, positions: ["a": p(0, 0)]) == nil)
#expect(SchemaGeometry.edgePath(edge, positions: ["a": p(0, 0), "b": p(400, 0)])?.start == p(240, 67))
}
@Test func boundsHoldEveryPlacedCard() {
let model = SchemaFixtures.model(["a", "b", "c"], edges: [])
let bounds = SchemaGeometry.bounds(model, positions: ["a": p(40, 40), "b": p(400, 10)])
#expect(bounds == SchemaRect(x: 40, y: 10, width: 600, height: 109))
#expect(SchemaGeometry.bounds(model, positions: [:]) == nil)
}
@Test func fitCentresAndCapsTheScale() {
let view = SchemaGeometry.fit(bounds: SchemaRect(x: 40, y: 40, width: 240, height: 200), in: SchemaSize(width: 1000, height: 800))
#expect(view == SchemaViewport(x: 291, y: 246, scale: 1.1))
}
@Test func fitNeverGoesBelowThirtyPercent() {
let view = SchemaGeometry.fit(bounds: SchemaRect(x: 0, y: 0, width: 5000, height: 5000), in: SchemaSize(width: 200, height: 200))
#expect(view.scale == 0.3)
}
@Test func fitShrinksToTheTighterSide() {
let view = SchemaGeometry.fit(bounds: SchemaRect(x: 0, y: 0, width: 1940, height: 400), in: SchemaSize(width: 1096, height: 800))
#expect(view.scale == 0.5)
#expect(view.x == 48)
}
@Test func zoomKeepsThePointUnderTheAnchor() {
let view = SchemaViewport(x: 30, y: -20, scale: 0.8)
let anchor = p(300, 200)
let before = SchemaGeometry.canvasPoint(anchor, in: view)
let zoomed = SchemaGeometry.zoom(view, by: 1.2, around: anchor)
let after = SchemaGeometry.canvasPoint(anchor, in: zoomed)
#expect(abs(zoomed.scale - 0.96) < 1e-9)
#expect(abs(before.x - after.x) < 1e-9)
#expect(abs(before.y - after.y) < 1e-9)
}
@Test func zoomIsClampedBetweenThirtyAndTwoHundredPercent() {
let view = SchemaViewport(x: 0, y: 0, scale: 1)
#expect(SchemaGeometry.zoom(view, by: 10, around: p(0, 0)).scale == 2)
#expect(SchemaGeometry.zoom(view, by: 0.01, around: p(0, 0)).scale == 0.3)
#expect(SchemaGeometry.zoom(view, by: 2, in: SchemaSize(width: 200, height: 200)) == SchemaViewport(x: -100, y: -100, scale: 2))
#expect(SchemaViewport(scale: 0.96).percentLabel == "96%")
}
@Test func centreKeepsTheScaleAndRounds() {
let table = SchemaFixtures.table("a")
let view = SchemaGeometry.centre(table, at: p(100, 200), in: SchemaSize(width: 800, height: 600), view: SchemaViewport(x: 5, y: 5, scale: 1))
#expect(view == SchemaViewport(x: 180, y: 61, scale: 1))
}
}
@@ -0,0 +1,90 @@
import Foundation
import HelderCore
import Testing
@Suite struct SchemaHighlightTests {
private let model = SchemaFixtures.contractModel
private func highlight(hovered: String? = nil, selected: String? = nil, column: String? = nil, query: String = "") -> SchemaHighlight {
SchemaHighlight(model: model, hovered: hovered, selected: selected, hoveredColumn: column, query: query)
}
private func ref(_ table: String, _ column: String) -> SchemaColumnRef {
SchemaColumnRef(table: table, column: column)
}
@Test func nothingFocusedHighlightsNothing() {
let h = highlight()
#expect(h.focus == nil)
#expect(h.activeEdges.isEmpty)
#expect(h.relatedTables.isEmpty)
#expect(h.dimmedTables.isEmpty)
#expect(h.highlightedColumns.isEmpty)
#expect(!h.linesRecede)
#expect(h.opacity(of: "users") == 1)
}
@Test func hoveringATableLightsEveryLineInAndOut() {
let h = highlight(hovered: "conversations")
#expect(h.activeEdges == ["conversations.user_id", "messages.conversation_id"])
#expect(h.relatedTables == ["conversations", "users", "messages"])
#expect(h.dimmedTables.isEmpty)
#expect(h.highlightedColumns == [ref("conversations", "user_id"), ref("users", "id"),
ref("messages", "conversation_id"), ref("conversations", "id")])
#expect(h.linesRecede)
}
@Test func unrelatedTablesDim() {
let h = highlight(hovered: "users")
#expect(h.activeEdges == ["conversations.user_id"])
#expect(h.relatedTables == ["users", "conversations"])
#expect(h.dimmedTables == ["messages"])
#expect(h.opacity(of: "messages") == 0.3)
#expect(h.isHighlighted(table: "users", column: "id"))
#expect(!h.isHighlighted(table: "conversations", column: "id"))
}
@Test func aHoveredKeyNarrowsToItsOneRelationship() {
let h = highlight(hovered: "conversations", column: "conversations.user_id")
#expect(h.activeEdges == ["conversations.user_id"])
#expect(h.relatedTables == ["conversations", "users"])
#expect(h.dimmedTables == ["messages"])
}
@Test func theHoverWinsOverTheSelection() {
#expect(highlight(selected: "users").focus == "users")
let h = highlight(hovered: "messages", selected: "users")
#expect(h.focus == "messages")
#expect(h.dimmedTables == ["users"])
}
@Test func aTableWithoutLinesKeepsOnlyItself() {
let lonely = SchemaFixtures.model(["a", "b"], edges: [])
let h = SchemaHighlight(model: lonely, hovered: "a", selected: nil, hoveredColumn: nil, query: "")
#expect(h.relatedTables == ["a"])
#expect(h.dimmedTables == ["b"])
}
@Test func searchDimsTheRestOnlyWithoutFocus() {
let h = highlight(query: " CON ")
#expect(h.searchMatches == ["conversations"])
#expect(h.dimmedTables == ["messages", "users"])
#expect(h.linesRecede)
let focused = highlight(hovered: "users", query: "con")
#expect(focused.searchMatches == ["conversations"])
#expect(focused.dimmedTables == ["messages"])
}
@Test func activeLinesAreDrawnLast() {
let h = highlight(hovered: "users")
#expect(h.drawingOrder(model.edges).map(\.id) == ["messages.conversation_id", "conversations.user_id"])
}
@Test func theTableListFiltersBySubstring() {
#expect(SchemaSearch.filter(model, query: "S").map(\.name) == ["conversations", "messages", "users"])
#expect(SchemaSearch.filter(model, query: "mess").map(\.name) == ["messages"])
#expect(SchemaSearch.filter(model, query: " ").count == 3)
#expect(SchemaSearch.listLabel(model, query: "") == "[ TABLES ] 3")
#expect(SchemaSearch.listLabel(model, query: "user") == "[ TABLES ] 1 of 3")
}
}
@@ -0,0 +1,71 @@
import Foundation
import HelderCore
import Testing
@Suite struct SchemaLayoutTests {
private typealias F = SchemaFixtures
@Test func lanesFollowTheForeignKeyDepth() {
#expect(SchemaLayout.lanes(F.contractModel) == ["users": 0, "conversations": 1, "messages": 2])
}
@Test func aTableTakesTheLaneAfterItsDeepestTarget() {
let model = F.model(["a", "b", "c"], edges: [F.edge("c", "a"), F.edge("c", "b", column: "c0", index: 0), F.edge("b", "a")])
#expect(SchemaLayout.lanes(model) == ["a": 0, "b": 1, "c": 2])
}
@Test func aSelfReferenceIsIgnored() {
let model = F.model(["a", "b"], edges: [F.edge("a", "a"), F.edge("b", "a", column: "c0", index: 0)])
#expect(SchemaLayout.lanes(model) == ["a": 0, "b": 1])
}
@Test func aCycleIsBrokenWhereItCloses() {
let model = F.model(["a", "b", "c"], edges: [F.edge("a", "b"), F.edge("b", "c"), F.edge("c", "a")])
#expect(SchemaLayout.lanes(model) == ["c": 0, "b": 1, "a": 2])
}
@Test func lanesAreSpacedAndCentredAgainstTheTallest() {
let model = F.model(["a", "b", "x"], edges: [F.edge("x", "a")])
let positions = SchemaLayout.defaultPositions(model)
// Cards of two columns are 79 tall: lane 0 holds two (254 with gaps), lane 1 one (127).
#expect(positions["a"] == SchemaPoint(x: 40, y: 40))
#expect(positions["b"] == SchemaPoint(x: 40, y: 167))
#expect(positions["x"] == SchemaPoint(x: 380, y: 104))
}
@Test func aLaneIsOrderedByTheHeightOfItsTargets() {
let model = F.model(["a", "b", "x", "y"], edges: [F.edge("x", "b"), F.edge("y", "a")])
let positions = SchemaLayout.defaultPositions(model)
#expect(positions["y"]!.y < positions["x"]!.y)
}
@Test func cardsInALaneDoNotOverlap() {
let model = F.model(["a", "b", "c", "d"], edges: [], columns: 5)
let ys = SchemaLayout.defaultPositions(model).values.map(\.y).sorted()
for (upper, lower) in zip(ys, ys.dropFirst()) {
#expect(lower - upper == SchemaGeometry.cardHeight(columns: 5) + SchemaMetrics.cardGap)
}
}
@Test func theLayoutIsDeterministic() {
let edges = [F.edge("a", "b"), F.edge("b", "a"), F.edge("c", "a"), F.edge("d", "c"), F.edge("e", "e")]
let model = F.model(["a", "b", "c", "d", "e"], edges: edges)
let reversed = SchemaModel(connectionLabel: "test", tables: model.tables.reversed(), edges: edges.reversed())
let first = SchemaLayout.defaultPositions(model)
#expect(first.count == 5)
#expect(SchemaLayout.defaultPositions(model) == first)
#expect(SchemaLayout.defaultPositions(reversed) == first)
}
@Test func anEmptyModelHasNoPositions() {
#expect(SchemaLayout.defaultPositions(F.model([], edges: [])).isEmpty)
}
@Test func savedPositionsWinForTablesThatStillExist() {
let model = F.model(["a", "b"], edges: [])
let positions = SchemaLayout.positions(model, saved: ["a": SchemaPoint(x: 1, y: 2), "gone": SchemaPoint(x: 9, y: 9)])
#expect(positions["a"] == SchemaPoint(x: 1, y: 2))
#expect(positions["b"] == SchemaLayout.defaultPositions(model)["b"])
#expect(positions["gone"] == nil)
}
}
@@ -0,0 +1,96 @@
import Foundation
import HelderCore
import Testing
@Suite struct SchemaModelTests {
@Test func tablesAreSortedAndCounted() {
let model = SchemaFixtures.contractModel
#expect(model.tables.map(\.name) == ["conversations", "messages", "users"])
#expect(model.connectionLabel == "mysql · odynt")
#expect(model.tableCount == 3)
#expect(model.columnCount == 10)
#expect(model.relationCount == 2)
#expect(model.generatedDate == ISO8601DateFormatter().date(from: "2026-11-02T13:32:05Z"))
}
@Test func columnsCarryTheirKeys() throws {
let model = SchemaFixtures.contractModel
let users = try #require(model.table(named: "users"))
#expect(users.columns[0] == SchemaColumn(name: "id", type: "bigint unsigned", isPrimary: true))
#expect(users.columns[1].isUnique)
#expect(users.columns[1].keyLabel == "UQ")
#expect(users.columns[2].displayType == "timestamp?")
#expect(users.rowsLabel == "1,284")
let conversations = try #require(model.table(named: "conversations"))
let userID = conversations.columns[1]
#expect(userID.isForeign)
#expect(userID.foreignTarget == SchemaColumnRef(table: "users", column: "id"))
#expect(userID.keyLabel == "FK")
#expect(userID.flags == "FK → users.id · NULL")
#expect(conversations.columns[0].flags == "PRIMARY · NOT NULL")
#expect(users.columns[1].flags == "UNIQUE · NOT NULL")
#expect(conversations.rowsLabel == "")
#expect(model.table(named: "messages")?.rowsLabel == "214,330")
}
@Test func edgesPointAtTheReferencedRowAndSkipMissingTables() {
let model = SchemaFixtures.contractModel
#expect(model.edges == [
SchemaEdge(from: "conversations", column: "user_id", columnIndex: 1, to: "users", targetColumnIndex: 0),
SchemaEdge(from: "messages", column: "conversation_id", columnIndex: 1, to: "conversations", targetColumnIndex: 0),
])
#expect(model.outgoing(from: "conversations").map(\.to) == ["users"])
#expect(model.incoming(to: "conversations").map(\.from) == ["messages"])
// The ghost_id key points at a table that is not in the dump: still a FK column, but no line.
#expect(model.table(named: "conversations")?.columns[3].isForeign == true)
}
@Test func theTargetRowFallsBackToThePrimaryKeyThenTheFirstRow() {
let dump = SchemaDump(tables: [
.init(name: "a", columns: [.init(name: "code"), .init(name: "uuid")],
indexes: [.init(columns: ["uuid"], primary: true)]),
.init(name: "b", columns: [.init(name: "x")]),
.init(name: "c", columns: [.init(name: "id"), .init(name: "a_ref"), .init(name: "b_ref")],
foreignKeys: [.init(columns: ["a_ref"], foreignTable: "a", foreignColumns: ["missing"]),
.init(columns: ["b_ref"], foreignTable: "b")]),
])
let edges = SchemaModel(dump: dump).edges
#expect(edges.map(\.targetColumnIndex) == [1, 0])
}
@Test func aKeyOnAColumnThatIsNotListedDrawsNoLine() {
let dump = SchemaDump(tables: [
.init(name: "a", columns: [.init(name: "id")]),
.init(name: "b", columns: [.init(name: "id")], foreignKeys: [.init(columns: ["a_id"], foreignTable: "a")]),
])
#expect(SchemaModel(dump: dump).edges.isEmpty)
}
@Test func theTypeFallsBackToTheTypeName() {
let dump = SchemaDump(tables: [.init(name: "t", columns: [.init(name: "a", typeName: "int"), .init(name: "b")])])
#expect(SchemaModel(dump: dump).tables[0].columns.map(\.type) == ["int", ""])
}
@Test func anAutoIncrementColumnIsPrimaryWhenNoIndexSaysSo() {
let dump = SchemaDump(tables: [.init(name: "t", columns: [.init(name: "id", autoIncrement: true), .init(name: "a")])])
#expect(SchemaModel(dump: dump).tables[0].columns.map(\.isPrimary) == [true, false])
}
@Test func aCompositeUniqueIndexDoesNotMarkItsColumns() {
let dump = SchemaDump(tables: [.init(name: "t", columns: [.init(name: "a"), .init(name: "b")],
indexes: [.init(columns: ["a", "b"], unique: true)])])
#expect(SchemaModel(dump: dump).tables[0].columns.map(\.isUnique) == [false, false])
}
@Test("the connection label falls back", arguments: [
(SchemaDump(connection: "main", driver: "pgsql", database: "shop"), "pgsql · shop"),
(SchemaDump(connection: "main", database: "shop"), "main · shop"),
(SchemaDump(connection: "main", driver: ""), "main"),
(SchemaDump(database: "shop"), "shop"),
(SchemaDump(), "database"),
])
func connectionLabel(dump: SchemaDump, expected: String) {
#expect(SchemaModel(dump: dump).connectionLabel == expected)
}
}