Files

229 lines
8.9 KiB
Swift

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)
}
}