From 522639282deae880cff3a8a0fccaa08602afacce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Feb 2020 14:03:12 +0100 Subject: [PATCH] Update JSONSynchronization playground --- .../Contents.swift | 52 ++-- .../Sources/SortedDifference.swift | 245 ++++++++++++++++++ .../Sources/sortedMerge.swift | 88 ------- 3 files changed, 276 insertions(+), 109 deletions(-) create mode 100644 Documentation/Playgrounds/JSONSynchronization.playground/Sources/SortedDifference.swift delete mode 100644 Documentation/Playgrounds/JSONSynchronization.playground/Sources/sortedMerge.swift diff --git a/Documentation/Playgrounds/JSONSynchronization.playground/Contents.swift b/Documentation/Playgrounds/JSONSynchronization.playground/Contents.swift index 553c57dd8..979ebeb7b 100644 --- a/Documentation/Playgrounds/JSONSynchronization.playground/Contents.swift +++ b/Documentation/Playgrounds/JSONSynchronization.playground/Contents.swift @@ -35,7 +35,7 @@ try dbQueue.inDatabase { db in } -// Define the Player `Codable` that is a `FetchableRecord` and `MutablePersistableRecord`. +// Define the Player codable record type struct Player: Codable, FetchableRecord, MutablePersistableRecord { var id: Int64 var name: String @@ -54,40 +54,33 @@ struct Player: Codable, FetchableRecord, MutablePersistableRecord { } } -extension Player { - static func orderedById() -> QueryInterfaceRequest { - return order(Columns.id) - } -} - -// This is just the container of our incoming JSON -struct PlayersToSync: Codable { - let players: [Player] -} +// Make Player identifiable +extension Player: Identifiable { } // Synchronizes the players table with a JSON payload func synchronizePlayers(with jsonString: String, in db: Database) throws { + struct SyncData: Decodable { + let players: [Player] + } let jsonData = jsonString.data(using: .utf8)! - let dataToSync = try JSONDecoder().decode(PlayersToSync.self, from: jsonData) + let syncData = try JSONDecoder().decode(SyncData.self, from: jsonData) - // Sort new players to sync by id: - let playersToSync = dataToSync.players.sorted { $0.id < $1.id } + // Sort players to sync by id: + let playersToSync = syncData.players.sorted { $0.id < $1.id } // Sort database players by id: - let players = try Player.orderedById().fetchAll(db) + let players = try Player.orderByPrimaryKey().fetchAll(db) // Now that both lists are sorted by id, we can compare them with - // the sortedMerge() function (see https://gist.github.com/groue/7e8510849ded36f7d770). + // SortedDifference (see https://github.com/groue/SortedDifference). // // We'll delete, insert or update players, depending on their presence // in either lists. - for mergeStep in sortedMerge( + for change in SortedDifference( left: players, // Database players - right: playersToSync, // PlayersToSync players (Decoded) - leftKey: { $0.id }, // The id of a database player - rightKey: { $0.id }) // The id of a PlayersToSync player + right: playersToSync) // PlayersToSync players (Decoded) { - switch mergeStep { + switch change { case .left(let player): // Delete database player without matching JSON player: try player.delete(db) @@ -140,3 +133,20 @@ do { try synchronizePlayers(with: jsonString2, in: db) } } + +do { + let jsonString3 = """ + { + "players": [ + { "id": 2, "name": "Barbara", "score": 3000}, + { "id": 3, "name": "Craig", "score": 500}, + { "id": 4, "name": "Daniel", "score": 1500}, + ] + } + """ + print("---\nImport \(jsonString3)") + try dbQueue.inDatabase { db in + // SELECT * FROM player ORDER BY id + try synchronizePlayers(with: jsonString3, in: db) + } +} diff --git a/Documentation/Playgrounds/JSONSynchronization.playground/Sources/SortedDifference.swift b/Documentation/Playgrounds/JSONSynchronization.playground/Sources/SortedDifference.swift new file mode 100644 index 000000000..78303105e --- /dev/null +++ b/Documentation/Playgrounds/JSONSynchronization.playground/Sources/SortedDifference.swift @@ -0,0 +1,245 @@ +// Copyright (C) 2019 Gwendal Roué +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +/// Given two sequences (left and right), this sequence tells whether elements +/// are only found on the left, on the right, or on both sides. +public struct SortedDifference: Sequence where + LeftSequence: Sequence, + RightSequence: Sequence, + ID: Comparable +{ + private let left: LeftSequence + private let right: RightSequence + private let lID: (LeftSequence.Element) -> ID + private let rID: (RightSequence.Element) -> ID + + /// Given two sequences (left and right), returns a sequence which tells + /// whether elements are only found on the left, on the right, or on + /// both sides. + /// + /// Both input sequences do not have to share the same element type, but + /// their elements must share a common comparable id. + /// + /// For example: + /// + /// // Prints: + /// // - common(Left(id: 1), Right(id: 1)) + /// // - left(Left(id: 2)) + /// struct Left { var id: Int } + /// struct Right { var id: Int } + /// for change in SortedDifference( + /// left: [Left(id: 1), Left(id: 2)], + /// identifiedBy: { $0.id }, + /// right: [Right(id: 1)], + /// identifiedBy: { $0.id }) + /// { + /// print(change) + /// } + /// + /// - precondition: Both input sequences must be sorted by id. + /// - precondition: Ids must be unique in each sequences. + /// - parameters: + /// - left: The left sequence. + /// - right: The right sequence. + /// - leftID: A function that returns the id of a left element. + /// - rightID: A function that returns the id of a right element. + public init( + left: LeftSequence, + identifiedBy leftID: @escaping (LeftSequence.Element) -> ID, + right: RightSequence, + identifiedBy rightID: @escaping (RightSequence.Element) -> ID) + { + self.left = left + self.right = right + self.lID = leftID + self.rID = rightID + } + + public func makeIterator() -> Iterator { + Iterator( + lIterator: left.makeIterator(), + rIterator: right.makeIterator(), + lID: lID, + rID: rID) + } + + public struct Iterator: IteratorProtocol { + private var lIterator: LeftSequence.Iterator + private var rIterator: RightSequence.Iterator + private var lOpt: LeftSequence.Element? + private var rOpt: RightSequence.Element? + private let lID: (LeftSequence.Element) -> ID + private let rID: (RightSequence.Element) -> ID + + init( + lIterator: LeftSequence.Iterator, + rIterator: RightSequence.Iterator, + lID: @escaping (LeftSequence.Element) -> ID, + rID: @escaping (RightSequence.Element) -> ID) + { + self.lIterator = lIterator + self.rIterator = rIterator + self.lID = lID + self.rID = rID + self.lOpt = self.lIterator.next() + self.rOpt = self.rIterator.next() + } + + public mutating func next() -> SortedDifferenceChange? { + switch (lOpt, rOpt) { + case let (lElem?, rElem?): + let (lID, rID) = (self.lID(lElem), self.rID(rElem)) + if lID > rID { + rOpt = rIterator.next() + return .right(rElem) + } else if lID == rID { + (lOpt, rOpt) = (lIterator.next(), rIterator.next()) + return .common(lElem, rElem) + } else { + lOpt = lIterator.next() + return .left(lElem) + } + case let (nil, rElem?): + rOpt = rIterator.next() + return .right(rElem) + case let (lElem?, nil): + lOpt = lIterator.next() + return .left(lElem) + case (nil, nil): + return nil + } + } + } +} + +@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension SortedDifference where + LeftSequence.Element: Identifiable, + RightSequence.Element: Identifiable, + LeftSequence.Element.ID == ID, + RightSequence.Element.ID == ID +{ + /// Given two sequences (left and right), returns a sequence which tells + /// whether elements are only found on the left, on the right, or on + /// both sides. + /// + /// Both input sequences do not have to share the same element type, but + /// their elements must share a common comparable id. + /// + /// For example: + /// + /// // Prints: + /// // - common(Left(id: 1), Right(id: 1)) + /// // - left(Left(id: 2)) + /// struct Left: Identifiable { var id: Int } + /// struct Right: Identifiable { var id: Int } + /// for change in SortedDifference( + /// left: [Left(id: 1), Left(id: 2)], + /// right: [Right(id: 1)]) + /// { + /// print(change) + /// } + /// + /// - precondition: Both input sequences must be sorted by id. + /// - precondition: Ids must be unique in each sequences. + /// - parameters: + /// - left: The left sequence. + /// - right: The right sequence. + public init(left: LeftSequence, right: RightSequence) { + self.init( + left: left, + identifiedBy: { $0.id }, + right: right, + identifiedBy: { $0.id }) + } +} + +extension SortedDifference where + LeftSequence.Element: Comparable, + RightSequence.Element == LeftSequence.Element, + LeftSequence.Element == ID +{ + /// Given two sequences (left and right), this sequence tells whether + /// elements are only found on the left, on the right, or on both sides. + /// + /// For example: + /// + /// // Prints: + /// // - common(1, 1) + /// // - left(2) + /// for change in SortedDifference(left: [1, 2], right: [1]) { + /// print(change) + /// } + /// + /// - precondition: Both input sequences must be sorted. + /// - precondition: Both input sequences must contain unique elements. + /// - parameters: + /// - left: The left sequence. + /// - right: The right sequence. + public init(left: LeftSequence, right: RightSequence) { + self.init( + left: left, + identifiedBy: { $0 }, + right: right, + identifiedBy: { $0 }) + } +} + +/// An element of the SortedDifference sequence. +public enum SortedDifferenceChange { + /// An element only found in the left sequence + case left(Left) + /// An element only found in the right sequence + case right(Right) + /// Left and right elements share a common id + case common(Left, Right) +} + +extension SortedDifferenceChange: CustomStringConvertible { + public var description: String { + switch self { + case let .left(lhs): + return "left(\(String(describing: lhs)))" + case let .right(rhs): + return "right(\(String(describing: rhs)))" + case let .common(lhs, rhs): + return "common(\(String(describing: lhs)), \(String(describing: rhs)))" + } + } +} + +extension SortedDifferenceChange: CustomDebugStringConvertible { + public var debugDescription: String { + switch self { + case let .left(lhs): + return "left(\(String(reflecting: lhs)))" + case let .right(rhs): + return "right(\(String(reflecting: rhs)))" + case let .common(lhs, rhs): + return "common(\(String(reflecting: lhs)), \(String(reflecting: rhs)))" + } + } +} + +extension SortedDifferenceChange: Equatable where + Left: Equatable, + Right: Equatable +{ } diff --git a/Documentation/Playgrounds/JSONSynchronization.playground/Sources/sortedMerge.swift b/Documentation/Playgrounds/JSONSynchronization.playground/Sources/sortedMerge.swift deleted file mode 100644 index 3ba6899f7..000000000 --- a/Documentation/Playgrounds/JSONSynchronization.playground/Sources/sortedMerge.swift +++ /dev/null @@ -1,88 +0,0 @@ -/// Given two sorted sequences (left and right), this function emits "merge steps" -/// which tell whether elements are only found on the left, on the right, or on -/// both sides. -/// -/// Both sequences do not have to share the same element type. Yet elements must -/// share a common comparable *key*. -/// -/// Both sequences must be sorted by this key. -/// -/// Keys must be unique in both sequences. -/// -/// The example below compare two sequences sorted by integer representation, -/// and prints: -/// -/// - Left: 1 -/// - Common: 2, 2 -/// - Common: 3, 3 -/// - Right: 4 -/// -/// for mergeStep in sortedMerge( -/// left: [1,2,3], -/// right: ["2", "3", "4"], -/// leftKey: { $0 }, -/// rightKey: { Int($0)! }) -/// { -/// switch mergeStep { -/// case .left(let left): -/// print("- Left: \(left)") -/// case .right(let right): -/// print("- Right: \(right)") -/// case .common(let left, let right): -/// print("- Common: \(left), \(right)") -/// } -/// } -/// -/// - parameters: -/// - left: The left sequence. -/// - right: The right sequence. -/// - leftKey: A function that returns the key of a left element. -/// - rightKey: A function that returns the key of a right element. -/// - returns: A sequence of MergeStep -public func sortedMerge( - left lSeq: LeftSequence, - right rSeq: RightSequence, - leftKey: @escaping (LeftSequence.Element) -> Key, - rightKey: @escaping (RightSequence.Element) -> Key) -> AnySequence> -{ - return AnySequence { () -> AnyIterator> in - var (lGen, rGen) = (lSeq.makeIterator(), rSeq.makeIterator()) - var (lOpt, rOpt) = (lGen.next(), rGen.next()) - return AnyIterator { - switch (lOpt, rOpt) { - case (let lElem?, let rElem?): - let (lKey, rKey) = (leftKey(lElem), rightKey(rElem)) - if lKey > rKey { - rOpt = rGen.next() - return .right(rElem) - } else if lKey == rKey { - (lOpt, rOpt) = (lGen.next(), rGen.next()) - return .common(lElem, rElem) - } else { - lOpt = lGen.next() - return .left(lElem) - } - case (nil, let rElem?): - rOpt = rGen.next() - return .right(rElem) - case (let lElem?, nil): - lOpt = lGen.next() - return .left(lElem) - case (nil, nil): - return nil - } - } - } -} - -/** - Support for sortedMerge() - */ -public enum MergeStep { - /// An element only found in the left sequence: - case left(LeftElement) - /// An element only found in the right sequence: - case right(RightElement) - /// Left and right elements share a common key: - case common(LeftElement, RightElement) -}