diff --git a/CHANGELOG.md b/CHANGELOG.md index b6e54ff9a..603a0e348 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: #### 5.x Releases +- `5.0.x` Releases - [5.0.0](#500) - `5.0.0` Betas - [5.0.0-beta](#500-beta) | [5.0.0-beta.2](#500-beta2) | [5.0.0-beta.3](#500-beta3) | [5.0.0-beta.4](#500-beta4) | [5.0.0-beta.5](#500-beta5) | [5.0.0-beta.6](#500-beta6) | [5.0.0-beta.7](#500-beta7) | [5.0.0-beta.8](#500-beta8) | [5.0.0-beta.9](#500-beta9) | [5.0.0-beta.10](#500-beta10) | [5.0.0-beta.11](#500-beta11) @@ -70,9 +71,12 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [0.110.0](#01100), ... - +## 5.0.0 + +Released September 20, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta.11...v5.0.0) + +- **Fixed**: [#838](https://github.com/groue/GRDB.swift/issues/838): Have indexed colums inherit the `ifNotExists` flag from table creation. + ## 5.0.0-beta.11 diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.pbxproj b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.pbxproj index 4e1ffc304..028490bdf 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.pbxproj +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.pbxproj @@ -12,12 +12,12 @@ 563F3E7724A78BD700982CF8 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 563F3E7624A78BD700982CF8 /* Assets.xcassets */; }; 563F3E7A24A78BD700982CF8 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 563F3E7924A78BD700982CF8 /* Preview Assets.xcassets */; }; 563F3E7D24A78BD700982CF8 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 563F3E7B24A78BD700982CF8 /* LaunchScreen.storyboard */; }; - 5651F47D24A8837800727C9D /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5651F47124A8835B00727C9D /* GRDB.framework */; }; - 5651F47F24A884B200727C9D /* World.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5651F47E24A884B200727C9D /* World.swift */; }; 5651F48124A8856300727C9D /* PlayerList.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5651F48024A8856300727C9D /* PlayerList.swift */; }; 5651F48324A885AF00727C9D /* PlayerListViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5651F48224A885AF00727C9D /* PlayerListViewModel.swift */; }; 5651F48524A8905100727C9D /* PlayerEditor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5651F48424A8905100727C9D /* PlayerEditor.swift */; }; 5651F48724A8909F00727C9D /* PlayerFormViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5651F48624A8909F00727C9D /* PlayerFormViewModel.swift */; }; + 566148C9251791570083D8B8 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5651F47124A8835B00727C9D /* GRDB.framework */; }; + 566148CA251791570083D8B8 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 5651F47124A8835B00727C9D /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 5678066124A8A4E400606BC6 /* Localizable.stringsdict in Resources */ = {isa = PBXBuildFile; fileRef = 5678066324A8A4E400606BC6 /* Localizable.stringsdict */; }; 5678066524A8B7DD00606BC6 /* PlayerCreationSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5678066424A8B7DD00606BC6 /* PlayerCreationSheet.swift */; }; 56AAFD4724A78F9A0077EADB /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AAFD4524A78F9A0077EADB /* AppDatabase.swift */; }; @@ -82,15 +82,22 @@ remoteGlobalIDString = AAA4DDD4230F262000C74B15; remoteInfo = GRDBtvOSTests; }; - 5651F47A24A8836B00727C9D /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 5651F45F24A8835B00727C9D /* GRDB.xcodeproj */; - proxyType = 1; - remoteGlobalIDString = 56E5D7C91B4D3FED00430942; - remoteInfo = GRDBiOS; - }; /* End PBXContainerItemProxy section */ +/* Begin PBXCopyFilesBuildPhase section */ + 566148CB251791570083D8B8 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + 566148CA251791570083D8B8 /* GRDB.framework in Embed Frameworks */, + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + /* Begin PBXFileReference section */ 563F3E6D24A78BD400982CF8 /* GRDBCombineDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBCombineDemo.app; sourceTree = BUILT_PRODUCTS_DIR; }; 563F3E7024A78BD400982CF8 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; @@ -100,7 +107,6 @@ 563F3E7C24A78BD700982CF8 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 563F3E7E24A78BD700982CF8 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 5651F45F24A8835B00727C9D /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = ""; }; - 5651F47E24A884B200727C9D /* World.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = World.swift; sourceTree = ""; }; 5651F48024A8856300727C9D /* PlayerList.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerList.swift; sourceTree = ""; }; 5651F48224A885AF00727C9D /* PlayerListViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerListViewModel.swift; sourceTree = ""; }; 5651F48424A8905100727C9D /* PlayerEditor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerEditor.swift; sourceTree = ""; }; @@ -117,7 +123,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 5651F47D24A8837800727C9D /* GRDB.framework in Frameworks */, + 566148C9251791570083D8B8 /* GRDB.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -158,7 +164,6 @@ 563F3E7224A78BD400982CF8 /* SceneDelegate.swift */, 56AAFD4524A78F9A0077EADB /* AppDatabase.swift */, 56AAFD4624A78F9A0077EADB /* Player.swift */, - 5651F47E24A884B200727C9D /* World.swift */, 56248FEF24A8F3DD009C144A /* ViewModels */, 56B1B12524A8DA1000D7FB31 /* Views */, 563F3E7824A78BD700982CF8 /* Preview Content */, @@ -237,11 +242,11 @@ 563F3E6924A78BD400982CF8 /* Sources */, 563F3E6A24A78BD400982CF8 /* Frameworks */, 563F3E6B24A78BD400982CF8 /* Resources */, + 566148CB251791570083D8B8 /* Embed Frameworks */, ); buildRules = ( ); dependencies = ( - 5651F47B24A8836B00727C9D /* PBXTargetDependency */, ); name = GRDBCombineDemo; productName = GRDBCombineDemo; @@ -255,7 +260,7 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 1150; - LastUpgradeCheck = 1150; + LastUpgradeCheck = 1200; ORGANIZATIONNAME = "Gwendal Roué"; TargetAttributes = { 563F3E6C24A78BD400982CF8 = { @@ -365,7 +370,6 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 5651F47F24A884B200727C9D /* World.swift in Sources */, 5651F48324A885AF00727C9D /* PlayerListViewModel.swift in Sources */, 56B1B13024A8E9A700D7FB31 /* PlayerForm.swift in Sources */, 5678066524A8B7DD00606BC6 /* PlayerCreationSheet.swift in Sources */, @@ -381,14 +385,6 @@ }; /* End PBXSourcesBuildPhase section */ -/* Begin PBXTargetDependency section */ - 5651F47B24A8836B00727C9D /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = GRDBiOS; - targetProxy = 5651F47A24A8836B00727C9D /* PBXContainerItemProxy */; - }; -/* End PBXTargetDependency section */ - /* Begin PBXVariantGroup section */ 563F3E7B24A78BD700982CF8 /* LaunchScreen.storyboard */ = { isa = PBXVariantGroup; @@ -435,6 +431,7 @@ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; @@ -495,6 +492,7 @@ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; @@ -536,7 +534,7 @@ "$(inherited)", "@executable_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCombineDemo; + PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCombineDemo2; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = 1; @@ -556,7 +554,7 @@ "$(inherited)", "@executable_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCombineDemo; + PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCombineDemo2; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = 1; diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift index ce1cd4ddc..8efe48b47 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift @@ -6,6 +6,9 @@ import GRDB /// It applies the pratices recommended at /// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md final class AppDatabase { + /// The shared AppDatabase + static var shared: AppDatabase! + private let dbQueue: DatabaseQueue /// Creates an AppDatabase and make sure the database schema is ready. @@ -125,9 +128,7 @@ extension AppDatabase { func playersOrderedByNamePublisher() -> AnyPublisher<[Player], Error> { ValueObservation .tracking(Player.all().orderedByName().fetchAll) - // Use the .immediate scheduling so that views do not have to wait - // until the players are loaded. - .publisher(in: dbQueue, scheduling: .immediate) + .publisher(in: dbQueue) .eraseToAnyPublisher() } @@ -135,9 +136,7 @@ extension AppDatabase { func playersOrderedByScorePublisher() -> AnyPublisher<[Player], Error> { ValueObservation .tracking(Player.all().orderedByScore().fetchAll) - // Use the .immediate scheduling so that views do not have to wait - // until the players are loaded. - .publisher(in: dbQueue, scheduling: .immediate) + .publisher(in: dbQueue) .eraseToAnyPublisher() } } diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDelegate.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDelegate.swift index c84522617..05640aef6 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDelegate.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDelegate.swift @@ -40,6 +40,6 @@ class AppDelegate: UIResponder, UIApplicationDelegate { try database.createRandomPlayersIfEmpty() // Expose it to the rest of the application - Current.database = { database } + AppDatabase.shared = database } } diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/SceneDelegate.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/SceneDelegate.swift index 5b7a7b693..5c5a8ae96 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/SceneDelegate.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/SceneDelegate.swift @@ -10,7 +10,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Create the SwiftUI view that provides the window contents. - let viewModel = PlayerListViewModel(database: Current.database()) + let viewModel = PlayerListViewModel(database: AppDatabase.shared) let rootView = PlayerList(viewModel: viewModel) // Use a UIHostingController as window root view controller. diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/ViewModels/PlayerListViewModel.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/ViewModels/PlayerListViewModel.swift index bc48a8ca8..a40aa71ed 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/ViewModels/PlayerListViewModel.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/ViewModels/PlayerListViewModel.swift @@ -9,11 +9,16 @@ final class PlayerListViewModel: ObservableObject { case byName } + struct PlayerList { + var players: [Player] + var animatedChanges: Bool + } + /// The list ordering @Published var ordering: Ordering = .byScore /// The players in the list - @Published var players: [Player] = [] + @Published var playerList = PlayerList(players: [], animatedChanges: false) /// The view model that edits a new player let newPlayerViewModel: PlayerFormViewModel @@ -24,9 +29,19 @@ final class PlayerListViewModel: ObservableObject { init(database: AppDatabase) { self.database = database newPlayerViewModel = PlayerFormViewModel(database: database, player: .new()) - playersCancellable = playersPublisher(in: database).sink { [weak self] players in - self?.players = players - } + playersCancellable = playersPublisher(in: database) + .scan(nil) { (previousList: PlayerList?, players: [Player]) in + if previousList == nil { + // Do not animate first view update + return PlayerList(players: players, animatedChanges: false) + } else { + return PlayerList(players: players, animatedChanges: true) + } + } + .compactMap { $0 } + .sink { [weak self] playerList in + self?.playerList = playerList + } } // MARK: - Players List Management @@ -39,7 +54,7 @@ final class PlayerListViewModel: ObservableObject { func deletePlayers(atOffsets offsets: IndexSet) { // Eventual error presentation is left as an exercise for the reader. - let playerIDs = offsets.compactMap { players[$0].id } + let playerIDs = offsets.compactMap { playerList.players[$0].id } try! database.deletePlayers(ids: playerIDs) } diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/PlayerCreationSheet.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/PlayerCreationSheet.swift index cdedb43f7..ca3561003 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/PlayerCreationSheet.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/PlayerCreationSheet.swift @@ -52,4 +52,3 @@ struct PlayerCreationSheet_Previews: PreviewProvider { } } #endif - diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/PlayerEditor.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/PlayerEditor.swift index 0a404967a..1e9853d0e 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/PlayerEditor.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/PlayerEditor.swift @@ -8,10 +8,10 @@ struct PlayerEditor: View { var body: some View { PlayerForm(viewModel: viewModel) - .onDisappear(perform: { - // Ignore validation errors - try? self.viewModel.savePlayer() - }) + .onDisappear(perform: { + // Ignore validation errors + try? self.viewModel.savePlayer() + }) } } diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/PlayerList.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/PlayerList.swift index eea7b466c..36e1eba89 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/PlayerList.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/PlayerList.swift @@ -14,7 +14,7 @@ struct PlayerList: View { playerList toolbar } - .navigationBarTitle(Text("\(viewModel.players.count) Players")) + .navigationBarTitle(Text("\(viewModel.playerList.players.count) Players")) .navigationBarItems( leading: HStack { EditButton() @@ -26,9 +26,10 @@ struct PlayerList: View { private var playerList: some View { List { - ForEach(viewModel.players) { player in + ForEach(viewModel.playerList.players) { player in NavigationLink(destination: self.editionView(for: player)) { PlayerRow(player: player) + .animation(nil) } } .onDelete(perform: { offsets in @@ -36,6 +37,7 @@ struct PlayerList: View { }) } .listStyle(PlainListStyle()) + .animation(viewModel.playerList.animatedChanges ? .default : nil) } private var toolbar: some View { @@ -52,7 +54,7 @@ struct PlayerList: View { action: viewModel.stressTest, label: { Image(systemName: "tornado").imageScale(.large) }) } - + .padding() } @@ -92,7 +94,7 @@ struct PlayerList: View { // Make sure we do not edit a previously created player. self.viewModel.newPlayerViewModel.editNewPlayer() self.newPlayerIsPresented = true - }, + }, label: { Image(systemName: "plus").imageScale(.large) }) .sheet( isPresented: $newPlayerIsPresented, @@ -105,7 +107,7 @@ struct PlayerList: View { viewModel: self.viewModel.newPlayerViewModel, dismissAction: { self.newPlayerIsPresented = false - }) + }) } } diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/World.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/World.swift deleted file mode 100644 index 05f47b9bd..000000000 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/World.swift +++ /dev/null @@ -1,11 +0,0 @@ -/// Dependency Injection based on the "How to Control the World" article: -/// https://www.pointfree.co/blog/posts/21-how-to-control-the-world -struct World { - /// The application database - var database: () -> AppDatabase -} - -/// The current world. -/// -/// Its setup is done by `AppDelegate`, or tests. -var Current = World(database: { fatalError("Database is uninitialized") }) diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj index b44cfca5f..fdb828ddc 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj @@ -26,7 +26,6 @@ 56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361A1E8D9F38003B6DA4 /* Player.swift */; }; 56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */; }; 56B036241E8D9F4C003B6DA4 /* PlayerListViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */; }; - 56FE6F1E24A90CC500711EDF /* World.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FE6F1D24A90CC500711EDF /* World.swift */; }; 56FE6F2624A90CE400711EDF /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FE6F2524A90CE400711EDF /* SceneDelegate.swift */; }; /* End PBXBuildFile section */ @@ -185,7 +184,6 @@ 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionViewController.swift; sourceTree = ""; }; 56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerListViewController.swift; sourceTree = ""; }; 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = ""; }; - 56FE6F1D24A90CC500711EDF /* World.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = World.swift; sourceTree = ""; }; 56FE6F2524A90CE400711EDF /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; /* End PBXFileReference section */ @@ -281,7 +279,6 @@ 56FE6F2524A90CE400711EDF /* SceneDelegate.swift */, 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */, 56B0361A1E8D9F38003B6DA4 /* Player.swift */, - 56FE6F1D24A90CC500711EDF /* World.swift */, 56FE6F4F24A9114200711EDF /* ViewControllers */, 56FE6F4E24A9112900711EDF /* Resources */, 56FE6F5124A9118000711EDF /* Support */, @@ -534,7 +531,6 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 56FE6F1E24A90CC500711EDF /* World.swift in Sources */, 56FE6F2624A90CE400711EDF /* SceneDelegate.swift in Sources */, 56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */, 56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */, diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata index 94b2795e2..919434a62 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -1,4 +1,7 @@ + + diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift index 686defde7..96c1655aa 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift @@ -5,6 +5,9 @@ import GRDB /// It applies the pratices recommended at /// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md final class AppDatabase { + /// The shared AppDatabase + static var shared: AppDatabase! + private let dbQueue: DatabaseQueue /// Creates an AppDatabase and make sure the database schema is ready. @@ -124,7 +127,7 @@ extension AppDatabase { func observePlayerCount( onError: @escaping (Error) -> Void, onChange: @escaping (Int) -> Void) - -> DatabaseCancellable + -> DatabaseCancellable { ValueObservation .tracking(Player.fetchCount) @@ -138,7 +141,7 @@ extension AppDatabase { func observePlayersOrderedByName( onError: @escaping (Error) -> Void, onChange: @escaping ([Player]) -> Void) - -> DatabaseCancellable + -> DatabaseCancellable { ValueObservation .tracking(Player.all().orderedByName().fetchAll) @@ -152,7 +155,7 @@ extension AppDatabase { func observePlayersOrderedByScore( onError: @escaping (Error) -> Void, onChange: @escaping ([Player]) -> Void) - -> DatabaseCancellable + -> DatabaseCancellable { ValueObservation .tracking(Player.all().orderedByScore().fetchAll) diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift index c84522617..05640aef6 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift @@ -40,6 +40,6 @@ class AppDelegate: UIResponder, UIApplicationDelegate { try database.createRandomPlayersIfEmpty() // Expose it to the rest of the application - Current.database = { database } + AppDatabase.shared = database } } diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/ViewControllers/PlayerEditionViewController.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/ViewControllers/PlayerEditionViewController.swift index 96f1a6364..f7f3624f1 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/ViewControllers/PlayerEditionViewController.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/ViewControllers/PlayerEditionViewController.swift @@ -127,7 +127,7 @@ extension PlayerEditionViewController: UITextFieldDelegate { } player.name = nameTextField.text ?? "" player.score = scoreTextField.text.flatMap { Int($0) } ?? 0 - try! Current.database().savePlayer(&player) + try! AppDatabase.shared.savePlayer(&player) self.player = player } } diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/ViewControllers/PlayerListViewController.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/ViewControllers/PlayerListViewController.swift index 8719184d3..72db91208 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/ViewControllers/PlayerListViewController.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/ViewControllers/PlayerListViewController.swift @@ -9,8 +9,8 @@ class PlayerListViewController: UITableViewController { } @IBOutlet private weak var newPlayerButtonItem: UIBarButtonItem! + private var dataSource: PlayerDataSource! private var animatesPlayersChange = false // Don't animate first update - private var players: [Player] = [] private var playersCancellable: DatabaseCancellable? private var playerCountCancellable: DatabaseCancellable? private var playerOrdering: PlayerOrdering = .byScore { @@ -67,7 +67,7 @@ class PlayerListViewController: UITableViewController { } private func configureTitle() { - playerCountCancellable = Current.database().observePlayerCount( + playerCountCancellable = AppDatabase.shared.observePlayerCount( onError: { error in fatalError("Unexpected error: \(error)") }, onChange: { [weak self] count in guard let self = self else { return } @@ -76,67 +76,53 @@ class PlayerListViewController: UITableViewController { case 1: self.navigationItem.title = "1 Player" default: self.navigationItem.title = "\(count) Players" } - }) + }) } private func configureTableView() { + dataSource = PlayerDataSource(tableView: tableView) { (tableView, indexPath, player) in + let cell = tableView.dequeueReusableCell(withIdentifier: "Player", for: indexPath) + if player.name.isEmpty { + cell.textLabel?.text = "(anonymous)" + } else { + cell.textLabel?.text = player.name + } + cell.detailTextLabel?.text = abs(player.score) > 1 ? "\(player.score) points" : "0 point" + return cell + } + dataSource.defaultRowAnimation = .fade + tableView.dataSource = dataSource + switch playerOrdering { case .byName: - playersCancellable = Current.database().observePlayersOrderedByName( + playersCancellable = AppDatabase.shared.observePlayersOrderedByName( onError: { error in fatalError("Unexpected error: \(error)") }, onChange: { [weak self] players in guard let self = self else { return } self.updateTableView(with: players) - }) + }) case .byScore: - playersCancellable = Current.database().observePlayersOrderedByScore( + playersCancellable = AppDatabase.shared.observePlayersOrderedByScore( onError: { error in fatalError("Unexpected error: \(error)") }, onChange: { [weak self] players in guard let self = self else { return } self.updateTableView(with: players) - }) + }) } } private func updateTableView(with players: [Player]) { - if animatesPlayersChange == false { - self.players = players - tableView.reloadData() - + var snapshot = NSDiffableDataSourceSnapshot() + snapshot.appendSections([0]) + snapshot.appendItems(players, toSection: 0) + + if animatesPlayersChange { + dataSource.apply(snapshot, animatingDifferences: true, completion: nil) + } else { // Future updates will be animated animatesPlayersChange = true - return + dataSource.apply(snapshot, animatingDifferences: false, completion: nil) } - - // Compute difference between current and new list of players - let difference = players - .difference(from: self.players) - .inferringMoves() - - // Apply those changes to the table view - tableView.performBatchUpdates({ - self.players = players - for change in difference { - switch change { - case let .remove(offset, _, associatedWith): - if let associatedWith = associatedWith { - self.tableView.moveRow( - at: IndexPath(row: offset, section: 0), - to: IndexPath(row: associatedWith, section: 0)) - } else { - self.tableView.deleteRows( - at: [IndexPath(row: offset, section: 0)], - with: .fade) - } - case let .insert(offset, _, associatedWith): - if associatedWith == nil { - self.tableView.insertRows( - at: [IndexPath(row: offset, section: 0)], - with: .fade) - } - } - } - }, completion: nil) } } @@ -147,20 +133,18 @@ extension PlayerListViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "Edit" { - guard - let controller = segue.destination as? PlayerEditionViewController, - let indexPath = tableView.indexPathForSelectedRow - else { return } - let player = players[indexPath.row] + guard let controller = segue.destination as? PlayerEditionViewController, + let indexPath = tableView.indexPathForSelectedRow, + let player = dataSource.itemIdentifier(for: indexPath) + else { return } controller.title = player.name controller.player = player controller.presentation = .push } else if segue.identifier == "New" { - guard - let navigationController = segue.destination as? UINavigationController, - let controller = navigationController.viewControllers.first as? PlayerEditionViewController - else { return } + guard let navigationController = segue.destination as? UINavigationController, + let controller = navigationController.viewControllers.first as? PlayerEditionViewController + else { return } setEditing(false, animated: true) controller.title = "New Player" controller.player = Player(id: nil, name: "", score: 0) @@ -180,33 +164,18 @@ extension PlayerListViewController { // MARK: - UITableViewDataSource -extension PlayerListViewController { - override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - players.count - } - - override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { - let cell = tableView.dequeueReusableCell(withIdentifier: "Player", for: indexPath) - configure(cell, at: indexPath) - return cell +/// Subclass of UITableViewDiffableDataSource that supports row deletion +private class PlayerDataSource: UITableViewDiffableDataSource { + override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { + true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { // Delete the player - if let id = players[indexPath.row].id { - try! Current.database().deletePlayers(ids: [id]) + if let player = itemIdentifier(for: indexPath), let id = player.id { + try! AppDatabase.shared.deletePlayers(ids: [id]) } } - - private func configure(_ cell: UITableViewCell, at indexPath: IndexPath) { - let player = players[indexPath.row] - if player.name.isEmpty { - cell.textLabel?.text = "(anonymous)" - } else { - cell.textLabel?.text = player.name - } - cell.detailTextLabel?.text = abs(player.score) > 1 ? "\(player.score) points" : "0 point" - } } @@ -225,19 +194,19 @@ extension PlayerListViewController { @IBAction func deletePlayers() { setEditing(false, animated: true) - try! Current.database().deleteAllPlayers() + try! AppDatabase.shared.deleteAllPlayers() } @IBAction func refresh() { setEditing(false, animated: true) - try! Current.database().refreshPlayers() + try! AppDatabase.shared.refreshPlayers() } @IBAction func stressTest() { setEditing(false, animated: true) for _ in 0..<50 { DispatchQueue.global().async { - try! Current.database().refreshPlayers() + try! AppDatabase.shared.refreshPlayers() } } } diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/World.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/World.swift deleted file mode 100644 index 05f47b9bd..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/World.swift +++ /dev/null @@ -1,11 +0,0 @@ -/// Dependency Injection based on the "How to Control the World" article: -/// https://www.pointfree.co/blog/posts/21-how-to-control-the-world -struct World { - /// The application database - var database: () -> AppDatabase -} - -/// The current world. -/// -/// Its setup is done by `AppDelegate`, or tests. -var Current = World(database: { fatalError("Database is uninitialized") }) diff --git a/Documentation/FullTextSearch.md b/Documentation/FullTextSearch.md index da7c1cb9b..5c2d7fc9f 100644 --- a/Documentation/FullTextSearch.md +++ b/Documentation/FullTextSearch.md @@ -280,7 +280,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.11/Structs/StatementArguments.html): +FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.0/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, @@ -529,7 +529,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.11/Structs/StatementArguments.html): +FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.0/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index 14ff66a85..f374ef102 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -68,7 +68,7 @@ try dbQueue.read { db in } ``` -See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.11/Structs/DatabaseMigrator.html) for more migrator methods. +See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.0/Structs/DatabaseMigrator.html) for more migrator methods. ## The `eraseDatabaseOnSchemaChange` Option diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 307e2ac8e..df94ba1d7 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '5.0.0-beta.11' + s.version = '5.0.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index b5e5a41b4..804f6396e 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -356,7 +356,6 @@ extension DatabaseError { } extension DatabaseError { - // TODO: test /// Returns true if the error has code `SQLITE_ABORT` or `SQLITE_INTERRUPT`. /// /// Such an error can be thrown when a database has been interrupted, or diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index 644d96cff..746df500e 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -403,7 +403,6 @@ public class TableAlias: Hashable { /// .filter(!authorAlias.exists) /// return try request.fetchAll(db) /// } - public var exists: SQLExpression { // TODO: this fails with SQL views. Can we do something? _SQLExpressionQualifiedFastPrimaryKey(alias: self) != nil diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 63d419bbe..901e6342b 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -179,7 +179,6 @@ struct SQLQueryGenerator: Refinable { case let .table(tableName: tableName, alias: alias) = relation.source, try db.tableExists(tableName) // skip views else { - // TODO: try harder return selectedRegion } diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index 4388adce8..5d69e121a 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -471,7 +471,7 @@ public final class TableDefinition { } let indexStatements = try columns - .compactMap { $0.indexDefinition(in: name) } + .compactMap { $0.indexDefinition(in: name, ifNotExists: ifNotExists) } .map { try $0.sql(db) } statements.append(contentsOf: indexStatements) return statements.joined(separator: "; ") @@ -570,7 +570,7 @@ public final class TableAlteration { let statement = chunks.joined(separator: " ") statements.append(statement) - if let indexDefinition = column.indexDefinition(in: name) { + if let indexDefinition = column.indexDefinition(in: name, ifNotExists: false) { try statements.append(indexDefinition.sql(db)) } case let .rename(oldName, newName): @@ -934,7 +934,7 @@ public final class ColumnDefinition { return chunks.joined(separator: " ") } - fileprivate func indexDefinition(in table: String) -> IndexDefinition? { + fileprivate func indexDefinition(in table: String, ifNotExists: Bool) -> IndexDefinition? { switch index { case .none: return nil case .unique: return nil @@ -944,7 +944,7 @@ public final class ColumnDefinition { table: table, columns: [name], unique: false, - ifNotExists: false, + ifNotExists: ifNotExists, condition: nil) } } diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index 371768271..72fb9aeb4 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -201,9 +201,10 @@ private struct _RowDecoder: Decoder { // "book", which is not the name of a column, and not the name of a // scope) has to be decoded right from the base row. if let decodedRootKey = decodedRootKey { - throw DecodingError.keyNotFound(decodedRootKey, DecodingError.Context( - codingPath: codingPath, - debugDescription: "No such key: \(decodedRootKey.stringValue)")) + let keys = [decodedRootKey.stringValue, key.stringValue].sorted() + throw DecodingError.keyNotFound(key, DecodingError.Context( + codingPath: codingPath, + debugDescription: "No such key: \(keys.joined(separator: " or "))")) } else { decodedRootKey = key return try decode(type, fromRow: row, codingPath: codingPath + [key]) diff --git a/Makefile b/Makefile index 739bff5c5..55893c1e0 100644 --- a/Makefile +++ b/Makefile @@ -408,10 +408,10 @@ ifdef JAZZY --author 'Gwendal Roué' \ --author_url https://github.com/groue \ --github_url https://github.com/groue/GRDB.swift \ - --github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.0.0-beta.11 \ - --module-version 5.0.0-beta.11 \ + --github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.0.0 \ + --module-version 5.0.0 \ --module GRDB \ - --root-url http://groue.github.io/GRDB.swift/docs/5.0.0-beta.11/ \ + --root-url http://groue.github.io/GRDB.swift/docs/5.0/ \ --output Documentation/Reference \ --xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS else diff --git a/README.md b/README.md index 82335d037..6a5841a26 100644 --- a/README.md +++ b/README.md @@ -11,23 +11,23 @@ --- -**Latest release**: September 7, 2020 • version 5.0.0-beta.11 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) +**Latest release**: September 20, 2020 • version 5.0.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) **Requirements**: iOS 10.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ • Swift 5.2+ / Xcode 11.4+ -| Swift version | GRDB version | -| ------------- | ----------------------------------------------------------- | -| **Swift 5.2** | **v5.0.0-beta.11**, [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0)| -| Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | -| Swift 5 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | -| Swift 4.2 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | -| Swift 4.1 | [v3.7.0](https://github.com/groue/GRDB.swift/tree/v3.7.0) | -| Swift 4 | [v2.10.0](https://github.com/groue/GRDB.swift/tree/v2.10.0) | -| Swift 3.2 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) | -| Swift 3.1 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) | -| Swift 3 | [v1.0](https://github.com/groue/GRDB.swift/tree/v1.0) | -| Swift 2.3 | [v0.81.2](https://github.com/groue/GRDB.swift/tree/v0.81.2) | -| Swift 2.2 | [v0.80.2](https://github.com/groue/GRDB.swift/tree/v0.80.2) | +| Swift version | GRDB version | +| -------------- | ----------------------------------------------------------- | +| **Swift 5.2+** | **v5.0.0** | +| Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | +| Swift 5 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | +| Swift 4.2 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | +| Swift 4.1 | [v3.7.0](https://github.com/groue/GRDB.swift/tree/v3.7.0) | +| Swift 4 | [v2.10.0](https://github.com/groue/GRDB.swift/tree/v2.10.0) | +| Swift 3.2 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) | +| Swift 3.1 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) | +| Swift 3 | [v1.0](https://github.com/groue/GRDB.swift/tree/v1.0) | +| Swift 2.3 | [v0.81.2](https://github.com/groue/GRDB.swift/tree/v0.81.2) | +| Swift 2.2 | [v0.80.2](https://github.com/groue/GRDB.swift/tree/v0.80.2) | **Contact**: @@ -278,7 +278,7 @@ Documentation #### Reference -- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.11/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) +- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.0/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) #### Getting Started @@ -480,7 +480,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.11/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0/Structs/Configuration.html) for more details. ## Database Pools @@ -560,7 +560,7 @@ let dbPool = try DatabasePool( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.11/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0/Structs/Configuration.html) for more details. Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information. @@ -620,7 +620,7 @@ try dbQueue.write { db in } ``` -The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.11/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. +The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. You can also embed query arguments right into your SQL queries, with the `literal` argument label, as in the example below. See [SQL Interpolation] for more details. @@ -823,7 +823,7 @@ try dbQueue.read { db in - **Cursors are granted with direct access to SQLite,** unlike arrays and sets that have to take the time to copy database values. If you look after extra performance, you may prefer cursors. -- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.11/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: +- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.0/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: ```swift // Prints all Github links @@ -906,7 +906,7 @@ let rows = try Row.fetchAll(db, arguments: ["name": "Arthur"]) ``` -See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.11/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. +See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care: @@ -1191,7 +1191,7 @@ GRDB ships with built-in support for the following value types: - Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol. -Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.11/Structs/StatementArguments.html): +Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.0/Structs/StatementArguments.html): ```swift let url: URL = ... @@ -1598,7 +1598,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction } ``` -Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.11/Structs/Configuration.html) configuration flag: +Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.0/Structs/Configuration.html) configuration flag: ```swift // fatal error: A transaction has been left opened at the end of a database access @@ -1712,7 +1712,7 @@ try dbQueue.write { db in } ``` -The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.11/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). +The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). ```swift updateStatement.arguments = ["name": "Arthur", "score": 1000] @@ -2489,7 +2489,7 @@ try Place.fetchSet(db, sql: "SELECT ...", arguments:...) // Set try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place? ``` -See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.11/Structs/StatementArguments.html) for more information about the query arguments. +See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0/Structs/StatementArguments.html) for more information about the query arguments. > :point_up: **Note**: for performance reasons, the same row argument to `init(row:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`. @@ -2870,7 +2870,7 @@ protocol EncodableRecord { } ``` -See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.11/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.11/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.11/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. +See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. > :point_up: **Note**: there is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs, and uuid strings). @@ -4318,7 +4318,7 @@ Player // SELECT * FROM player ``` -Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.11/Structs/StatementArguments.html): +Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.0/Structs/StatementArguments.html): ```swift // SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate) @@ -4974,7 +4974,7 @@ try Player.customRequest().fetchAll(db) // [Player] - The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method. -- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.11/Structs/AnyFetchRequest.html): a type-erased request. +- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.0/Structs/AnyFetchRequest.html): a type-erased request. ## Joined Queries Support @@ -6134,7 +6134,7 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan ### DatabaseRegion -**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.11/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**. +**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/5.0/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**. A request knows which database modifications can impact its results. It can communicate this information to [transaction observers](#transactionobserver-protocol) by the way of a DatabaseRegion. @@ -6144,7 +6144,7 @@ DatabaseRegion fuels, for example, [ValueObservation and DatabaseRegionObservati For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table. -For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.11/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). +For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/5.0/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). #### The DatabaseRegionConvertible Protocol @@ -7248,7 +7248,7 @@ try snapshot2.read { db in ### DatabaseWriter and DatabaseReader Protocols -Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.11/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.11/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only. +Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.0/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.0/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only. These protocols provide a unified API that let you write generic code that targets all concurrency modes. They fuel, for example: @@ -7864,7 +7864,7 @@ When this is the case, there are two possible explanations: try db.execute(sql: "UPDATE player SET name = ?", arguments: [name]) ``` -For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.11/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp). +For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.0/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp). @@ -8024,4 +8024,4 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv [Sharing a Database]: Documentation/SharingADatabase.md [FAQ]: #faq [Database Observation]: #database-changes-observation -[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.0.0-beta.11/Structs/SQLRequest.html +[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.0/Structs/SQLRequest.html diff --git a/Support/Info.plist b/Support/Info.plist index 119083c9d..909b3b299 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 5.0.0-beta.11 + 5.0.0 CFBundleSignature ???? CFBundleVersion diff --git a/Tests/GRDBTests/FetchableRecordDecodableTests.swift b/Tests/GRDBTests/FetchableRecordDecodableTests.swift index 5baae4ecb..5d1d3e1ab 100644 --- a/Tests/GRDBTests/FetchableRecordDecodableTests.swift +++ b/Tests/GRDBTests/FetchableRecordDecodableTests.swift @@ -1088,4 +1088,46 @@ extension FetchableRecordDecodableTests { // a or b can not be decoded because only one key is allowed to be missing } } + + // Regression test for https://github.com/groue/GRDB.swift/issues/836 + func testRootKeyDecodingError() throws { + struct Record: Decodable { } + struct Composed: Decodable, FetchableRecord { + var a: Record + var b: Record + var c: Record + } + try makeDatabaseQueue().read { db in + do { + // - a is present + // - root is b and c is missing, or the opposite (two possible user intents) + let row = try Row.fetchOne(db, sql: "SELECT NULL", adapter: ScopeAdapter(["a": EmptyRowAdapter()]))! + _ = try RowDecoder().decode(Composed.self, from: row) + XCTFail("Expected error") + } catch let DecodingError.keyNotFound(key, context) { + XCTAssert(["b", "c"].contains(key.stringValue)) + XCTAssertEqual(context.debugDescription, "No such key: b or c") + } + do { + // - b is present + // - root is a and c is missing, or the opposite (two possible user intents) + let row = try Row.fetchOne(db, sql: "SELECT NULL", adapter: ScopeAdapter(["b": EmptyRowAdapter()]))! + _ = try RowDecoder().decode(Composed.self, from: row) + XCTFail("Expected error") + } catch let DecodingError.keyNotFound(key, context) { + XCTAssert(["a", "c"].contains(key.stringValue)) + XCTAssertEqual(context.debugDescription, "No such key: a or c") + } + do { + // - c is present + // - root is a and b is missing, or the opposite (two possible user intents) + let row = try Row.fetchOne(db, sql: "SELECT NULL", adapter: ScopeAdapter(["c": EmptyRowAdapter()]))! + _ = try RowDecoder().decode(Composed.self, from: row) + XCTFail("Expected error") + } catch let DecodingError.keyNotFound(key, context) { + XCTAssert(["a", "b"].contains(key.stringValue)) + XCTAssertEqual(context.debugDescription, "No such key: a or b") + } + } + } } diff --git a/Tests/GRDBTests/TableDefinitionTests.swift b/Tests/GRDBTests/TableDefinitionTests.swift index 8ffc2b079..dc789db30 100644 --- a/Tests/GRDBTests/TableDefinitionTests.swift +++ b/Tests/GRDBTests/TableDefinitionTests.swift @@ -140,6 +140,21 @@ class TableDefinitionTests: GRDBTestCase { } } + // Regression test for https://github.com/groue/GRDB.swift/issues/838 + func testColumnIndexedInheritsIfNotExistsFlag() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + sqlQueries.removeAll() + try db.create(table: "test", ifNotExists: true) { t in + t.column("a", .integer).indexed() + t.column("b", .integer).indexed() + } + assertEqualSQL(sqlQueries[0], "CREATE TABLE IF NOT EXISTS \"test\" (\"a\" INTEGER, \"b\" INTEGER)") + assertEqualSQL(sqlQueries[1], "CREATE INDEX IF NOT EXISTS \"test_on_a\" ON \"test\"(\"a\")") + assertEqualSQL(sqlQueries[2], "CREATE INDEX IF NOT EXISTS \"test_on_b\" ON \"test\"(\"b\")") + } + } + func testColumnUnique() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in diff --git a/Tests/Performance/GRDBPerformance/FetchNamedValuesTests.swift b/Tests/Performance/GRDBPerformance/FetchNamedValuesTests.swift index 77adee3cf..eda7f0767 100644 --- a/Tests/Performance/GRDBPerformance/FetchNamedValuesTests.swift +++ b/Tests/Performance/GRDBPerformance/FetchNamedValuesTests.swift @@ -10,8 +10,9 @@ private let expectedRowCount = 100_000 class FetchNamedValuesTests: XCTestCase { func testGRDB() throws { - let databasePath = Bundle(for: type(of: self)).path(forResource: "PerformanceTests", ofType: "sqlite")! - let dbQueue = try DatabaseQueue(path: databasePath) + let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("GRDBPerformanceTests.sqlite") + try generateSQLiteDatabaseIfMissing(at: url, insertedRowCount: expectedRowCount) + let dbQueue = try DatabaseQueue(path: url.path) measure { var count = 0 @@ -39,9 +40,10 @@ class FetchNamedValuesTests: XCTestCase { } #if GRDB_COMPARE - func testFMDB() { - let databasePath = Bundle(for: type(of: self)).path(forResource: "PerformanceTests", ofType: "sqlite")! - let dbQueue = FMDatabaseQueue(path: databasePath)! + func testFMDB() throws { + let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("GRDBPerformanceTests.sqlite") + try generateSQLiteDatabaseIfMissing(at: url, insertedRowCount: expectedRowCount) + let dbQueue = FMDatabaseQueue(path: url.path)! measure { var count = 0 @@ -69,8 +71,9 @@ class FetchNamedValuesTests: XCTestCase { } func testSQLiteSwift() throws { - let databasePath = Bundle(for: type(of: self)).path(forResource: "PerformanceTests", ofType: "sqlite")! - let db = try Connection(databasePath) + let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("GRDBPerformanceTests.sqlite") + try generateSQLiteDatabaseIfMissing(at: url, insertedRowCount: expectedRowCount) + let db = try Connection(url.path) measure { var count = 0 diff --git a/Tests/Performance/GRDBPerformance/FetchPositionalValuesTests.swift b/Tests/Performance/GRDBPerformance/FetchPositionalValuesTests.swift index e8bb430e6..610cf2cd2 100644 --- a/Tests/Performance/GRDBPerformance/FetchPositionalValuesTests.swift +++ b/Tests/Performance/GRDBPerformance/FetchPositionalValuesTests.swift @@ -9,10 +9,11 @@ private let expectedRowCount = 100_000 /// Here we test the extraction of values by column index. class FetchPositionalValuesTests: XCTestCase { - func testSQLite() { - let databasePath = Bundle(for: type(of: self)).path(forResource: "PerformanceTests", ofType: "sqlite")! + func testSQLite() throws { + let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("GRDBPerformanceTests.sqlite") + try generateSQLiteDatabaseIfMissing(at: url, insertedRowCount: expectedRowCount) var connection: OpaquePointer? = nil - sqlite3_open_v2(databasePath, &connection, 0x00000004 /*SQLITE_OPEN_CREATE*/ | 0x00000002 /*SQLITE_OPEN_READWRITE*/, nil) + sqlite3_open_v2(url.path, &connection, 0x00000004 /*SQLITE_OPEN_CREATE*/ | 0x00000002 /*SQLITE_OPEN_READWRITE*/, nil) measure { var count = 0 @@ -51,8 +52,9 @@ class FetchPositionalValuesTests: XCTestCase { } func testGRDB() throws { - let databasePath = Bundle(for: type(of: self)).path(forResource: "PerformanceTests", ofType: "sqlite")! - let dbQueue = try DatabaseQueue(path: databasePath) + let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("GRDBPerformanceTests.sqlite") + try generateSQLiteDatabaseIfMissing(at: url, insertedRowCount: expectedRowCount) + let dbQueue = try DatabaseQueue(path: url.path) measure { var count = 0 @@ -80,9 +82,10 @@ class FetchPositionalValuesTests: XCTestCase { } #if GRDB_COMPARE - func testFMDB() { - let databasePath = Bundle(for: type(of: self)).path(forResource: "PerformanceTests", ofType: "sqlite")! - let dbQueue = FMDatabaseQueue(path: databasePath)! + func testFMDB() throws { + let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("GRDBPerformanceTests.sqlite") + try generateSQLiteDatabaseIfMissing(at: url, insertedRowCount: expectedRowCount) + let dbQueue = FMDatabaseQueue(path: url.path)! measure { var count = 0 @@ -110,8 +113,9 @@ class FetchPositionalValuesTests: XCTestCase { } func testSQLiteSwift() throws { - let databasePath = Bundle(for: type(of: self)).path(forResource: "PerformanceTests", ofType: "sqlite")! - let db = try Connection(databasePath) + let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("GRDBPerformanceTests.sqlite") + try generateSQLiteDatabaseIfMissing(at: url, insertedRowCount: expectedRowCount) + let db = try Connection(url.path) measure { var count = 0 diff --git a/Tests/Performance/GRDBPerformance/FetchRecordClassTests.swift b/Tests/Performance/GRDBPerformance/FetchRecordClassTests.swift index b0c7c94ee..67230aece 100644 --- a/Tests/Performance/GRDBPerformance/FetchRecordClassTests.swift +++ b/Tests/Performance/GRDBPerformance/FetchRecordClassTests.swift @@ -11,8 +11,9 @@ private let expectedRowCount = 100_000 class FetchRecordClassTests: XCTestCase { func testGRDB() throws { - let databasePath = Bundle(for: type(of: self)).path(forResource: "PerformanceTests", ofType: "sqlite")! - let dbQueue = try DatabaseQueue(path: databasePath) + let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("GRDBPerformanceTests.sqlite") + try generateSQLiteDatabaseIfMissing(at: url, insertedRowCount: expectedRowCount) + let dbQueue = try DatabaseQueue(path: url.path) measure { let items = try! dbQueue.inDatabase { db in @@ -27,11 +28,12 @@ class FetchRecordClassTests: XCTestCase { #if GRDB_COMPARE func testCoreData() throws { - let databasePath = Bundle(for: type(of: self)).path(forResource: "PerformanceCoreDataTests", ofType: "sqlite")! let modelURL = Bundle(for: type(of: self)).url(forResource: "PerformanceModel", withExtension: "momd")! + let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("GRDBCoreDataPerformanceTests.sqlite") + try generateCoreDataDatabaseIfMissing(at: url, fromModelAt: modelURL, insertedRowCount: expectedRowCount) let mom = NSManagedObjectModel(contentsOf: modelURL)! let psc = NSPersistentStoreCoordinator(managedObjectModel: mom) - try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: URL(fileURLWithPath: databasePath), options: nil) + try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) let moc = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) moc.persistentStoreCoordinator = psc @@ -56,8 +58,9 @@ class FetchRecordClassTests: XCTestCase { } func testRealm() throws { - let databaseURL = Bundle(for: type(of: self)).url(forResource: "PerformanceRealmTests", withExtension: "realm")! - let realm = try Realm(fileURL: databaseURL) + let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("GRDBRealmPerformanceTests.realm") + try generateRealmDatabaseIfMissing(at: url, insertedRowCount: expectedRowCount) + let realm = try Realm(fileURL: url) measure { let items = realm.objects(RealmItem.self) diff --git a/Tests/Performance/GRDBPerformance/FetchRecordCodableTests.swift b/Tests/Performance/GRDBPerformance/FetchRecordCodableTests.swift index 73f0729ca..c08d45cf2 100644 --- a/Tests/Performance/GRDBPerformance/FetchRecordCodableTests.swift +++ b/Tests/Performance/GRDBPerformance/FetchRecordCodableTests.swift @@ -10,8 +10,9 @@ private let expectedRowCount = 100_000 class FetchRecordCodableTests: XCTestCase { func testGRDB() throws { - let databasePath = Bundle(for: type(of: self)).path(forResource: "PerformanceTests", ofType: "sqlite")! - let dbQueue = try DatabaseQueue(path: databasePath) + let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("GRDBPerformanceTests.sqlite") + try generateSQLiteDatabaseIfMissing(at: url, insertedRowCount: expectedRowCount) + let dbQueue = try DatabaseQueue(path: url.path) measure { let items = try! dbQueue.inDatabase { db in diff --git a/Tests/Performance/GRDBPerformance/FetchRecordStructTests.swift b/Tests/Performance/GRDBPerformance/FetchRecordStructTests.swift index 869e3a490..433b917e9 100644 --- a/Tests/Performance/GRDBPerformance/FetchRecordStructTests.swift +++ b/Tests/Performance/GRDBPerformance/FetchRecordStructTests.swift @@ -9,10 +9,11 @@ private let expectedRowCount = 100_000 /// Here we test the extraction of models from rows class FetchRecordStructTests: XCTestCase { - func testSQLite() { - let databasePath = Bundle(for: type(of: self)).path(forResource: "PerformanceTests", ofType: "sqlite")! + func testSQLite() throws { + let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("GRDBPerformanceTests.sqlite") + try generateSQLiteDatabaseIfMissing(at: url, insertedRowCount: expectedRowCount) var connection: OpaquePointer? = nil - sqlite3_open_v2(databasePath, &connection, 0x00000004 /*SQLITE_OPEN_CREATE*/ | 0x00000002 /*SQLITE_OPEN_READWRITE*/, nil) + sqlite3_open_v2(url.path, &connection, 0x00000004 /*SQLITE_OPEN_CREATE*/ | 0x00000002 /*SQLITE_OPEN_READWRITE*/, nil) measure { var statement: OpaquePointer? = nil @@ -66,8 +67,9 @@ class FetchRecordStructTests: XCTestCase { } func testGRDB() throws { - let databasePath = Bundle(for: type(of: self)).path(forResource: "PerformanceTests", ofType: "sqlite")! - let dbQueue = try DatabaseQueue(path: databasePath) + let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("GRDBPerformanceTests.sqlite") + try generateSQLiteDatabaseIfMissing(at: url, insertedRowCount: expectedRowCount) + let dbQueue = try DatabaseQueue(path: url.path) measure { let items = try! dbQueue.inDatabase { db in @@ -81,11 +83,12 @@ class FetchRecordStructTests: XCTestCase { } #if GRDB_COMPARE - func testFMDB() { + func testFMDB() throws { // Here we test the loading of an array of Records. - let databasePath = Bundle(for: type(of: self)).path(forResource: "PerformanceTests", ofType: "sqlite")! - let dbQueue = FMDatabaseQueue(path: databasePath)! + let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("GRDBPerformanceTests.sqlite") + try generateSQLiteDatabaseIfMissing(at: url, insertedRowCount: expectedRowCount) + let dbQueue = FMDatabaseQueue(path: url.path)! measure { var items = [ItemStruct]() @@ -104,8 +107,9 @@ class FetchRecordStructTests: XCTestCase { } func testSQLiteSwift() throws { - let databasePath = Bundle(for: type(of: self)).path(forResource: "PerformanceTests", ofType: "sqlite")! - let db = try Connection(databasePath) + let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("GRDBPerformanceTests.sqlite") + try generateSQLiteDatabaseIfMissing(at: url, insertedRowCount: expectedRowCount) + let db = try Connection(url.path) measure { var items = [ItemStruct]() diff --git a/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.pbxproj b/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.pbxproj index 17a196df8..93e46c4f6 100755 --- a/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.pbxproj +++ b/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.pbxproj @@ -22,10 +22,8 @@ 56439B3E1F4CA1DC0066043F /* PerformanceModel.xcdatamodeld in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B2D1C42B23B00861EB8 /* PerformanceModel.xcdatamodeld */; }; 56439B3F1F4CA1DC0066043F /* FetchPositionalValuesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B291C4130AF00861EB8 /* FetchPositionalValuesTests.swift */; }; 56439B431F4CA1DC0066043F /* CoreData.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56DE7B341C42B37E00861EB8 /* CoreData.framework */; }; - 56439B471F4CA1DC0066043F /* PerformanceRealmTests.realm in Resources */ = {isa = PBXBuildFile; fileRef = 563363F81C960711000BE133 /* PerformanceRealmTests.realm */; }; - 56439B481F4CA1DC0066043F /* PerformanceTests.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 56BB86111BA9886D001F9168 /* PerformanceTests.sqlite */; }; - 56439B491F4CA1DC0066043F /* PerformanceCoreDataTests.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 56DE7B361C42BBBB00861EB8 /* PerformanceCoreDataTests.sqlite */; }; - 56439B581F4CA5AE0066043F /* PerformanceTests.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 56BB86111BA9886D001F9168 /* PerformanceTests.sqlite */; }; + 565BC5E82517645D00D2B53E /* Generation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565BC5E72517645D00D2B53E /* Generation.swift */; }; + 565BC5E92517645D00D2B53E /* Generation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565BC5E72517645D00D2B53E /* Generation.swift */; }; 56707201208A509C006AD95A /* DateParsingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071FA208A509C006AD95A /* DateParsingTests.swift */; }; 5679870223A37A6A0076902D /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 567986B923A378CD0076902D /* GRDB.framework */; }; 5679870523A37A790076902D /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 567986B923A378CD0076902D /* GRDB.framework */; }; @@ -131,13 +129,12 @@ /* Begin PBXFileReference section */ 560C981A1C0E22D300BF8471 /* GRDBOSXPerformanceTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXPerformanceTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 563363F81C960711000BE133 /* PerformanceRealmTests.realm */ = {isa = PBXFileReference; lastKnownFileType = file; path = PerformanceRealmTests.realm; sourceTree = ""; }; 56439B501F4CA1DC0066043F /* GRDBOSXPerformanceComparisonTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXPerformanceComparisonTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 565BC5E72517645D00D2B53E /* Generation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Generation.swift; sourceTree = ""; }; 567071FA208A509C006AD95A /* DateParsingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DateParsingTests.swift; sourceTree = ""; }; 567986AD23A378CD0076902D /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = ""; }; 5690AFD72120589A001530EA /* InsertRecordCodableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InsertRecordCodableTests.swift; sourceTree = ""; }; 5690AFDA212058CB001530EA /* FetchRecordCodableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRecordCodableTests.swift; sourceTree = ""; }; - 56BB86111BA9886D001F9168 /* PerformanceTests.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = PerformanceTests.sqlite; sourceTree = ""; }; 56BB86121BA9886D001F9168 /* InsertRecordClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InsertRecordClassTests.swift; sourceTree = ""; }; 56BB862D1BA98933001F9168 /* GRDBPerformanceComparisonTests-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDBPerformanceComparisonTests-Bridging.h"; sourceTree = ""; }; 56CA22211BB41565009A04C5 /* PerformanceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PerformanceTests.swift; sourceTree = ""; }; @@ -150,7 +147,6 @@ 56DE7B2B1C41311900861EB8 /* FetchRecordClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRecordClassTests.swift; sourceTree = ""; }; 56DE7B2E1C42B23B00861EB8 /* PerformanceModel.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = PerformanceModel.xcdatamodel; sourceTree = ""; }; 56DE7B341C42B37E00861EB8 /* CoreData.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreData.framework; path = System/Library/Frameworks/CoreData.framework; sourceTree = SDKROOT; }; - 56DE7B361C42BBBB00861EB8 /* PerformanceCoreDataTests.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = PerformanceCoreDataTests.sqlite; sourceTree = ""; }; DC37740419C8CBB3004FCF85 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; /* End PBXFileReference section */ @@ -205,16 +201,14 @@ isa = PBXGroup; children = ( 56BB862D1BA98933001F9168 /* GRDBPerformanceComparisonTests-Bridging.h */, - 56BB86111BA9886D001F9168 /* PerformanceTests.sqlite */, - 56DE7B361C42BBBB00861EB8 /* PerformanceCoreDataTests.sqlite */, 56DE7B2D1C42B23B00861EB8 /* PerformanceModel.xcdatamodeld */, - 563363F81C960711000BE133 /* PerformanceRealmTests.realm */, 567071FA208A509C006AD95A /* DateParsingTests.swift */, 56DE7B271C41302500861EB8 /* FetchNamedValuesTests.swift */, 56DE7B291C4130AF00861EB8 /* FetchPositionalValuesTests.swift */, 56DE7B2B1C41311900861EB8 /* FetchRecordClassTests.swift */, 5690AFDA212058CB001530EA /* FetchRecordCodableTests.swift */, 56D3BE701F4EB1900034C6D2 /* FetchRecordStructTests.swift */, + 565BC5E72517645D00D2B53E /* Generation.swift */, 56DE7B251C412FDA00861EB8 /* InsertNamedValuesTests.swift */, 56DE7B231C412F7E00861EB8 /* InsertPositionalValuesTests.swift */, 56BB86121BA9886D001F9168 /* InsertRecordClassTests.swift */, @@ -312,7 +306,7 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0730; - LastUpgradeCheck = 1020; + LastUpgradeCheck = 1200; ORGANIZATIONNAME = "Gwendal Roué"; }; buildConfigurationList = DC3773ED19C8CBB3004FCF85 /* Build configuration list for PBXProject "GRDBPerformance" */; @@ -409,7 +403,6 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( - 56439B581F4CA5AE0066043F /* PerformanceTests.sqlite in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -417,9 +410,6 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( - 56439B471F4CA1DC0066043F /* PerformanceRealmTests.realm in Resources */, - 56439B481F4CA1DC0066043F /* PerformanceTests.sqlite in Resources */, - 56439B491F4CA1DC0066043F /* PerformanceCoreDataTests.sqlite in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -431,6 +421,7 @@ buildActionMask = 2147483647; files = ( 56D3BE711F4EB1A00034C6D2 /* FetchRecordStructTests.swift in Sources */, + 565BC5E82517645D00D2B53E /* Generation.swift in Sources */, 560C98231C0E23BB00BF8471 /* InsertRecordClassTests.swift in Sources */, 56707201208A509C006AD95A /* DateParsingTests.swift in Sources */, 56DE7B2C1C41311900861EB8 /* FetchRecordClassTests.swift in Sources */, @@ -450,6 +441,7 @@ buildActionMask = 2147483647; files = ( 56439B341F4CA1DC0066043F /* InsertRecordClassTests.swift in Sources */, + 565BC5E92517645D00D2B53E /* Generation.swift in Sources */, 56439B361F4CA1DC0066043F /* FetchRecordClassTests.swift in Sources */, 56439B381F4CA1DC0066043F /* FetchNamedValuesTests.swift in Sources */, 56439B391F4CA1DC0066043F /* InsertPositionalValuesTests.swift in Sources */, @@ -494,7 +486,6 @@ "@executable_path/../Frameworks", "@loader_path/../Frameworks", ); - MACOSX_DEPLOYMENT_TARGET = 10.10; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; @@ -516,7 +507,6 @@ "@executable_path/../Frameworks", "@loader_path/../Frameworks", ); - MACOSX_DEPLOYMENT_TARGET = 10.10; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; @@ -538,7 +528,6 @@ "@executable_path/../Frameworks", "@loader_path/../Frameworks", ); - MACOSX_DEPLOYMENT_TARGET = 10.10; OTHER_SWIFT_FLAGS = "$(inherited) -D GRDB_COMPARE"; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; @@ -561,7 +550,6 @@ "@executable_path/../Frameworks", "@loader_path/../Frameworks", ); - MACOSX_DEPLOYMENT_TARGET = 10.10; OTHER_SWIFT_FLAGS = "$(inherited) -D GRDB_COMPARE"; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; @@ -595,6 +583,7 @@ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; @@ -652,6 +641,7 @@ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; @@ -734,7 +724,7 @@ repositoryURL = "https://github.com/realm/realm-cocoa.git"; requirement = { kind = exactVersion; - version = 4.4.0; + version = 5.4.2; }; }; /* End XCRemoteSwiftPackageReference section */ diff --git a/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 5e1c3a772..7eede11d0 100644 --- a/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -15,8 +15,8 @@ "repositoryURL": "https://github.com/realm/realm-cocoa.git", "state": { "branch": null, - "revision": "07734d6ee4b49b5656c51dab51c20a2d59b9de45", - "version": "4.4.0" + "revision": "f64ac045d8cb171d8e317d9b854df7215aed7466", + "version": "5.4.2" } }, { @@ -24,8 +24,8 @@ "repositoryURL": "https://github.com/realm/realm-core", "state": { "branch": null, - "revision": "35662ff940e340bf630ad1d1d88acfc7af18bee6", - "version": "5.23.8" + "revision": "e051fc73c56830bf3ab0b8a82f7a613968cec6c6", + "version": "6.0.26" } }, { diff --git a/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/xcshareddata/xcschemes/GRDBOSXPerformanceComparisonTests.xcscheme b/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/xcshareddata/xcschemes/GRDBOSXPerformanceComparisonTests.xcscheme index 3e527939b..98a74d686 100644 --- a/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/xcshareddata/xcschemes/GRDBOSXPerformanceComparisonTests.xcscheme +++ b/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/xcshareddata/xcschemes/GRDBOSXPerformanceComparisonTests.xcscheme @@ -1,6 +1,6 @@ (entityName: "Item") + if try! moc.count(for: request) == insertedRowCount { + return + } + try! moc.execute(NSBatchDeleteRequest(fetchRequest: request)) + + for i in 0..(.*)<\/configCode>/; hardware = $1 STDERR.puts "GRDB #{grdb_version}" STDERR.puts "FMDB #{fmdb_version}" STDERR.puts "SQLite.swift #{sqlite_swift_version}" STDERR.puts "Realm #{realm_version}" +STDERR.puts "Xcode #{xcode_version}" +STDERR.puts "Hardware #{hardware}" # Generate puts <<-REPORT @@ -68,7 +72,7 @@ puts <<-REPORT Below are performance benchmarks made on for [GRDB #{grdb_version}](https://github.com/groue/GRDB.swift), [FMDB #{fmdb_version}](https://github.com/ccgus/fmdb), and [SQLite.swift #{sqlite_swift_version}](https://github.com/stephencelis/SQLite.swift). They are compared to Core Data, [Realm #{realm_version}](https://realm.io) and the raw use of the SQLite C API from Swift. -This report was generated on a MacBook Pro (15-inch, Late 2016), with Xcode 10.2.1, by running the following command: +This report was generated on a #{hardware}, with Xcode #{xcode_version}, by running the following command: ```sh make test_performance | Tests/parsePerformanceTests.rb | Tests/generatePerformanceReport.rb