Update playgrounds

This commit is contained in:
Gwendal Roué committed 2020-07-11 11:17:23 +02:00
1 parent ae41859bbb
commit 8a8518a961
10 files changed
+27 -430

No files matched your search

@@ -10,9 +10,11 @@ import GRDB
//: Open a database connection
var config = Configuration()
config.trace = { print("SQL > \($0)") }
let dbQueue = DatabaseQueue(configuration: config)
var configuration = Configuration()
configuration.prepareDatabase = { db in
db.trace { print("SQL> \($0)") }
}
let dbQueue = DatabaseQueue(configuration: configuration)
//: Use a migrator to define the database schema
@@ -265,18 +265,20 @@ extension MyDatabaseDecoder {
// MARK: - Fetch from FetchRequest
static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> MapCursor<RowCursor, DecodedType> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
let preparedRequest = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchCursor(preparedRequest.statement, adapter: preparedRequest.adapter)
}
static func fetchAll<R: FetchRequest>(_ db: Database, _ request: R) throws -> [DecodedType] {
let (statement, adapter) = try request.prepare(db)
return try fetchAll(statement, adapter: adapter)
let preparedRequest = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchAll(preparedRequest.statement, adapter: preparedRequest.adapter)
}
static func fetchOne<R: FetchRequest>(_ db: Database, _ request: R) throws -> DecodedType? {
let (statement, adapter) = try request.prepare(db)
return try fetchOne(statement, adapter: adapter)
// The `forSingleResult: true` argument hints the request that a single
// row will be consumed. Some requests will add a LIMIT SQL clause.
let preparedRequest = try request.makePreparedRequest(db, forSingleResult: true)
return try fetchOne(preparedRequest.statement, adapter: preparedRequest.adapter)
}
}
@@ -1,152 +0,0 @@
//: To run this playground:
//:
//: - Open GRDB.xcworkspace
//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX
//: - Build: menu Product > Build
//: - Select the playground in the Playgrounds Group
//: - Run the playground
//:
//: This sample code shows how to use GRDB to synchronize a database table
//: with a JSON payload. We use as few SQL queries as possible:
//:
//: - Only one SELECT query.
//: - One query per insert, delete, and update.
//: - Useless UPDATE statements are avoided.
import Foundation
import GRDB
// Open an in-memory database that logs all its SQL statements
var configuration = Configuration()
configuration.trace = { print($0) }
let dbQueue = DatabaseQueue(configuration: configuration)
// Create the database table to store the players
try dbQueue.inDatabase { db in
try db.create(table: "player") { t in
t.column("id", .integer).primaryKey()
t.column("name", .text)
t.column("score", .integer)
}
}
// Define the Player codable record type
struct Player: Codable, FetchableRecord, MutablePersistableRecord {
var id: Int64
var name: String
var score: Int
// Define database columns from CodingKeys
private enum Columns {
static let id = Column(CodingKeys.id)
static let name = Column(CodingKeys.name)
static let score = Column(CodingKeys.score)
}
// Update a player id after it has been inserted in the database.
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
// 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 syncData = try JSONDecoder().decode(SyncData.self, from: jsonData)
// Sort players to sync by id:
let playersToSync = syncData.players.sorted { $0.id < $1.id }
// Sort database players by id:
let players = try Player.orderByPrimaryKey().fetchAll(db)
// Now that both lists are sorted by id, we can compare them with
// SortedDifference (see https://github.com/groue/SortedDifference).
//
// We'll delete, insert or update players, depending on their presence
// in either lists.
for change in SortedDifference(
left: players, // Database players
right: playersToSync) // PlayersToSync players (Decoded)
{
switch change {
case .left(let player):
// Delete database player without matching JSON player:
try player.delete(db)
case .right(var playerToSync):
// Insert the Codable player without matching database player:
try playerToSync.insert(db)
case .common(let player, let playerToSync):
// Update database player with its JSON counterpart:
try playerToSync.updateChanges(db, from: player)
}
}
}
do {
let jsonString1 = """
{
"players": [
{ "id": 1, "name": "Arthur", "score": 1000},
{ "id": 2, "name": "Barbara", "score": 2000},
{ "id": 3, "name": "Craig", "score": 500},
]
}
"""
print("---\nImport \(jsonString1)")
try dbQueue.inDatabase { db in
// SELECT * FROM player ORDER BY id
// INSERT INTO "player" ("id", "name", "score") VALUES (1,'Arthur',1000)
// INSERT INTO "player" ("id", "name", "score") VALUES (2,'Barbara',2000)
// INSERT INTO "player" ("id", "name", "score") VALUES (3,'Craig',500)
try synchronizePlayers(with: jsonString1, in: db)
}
}
do {
let jsonString2 = """
{
"players": [
{ "id": 2, "name": "Barbara", "score": 3000},
{ "id": 3, "name": "Craig", "score": 500},
{ "id": 4, "name": "Daniel", "score": 1500},
]
}
"""
print("---\nImport \(jsonString2)")
try dbQueue.inDatabase { db in
// SELECT * FROM player ORDER BY id
// DELETE FROM "player" WHERE "id"=1
// UPDATE "player" SET "score"=3000 WHERE "id"=2
// INSERT INTO "player" ("id", "name", "score") VALUES (4,'Daniel',1500)
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)
}
}
@@ -1,245 +0,0 @@
// Copyright (C) 2020 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<LeftSequence, RightSequence, ID>: 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<LeftSequence.Element, RightSequence.Element>? {
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<Left, Right> {
/// 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
{ }
@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='osx' display-mode='raw' last-migration='0800'>
<timeline fileName='timeline.xctimeline'/>
</playground>
@@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
@@ -2,20 +2,22 @@
import GRDB
var configuration = Configuration()
configuration.trace = { print($0) }
configuration.prepareDatabase = { db in
db.trace { print("SQL> \($0)") }
}
let dbQueue = DatabaseQueue(configuration: configuration)
try! dbQueue.inDatabase { db in
try db.create(table: "persons") { t in
t.column("id", .integer).primaryKey()
t.column("name", .text)
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
t.column("score", .integer).notNull()
}
try db.execute(sql: "INSERT INTO persons (name) VALUES (?)", arguments: ["Arthur"])
try db.execute(sql: "INSERT INTO persons (name) VALUES (?)", arguments: ["Barbara"])
try db.execute(sql: "INSERT INTO player (name, score) VALUES (?, ?)", arguments: ["Arthur", 1000])
try db.execute(sql: "INSERT INTO player (name, score) VALUES (?, ?)", arguments: ["Barbara", 1000])
let names = try String.fetchAll(db, sql: "SELECT name FROM persons")
let names = try String.fetchAll(db, sql: "SELECT name FROM player")
print(names)
}
@@ -19,7 +19,9 @@ import CoreLocation
// Open an in-memory database that logs all SQL statements
var configuration = Configuration()
configuration.trace = { print($0) }
configuration.prepareDatabase = { db in
db.trace { print("SQL> \($0)") }
}
let dbQueue = DatabaseQueue(configuration: configuration)
-3
View File
@@ -7,9 +7,6 @@
<FileRef
location = "group:Tour.playground">
</FileRef>
<FileRef
location = "group:JSONSynchronization.playground">
</FileRef>
<FileRef
location = "group:TransactionObserver.playground">
</FileRef>
+1 -1
View File
@@ -3061,7 +3061,7 @@ player.hasDatabaseChanges // true
player.databaseChanges // ["score": 750]
```
For an efficient algorithm which synchronizes the content of a database table with a JSON payload, check [JSONSynchronization.playground](Documentation/Playgrounds/JSONSynchronization.playground/Contents.swift).
For an efficient algorithm which synchronizes the content of a database table with a JSON payload, check [groue/SortedDifference](https://github.com/groue/SortedDifference).
## Record Customization Options