SPB Git

Repository Public

SchemaMigration.swift 2.6 KB 60 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocFormats/SchemaMigration.swift3// Description: JSON-level schema migrations of document.json: one step per source version, applied in sequence before decoding.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import DocModel9import DocContainer1011/// Upgrades the JSON form of a document from the schema version it was written with to the current one.12///13/// A step is registered under the version it upgrades FROM and returns the document at the next version. Steps work on the14/// untyped JSON tree so they keep running after the Swift model has moved on.15/// Only schema 1 exists today, so `standard` has no step; the pipeline is exercised in tests through the internal initialiser.16public struct SchemaMigrator: Sendable {17    public typealias Step = @Sendable ([String: Any]) throws -> [String: Any]1819    public let targetVersion: Int20    let steps: [Int: Step]2122    /// The migrations shipped with this build.23    public static let standard = SchemaMigrator(steps: [:], targetVersion: DocumentModel.currentSchemaVersion)2425    init(steps: [Int: Step], targetVersion: Int) {26        self.steps = steps27        self.targetVersion = targetVersion28    }2930    /// Versions this migrator can read.31    public func canRead(_ version: Int) -> Bool {32        guard version <= targetVersion else { return false }33        var v = version34        while v < targetVersion { guard steps[v] != nil else { return false }; v += 1 }35        return true36    }3738    /// Runs every step from the document's version to `targetVersion`. Returns the upgraded tree and the versions migrated from.39    public func migrate(_ json: [String: Any]) throws -> (json: [String: Any], applied: [Int]) {40        guard let number = json["schemaVersion"] as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(),41              Double(number.intValue) == number.doubleValue else {42            throw FormatError.unreadable("document.json has no schema version")43        }44        var version = number.intValue45        guard version <= targetVersion else { throw FormatError.unsupportedVersion(version) }46        var tree = json47        var applied: [Int] = []48        while version < targetVersion {49            guard let step = steps[version] else {50                throw FormatError.unreadable("no migration is available from document schema \(version)")51            }52            tree = try step(tree)53            applied.append(version)54            version += 155            tree["schemaVersion"] = version56        }57        return (tree, applied)58    }59}60
Files main
Menu

Theme