mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-27 04:14:21 +00:00
Merge branch 'development'
This commit is contained in:
commit
6dc7367853
37 files changed
+536
-704
No files matched your search
@@ -106,6 +106,7 @@ Podfile.lock
|
||||
|
||||
# SPM
|
||||
.build
|
||||
.swiftpm/
|
||||
GRDB.xcworkspace/xcshareddata/swiftpm
|
||||
#Package.resolved
|
||||
Tests/SPM/Packages
|
||||
|
||||
@@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 5.x Releases
|
||||
|
||||
- `5.14.x` Releases - [5.14.0](#5140)
|
||||
- `5.13.x` Releases - [5.13.0](#5130)
|
||||
- `5.12.x` Releases - [5.12.0](#5120)
|
||||
- `5.11.x` Releases - [5.11.0](#5110)
|
||||
@@ -80,6 +81,15 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## 5.14.0
|
||||
|
||||
Released November 25, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.13.0...v5.14.0)
|
||||
|
||||
- **Fix**: `ForeignKeyViolation.failureDescription(_:)` now accepts table names that require quoting.
|
||||
- **Fix**: Add missing `public` qualifier on `ForeignKeyViolation` properties.
|
||||
- **New**: `ForeignKeyViolation.databaseError(_:)` turns a foreign key violation into a `DatabaseError`.
|
||||
- **Documentation Update**: the demo apps were modernized for iOS 15+. The SwiftUI demo app now uses the [GRDBQuery](https://github.com/groue/GRDBQuery) package in order to update its views according to the database content.
|
||||
|
||||
## 5.13.0
|
||||
|
||||
Released November 7, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.12.0...v5.13.0)
|
||||
|
||||
@@ -9,14 +9,12 @@
|
||||
/* Begin PBXBuildFile section */
|
||||
56026CAC25B8A7EF00D1DF3F /* PlayerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */; };
|
||||
56026CAD25B8A7EF00D1DF3F /* AppDatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */; };
|
||||
5671722A261A185300423B6F /* Query.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717229261A185300423B6F /* Query.swift */; };
|
||||
56519DC7274FC85600ED16D8 /* GRDBQuery in Frameworks */ = {isa = PBXBuildFile; productRef = 56519DC6274FC85600ED16D8 /* GRDBQuery */; };
|
||||
5671723A261B23C800423B6F /* PlayerList.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717239261B23C800423B6F /* PlayerList.swift */; };
|
||||
56717252261B334D00423B6F /* PlayerRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717251261B334D00423B6F /* PlayerRequestTests.swift */; };
|
||||
567C3E1A2520B6DE0011F6E9 /* GRDBCombineDemoApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */; };
|
||||
567C3E1E2520B6DF0011F6E9 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */; };
|
||||
567C3E212520B6DF0011F6E9 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E202520B6DF0011F6E9 /* Preview Assets.xcassets */; };
|
||||
567C3E4E2520B70E0011F6E9 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 567C3E3B2520B7000011F6E9 /* GRDB.framework */; };
|
||||
567C3E4F2520B70E0011F6E9 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 567C3E3B2520B7000011F6E9 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
|
||||
567C3E5D2520B75C0011F6E9 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E532520B75C0011F6E9 /* Player.swift */; };
|
||||
567C3E5E2520B75C0011F6E9 /* Persistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E542520B75C0011F6E9 /* Persistence.swift */; };
|
||||
567C3E612520B75D0011F6E9 /* PlayerFormView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E592520B75C0011F6E9 /* PlayerFormView.swift */; };
|
||||
@@ -27,6 +25,7 @@
|
||||
567C3E792520BB650011F6E9 /* Localizable.stringsdict in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E752520BB650011F6E9 /* Localizable.stringsdict */; };
|
||||
567C3E7A2520BB650011F6E9 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */; };
|
||||
56B6D1092619EC1B003CC455 /* PlayerRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D1082619EC1B003CC455 /* PlayerRequest.swift */; };
|
||||
56F8A1202735989D0011ACBE /* GRDB in Frameworks */ = {isa = PBXBuildFile; productRef = 56F8A11F2735989D0011ACBE /* GRDB */; };
|
||||
78E2F9E6261EEC22005D1F7F /* GRDBCombineDemoUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78E2F9E5261EEC22005D1F7F /* GRDBCombineDemoUITests.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
@@ -38,69 +37,6 @@
|
||||
remoteGlobalIDString = 567C3E152520B6DE0011F6E9;
|
||||
remoteInfo = GRDBCombineDemo;
|
||||
};
|
||||
567C3E342520B7000011F6E9 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = DC3773F319C8CBB3004FCF85;
|
||||
remoteInfo = GRDBOSX;
|
||||
};
|
||||
567C3E362520B7000011F6E9 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56E5D7F91B4D422D00430942;
|
||||
remoteInfo = GRDBOSXTests;
|
||||
};
|
||||
567C3E382520B7000011F6E9 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56553C181C3E906C00522B5C;
|
||||
remoteInfo = GRDBOSXCrashTests;
|
||||
};
|
||||
567C3E3A2520B7000011F6E9 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56E5D7CA1B4D3FED00430942;
|
||||
remoteInfo = GRDBiOS;
|
||||
};
|
||||
567C3E3C2520B7000011F6E9 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56E5D7D31B4D3FEE00430942;
|
||||
remoteInfo = GRDBiOSTests;
|
||||
};
|
||||
567C3E3E2520B7000011F6E9 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 565490A01D5A4798005622CB;
|
||||
remoteInfo = GRDBWatchOS;
|
||||
};
|
||||
567C3E402520B7000011F6E9 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = AAA4DCFE230F1E0600C74B15;
|
||||
remoteInfo = GRDBtvOS;
|
||||
};
|
||||
567C3E422520B7000011F6E9 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = AAA4DDD4230F262000C74B15;
|
||||
remoteInfo = GRDBtvOSTests;
|
||||
};
|
||||
567C3E512520B71C0011F6E9 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 56E5D7C91B4D3FED00430942;
|
||||
remoteInfo = GRDBiOS;
|
||||
};
|
||||
78E2F9E8261EEC22005D1F7F /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 567C3E0E2520B6DE0011F6E9 /* Project object */;
|
||||
@@ -117,7 +53,6 @@
|
||||
dstPath = "";
|
||||
dstSubfolderSpec = 10;
|
||||
files = (
|
||||
567C3E4F2520B70E0011F6E9 /* GRDB.framework in Embed Frameworks */,
|
||||
);
|
||||
name = "Embed Frameworks";
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
@@ -129,7 +64,6 @@
|
||||
56026C9C25B8A7D000D1DF3F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerTests.swift; sourceTree = "<group>"; };
|
||||
56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabaseTests.swift; sourceTree = "<group>"; };
|
||||
56717229261A185300423B6F /* Query.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Query.swift; sourceTree = "<group>"; };
|
||||
56717239261B23C800423B6F /* PlayerList.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerList.swift; sourceTree = "<group>"; };
|
||||
56717251261B334D00423B6F /* PlayerRequestTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerRequestTests.swift; sourceTree = "<group>"; };
|
||||
567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBCombineDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
@@ -137,7 +71,6 @@
|
||||
567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
|
||||
567C3E202520B6DF0011F6E9 /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = "<group>"; };
|
||||
567C3E222520B6DF0011F6E9 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
567C3E292520B7000011F6E9 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = "<group>"; };
|
||||
567C3E532520B75C0011F6E9 /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = "<group>"; };
|
||||
567C3E542520B75C0011F6E9 /* Persistence.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistence.swift; sourceTree = "<group>"; };
|
||||
567C3E592520B75C0011F6E9 /* PlayerFormView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerFormView.swift; sourceTree = "<group>"; };
|
||||
@@ -148,6 +81,7 @@
|
||||
567C3E762520BB650011F6E9 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.stringsdict; name = en; path = en.lproj/Localizable.stringsdict; sourceTree = "<group>"; };
|
||||
567C3E782520BB650011F6E9 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
|
||||
56B6D1082619EC1B003CC455 /* PlayerRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerRequest.swift; sourceTree = "<group>"; };
|
||||
56F8A11C2735988F0011ACBE /* GRDB.swift */ = {isa = PBXFileReference; lastKnownFileType = folder; name = GRDB.swift; path = ../../..; sourceTree = "<group>"; };
|
||||
78E2F9E3261EEC22005D1F7F /* GRDBCombineDemoUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCombineDemoUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
78E2F9E5261EEC22005D1F7F /* GRDBCombineDemoUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GRDBCombineDemoUITests.swift; sourceTree = "<group>"; };
|
||||
78E2F9E7261EEC22005D1F7F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
@@ -165,7 +99,8 @@
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
567C3E4E2520B70E0011F6E9 /* GRDB.framework in Frameworks */,
|
||||
56519DC7274FC85600ED16D8 /* GRDBQuery in Frameworks */,
|
||||
56F8A1202735989D0011ACBE /* GRDB in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -200,23 +135,15 @@
|
||||
path = Resources;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
56185BC225B8048B00B9C30F /* Support */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567C3E222520B6DF0011F6E9 /* Info.plist */,
|
||||
);
|
||||
name = Support;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
567C3E0D2520B6DE0011F6E9 = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567C3E292520B7000011F6E9 /* GRDB.xcodeproj */,
|
||||
567C3E182520B6DE0011F6E9 /* GRDBCombineDemo */,
|
||||
56026C9925B8A7D000D1DF3F /* GRDBCombineDemoTests */,
|
||||
78E2F9E4261EEC22005D1F7F /* GRDBCombineDemoUITests */,
|
||||
567C3E172520B6DE0011F6E9 /* Products */,
|
||||
567C3E4D2520B70E0011F6E9 /* Frameworks */,
|
||||
56F8A11C2735988F0011ACBE /* GRDB.swift */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
@@ -233,15 +160,14 @@
|
||||
567C3E182520B6DE0011F6E9 /* GRDBCombineDemo */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567C3E222520B6DF0011F6E9 /* Info.plist */,
|
||||
567C3E652520B7880011F6E9 /* AppDatabase.swift */,
|
||||
567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */,
|
||||
567C3E542520B75C0011F6E9 /* Persistence.swift */,
|
||||
567C3E532520B75C0011F6E9 /* Player.swift */,
|
||||
56B6D1082619EC1B003CC455 /* PlayerRequest.swift */,
|
||||
56717229261A185300423B6F /* Query.swift */,
|
||||
567C3E1F2520B6DF0011F6E9 /* Preview Content */,
|
||||
56185BC125B8047D00B9C30F /* Resources */,
|
||||
56185BC225B8048B00B9C30F /* Support */,
|
||||
567C3E582520B75C0011F6E9 /* Views */,
|
||||
);
|
||||
path = GRDBCombineDemo;
|
||||
@@ -255,21 +181,6 @@
|
||||
path = "Preview Content";
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
567C3E2A2520B7000011F6E9 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567C3E352520B7000011F6E9 /* GRDB.framework */,
|
||||
567C3E372520B7000011F6E9 /* GRDBOSXTests.xctest */,
|
||||
567C3E392520B7000011F6E9 /* GRDBOSXCrashTests.xctest */,
|
||||
567C3E3B2520B7000011F6E9 /* GRDB.framework */,
|
||||
567C3E3D2520B7000011F6E9 /* GRDBiOSTests.xctest */,
|
||||
567C3E3F2520B7000011F6E9 /* GRDB.framework */,
|
||||
567C3E412520B7000011F6E9 /* GRDB.framework */,
|
||||
567C3E432520B7000011F6E9 /* GRDBtvOSTests.xctest */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
567C3E4D2520B70E0011F6E9 /* Frameworks */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@@ -331,9 +242,13 @@
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
567C3E522520B71C0011F6E9 /* PBXTargetDependency */,
|
||||
56F8A11E273598960011ACBE /* PBXTargetDependency */,
|
||||
);
|
||||
name = GRDBCombineDemo;
|
||||
packageProductDependencies = (
|
||||
56F8A11F2735989D0011ACBE /* GRDB */,
|
||||
56519DC6274FC85600ED16D8 /* GRDBQuery */,
|
||||
);
|
||||
productName = GRBCombineDemo;
|
||||
productReference = 567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */;
|
||||
productType = "com.apple.product-type.application";
|
||||
@@ -387,14 +302,11 @@
|
||||
Base,
|
||||
);
|
||||
mainGroup = 567C3E0D2520B6DE0011F6E9;
|
||||
packageReferences = (
|
||||
56519DC5274FC85600ED16D8 /* XCRemoteSwiftPackageReference "GRDBQuery" */,
|
||||
);
|
||||
productRefGroup = 567C3E172520B6DE0011F6E9 /* Products */;
|
||||
projectDirPath = "";
|
||||
projectReferences = (
|
||||
{
|
||||
ProductGroup = 567C3E2A2520B7000011F6E9 /* Products */;
|
||||
ProjectRef = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
|
||||
},
|
||||
);
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */,
|
||||
@@ -404,65 +316,6 @@
|
||||
};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXReferenceProxy section */
|
||||
567C3E352520B7000011F6E9 /* GRDB.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = GRDB.framework;
|
||||
remoteRef = 567C3E342520B7000011F6E9 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
567C3E372520B7000011F6E9 /* GRDBOSXTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBOSXTests.xctest;
|
||||
remoteRef = 567C3E362520B7000011F6E9 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
567C3E392520B7000011F6E9 /* GRDBOSXCrashTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBOSXCrashTests.xctest;
|
||||
remoteRef = 567C3E382520B7000011F6E9 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
567C3E3B2520B7000011F6E9 /* GRDB.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = GRDB.framework;
|
||||
remoteRef = 567C3E3A2520B7000011F6E9 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
567C3E3D2520B7000011F6E9 /* GRDBiOSTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBiOSTests.xctest;
|
||||
remoteRef = 567C3E3C2520B7000011F6E9 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
567C3E3F2520B7000011F6E9 /* GRDB.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = GRDB.framework;
|
||||
remoteRef = 567C3E3E2520B7000011F6E9 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
567C3E412520B7000011F6E9 /* GRDB.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = GRDB.framework;
|
||||
remoteRef = 567C3E402520B7000011F6E9 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
567C3E432520B7000011F6E9 /* GRDBtvOSTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBtvOSTests.xctest;
|
||||
remoteRef = 567C3E422520B7000011F6E9 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
/* End PBXReferenceProxy section */
|
||||
|
||||
/* Begin PBXResourcesBuildPhase section */
|
||||
56026C9625B8A7D000D1DF3F /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
@@ -506,7 +359,6 @@
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
5671722A261A185300423B6F /* Query.swift in Sources */,
|
||||
567C3E5E2520B75C0011F6E9 /* Persistence.swift in Sources */,
|
||||
567C3E5D2520B75C0011F6E9 /* Player.swift in Sources */,
|
||||
56B6D1092619EC1B003CC455 /* PlayerRequest.swift in Sources */,
|
||||
@@ -536,10 +388,9 @@
|
||||
target = 567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */;
|
||||
targetProxy = 56026C9D25B8A7D000D1DF3F /* PBXContainerItemProxy */;
|
||||
};
|
||||
567C3E522520B71C0011F6E9 /* PBXTargetDependency */ = {
|
||||
56F8A11E273598960011ACBE /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
name = GRDBiOS;
|
||||
targetProxy = 567C3E512520B71C0011F6E9 /* PBXContainerItemProxy */;
|
||||
productRef = 56F8A11D273598960011ACBE /* GRDB */;
|
||||
};
|
||||
78E2F9E9261EEC22005D1F7F /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
@@ -574,7 +425,6 @@
|
||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
INFOPLIST_FILE = GRDBCombineDemoTests/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 14.3;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -594,7 +444,6 @@
|
||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
INFOPLIST_FILE = GRDBCombineDemoTests/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 14.3;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -659,7 +508,7 @@
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
|
||||
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
|
||||
MTL_FAST_MATH = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
@@ -714,7 +563,7 @@
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
MTL_FAST_MATH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
@@ -734,7 +583,6 @@
|
||||
DEVELOPMENT_TEAM = "";
|
||||
ENABLE_PREVIEWS = YES;
|
||||
INFOPLIST_FILE = GRDBCombineDemo/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -756,7 +604,6 @@
|
||||
DEVELOPMENT_TEAM = "";
|
||||
ENABLE_PREVIEWS = YES;
|
||||
INFOPLIST_FILE = GRDBCombineDemo/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -846,6 +693,33 @@
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
|
||||
/* Begin XCRemoteSwiftPackageReference section */
|
||||
56519DC5274FC85600ED16D8 /* XCRemoteSwiftPackageReference "GRDBQuery" */ = {
|
||||
isa = XCRemoteSwiftPackageReference;
|
||||
repositoryURL = "https://github.com/groue/GRDBQuery";
|
||||
requirement = {
|
||||
kind = upToNextMajorVersion;
|
||||
minimumVersion = 0.1.0;
|
||||
};
|
||||
};
|
||||
/* End XCRemoteSwiftPackageReference section */
|
||||
|
||||
/* Begin XCSwiftPackageProductDependency section */
|
||||
56519DC6274FC85600ED16D8 /* GRDBQuery */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = 56519DC5274FC85600ED16D8 /* XCRemoteSwiftPackageReference "GRDBQuery" */;
|
||||
productName = GRDBQuery;
|
||||
};
|
||||
56F8A11D273598960011ACBE /* GRDB */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
productName = GRDB;
|
||||
};
|
||||
56F8A11F2735989D0011ACBE /* GRDB */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
productName = GRDB;
|
||||
};
|
||||
/* End XCSwiftPackageProductDependency section */
|
||||
};
|
||||
rootObject = 567C3E0E2520B6DE0011F6E9 /* Project object */;
|
||||
}
|
||||
+1
-1
@@ -2,6 +2,6 @@
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
<FileRef
|
||||
location = "self:/Users/groue/Documents/git/groue/GRDB.swift/Documentation/DemoApps/GRBCombineDemo/GRDBCombineDemo.xcodeproj">
|
||||
location = "self:">
|
||||
</FileRef>
|
||||
</Workspace>
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"object": {
|
||||
"pins": [
|
||||
{
|
||||
"package": "GRDBQuery",
|
||||
"repositoryURL": "https://github.com/groue/GRDBQuery",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "4301166cd2aee9ce37b4057c9a58f5cc3bbeae06",
|
||||
"version": "0.1.0"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": 1
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import Combine
|
||||
import Foundation
|
||||
import GRDB
|
||||
|
||||
/// AppDatabase lets the application access the database.
|
||||
@@ -95,14 +96,13 @@ extension AppDatabase {
|
||||
/// Refresh all players (by performing some random changes, for demo purpose).
|
||||
func refreshPlayers() throws {
|
||||
try dbWriter.write { db in
|
||||
if try Player.fetchCount(db) == 0 {
|
||||
if try Player.all().isEmpty(db) {
|
||||
// When database is empty, insert new random players
|
||||
try createRandomPlayers(db)
|
||||
} else {
|
||||
// Insert a player
|
||||
if Bool.random() {
|
||||
var player = Player.newRandom()
|
||||
try player.insert(db)
|
||||
_ = try Player.makeRandom().inserted(db) // insert but ignore inserted id
|
||||
}
|
||||
|
||||
// Delete a random player
|
||||
@@ -123,7 +123,7 @@ extension AppDatabase {
|
||||
/// Create random players if the database is empty.
|
||||
func createRandomPlayersIfEmpty() throws {
|
||||
try dbWriter.write { db in
|
||||
if try Player.fetchCount(db) == 0 {
|
||||
if try Player.all().isEmpty(db) {
|
||||
try createRandomPlayers(db)
|
||||
}
|
||||
}
|
||||
@@ -142,8 +142,7 @@ extension AppDatabase {
|
||||
func createPlayersForUITests() throws {
|
||||
try dbWriter.write { db in
|
||||
try AppDatabase.uiTestPlayers.forEach { player in
|
||||
var mutablePlayer = player
|
||||
try mutablePlayer.save(db)
|
||||
_ = try player.inserted(db) // insert but ignore inserted id
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -151,14 +150,17 @@ extension AppDatabase {
|
||||
/// Support for `createRandomPlayersIfEmpty()` and `refreshPlayers()`.
|
||||
private func createRandomPlayers(_ db: Database) throws {
|
||||
for _ in 0..<8 {
|
||||
var player = Player.newRandom()
|
||||
try player.insert(db)
|
||||
_ = try Player.makeRandom().inserted(db) // insert but ignore inserted id
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Database Access: Reads
|
||||
|
||||
// This demo app does not provide any specific reading method, and instead
|
||||
// gives an unrestricted read-only access to the rest of the application.
|
||||
// In your app, you are free to choose another path, and define focused
|
||||
// reading methods.
|
||||
extension AppDatabase {
|
||||
/// Provides a read-only access to the database
|
||||
var databaseReader: DatabaseReader {
|
||||
|
||||
@@ -1,23 +1,40 @@
|
||||
import GRDB
|
||||
import GRDBQuery
|
||||
import SwiftUI
|
||||
|
||||
@main
|
||||
struct GRDBCombineDemoApp: App {
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
AppView().environment(\.appDatabase, AppDatabase.shared)
|
||||
AppView().environment(\.appDatabase, .shared)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Let SwiftUI views access the database through the SwiftUI environment
|
||||
// MARK: - Give SwiftUI access to the database
|
||||
//
|
||||
// Define a new environment key that grants access to an AppDatabase.
|
||||
//
|
||||
// The technique is documented at
|
||||
// <https://developer.apple.com/documentation/swiftui/environmentkey>.
|
||||
|
||||
private struct AppDatabaseKey: EnvironmentKey {
|
||||
static let defaultValue: AppDatabase? = nil
|
||||
static var defaultValue: AppDatabase { .empty() }
|
||||
}
|
||||
|
||||
extension EnvironmentValues {
|
||||
var appDatabase: AppDatabase? {
|
||||
var appDatabase: AppDatabase {
|
||||
get { self[AppDatabaseKey.self] }
|
||||
set { self[AppDatabaseKey.self] = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
// In this demo app, views observe the database with the @Query property
|
||||
// wrapper, defined in the GRDBQuery package. Its documentation recommends to
|
||||
// define a dedicated initializer for `appDatabase` access, so we comply:
|
||||
|
||||
extension Query where Request.DatabaseContext == AppDatabase {
|
||||
/// Convenience initializer for requests that feed from `AppDatabase`.
|
||||
init(_ request: Request) {
|
||||
self.init(request, in: \.appDatabase)
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import Foundation
|
||||
import GRDB
|
||||
|
||||
extension AppDatabase {
|
||||
|
||||
@@ -32,7 +32,7 @@ extension Player {
|
||||
}
|
||||
|
||||
/// Creates a new player with random name and random score
|
||||
static func newRandom() -> Player {
|
||||
static func makeRandom() -> Player {
|
||||
Player(id: nil, name: randomName(), score: randomScore())
|
||||
}
|
||||
|
||||
|
||||
@@ -1,23 +1,55 @@
|
||||
import Combine
|
||||
import GRDB
|
||||
import GRDBQuery
|
||||
|
||||
/// A player request defines how to feed the player list
|
||||
struct PlayerRequest {
|
||||
/// A player request can be used with the `@Query` property wrapper in order to
|
||||
/// feed a view with a list of players.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct MyView: View {
|
||||
/// @Query(PlayerRequest(ordering: .byName)) private var players: [Player]
|
||||
///
|
||||
/// var body: some View {
|
||||
/// List(players) { player in ... )
|
||||
/// }
|
||||
/// }
|
||||
struct PlayerRequest: Queryable {
|
||||
enum Ordering {
|
||||
case byScore
|
||||
case byName
|
||||
}
|
||||
|
||||
/// The ordering used by the player request.
|
||||
var ordering: Ordering
|
||||
}
|
||||
|
||||
/// Make `PlayerRequest` able to be used with the `@Query` property wrapper.
|
||||
extension PlayerRequest: Queryable {
|
||||
|
||||
// MARK: - Queryable Implementation
|
||||
|
||||
static var defaultValue: [Player] { [] }
|
||||
|
||||
func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], Error> {
|
||||
// Build the publisher from the general-purpose read-only access
|
||||
// granted by `appDatabase.databaseReader`.
|
||||
// Some apps will prefer to call a dedicated method of `appDatabase`.
|
||||
ValueObservation
|
||||
.tracking(fetchValue(_:))
|
||||
.publisher(
|
||||
in: appDatabase.databaseReader,
|
||||
// The `.immediate` scheduling feeds the view right on
|
||||
// subscription, and avoids an undesired animation when the
|
||||
// application starts.
|
||||
scheduling: .immediate)
|
||||
.eraseToAnyPublisher()
|
||||
}
|
||||
|
||||
// This method is not required by Queryable, but it makes it easier
|
||||
// to test PlayerRequest.
|
||||
func fetchValue(_ db: Database) throws -> [Player] {
|
||||
switch ordering {
|
||||
case .byScore: return try Player.all().orderedByScore().fetchAll(db)
|
||||
case .byName: return try Player.all().orderedByName().fetchAll(db)
|
||||
case .byScore:
|
||||
return try Player.all().orderedByScore().fetchAll(db)
|
||||
case .byName:
|
||||
return try Player.all().orderedByName().fetchAll(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
//
|
||||
// Query.swift
|
||||
//
|
||||
// A property wrapper inspired from
|
||||
// https://davedelong.com/blog/2021/04/03/core-data-and-swiftui/
|
||||
//
|
||||
|
||||
import Combine
|
||||
import GRDB
|
||||
import SwiftUI
|
||||
|
||||
/// The protocol that feeds the `@Query` property wrapper.
|
||||
protocol Queryable: Equatable {
|
||||
/// The type of the fetched value
|
||||
associatedtype Value
|
||||
|
||||
/// The default value, used whenever the database is not available
|
||||
static var defaultValue: Value { get }
|
||||
|
||||
/// Fetches the database value
|
||||
func fetchValue(_ db: Database) throws -> Value
|
||||
}
|
||||
|
||||
/// The property wrapper that observes a database query
|
||||
@propertyWrapper
|
||||
struct Query<Query: Queryable>: DynamicProperty {
|
||||
/// The database reader that makes it possible to observe the database
|
||||
@Environment(\.appDatabase?.databaseReader) private var databaseReader: DatabaseReader?
|
||||
@StateObject private var core = Core()
|
||||
private var baseQuery: Query
|
||||
|
||||
/// The fetched value
|
||||
var wrappedValue: Query.Value {
|
||||
core.value ?? Query.defaultValue
|
||||
}
|
||||
|
||||
/// A binding to the query, that lets your views modify it.
|
||||
///
|
||||
/// This is how the demo app changes the player ordering.
|
||||
var projectedValue: Binding<Query> {
|
||||
Binding(
|
||||
get: { core.query ?? baseQuery },
|
||||
set: {
|
||||
core.usesBaseQuery = false
|
||||
core.query = $0
|
||||
})
|
||||
}
|
||||
|
||||
init(_ query: Query) {
|
||||
baseQuery = query
|
||||
}
|
||||
|
||||
func update() {
|
||||
guard let databaseReader = databaseReader else {
|
||||
fatalError("Attempting to use @Query without any database in the environment")
|
||||
}
|
||||
// Feed core with necessary information, and make sure tracking has started
|
||||
if core.usesBaseQuery { core.query = baseQuery }
|
||||
core.startTrackingIfNecessary(in: databaseReader)
|
||||
}
|
||||
|
||||
private class Core: ObservableObject {
|
||||
private(set) var value: Query.Value?
|
||||
var databaseReader: DatabaseReader?
|
||||
var usesBaseQuery = true
|
||||
var query: Query? {
|
||||
willSet {
|
||||
if query != newValue {
|
||||
// Stop tracking, and tell SwiftUI about the update
|
||||
objectWillChange.send()
|
||||
cancellable = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
private var cancellable: AnyCancellable?
|
||||
|
||||
init() { }
|
||||
|
||||
func startTrackingIfNecessary(in databaseReader: DatabaseReader) {
|
||||
if databaseReader !== self.databaseReader {
|
||||
// Database has changed. Stop tracking.
|
||||
self.databaseReader = databaseReader
|
||||
cancellable = nil
|
||||
}
|
||||
|
||||
guard let query = query else {
|
||||
// No query set
|
||||
return
|
||||
}
|
||||
|
||||
guard cancellable == nil else {
|
||||
// Already tracking
|
||||
return
|
||||
}
|
||||
|
||||
cancellable = ValueObservation
|
||||
.tracking(query.fetchValue)
|
||||
.publisher(
|
||||
in: databaseReader,
|
||||
scheduling: .immediate)
|
||||
.sink(
|
||||
receiveCompletion: { _ in
|
||||
// Ignore errors
|
||||
},
|
||||
receiveValue: { [weak self] value in
|
||||
guard let self = self else { return }
|
||||
// Tell SwiftUI about the new value
|
||||
self.objectWillChange.send()
|
||||
self.value = value
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,20 @@
|
||||
import GRDBQuery
|
||||
import SwiftUI
|
||||
|
||||
/// The main application view
|
||||
struct AppView: View {
|
||||
/// Database access
|
||||
/// Write access to the database
|
||||
@Environment(\.appDatabase) private var appDatabase
|
||||
|
||||
/// The `players` property is kept up-to-date with the list of players.
|
||||
/// The `players` property is automatically updated when the database changes
|
||||
@Query(PlayerRequest(ordering: .byScore)) private var players: [Player]
|
||||
|
||||
/// We'll need to leave edit mode in several occasions.
|
||||
@State private var editMode = EditMode.inactive
|
||||
|
||||
/// Tracks the presentation of the player creation sheet.
|
||||
@State private var newPlayerIsPresented = false
|
||||
|
||||
|
||||
// If you want to define the query on initialization, you will prefer:
|
||||
//
|
||||
// @Query<PlayerRequest> private var players: [Player]
|
||||
@@ -28,62 +32,102 @@ struct AppView: View {
|
||||
EditButton()
|
||||
newPlayerButton
|
||||
},
|
||||
trailing: ToggleOrderingButton(ordering: $players.ordering))
|
||||
trailing: ToggleOrderingButton(
|
||||
ordering: $players.ordering,
|
||||
willChange: {
|
||||
// onChange(of: $players.wrappedValue.ordering)
|
||||
// is not able to leave the editing mode during
|
||||
// the animation of the list content.
|
||||
// Workaround: stop editing before the ordering
|
||||
// is changed, and the list content is updated.
|
||||
stopEditing()
|
||||
}))
|
||||
.toolbar { toolbarContent }
|
||||
.onChange(of: players) { players in
|
||||
if players.isEmpty {
|
||||
stopEditing()
|
||||
}
|
||||
}
|
||||
.environment(\.editMode, $editMode)
|
||||
}
|
||||
}
|
||||
|
||||
private var toolbarContent: some ToolbarContent {
|
||||
ToolbarItemGroup(placement: .bottomBar) {
|
||||
Button(
|
||||
action: { try? appDatabase?.deleteAllPlayers() },
|
||||
label: { Image(systemName: "trash").imageScale(.large) })
|
||||
Button {
|
||||
// Don't stopEditing() here because this is
|
||||
// performed `onChange(of: players)`
|
||||
try! appDatabase.deleteAllPlayers()
|
||||
} label: {
|
||||
Image(systemName: "trash").imageScale(.large)
|
||||
}
|
||||
|
||||
Spacer()
|
||||
Button(
|
||||
action: { try? appDatabase?.refreshPlayers() },
|
||||
label: { Image(systemName: "arrow.clockwise").imageScale(.large) })
|
||||
|
||||
Button {
|
||||
stopEditing()
|
||||
try! appDatabase.refreshPlayers()
|
||||
} label: {
|
||||
Image(systemName: "arrow.clockwise").imageScale(.large)
|
||||
}
|
||||
|
||||
Spacer()
|
||||
|
||||
Button {
|
||||
stopEditing()
|
||||
// Perform 50 refreshes in parallel
|
||||
for _ in 0..<50 {
|
||||
DispatchQueue.global().async {
|
||||
try! AppDatabase.shared.refreshPlayers()
|
||||
}
|
||||
}
|
||||
} label: {
|
||||
Image(systemName: "tornado").imageScale(.large)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The button that presents the player creation sheet.
|
||||
private var newPlayerButton: some View {
|
||||
Button(
|
||||
action: { newPlayerIsPresented = true },
|
||||
label: { Image(systemName: "plus") })
|
||||
.accessibility(label: Text("New Player"))
|
||||
.sheet(
|
||||
isPresented: $newPlayerIsPresented,
|
||||
content: {
|
||||
PlayerCreationView(dismissAction: {
|
||||
newPlayerIsPresented = false
|
||||
})
|
||||
})
|
||||
Button {
|
||||
stopEditing()
|
||||
newPlayerIsPresented = true
|
||||
} label: {
|
||||
Image(systemName: "plus")
|
||||
}
|
||||
.accessibility(label: Text("New Player"))
|
||||
.sheet(isPresented: $newPlayerIsPresented) {
|
||||
PlayerCreationView()
|
||||
}
|
||||
}
|
||||
|
||||
private func stopEditing() {
|
||||
withAnimation {
|
||||
editMode = .inactive
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct ToggleOrderingButton: View {
|
||||
@Binding var ordering: PlayerRequest.Ordering
|
||||
let willChange: () -> Void
|
||||
|
||||
var body: some View {
|
||||
switch ordering {
|
||||
case .byName:
|
||||
Button(
|
||||
action: { ordering = .byScore },
|
||||
label: {
|
||||
HStack {
|
||||
Text("Name")
|
||||
Image(systemName: "arrowtriangle.up.fill")
|
||||
}
|
||||
})
|
||||
Button {
|
||||
willChange()
|
||||
ordering = .byScore
|
||||
} label: {
|
||||
Label("Name", systemImage: "arrowtriangle.up.fill").labelStyle(.titleAndIcon)
|
||||
}
|
||||
case .byScore:
|
||||
Button(
|
||||
action: { ordering = .byName },
|
||||
label: {
|
||||
HStack {
|
||||
Text("Score")
|
||||
Image(systemName: "arrowtriangle.down.fill")
|
||||
}
|
||||
})
|
||||
Button {
|
||||
willChange()
|
||||
ordering = .byName
|
||||
} label: {
|
||||
Label("Score", systemImage: "arrowtriangle.down.fill").labelStyle(.titleAndIcon)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -91,11 +135,11 @@ private struct ToggleOrderingButton: View {
|
||||
struct AppView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
Group {
|
||||
// Preview the default, empty database
|
||||
AppView()
|
||||
|
||||
// Preview a database of random players
|
||||
AppView().environment(\.appDatabase, .random())
|
||||
|
||||
// Preview an empty database
|
||||
AppView().environment(\.appDatabase, .empty())
|
||||
}
|
||||
}
|
||||
}
|
||||
+19
-17
@@ -2,37 +2,40 @@ import SwiftUI
|
||||
|
||||
/// The view that creates a new player.
|
||||
struct PlayerCreationView: View {
|
||||
/// Executed when user cancels or saves the new user.
|
||||
let dismissAction: () -> Void
|
||||
|
||||
/// Write access to the database
|
||||
@Environment(\.appDatabase) private var appDatabase
|
||||
@State private var name = ""
|
||||
@State private var score = ""
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@State private var form = PlayerForm(name: "", score: "")
|
||||
@State private var errorAlertIsPresented = false
|
||||
@State private var errorAlertTitle = ""
|
||||
|
||||
var body: some View {
|
||||
NavigationView {
|
||||
PlayerFormView(name: $name, score: $score)
|
||||
PlayerFormView(form: $form)
|
||||
.alert(
|
||||
isPresented: $errorAlertIsPresented,
|
||||
content: { Alert(title: Text(errorAlertTitle)) })
|
||||
.navigationBarTitle("New Player")
|
||||
.navigationBarItems(
|
||||
leading: Button(
|
||||
action: dismissAction,
|
||||
label: { Text("Cancel") }),
|
||||
trailing: Button(
|
||||
action: save,
|
||||
label: { Text("Save") }))
|
||||
leading: Button(role: .cancel) {
|
||||
dismiss()
|
||||
} label: {
|
||||
Text("Cancel")
|
||||
},
|
||||
trailing: Button {
|
||||
save()
|
||||
} label: {
|
||||
Text("Save")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private func save() {
|
||||
do {
|
||||
var player = Player(id: nil, name: name, score: Int(score) ?? 0)
|
||||
try appDatabase?.savePlayer(&player)
|
||||
dismissAction()
|
||||
var player = Player(id: nil, name: "", score: 0)
|
||||
form.apply(to: &player)
|
||||
try appDatabase.savePlayer(&player)
|
||||
dismiss()
|
||||
} catch {
|
||||
errorAlertTitle = (error as? LocalizedError)?.errorDescription ?? "An error occurred"
|
||||
errorAlertIsPresented = true
|
||||
@@ -42,7 +45,6 @@ struct PlayerCreationView: View {
|
||||
|
||||
struct PlayerCreationSheet_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
PlayerCreationView(dismissAction: { })
|
||||
.environment(\.appDatabase, .empty())
|
||||
PlayerCreationView()
|
||||
}
|
||||
}
|
||||
+20
-10
@@ -2,18 +2,28 @@ import SwiftUI
|
||||
|
||||
/// The view that edits an existing player.
|
||||
struct PlayerEditionView: View {
|
||||
/// Write access to the database
|
||||
@Environment(\.appDatabase) private var appDatabase
|
||||
@State var player: Player
|
||||
@Environment(\.isPresented) private var isPresented
|
||||
private let player: Player
|
||||
@State private var form: PlayerForm
|
||||
|
||||
init(player: Player) {
|
||||
self.player = player
|
||||
self.form = PlayerForm(player)
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
PlayerFormView(
|
||||
name: $player.name,
|
||||
score: Binding(
|
||||
get: { "\(player.score)" },
|
||||
set: { player.score = Int($0) ?? 0 }))
|
||||
.onDisappear {
|
||||
// save and ignore error
|
||||
try? appDatabase?.savePlayer(&player)
|
||||
PlayerFormView(form: $form)
|
||||
.onChange(of: isPresented) { isPresented in
|
||||
// Save when back button is pressed
|
||||
if !isPresented {
|
||||
var savedPlayer = player
|
||||
form.apply(to: &savedPlayer)
|
||||
// Ignore error because I don't know how to cancel the
|
||||
// back button and present the error
|
||||
try? appDatabase.savePlayer(&savedPlayer)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,7 +31,7 @@ struct PlayerEditionView: View {
|
||||
struct PlayerEditionView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
NavigationView {
|
||||
PlayerEditionView(player: Player.newRandom())
|
||||
PlayerEditionView(player: Player.makeRandom())
|
||||
.navigationBarTitle("Player Edition")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,29 +3,45 @@ import SwiftUI
|
||||
/// The Player editing form, embedded in both
|
||||
/// `PlayerCreationView` and `PlayerEditionView`.
|
||||
struct PlayerFormView: View {
|
||||
@Binding var name: String
|
||||
@Binding var score: String
|
||||
|
||||
@Binding var form: PlayerForm
|
||||
|
||||
var body: some View {
|
||||
List {
|
||||
TextField("Name", text: $name)
|
||||
TextField("Name", text: $form.name)
|
||||
.accessibility(label: Text("Player Name"))
|
||||
TextField("Score", text: $score).keyboardType(.numberPad)
|
||||
TextField("Score", text: $form.score).keyboardType(.numberPad)
|
||||
.accessibility(label: Text("Player Score"))
|
||||
}
|
||||
.listStyle(InsetGroupedListStyle())
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerForm {
|
||||
var name: String
|
||||
var score: String
|
||||
}
|
||||
|
||||
extension PlayerForm {
|
||||
init(_ player: Player) {
|
||||
self.name = player.name
|
||||
self.score = "\(player.score)"
|
||||
}
|
||||
|
||||
func apply(to player: inout Player) {
|
||||
player.name = name
|
||||
player.score = Int(score) ?? 0
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerFormView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
Group {
|
||||
PlayerFormView(
|
||||
name: .constant(""),
|
||||
score: .constant(""))
|
||||
PlayerFormView(
|
||||
name: .constant(Player.randomName()),
|
||||
score: .constant("\(Player.randomScore())"))
|
||||
PlayerFormView(form: .constant(PlayerForm(
|
||||
name: "",
|
||||
score: "")))
|
||||
PlayerFormView(form: .constant(PlayerForm(
|
||||
name: Player.randomName(),
|
||||
score: "\(Player.randomScore())")))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import SwiftUI
|
||||
|
||||
struct PlayerList: View {
|
||||
/// Database access
|
||||
/// Write access to the database
|
||||
@Environment(\.appDatabase) private var appDatabase
|
||||
|
||||
/// The players in the list
|
||||
@@ -11,16 +11,19 @@ struct PlayerList: View {
|
||||
List {
|
||||
ForEach(players) { player in
|
||||
NavigationLink(destination: editionView(for: player)) {
|
||||
PlayerRow(player: player).animation(nil)
|
||||
PlayerRow(player: player)
|
||||
// Don't animate player update
|
||||
.animation(nil, value: player)
|
||||
}
|
||||
}
|
||||
.onDelete(perform: { offsets in
|
||||
.onDelete { offsets in
|
||||
let playerIds = offsets.compactMap { players[$0].id }
|
||||
try? appDatabase?.deletePlayers(ids: playerIds)
|
||||
})
|
||||
try? appDatabase.deletePlayers(ids: playerIds)
|
||||
}
|
||||
}
|
||||
.animation(.default)
|
||||
.listStyle(PlainListStyle())
|
||||
// Animate list updates
|
||||
.animation(.default, value: players)
|
||||
.listStyle(.plain)
|
||||
}
|
||||
|
||||
/// The view that edits a player in the list.
|
||||
@@ -48,7 +51,7 @@ struct PlayerList_Previews: PreviewProvider {
|
||||
Player(id: 1, name: "Arthur", score: 100),
|
||||
Player(id: 2, name: "Barbara", score: 1000),
|
||||
])
|
||||
.navigationTitle("Preview")
|
||||
.navigationTitle("Preview")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,8 @@ Combine + SwiftUI Demo Application
|
||||
|
||||
**This demo application is a Combine + SwiftUI application.** For a demo application that uses UIKit, see [GRDBDemoiOS](../GRDBDemoiOS/README.md).
|
||||
|
||||
**Requirements**: iOS 15.0+ / Xcode 12+
|
||||
|
||||
> :point_up: **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration.
|
||||
|
||||
The topics covered in this demo are:
|
||||
@@ -23,7 +25,7 @@ The topics covered in this demo are:
|
||||
|
||||
- [AppDatabase.swift](GRDBCombineDemo/AppDatabase.swift)
|
||||
|
||||
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema, and [ValueObservation](../../../README.md#valueobservation) in order to let the application observe database changes.
|
||||
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema.
|
||||
|
||||
- [Persistence.swift](GRDBCombineDemo/Persistence.swift)
|
||||
|
||||
@@ -33,11 +35,11 @@ The topics covered in this demo are:
|
||||
|
||||
`Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../../README.md#codable-records).
|
||||
|
||||
- [PlayerRequest.swift](GRDBCombineDemo/PlayerRequest.swift), [Query.swift](GRDBCombineDemo/Query.swift), [AppView.swift](GRDBCombineDemo/Views/AppView.swift)
|
||||
- [PlayerRequest.swift](GRDBCombineDemo/PlayerRequest.swift), [AppView.swift](GRDBCombineDemo/Views/AppView.swift)
|
||||
|
||||
`PlayerRequest` defines the player requests used by the app (sorted by score, or by name).
|
||||
|
||||
`PlayerRequest` feeds the `@Query` property wrapper. `@Query`, inspired by [this article](https://davedelong.com/blog/2021/04/03/core-data-and-swiftui/), allows SwiftUI views to display up-to-date database content thanks to GRDB's [ValueObservation](../../../README.md#valueobservation).
|
||||
`PlayerRequest` feeds the `@Query` property wrapper (`@Query`, defined in [GRDBQuery](https://github.com/groue/GRDBQuery), allows SwiftUI views to display up-to-date database content).
|
||||
|
||||
`AppView` is the SwiftUI view that uses `@Query` in order to feed its player list.
|
||||
|
||||
|
||||
+10
-5
@@ -15,7 +15,6 @@ class ExtensionDelegate: NSObject, WKExtensionDelegate {
|
||||
// Use this method to pause ongoing tasks, disable timers, etc.
|
||||
}
|
||||
|
||||
@available(watchOSApplicationExtension 3.0, *)
|
||||
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
|
||||
// Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one.
|
||||
for task in backgroundTasks {
|
||||
@@ -23,19 +22,25 @@ class ExtensionDelegate: NSObject, WKExtensionDelegate {
|
||||
switch task {
|
||||
case let backgroundTask as WKApplicationRefreshBackgroundTask:
|
||||
// Be sure to complete the background task once you’re done.
|
||||
backgroundTask.setTaskCompleted()
|
||||
backgroundTask.setTaskCompletedWithSnapshot(false)
|
||||
case let snapshotTask as WKSnapshotRefreshBackgroundTask:
|
||||
// Snapshot tasks have a unique completion call, make sure to set your expiration date
|
||||
snapshotTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.distantFuture, userInfo: nil)
|
||||
case let connectivityTask as WKWatchConnectivityRefreshBackgroundTask:
|
||||
// Be sure to complete the connectivity task once you’re done.
|
||||
connectivityTask.setTaskCompleted()
|
||||
connectivityTask.setTaskCompletedWithSnapshot(false)
|
||||
case let urlSessionTask as WKURLSessionRefreshBackgroundTask:
|
||||
// Be sure to complete the URL session task once you’re done.
|
||||
urlSessionTask.setTaskCompleted()
|
||||
urlSessionTask.setTaskCompletedWithSnapshot(false)
|
||||
case let relevantShortcutTask as WKRelevantShortcutRefreshBackgroundTask:
|
||||
// Be sure to complete the relevant-shortcut task once you're done.
|
||||
relevantShortcutTask.setTaskCompletedWithSnapshot(false)
|
||||
case let intentDidRunTask as WKIntentDidRunRefreshBackgroundTask:
|
||||
// Be sure to complete the intent-did-run task once you're done.
|
||||
intentDidRunTask.setTaskCompletedWithSnapshot(false)
|
||||
default:
|
||||
// make sure to complete unhandled task types
|
||||
task.setTaskCompleted()
|
||||
task.setTaskCompletedWithSnapshot(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -309,13 +309,13 @@
|
||||
56B036051E8D9EBE003B6DA4 /* GRDBDemoiOS */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56B036121E8D9EBE003B6DA4 /* Info.plist */,
|
||||
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */,
|
||||
56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */,
|
||||
56185BBE25B8036100B9C30F /* Persistence.swift */,
|
||||
56B0361A1E8D9F38003B6DA4 /* Player.swift */,
|
||||
56FE6F2524A90CE400711EDF /* SceneDelegate.swift */,
|
||||
56FE6F4E24A9112900711EDF /* Resources */,
|
||||
56FE6F5124A9118000711EDF /* Support */,
|
||||
56FE6F4F24A9114200711EDF /* ViewControllers */,
|
||||
);
|
||||
path = GRDBDemoiOS;
|
||||
@@ -340,14 +340,6 @@
|
||||
path = ViewControllers;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
56FE6F5124A9118000711EDF /* Support */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56B036121E8D9EBE003B6DA4 /* Info.plist */,
|
||||
);
|
||||
name = Support;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
@@ -686,7 +678,6 @@
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu11;
|
||||
INFOPLIST_FILE = GRDBDemoiOSTests/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 14.3;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -713,7 +704,6 @@
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu11;
|
||||
INFOPLIST_FILE = GRDBDemoiOSTests/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 14.3;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -853,14 +843,14 @@
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
|
||||
MTL_ENABLE_DEBUG_INFO = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 5.0;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 2.0;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 8.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -909,14 +899,14 @@
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
SDKROOT = iphoneos;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
SWIFT_VERSION = 5.0;
|
||||
VALIDATE_PRODUCT = YES;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 2.0;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 8.0;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
|
||||
@@ -78,14 +78,13 @@ extension AppDatabase {
|
||||
/// Refresh all players (by performing some random changes, for demo purpose).
|
||||
func refreshPlayers() throws {
|
||||
try dbWriter.write { db in
|
||||
if try Player.fetchCount(db) == 0 {
|
||||
if try Player.all().isEmpty(db) {
|
||||
// When database is empty, insert new random players
|
||||
try createRandomPlayers(db)
|
||||
} else {
|
||||
// Insert a player
|
||||
if Bool.random() {
|
||||
var player = Player.newRandom()
|
||||
try player.insert(db)
|
||||
_ = try Player.makeRandom().inserted(db) // insert but ignore inserted id
|
||||
}
|
||||
|
||||
// Delete a random player
|
||||
@@ -106,7 +105,7 @@ extension AppDatabase {
|
||||
/// Create random players if the database is empty.
|
||||
func createRandomPlayersIfEmpty() throws {
|
||||
try dbWriter.write { db in
|
||||
if try Player.fetchCount(db) == 0 {
|
||||
if try Player.all().isEmpty(db) {
|
||||
try createRandomPlayers(db)
|
||||
}
|
||||
}
|
||||
@@ -115,40 +114,20 @@ extension AppDatabase {
|
||||
/// Support for `createRandomPlayersIfEmpty()` and `refreshPlayers()`.
|
||||
private func createRandomPlayers(_ db: Database) throws {
|
||||
for _ in 0..<8 {
|
||||
var player = Player.newRandom()
|
||||
try player.insert(db)
|
||||
_ = try Player.makeRandom().inserted(db) // insert but ignore inserted id
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Database Access: Reads
|
||||
|
||||
// This demo app does not provide any specific reading method, and instead
|
||||
// gives an unrestricted read-only access to the rest of the application.
|
||||
// In your app, you are free to choose another path, and define focused
|
||||
// reading methods.
|
||||
extension AppDatabase {
|
||||
/// Tracks changes in players ordered by name
|
||||
func observePlayersOrderedByName(
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping ([Player]) -> Void)
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
ValueObservation
|
||||
.tracking(Player.all().orderedByName().fetchAll)
|
||||
.start(
|
||||
in: dbWriter,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
}
|
||||
|
||||
/// Tracks changes in players ordered by score
|
||||
func observePlayersOrderedByScore(
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping ([Player]) -> Void)
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
ValueObservation
|
||||
.tracking(Player.all().orderedByScore().fetchAll)
|
||||
.start(
|
||||
in: dbWriter,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
/// Provides a read-only access to the database
|
||||
var databaseReader: DatabaseReader {
|
||||
dbWriter
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import Foundation
|
||||
import GRDB
|
||||
|
||||
extension AppDatabase {
|
||||
|
||||
@@ -31,7 +31,7 @@ extension Player {
|
||||
}
|
||||
|
||||
/// Creates a new player with random name and random score
|
||||
static func newRandom() -> Player {
|
||||
static func makeRandom() -> Player {
|
||||
Player(id: nil, name: randomName(), score: randomScore())
|
||||
}
|
||||
|
||||
|
||||
+34
-23
@@ -1,8 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="16097" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="UAh-8N-CM8">
|
||||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="19455" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="UAh-8N-CM8">
|
||||
<device id="retina6_1" orientation="portrait" appearance="light"/>
|
||||
<dependencies>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="16087"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="19454"/>
|
||||
<capability name="System colors in document resources" minToolsVersion="11.0"/>
|
||||
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
|
||||
</dependencies>
|
||||
<scenes>
|
||||
@@ -17,14 +18,14 @@
|
||||
<tableViewSection headerTitle="Name" id="Nzq-eO-jT3">
|
||||
<cells>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="2gb-gB-918">
|
||||
<rect key="frame" x="20" y="55.5" width="374" height="44"/>
|
||||
<rect key="frame" x="20" y="32" width="374" height="40.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="2gb-gB-918" id="iyM-TJ-JB4">
|
||||
<rect key="frame" x="0.0" y="0.0" width="374" height="44"/>
|
||||
<rect key="frame" x="0.0" y="0.0" width="374" height="40.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" adjustsFontForContentSizeCategory="YES" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="m5m-Zs-j0z">
|
||||
<rect key="frame" x="20" y="11" width="334" height="22"/>
|
||||
<rect key="frame" x="20" y="11" width="334" height="18.5"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
|
||||
<textInputTraits key="textInputTraits" autocapitalizationType="words" autocorrectionType="no" spellCheckingType="no" returnKeyType="next"/>
|
||||
<connections>
|
||||
@@ -36,7 +37,8 @@
|
||||
<constraints>
|
||||
<constraint firstItem="m5m-Zs-j0z" firstAttribute="leading" secondItem="iyM-TJ-JB4" secondAttribute="leadingMargin" id="9cK-nj-70V"/>
|
||||
<constraint firstAttribute="trailingMargin" secondItem="m5m-Zs-j0z" secondAttribute="trailing" id="JsE-8v-XAS"/>
|
||||
<constraint firstItem="m5m-Zs-j0z" firstAttribute="centerY" secondItem="iyM-TJ-JB4" secondAttribute="centerY" id="psG-tW-QrM"/>
|
||||
<constraint firstAttribute="bottomMargin" secondItem="m5m-Zs-j0z" secondAttribute="bottom" id="KbI-Yl-Las"/>
|
||||
<constraint firstItem="m5m-Zs-j0z" firstAttribute="top" secondItem="iyM-TJ-JB4" secondAttribute="topMargin" id="v2S-en-21g"/>
|
||||
</constraints>
|
||||
</tableViewCellContentView>
|
||||
</tableViewCell>
|
||||
@@ -45,14 +47,14 @@
|
||||
<tableViewSection headerTitle="Score" id="Urb-uF-sj1">
|
||||
<cells>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="vp3-Ft-Gth">
|
||||
<rect key="frame" x="20" y="155" width="374" height="44"/>
|
||||
<rect key="frame" x="20" y="122" width="374" height="40.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="vp3-Ft-Gth" id="ccO-0O-u72">
|
||||
<rect key="frame" x="0.0" y="0.0" width="374" height="44"/>
|
||||
<rect key="frame" x="0.0" y="0.0" width="374" height="40.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="0" adjustsFontForContentSizeCategory="YES" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="rZ9-Fa-cyr">
|
||||
<rect key="frame" x="20" y="11" width="334" height="22"/>
|
||||
<rect key="frame" x="20" y="11" width="334" height="18.5"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
|
||||
<textInputTraits key="textInputTraits" autocorrectionType="no" spellCheckingType="no" keyboardType="numberPad" returnKeyType="done"/>
|
||||
<connections>
|
||||
@@ -61,9 +63,10 @@
|
||||
</textField>
|
||||
</subviews>
|
||||
<constraints>
|
||||
<constraint firstAttribute="bottomMargin" secondItem="rZ9-Fa-cyr" secondAttribute="bottom" id="3Ya-Po-TQ3"/>
|
||||
<constraint firstAttribute="trailingMargin" secondItem="rZ9-Fa-cyr" secondAttribute="trailing" id="Gso-FU-Ct1"/>
|
||||
<constraint firstItem="rZ9-Fa-cyr" firstAttribute="centerY" secondItem="ccO-0O-u72" secondAttribute="centerY" id="UqA-ea-emb"/>
|
||||
<constraint firstItem="rZ9-Fa-cyr" firstAttribute="leading" secondItem="ccO-0O-u72" secondAttribute="leadingMargin" id="WrY-St-72v"/>
|
||||
<constraint firstItem="rZ9-Fa-cyr" firstAttribute="top" secondItem="ccO-0O-u72" secondAttribute="topMargin" id="mmE-f2-e9r"/>
|
||||
</constraints>
|
||||
</tableViewCellContentView>
|
||||
</tableViewCell>
|
||||
@@ -90,10 +93,10 @@
|
||||
</navigationItem>
|
||||
<simulatedToolbarMetrics key="simulatedBottomBarMetrics"/>
|
||||
<connections>
|
||||
<outlet property="cancelBarButtonItem" destination="VIN-Hi-Twt" id="dET-mF-ZXe"/>
|
||||
<outlet property="commitBarButtonItem" destination="2um-u5-BhV" id="Jym-us-zdP"/>
|
||||
<outlet property="cancelButtonItem" destination="VIN-Hi-Twt" id="dET-mF-ZXe"/>
|
||||
<outlet property="nameCell" destination="2gb-gB-918" id="ch2-MB-uRm"/>
|
||||
<outlet property="nameTextField" destination="m5m-Zs-j0z" id="A6a-pw-q8s"/>
|
||||
<outlet property="saveButtonItem" destination="2um-u5-BhV" id="Jym-us-zdP"/>
|
||||
<outlet property="scoreCell" destination="vp3-Ft-Gth" id="b8A-42-8Dw"/>
|
||||
<outlet property="scoreTextField" destination="rZ9-Fa-cyr" id="4kw-gV-uih"/>
|
||||
</connections>
|
||||
@@ -112,7 +115,7 @@
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
</navigationBar>
|
||||
<connections>
|
||||
<segue destination="iNr-Oe-muq" kind="relationship" relationship="rootViewController" id="e5b-3U-9Vz"/>
|
||||
<segue destination="iNr-Oe-muq" kind="relationship" relationship="rootViewController" destinationCreationSelector="makePlayerCreationViewController:" id="e5b-3U-9Vz"/>
|
||||
</connections>
|
||||
</navigationController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="kNr-vk-I5l" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
@@ -123,8 +126,8 @@
|
||||
<scene sceneID="N1X-4j-Re4">
|
||||
<objects>
|
||||
<navigationController id="UAh-8N-CM8" sceneMemberID="viewController">
|
||||
<navigationBar key="navigationBar" contentMode="scaleToFill" id="U7d-1C-GnL">
|
||||
<rect key="frame" x="0.0" y="44" width="414" height="44"/>
|
||||
<navigationBar key="navigationBar" contentMode="scaleToFill" largeTitles="YES" id="U7d-1C-GnL">
|
||||
<rect key="frame" x="0.0" y="44" width="414" height="96"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
</navigationBar>
|
||||
<connections>
|
||||
@@ -142,32 +145,32 @@
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="-1" estimatedSectionHeaderHeight="-1" sectionFooterHeight="-1" estimatedSectionFooterHeight="-1" id="tX0-ON-WSI">
|
||||
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
|
||||
<color key="backgroundColor" systemColor="systemBackgroundColor"/>
|
||||
<prototypes>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" reuseIdentifier="Player" textLabel="G8y-VE-YRu" detailTextLabel="NNc-J4-xiE" style="IBUITableViewCellStyleValue1" id="bFj-Hd-fwd">
|
||||
<rect key="frame" x="0.0" y="28" width="414" height="43.5"/>
|
||||
<rect key="frame" x="0.0" y="44.5" width="414" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="bFj-Hd-fwd" id="kDf-TZ-xhb">
|
||||
<rect key="frame" x="0.0" y="0.0" width="383" height="43.5"/>
|
||||
<rect key="frame" x="0.0" y="0.0" width="384.5" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontForContentSizeCategory="YES" adjustsFontSizeToFit="NO" id="G8y-VE-YRu">
|
||||
<rect key="frame" x="20" y="12" width="33.5" height="20.5"/>
|
||||
<rect key="frame" x="20" y="14" width="28.5" height="17"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Detail" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontForContentSizeCategory="YES" adjustsFontSizeToFit="NO" id="NNc-J4-xiE">
|
||||
<rect key="frame" x="331" y="12" width="44" height="20.5"/>
|
||||
<rect key="frame" x="339" y="14" width="37.5" height="17"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
|
||||
<color key="textColor" systemColor="secondaryLabelColor" red="0.23529411759999999" green="0.23529411759999999" blue="0.26274509800000001" alpha="0.59999999999999998" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<color key="textColor" systemColor="secondaryLabelColor"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
</subviews>
|
||||
</tableViewCellContentView>
|
||||
<connections>
|
||||
<segue destination="iNr-Oe-muq" kind="show" identifier="Edit" id="Lgu-Yd-HSy"/>
|
||||
<segue destination="iNr-Oe-muq" kind="show" identifier="" destinationCreationSelector="makePlayerEditionViewController:" id="Lgu-Yd-HSy"/>
|
||||
</connections>
|
||||
</tableViewCell>
|
||||
</prototypes>
|
||||
@@ -182,7 +185,7 @@
|
||||
<navigationItem key="navigationItem" title="Hall Of Fame" id="QIv-M6-kT1">
|
||||
<barButtonItem key="leftBarButtonItem" systemItem="add" id="2bK-Fl-55Q">
|
||||
<connections>
|
||||
<segue destination="ein-Sr-i8w" kind="presentation" identifier="New" id="ehP-ZN-Nt4"/>
|
||||
<segue destination="ein-Sr-i8w" kind="presentation" identifier="" id="ehP-ZN-Nt4"/>
|
||||
</connections>
|
||||
</barButtonItem>
|
||||
</navigationItem>
|
||||
@@ -199,4 +202,12 @@
|
||||
<inferredMetricsTieBreakers>
|
||||
<segue reference="Lgu-Yd-HSy"/>
|
||||
</inferredMetricsTieBreakers>
|
||||
<resources>
|
||||
<systemColor name="secondaryLabelColor">
|
||||
<color red="0.23529411764705882" green="0.23529411764705882" blue="0.2627450980392157" alpha="0.59999999999999998" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
</systemColor>
|
||||
<systemColor name="systemBackgroundColor">
|
||||
<color white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
|
||||
</systemColor>
|
||||
</resources>
|
||||
</document>
|
||||
+33
-38
@@ -1,39 +1,42 @@
|
||||
import UIKit
|
||||
|
||||
class PlayerEditionViewController: UITableViewController {
|
||||
enum Presentation {
|
||||
/// Modal presentation: edition ends with the "Commit" unwind segue.
|
||||
case modal
|
||||
enum Mode {
|
||||
/// Edition ends with the "Commit" unwind segue.
|
||||
case creation
|
||||
|
||||
/// Push presentation: edition ends when user hits the back button.
|
||||
case push
|
||||
/// Edition ends when user hits the back button.
|
||||
case edition
|
||||
}
|
||||
|
||||
/// The edited player
|
||||
var player: Player! {
|
||||
didSet {
|
||||
configureForm()
|
||||
}
|
||||
}
|
||||
private(set) var player: Player
|
||||
|
||||
/// The presentation mode
|
||||
var presentation: Presentation! {
|
||||
didSet {
|
||||
configureNavigationItem()
|
||||
}
|
||||
}
|
||||
let mode: Mode
|
||||
|
||||
@IBOutlet private weak var cancelBarButtonItem: UIBarButtonItem!
|
||||
@IBOutlet private weak var commitBarButtonItem: UIBarButtonItem!
|
||||
@IBOutlet private weak var cancelButtonItem: UIBarButtonItem!
|
||||
@IBOutlet private weak var saveButtonItem: UIBarButtonItem!
|
||||
@IBOutlet private weak var nameCell: UITableViewCell!
|
||||
@IBOutlet private weak var nameTextField: UITextField!
|
||||
@IBOutlet private weak var scoreCell: UITableViewCell!
|
||||
@IBOutlet private weak var scoreTextField: UITextField!
|
||||
|
||||
init?(_ coder: NSCoder, mode: Mode, player: Player) {
|
||||
self.mode = mode
|
||||
self.player = player
|
||||
super.init(coder: coder)
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) {
|
||||
fatalError("init(coder:) has not been implemented")
|
||||
}
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
configureForm()
|
||||
configureNavigationItem()
|
||||
configureForm()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,24 +58,22 @@ extension PlayerEditionViewController {
|
||||
override func willMove(toParent parent: UIViewController?) {
|
||||
super.willMove(toParent: parent)
|
||||
|
||||
if case .push = presentation, parent == nil {
|
||||
if mode == .edition, parent == nil {
|
||||
// Self is popping from its navigation controller
|
||||
saveChanges()
|
||||
}
|
||||
}
|
||||
|
||||
private func configureNavigationItem() {
|
||||
guard isViewLoaded else { return }
|
||||
|
||||
if let presentation = presentation {
|
||||
switch presentation {
|
||||
case .modal:
|
||||
navigationItem.leftBarButtonItem = cancelBarButtonItem
|
||||
navigationItem.rightBarButtonItem = commitBarButtonItem
|
||||
case .push:
|
||||
navigationItem.leftBarButtonItem = nil
|
||||
navigationItem.rightBarButtonItem = nil
|
||||
}
|
||||
switch mode {
|
||||
case .creation:
|
||||
navigationItem.title = "New Player"
|
||||
navigationItem.leftBarButtonItem = cancelButtonItem
|
||||
navigationItem.rightBarButtonItem = saveButtonItem
|
||||
case .edition:
|
||||
navigationItem.title = player.name
|
||||
navigationItem.leftBarButtonItem = nil
|
||||
navigationItem.rightBarButtonItem = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -104,14 +105,10 @@ extension PlayerEditionViewController: UITextFieldDelegate {
|
||||
|
||||
@IBAction func textFieldDidChange(_ textField: UITextField) {
|
||||
// User has edited the player: prevent interactive dismissal
|
||||
if case .modal = presentation {
|
||||
isModalInPresentation = true
|
||||
}
|
||||
isModalInPresentation = true
|
||||
}
|
||||
|
||||
private func configureForm() {
|
||||
guard isViewLoaded else { return }
|
||||
|
||||
nameTextField.text = player.name
|
||||
|
||||
if player.score == 0 && player.id == nil {
|
||||
@@ -122,9 +119,7 @@ extension PlayerEditionViewController: UITextFieldDelegate {
|
||||
}
|
||||
|
||||
private func saveChanges() {
|
||||
guard var player = self.player else {
|
||||
return
|
||||
}
|
||||
var player = self.player
|
||||
player.name = nameTextField.text ?? ""
|
||||
player.score = scoreTextField.text.flatMap { Int($0) } ?? 0
|
||||
try! AppDatabase.shared.savePlayer(&player)
|
||||
|
||||
+61
-81
@@ -10,7 +10,6 @@ class PlayerListViewController: UITableViewController {
|
||||
|
||||
@IBOutlet private weak var newPlayerButtonItem: UIBarButtonItem!
|
||||
private var dataSource: PlayerDataSource!
|
||||
private var animatesPlayersChange = false // Don't animate first update
|
||||
private var playersCancellable: DatabaseCancellable?
|
||||
private var playerOrdering: PlayerOrdering = .byScore {
|
||||
didSet {
|
||||
@@ -34,18 +33,29 @@ class PlayerListViewController: UITableViewController {
|
||||
|
||||
private func configureToolbar() {
|
||||
toolbarItems = [
|
||||
UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deletePlayers)),
|
||||
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
|
||||
UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refresh)),
|
||||
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
|
||||
UIBarButtonItem(image: UIImage(systemName: "tornado"), style: .plain, target: self, action: #selector(stressTest)),
|
||||
UIBarButtonItem(systemItem: .trash, primaryAction: UIAction { [unowned self] _ in
|
||||
setEditing(false, animated: true)
|
||||
try! AppDatabase.shared.deleteAllPlayers()
|
||||
}),
|
||||
UIBarButtonItem(systemItem: .flexibleSpace),
|
||||
UIBarButtonItem(systemItem: .refresh, primaryAction: UIAction { [unowned self] _ in
|
||||
setEditing(false, animated: true)
|
||||
try! AppDatabase.shared.refreshPlayers()
|
||||
}),
|
||||
UIBarButtonItem(systemItem: .flexibleSpace),
|
||||
UIBarButtonItem(image: UIImage(systemName: "tornado"), primaryAction: UIAction { [unowned self] _ in
|
||||
setEditing(false, animated: true)
|
||||
for _ in 0..<50 {
|
||||
DispatchQueue.global().async {
|
||||
try! AppDatabase.shared.refreshPlayers()
|
||||
}
|
||||
}
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
private func configureNavigationItem() {
|
||||
navigationItem.backBarButtonItem = UIBarButtonItem(
|
||||
title: "Players", style: .plain,
|
||||
target: nil, action: nil)
|
||||
navigationItem.backBarButtonItem = UIBarButtonItem(title: "Players")
|
||||
navigationItem.leftBarButtonItems = [editButtonItem, newPlayerButtonItem]
|
||||
configureOrderingBarButtonItem()
|
||||
}
|
||||
@@ -55,13 +65,17 @@ class PlayerListViewController: UITableViewController {
|
||||
case .byScore:
|
||||
navigationItem.rightBarButtonItem = UIBarButtonItem(
|
||||
title: "Score ▼",
|
||||
style: .plain,
|
||||
target: self, action: #selector(sortByName))
|
||||
primaryAction: UIAction { [unowned self] _ in
|
||||
setEditing(false, animated: true)
|
||||
playerOrdering = .byName
|
||||
})
|
||||
case .byName:
|
||||
navigationItem.rightBarButtonItem = UIBarButtonItem(
|
||||
title: "Name ▲",
|
||||
style: .plain,
|
||||
target: self, action: #selector(sortByScore))
|
||||
primaryAction: UIAction { [unowned self] _ in
|
||||
setEditing(false, animated: true)
|
||||
playerOrdering = .byScore
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,34 +110,44 @@ class PlayerListViewController: UITableViewController {
|
||||
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
|
||||
dataSource.apply(snapshot, animatingDifferences: false, completion: nil)
|
||||
// Remember selection
|
||||
let selectedPlayerId = tableView.indexPathForSelectedRow.flatMap {
|
||||
dataSource.itemIdentifier(for: $0)?.id
|
||||
}
|
||||
|
||||
// Avoid a UIKit warning; don't animate when popping from edition
|
||||
let animated = view.window != nil
|
||||
|
||||
dataSource.apply(snapshot, animatingDifferences: animated, completion: {
|
||||
// Restore selection
|
||||
if let index = players.firstIndex(where: { $0.id == selectedPlayerId }) {
|
||||
self.tableView.selectRow(at: IndexPath(row: index, section: 0), animated: false, scrollPosition: .none)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private func observePlayers() {
|
||||
let request: QueryInterfaceRequest<Player>
|
||||
switch playerOrdering {
|
||||
case .byName:
|
||||
playersCancellable = AppDatabase.shared.observePlayersOrderedByName(
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] players in
|
||||
guard let self = self else { return }
|
||||
self.configureTitle(from: players)
|
||||
self.configureDataSource(from: players)
|
||||
})
|
||||
request = Player.all().orderedByName()
|
||||
case .byScore:
|
||||
playersCancellable = AppDatabase.shared.observePlayersOrderedByScore(
|
||||
request = Player.all().orderedByScore()
|
||||
}
|
||||
|
||||
playersCancellable = ValueObservation
|
||||
.tracking(request.fetchAll(_:))
|
||||
.start(
|
||||
in: AppDatabase.shared.databaseReader,
|
||||
// Immediate scheduling feeds the data source right on subscription,
|
||||
// and avoids an undesired animation when the application starts.
|
||||
scheduling: .immediate,
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] players in
|
||||
guard let self = self else { return }
|
||||
self.configureTitle(from: players)
|
||||
self.configureDataSource(from: players)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,26 +155,16 @@ class PlayerListViewController: UITableViewController {
|
||||
// MARK: - Navigation
|
||||
|
||||
extension PlayerListViewController {
|
||||
@IBSegueAction func makePlayerEditionViewController(_ coder: NSCoder) -> PlayerEditionViewController? {
|
||||
guard let indexPath = tableView.indexPathForSelectedRow,
|
||||
let player = dataSource.itemIdentifier(for: indexPath)
|
||||
else { return nil }
|
||||
return PlayerEditionViewController(coder, mode: .edition, player: player)
|
||||
}
|
||||
|
||||
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
|
||||
if segue.identifier == "Edit" {
|
||||
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 }
|
||||
setEditing(false, animated: true)
|
||||
controller.title = "New Player"
|
||||
controller.player = Player(id: nil, name: "", score: 0)
|
||||
controller.presentation = .modal
|
||||
}
|
||||
@IBSegueAction func makePlayerCreationViewController(_ coder: NSCoder) -> PlayerEditionViewController? {
|
||||
let player = Player(id: nil, name: "", score: 0)
|
||||
return PlayerEditionViewController(coder, mode: .creation, player: player)
|
||||
}
|
||||
|
||||
@IBAction func cancelPlayerEdition(_ segue: UIStoryboardSegue) {
|
||||
@@ -178,37 +192,3 @@ private class PlayerDataSource: UITableViewDiffableDataSource<Int, Player> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Actions
|
||||
|
||||
extension PlayerListViewController {
|
||||
@IBAction func sortByName() {
|
||||
setEditing(false, animated: true)
|
||||
playerOrdering = .byName
|
||||
}
|
||||
|
||||
@IBAction func sortByScore() {
|
||||
setEditing(false, animated: true)
|
||||
playerOrdering = .byScore
|
||||
}
|
||||
|
||||
@IBAction func deletePlayers() {
|
||||
setEditing(false, animated: true)
|
||||
try! AppDatabase.shared.deleteAllPlayers()
|
||||
}
|
||||
|
||||
@IBAction func refresh() {
|
||||
setEditing(false, animated: true)
|
||||
try! AppDatabase.shared.refreshPlayers()
|
||||
}
|
||||
|
||||
@IBAction func stressTest() {
|
||||
setEditing(false, animated: true)
|
||||
for _ in 0..<50 {
|
||||
DispatchQueue.global().async {
|
||||
try! AppDatabase.shared.refreshPlayers()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -143,64 +143,4 @@ class AppDatabaseTests: XCTestCase {
|
||||
let players = try dbQueue.read(Player.fetchAll)
|
||||
XCTAssertEqual(players, [player])
|
||||
}
|
||||
|
||||
func test_observePlayersOrderedByName() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 1000)
|
||||
try dbQueue.write { db in
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
}
|
||||
|
||||
// When we observe players and wait for the first value
|
||||
let exp = expectation(description: "Players")
|
||||
var players: [Player]?
|
||||
let cancellable = appDatabase.observePlayersOrderedByName(
|
||||
onError: { error in
|
||||
XCTFail("Unexpected error \(error)")
|
||||
},
|
||||
onChange: {
|
||||
players = $0
|
||||
exp.fulfill()
|
||||
})
|
||||
withExtendedLifetime(cancellable) {
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
}
|
||||
|
||||
// Then the players are the two players ordered by name
|
||||
XCTAssertEqual(players, [player1, player2])
|
||||
}
|
||||
|
||||
func test_observePlayersOrderedByScore() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 1000)
|
||||
try dbQueue.write { db in
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
}
|
||||
|
||||
// When we observe players and wait for the first value
|
||||
let exp = expectation(description: "Players")
|
||||
var players: [Player]?
|
||||
let cancellable = appDatabase.observePlayersOrderedByScore(
|
||||
onError: { error in
|
||||
XCTFail("Unexpected error \(error)")
|
||||
},
|
||||
onChange: {
|
||||
players = $0
|
||||
exp.fulfill()
|
||||
})
|
||||
withExtendedLifetime(cancellable) {
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
}
|
||||
|
||||
// Then the players are the two players ordered by score descending
|
||||
XCTAssertEqual(players, [player2, player1])
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,9 @@ UIKit Demo Application
|
||||
|
||||
<img align="right" src="https://github.com/groue/GRDB.swift/raw/master/Documentation/DemoApps/GRDBDemoiOS/Screenshot.png" width="50%">
|
||||
|
||||
**This demo application is a storyboard-based UIKit application.** For a demo application that uses Combine and SwiftUI, see [GRDBCombineDemo](../GRDBCombineDemo/README.md).
|
||||
**This demo application is a storyboard-based UIKit application.** For a demo application that uses Combine + SwiftUI, see [GRDBCombineDemo](../GRDBCombineDemo/README.md).
|
||||
|
||||
**Requirements**: iOS 15.0+ / Xcode 12+
|
||||
|
||||
> :point_up: **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration.
|
||||
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
Demo Applications
|
||||
=================
|
||||
|
||||
- [UIKit Demo Application](GRDBDemoiOS/README.md): a storyboard-based UIKit application.
|
||||
- [Combine + SwiftUI Demo Application](GRDBCombineDemo/README.md): a Combine + SwiftUI application.
|
||||
- [GRDBDemoiOS]: a storyboard-based UIKit application.
|
||||
- [GRDBCombineDemo]: a Combine + SwiftUI application.
|
||||
|
||||
[GRDBCombineDemo] uses the `@Query` property wrapper, that lets SwiftUI views automatically update their content when the database changes. It is defined in the [GRDBQuery] package.
|
||||
|
||||
[GRDBDemoiOS]: GRDBDemoiOS
|
||||
[GRDBCombineDemo]: GRDBCombineDemo
|
||||
[GRDBQuery]: https://github.com/groue/GRDBQuery
|
||||
@@ -304,7 +304,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.13/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.14/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -587,7 +587,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.13/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.14/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
|
||||
@@ -77,7 +77,7 @@ try dbQueue.read { db in
|
||||
}
|
||||
```
|
||||
|
||||
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.13/Structs/DatabaseMigrator.html) for more migrator methods.
|
||||
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.14/Structs/DatabaseMigrator.html) for more migrator methods.
|
||||
|
||||
|
||||
## The `eraseDatabaseOnSchemaChange` Option
|
||||
@@ -260,6 +260,9 @@ while let violation = try violations.next() {
|
||||
// "FOREIGN KEY constraint violation - from player(teamId) to team(id),
|
||||
// in [id:1 teamId:2 name:"O'Brien" score:1000]"
|
||||
try violation.failureDescription(db)
|
||||
|
||||
// Turn violation into a DatabaseError
|
||||
throw violation.databaseError(db)
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '5.13.0'
|
||||
s.version = '5.14.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
@@ -496,16 +496,9 @@ extension Database {
|
||||
}
|
||||
|
||||
private func checkForeignKeys(from violations: RecordCursor<ForeignKeyViolation>) throws {
|
||||
guard let violation = try violations.next() else {
|
||||
return
|
||||
if let violation = try violations.next() {
|
||||
throw violation.databaseError(self)
|
||||
}
|
||||
|
||||
// Grab detailed information, if possible, for better error message.
|
||||
// If detailed information is not available, fallback to plain description.
|
||||
let message = (try? violation.failureDescription(self)) ?? String(describing: violation)
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_CONSTRAINT_FOREIGNKEY,
|
||||
message: message)
|
||||
}
|
||||
|
||||
/// Returns the actual name of the database table, in the main or temp
|
||||
@@ -777,19 +770,19 @@ public struct IndexInfo {
|
||||
/// See <https://www.sqlite.org/pragma.html#pragma_foreign_key_check>
|
||||
public struct ForeignKeyViolation: FetchableRecord, CustomStringConvertible {
|
||||
/// The name of the table that contains the `REFERENCES` clause
|
||||
var originTable: String
|
||||
public var originTable: String
|
||||
|
||||
/// The rowid of the row that contains the invalid `REFERENCES` clause, or
|
||||
/// nil if the origin table is a `WITHOUT ROWID` table.
|
||||
var originRowID: Int64?
|
||||
public var originRowID: Int64?
|
||||
|
||||
/// The name of the table that is referred to.
|
||||
var destinationTable: String
|
||||
public var destinationTable: String
|
||||
|
||||
/// The id of the specific foreign key constraint that failed. This id
|
||||
/// matches `ForeignKeyInfo.id`. See `Database.foreignKeys(on:)` for more
|
||||
/// information.
|
||||
var foreignKeyId: Int
|
||||
public var foreignKeyId: Int
|
||||
|
||||
public init(row: Row) {
|
||||
originTable = row[0]
|
||||
@@ -818,7 +811,7 @@ public struct ForeignKeyViolation: FetchableRecord, CustomStringConvertible {
|
||||
public func failureDescription(_ db: Database) throws -> String {
|
||||
// Grab detailed information, if possible, for better error message
|
||||
let originRow = try originRowID.flatMap { rowid in
|
||||
try Row.fetchOne(db, sql: "SELECT * FROM \(originTable) WHERE rowid = \(rowid)")
|
||||
try Row.fetchOne(db, sql: "SELECT * FROM \(originTable.quotedDatabaseIdentifier) WHERE rowid = \(rowid)")
|
||||
}
|
||||
let foreignKey = try db.foreignKeys(on: originTable).first(where: { foreignKey in
|
||||
foreignKey.id == foreignKeyId
|
||||
@@ -843,6 +836,16 @@ public struct ForeignKeyViolation: FetchableRecord, CustomStringConvertible {
|
||||
|
||||
return description
|
||||
}
|
||||
|
||||
/// Returns a DatabaseError of extended code `SQLITE_CONSTRAINT_FOREIGNKEY`
|
||||
public func databaseError(_ db: Database) -> DatabaseError {
|
||||
// Grab detailed information, if possible, for better error message.
|
||||
// If detailed information is not available, fallback to plain description.
|
||||
let message = (try? failureDescription(db)) ?? String(describing: self)
|
||||
return DatabaseError(
|
||||
resultCode: .SQLITE_CONSTRAINT_FOREIGNKEY,
|
||||
message: message)
|
||||
}
|
||||
}
|
||||
|
||||
/// Primary keys are returned from the Database.primaryKey(_:) method.
|
||||
|
||||
@@ -150,8 +150,8 @@ public final class Statement {
|
||||
|
||||
// Returns ["id", nil", "name"] for "INSERT INTO table VALUES (:id, ?, :name)"
|
||||
fileprivate lazy var sqliteArgumentNames: [String?] = {
|
||||
(0..<self.sqliteArgumentCount).map {
|
||||
guard let cString = sqlite3_bind_parameter_name(self.sqliteStatement, Int32($0 + 1)) else {
|
||||
(0..<Int32(self.sqliteArgumentCount)).map {
|
||||
guard let cString = sqlite3_bind_parameter_name(self.sqliteStatement, $0 + 1) else {
|
||||
return nil
|
||||
}
|
||||
return String(String(cString: cString).dropFirst()) // Drop initial ":", "@", "$"
|
||||
|
||||
@@ -288,9 +288,9 @@ public struct DatabaseMigrator {
|
||||
public func completedMigrations(_ db: Database) throws -> [String] {
|
||||
let appliedIdentifiers = try appliedMigrations(db)
|
||||
let knownIdentifiers = _migrations.map(\.identifier)
|
||||
return Array(zip(appliedIdentifiers, knownIdentifiers)
|
||||
.prefix(while: { $0 == $1 })
|
||||
.map { $0.0 })
|
||||
return zip(appliedIdentifiers, knownIdentifiers)
|
||||
.prefix(while: { (applied: String, known: String) in applied == known })
|
||||
.map { $0.0 }
|
||||
}
|
||||
|
||||
/// Returns true if all migrations are applied.
|
||||
|
||||
@@ -488,10 +488,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.13.0 \
|
||||
--module-version 5.13.0 \
|
||||
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.14.0 \
|
||||
--module-version 5.14.0 \
|
||||
--module GRDB \
|
||||
--root-url http://groue.github.io/GRDB.swift/docs/5.13/ \
|
||||
--root-url http://groue.github.io/GRDB.swift/docs/5.14/ \
|
||||
--output Documentation/Reference \
|
||||
--xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS
|
||||
else
|
||||
|
||||
@@ -11,13 +11,13 @@
|
||||
|
||||
---
|
||||
|
||||
**Latest release**: November 7, 2021 • version 5.13.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
|
||||
**Latest release**: November 7, 2021 • [version 5.14.0](https://github.com/groue/GRDB.swift/tree/v5.14.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
|
||||
|
||||
**Requirements**: iOS 11.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ • SQLite 3.8.5+ • Swift 5.3+ / Xcode 12+
|
||||
|
||||
| Swift version | GRDB version |
|
||||
| -------------- | ----------------------------------------------------------- |
|
||||
| **Swift 5.3+** | **v5.13.0** |
|
||||
| **Swift 5.3+** | **v5.14.0** |
|
||||
| Swift 5.2 | [v5.12.0](https://github.com/groue/GRDB.swift/tree/v5.12.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) |
|
||||
@@ -317,7 +317,7 @@ Documentation
|
||||
|
||||
#### Reference
|
||||
|
||||
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.13/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
|
||||
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.14/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
|
||||
|
||||
#### Getting Started
|
||||
|
||||
@@ -511,7 +511,7 @@ let dbQueue = try DatabaseQueue(
|
||||
configuration: config)
|
||||
```
|
||||
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.13/Structs/Configuration.html) for more details.
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.14/Structs/Configuration.html) for more details.
|
||||
|
||||
|
||||
## Database Pools
|
||||
@@ -591,7 +591,7 @@ let dbPool = try DatabasePool(
|
||||
configuration: config)
|
||||
```
|
||||
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.13/Structs/Configuration.html) for more details.
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.14/Structs/Configuration.html) for more details.
|
||||
|
||||
|
||||
Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information.
|
||||
@@ -651,7 +651,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.13/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.14/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.
|
||||
|
||||
@@ -909,7 +909,7 @@ try dbQueue.read { db in
|
||||
let dictionary = try Dictionary(uniqueKeysWithValues: cursor)
|
||||
```
|
||||
|
||||
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.13/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.14/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
|
||||
@@ -988,7 +988,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.13/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.14/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:
|
||||
|
||||
@@ -1273,7 +1273,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.13/Structs/StatementArguments.html):
|
||||
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.14/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let url: URL = ...
|
||||
@@ -1720,7 +1720,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.13/Structs/Configuration.html) configuration flag:
|
||||
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.14/Structs/Configuration.html) configuration flag:
|
||||
|
||||
```swift
|
||||
// fatal error: A transaction has been left opened at the end of a database access
|
||||
@@ -1832,7 +1832,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.13/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.14/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
|
||||
|
||||
```swift
|
||||
insertStatement.arguments = ["name": "Arthur", "score": 1000]
|
||||
@@ -1915,7 +1915,7 @@ See also `Database.execute(sql:)` in the [Executing Updates](#executing-updates)
|
||||
|
||||
> :point_up: **Note**: it is a programmer error to reuse a prepared statement that has failed: GRDB may crash if you do so.
|
||||
|
||||
For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/5.13/Classes/Statement.html).
|
||||
For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/5.14/Classes/Statement.html).
|
||||
|
||||
|
||||
### Prepared Statements Cache
|
||||
@@ -2658,7 +2658,7 @@ try Place.fetchSet(db, sql: "SELECT ...", arguments:...) // Set<Place>
|
||||
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.13/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.14/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()`.
|
||||
|
||||
@@ -3098,7 +3098,7 @@ protocol EncodableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.13/Enums/DatabaseColumnDecodingStrategy.html) and [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.13/Enums/DatabaseColumnEncodingStrategy.html) to learn about all available strategies.
|
||||
See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.14/Enums/DatabaseColumnDecodingStrategy.html) and [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.14/Enums/DatabaseColumnEncodingStrategy.html) to learn about all available strategies.
|
||||
|
||||
|
||||
### Date and UUID Coding Strategies
|
||||
@@ -3120,7 +3120,7 @@ protocol EncodableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.13/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.13/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.13/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
|
||||
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.14/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.14/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.14/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
|
||||
|
||||
There is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs and uuid strings, both uppercase and lowercase).
|
||||
|
||||
@@ -4642,7 +4642,7 @@ Player // SELECT * FROM player
|
||||
```
|
||||
|
||||
|
||||
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.13/Structs/StatementArguments.html):
|
||||
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.14/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
// SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate)
|
||||
@@ -5410,7 +5410,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.13/Structs/AnyFetchRequest.html): a type-erased request.
|
||||
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.14/Structs/AnyFetchRequest.html): a type-erased request.
|
||||
|
||||
|
||||
## Joined Queries Support
|
||||
@@ -6665,7 +6665,7 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan
|
||||
|
||||
### DatabaseRegion
|
||||
|
||||
**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/5.13/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.14/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.
|
||||
|
||||
@@ -6675,7 +6675,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.13/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF).
|
||||
For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/5.14/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF).
|
||||
|
||||
|
||||
#### The DatabaseRegionConvertible Protocol
|
||||
@@ -7943,7 +7943,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.13/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.14/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp).
|
||||
|
||||
|
||||
|
||||
@@ -8084,7 +8084,7 @@ This chapter has [moved](Documentation/Concurrency.md#database-snapshots).
|
||||
|
||||
#### DatabaseWriter and DatabaseReader Protocols
|
||||
|
||||
This chapter was removed. See the references of [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.13/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.13/Protocols/DatabaseWriter.html).
|
||||
This chapter was removed. See the references of [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.14/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.14/Protocols/DatabaseWriter.html).
|
||||
|
||||
#### Asynchronous APIs
|
||||
|
||||
@@ -8132,7 +8132,7 @@ This chapter has [moved](Documentation/Concurrency.md#safe-and-unsafe-database-a
|
||||
[Sharing a Database]: Documentation/SharingADatabase.md
|
||||
[FAQ]: #faq
|
||||
[Database Observation]: #database-changes-observation
|
||||
[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.13/Structs/SQLRequest.html
|
||||
[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.14/Structs/SQLRequest.html
|
||||
[SQL literal]: Documentation/SQLInterpolation.md#sql-literal
|
||||
[Identifiable]: https://developer.apple.com/documentation/swift/identifiable
|
||||
[Query Interface Organization]: Documentation/QueryInterfaceOrganization.md
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>5.13.0</string>
|
||||
<string>5.14.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
|
||||
Reference in new issue
Block a user