Files
helder/Sources/HelderCore/Schema/SchemaDump.swift
T

278 lines
11 KiB
Swift

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