Merge branch 'development'

This commit is contained in:
Gwendal Roué committed 2020-06-15 20:06:34 +02:00
commit 4cdb45e012
55 files changed
+2229 -649

No files matched your search

+21 -1
View File
@@ -11,7 +11,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 5.x Releases
- `5.0.0` Betas - [5.0.0-beta](#500-beta) | [5.0.0-beta.2](#500-beta2) | [5.0.0-beta.3](#500-beta3) | [5.0.0-beta.4](#500-beta4)
- `5.0.0` Betas - [5.0.0-beta](#500-beta) | [5.0.0-beta.2](#500-beta2) | [5.0.0-beta.3](#500-beta3) | [5.0.0-beta.4](#500-beta4) | [5.0.0-beta.5](#500-beta5)
#### 4.x Releases
@@ -74,6 +74,26 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
## Next Release
-->
## 5.0.0-beta.5
Released June 15, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta.4...v5.0.0-beta.5)
- **Breaking Change** [#795](https://github.com/groue/GRDB.swift/pull/795): Enhanced support for WAL Checkpoints
- **New**: `Database.maximumStatementArgumentCount` returns the maximum number of arguments accepted by an SQLite statement.
- **New**: Optimize DatabasePool handling of ValueObservation when SQLite is compiled with the SQLITE_ENABLE_SNAPSHOT option. We are now able to avoid fetching the observed value when we can prove that the database wasn't changed between the initial fetch and the beginning of transaction tracking. This optimization avoids duplicate notifications.
- **New**: The query interface now exposes the primary key through `TableRecord.primaryKey`, as well as the `selectPrimaryKey(as:)` method.
### Documentation Diff
- The [Demo Application](Documentation/DemoApps/GRDBDemoiOS) was updated for better conformance with the [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) Guide.
- A new [FAQ: Associations](README.md#faq-associations) addresses three frequent questions:
- [How do I filter records and only keep those that are associated to another record?](README.md#how-do-i-filter-records-and-only-keep-those-that-are-associated-to-another-record)
- [How do I filter records and only keep those that are NOT associated to another record?](README.md#how-do-i-filter-records-and-only-keep-those-that-are-not-associated-to-another-record)
- [How do I select only one column of an associated record?](README.md#how-do-i-select-only-one-column-of-an-associated-record)
- The guide for [Custom SQLite builds](Documentation/CustomSQLiteBuilds.md) now recommends enabling the `SQLITE_ENABLE_SNAPSHOT` option.
## 5.0.0-beta.4
+9 -1
View File
@@ -39,7 +39,14 @@ GRDB Associations
- [Aggregate Operations]
- [Isolation of Multiple Aggregates]
- [DerivableRequest Protocol]
- [Known Issues]
**[FAQ]**
- [How do I filter records and only keep those that are associated to another record?](../README.md#how-do-i-filter-records-and-only-keep-those-that-are-associated-to-another-record)
- [How do I filter records and only keep those that are NOT associated to another record?](../README.md#how-do-i-filter-records-and-only-keep-those-that-are-not-associated-to-another-record)
- [How do I select only one column of an associated record?](../README.md#how-do-i-select-only-one-column-of-an-associated-record)
**[Known Issues]**
## Associations Benefits
@@ -2468,3 +2475,4 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[persistence methods]: ../README.md#persistence-methods
[database observation tools]: ../README.md#database-changes-observation
[ValueObservation]: ../README.md#valueobservation
[FAQ]: ../README.md#faq-associations
+6 -4
View File
@@ -19,7 +19,9 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
git submodule update --init SQLiteCustom/src
```
2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5` and `SQLITE_ENABLE_PREUPDATE_HOOK`.
2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5`, `SQLITE_ENABLE_PREUPDATE_HOOK`.
It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](../README.md#valueobservation) when you use a [Database Pool](../README.md#database-pools).
3. Create a folder named `GRDBCustomSQLite` somewhere in your project directory.
@@ -30,7 +32,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
```xcconfig
// As many -D options as there are custom SQLite compilation options
// Note: there is no space between -D and the option name.
CUSTOM_SQLLIBRARY_CFLAGS = -DSQLITE_ENABLE_FTS5 -DSQLITE_ENABLE_PREUPDATE_HOOK
CUSTOM_SQLLIBRARY_CFLAGS = -DSQLITE_ENABLE_SNAPSHOT -DSQLITE_ENABLE_FTS5
```
- `GRDBCustomSQLite-USER.xcconfig`: this file lets GRDB know about extra compilation flags, and enables extra GRDB APIs.
@@ -38,15 +40,15 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
```xcconfig
// As many -D options as there are custom SQLite compilation options
// Note: there is one space between -D and the option name.
CUSTOM_OTHER_SWIFT_FLAGS = -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK
CUSTOM_OTHER_SWIFT_FLAGS = -D SQLITE_ENABLE_SNAPSHOT -D SQLITE_ENABLE_FTS5
```
- `GRDBCustomSQLite-USER.h`: this file lets your application know about extra compilation flags.
```c
// As many #define as there are custom SQLite compilation options
#define SQLITE_ENABLE_SNAPSHOT
#define SQLITE_ENABLE_FTS5
#define SQLITE_ENABLE_PREUPDATE_HOOK
```
- `GRDBCustomSQLite-INSTALL.sh`: this file installs the three other files.
@@ -25,7 +25,7 @@
56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */; };
56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361A1E8D9F38003B6DA4 /* Player.swift */; };
56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */; };
56B036241E8D9F4C003B6DA4 /* PlayersViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */; };
56B036241E8D9F4C003B6DA4 /* PlayerListViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -181,7 +181,7 @@
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
56B0361A1E8D9F38003B6DA4 /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = "<group>"; };
56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionViewController.swift; sourceTree = "<group>"; };
56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayersViewController.swift; sourceTree = "<group>"; };
56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerListViewController.swift; sourceTree = "<group>"; };
56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = "<group>"; };
/* End PBXFileReference section */
@@ -273,15 +273,15 @@
56B036051E8D9EBE003B6DA4 /* GRDBDemoiOS */ = {
isa = PBXGroup;
children = (
56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */,
56B036121E8D9EBE003B6DA4 /* Info.plist */,
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */,
56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */,
56B0361A1E8D9F38003B6DA4 /* Player.swift */,
56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */,
56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */,
56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */,
56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */,
56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */,
56B0360F1E8D9EBE003B6DA4 /* LaunchScreen.storyboard */,
56B036121E8D9EBE003B6DA4 /* Info.plist */,
56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */,
);
path = GRDBDemoiOS;
sourceTree = "<group>";
@@ -507,7 +507,7 @@
56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */,
56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */,
56B036071E8D9EBE003B6DA4 /* AppDelegate.swift in Sources */,
56B036241E8D9F4C003B6DA4 /* PlayersViewController.swift in Sources */,
56B036241E8D9F4C003B6DA4 /* PlayerListViewController.swift in Sources */,
56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -1,26 +1,22 @@
import GRDB
/// A type responsible for initializing the application database.
/// AppDatabase lets the application access the database.
///
/// See AppDelegate.setupDatabase()
struct AppDatabase {
/// It applies the pratices recommended at
/// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
final class AppDatabase {
private let dbQueue: DatabaseQueue
/// Creates a fully initialized database at path
static func openDatabase(atPath path: String) throws -> DatabaseQueue {
// Connect to the database
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
let dbQueue = try DatabaseQueue(path: path)
// Define the database schema
/// Creates an AppDatabase and updates its schema if necessary.
init(_ dbQueue: DatabaseQueue) throws {
self.dbQueue = dbQueue
try migrator.migrate(dbQueue)
return dbQueue
}
/// The DatabaseMigrator that defines the database schema.
///
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md
static var migrator: DatabaseMigrator {
private var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
migrator.registerMigration("createPlayer") { db in
@@ -54,3 +50,107 @@ struct AppDatabase {
}
}
// MARK: - Database Access
//
// This extension defines methods that fulfill application needs, both in terms
// of writes and reads.
extension AppDatabase {
// MARK: Writes
/// Save (insert or update) a player.
func savePlayer(_ player: inout Player) throws {
try dbQueue.write { db in
try player.save(db)
}
}
/// Delete one player
func deletePlayer(_ player: Player) throws {
try dbQueue.write { db in
_ = try player.delete(db)
}
}
/// Delete all players
func deleteAllPlayers() throws {
try dbQueue.write { db in
_ = try Player.deleteAll(db)
}
}
/// Refresh all players (by performing some random changes, for demo purpose).
func refreshPlayers() throws {
try dbQueue.write { db in
if try Player.fetchCount(db) == 0 {
// Insert new random players
for _ in 0..<8 {
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
try player.insert(db)
}
} else {
// Insert a player
if Bool.random() {
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
try player.insert(db)
}
// Delete a random player
if Bool.random() {
try Player.order(sql: "RANDOM()").limit(1).deleteAll(db)
}
// Update some players
for var player in try Player.fetchAll(db) where Bool.random() {
try player.updateChanges(db) {
$0.score = Player.randomScore()
}
}
}
}
}
// MARK: Reads
/// Tracks changes in the number of players
func observePlayerCount(
onError: @escaping (Error) -> Void,
onChange: @escaping (Int) -> Void)
-> DatabaseCancellable
{
ValueObservation
.tracking(Player.fetchCount)
.start(
in: dbQueue,
onError: onError,
onChange: onChange)
}
/// 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: dbQueue,
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: dbQueue,
onError: onError,
onChange: onChange)
}
}
@@ -1,8 +1,8 @@
import UIKit
import GRDB
// The shared database queue
var dbQueue: DatabaseQueue!
// The shared application database
var appDatabase: AppDatabase!
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
@@ -14,9 +14,14 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
}
private func setupDatabase(_ application: UIApplication) throws {
// AppDelegate is responsible for choosing the location of the database file.
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
let databaseURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("db.sqlite")
dbQueue = try AppDatabase.openDatabase(atPath: databaseURL.path)
let dbQueue = try DatabaseQueue(path: databaseURL.path)
// Create the shared application database
appDatabase = try AppDatabase(dbQueue)
}
}
@@ -1,8 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="15505" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="UAh-8N-CM8">
<device id="retina4_7" orientation="portrait" appearance="light"/>
<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">
<device id="retina6_1" orientation="portrait" appearance="light"/>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="15510"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="16087"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
@@ -10,25 +10,25 @@
<scene sceneID="Juk-Ad-tZ2">
<objects>
<tableViewController id="iNr-Oe-muq" customClass="PlayerEditionViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" dataMode="static" style="plain" separatorStyle="none" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="28" sectionFooterHeight="28" id="vlV-lc-eQA">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" dataMode="static" style="insetGrouped" separatorStyle="none" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="-1" estimatedSectionHeaderHeight="-1" sectionFooterHeight="-1" estimatedSectionFooterHeight="-1" id="vlV-lc-eQA">
<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"/>
<sections>
<tableViewSection id="Nzq-eO-jT3">
<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="0.0" y="28" width="375" height="44"/>
<rect key="frame" x="20" y="55.5" width="374" height="44"/>
<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="375" height="44"/>
<rect key="frame" x="0.0" y="0.0" width="374" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="Name" adjustsFontForContentSizeCategory="YES" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="m5m-Zs-j0z">
<rect key="frame" x="16" y="11.5" width="343" height="21"/>
<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"/>
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
<textInputTraits key="textInputTraits" autocapitalizationType="words" autocorrectionType="no" spellCheckingType="no" returnKeyType="next"/>
<connections>
<action selector="textFieldDidChange:" destination="iNr-Oe-muq" eventType="editingChanged" id="EmC-Rp-f6S"/>
<outlet property="delegate" destination="iNr-Oe-muq" id="K2p-7d-teD"/>
</connections>
</textField>
@@ -40,17 +40,24 @@
</constraints>
</tableViewCellContentView>
</tableViewCell>
</cells>
</tableViewSection>
<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="0.0" y="72" width="375" height="44"/>
<rect key="frame" x="20" y="155" width="374" height="44"/>
<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="375" height="44"/>
<rect key="frame" x="0.0" y="0.0" width="374" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="Score" adjustsFontForContentSizeCategory="YES" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="rZ9-Fa-cyr">
<rect key="frame" x="16" y="11.5" width="343" height="21"/>
<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"/>
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
<textInputTraits key="textInputTraits" autocorrectionType="no" spellCheckingType="no" keyboardType="numberPad" returnKeyType="done"/>
<connections>
<action selector="textFieldDidChange:" destination="iNr-Oe-muq" eventType="editingChanged" id="ebo-2z-Z9P"/>
</connections>
</textField>
</subviews>
<constraints>
@@ -101,7 +108,7 @@
<objects>
<navigationController id="ein-Sr-i8w" sceneMemberID="viewController">
<navigationBar key="navigationBar" contentMode="scaleToFill" id="zIT-dB-Mfo">
<rect key="frame" x="0.0" y="0.0" width="375" height="56"/>
<rect key="frame" x="0.0" y="0.0" width="414" height="56"/>
<autoresizingMask key="autoresizingMask"/>
</navigationBar>
<connections>
@@ -117,7 +124,7 @@
<objects>
<navigationController id="UAh-8N-CM8" sceneMemberID="viewController">
<navigationBar key="navigationBar" contentMode="scaleToFill" id="U7d-1C-GnL">
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
<rect key="frame" x="0.0" y="44" width="414" height="44"/>
<autoresizingMask key="autoresizingMask"/>
</navigationBar>
<connections>
@@ -131,27 +138,27 @@
<!--Hall Of Fame-->
<scene sceneID="9su-ms-vdJ">
<objects>
<tableViewController id="PJp-Eq-ZjA" customClass="PlayersViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
<tableViewController id="PJp-Eq-ZjA" customClass="PlayerListViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
<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="375" height="667"/>
<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"/>
<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="375" height="43.5"/>
<rect key="frame" x="0.0" y="28" 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="348" height="43.5"/>
<rect key="frame" x="0.0" y="0.0" width="383" 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="16" y="12" width="33.5" height="20.5"/>
<rect key="frame" x="20" y="12" width="33.5" height="20.5"/>
<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="296" y="12" width="44" height="20.5"/>
<rect key="frame" x="331" y="12" width="44" height="20.5"/>
<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"/>
@@ -1,23 +1,23 @@
import GRDB
// A plain Player struct
/// The Player struct
struct Player {
// Prefer Int64 for auto-incremented database ids
var id: Int64?
var id: Int64? // Use Int64 for auto-incremented database ids
var name: String
var score: Int
}
// Hashable conformance supports tableView diffing
/// Hashable conformance supports tableView diffing
extension Player: Hashable { }
// MARK: - Persistence
// Turn Player into a Codable Record.
// See https://github.com/groue/GRDB.swift/blob/master/README.md#records
/// Make Player a Codable Record.
///
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#records
extension Player: Codable, FetchableRecord, MutablePersistableRecord {
// Define database columns from CodingKeys
private enum Columns {
fileprivate enum Columns {
static let id = Column(CodingKeys.id)
static let name = Column(CodingKeys.name)
static let score = Column(CodingKeys.score)
@@ -29,17 +29,33 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
}
}
// MARK: - Database access
// MARK: - Player Requests
// Define some useful player requests.
// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
extension Player {
static func orderedByName() -> QueryInterfaceRequest<Player> {
Player.order(Columns.name)
/// Define some player requests used by the application.
///
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
extension DerivableRequest where RowDecoder == Player {
/// A request of players ordered by name
///
/// For example:
///
/// let players = try dbQueue.read { db in
/// try Player.all().orderedByName().fetchAll(db)
/// }
func orderedByName() -> Self {
order(Player.Columns.name)
}
static func orderedByScore() -> QueryInterfaceRequest<Player> {
Player.order(Columns.score.desc, Columns.name)
/// A request of players ordered by score
///
/// For example:
///
/// let players = try dbQueue.read { db in
/// try Player.all().orderedByScore().fetchAll(db)
/// }
func orderedByScore() -> Self {
order(Player.Columns.score.desc, Player.Columns.name)
}
}
@@ -2,55 +2,44 @@ import UIKit
class PlayerEditionViewController: UITableViewController {
enum Presentation {
/// Modal presentation: edition ends with the "Commit" segue.
/// Modal presentation: edition ends with the "Commit" unwind segue.
case modal
/// Push presentation: edition ends when user hits the back button.
case push
}
var player: Player! { didSet { configureView() } }
var presentation: Presentation! { didSet { configureView() } }
@IBOutlet fileprivate weak var cancelBarButtonItem: UIBarButtonItem!
@IBOutlet fileprivate weak var commitBarButtonItem: UIBarButtonItem!
@IBOutlet fileprivate weak var nameCell: UITableViewCell!
@IBOutlet fileprivate weak var nameTextField: UITextField!
@IBOutlet fileprivate weak var scoreCell: UITableViewCell!
@IBOutlet fileprivate weak var scoreTextField: UITextField!
/// The edited player
var player: Player! {
didSet {
configureForm()
}
}
/// The presentation mode
var presentation: Presentation! {
didSet {
configureNavigationItem()
}
}
@IBOutlet private weak var cancelBarButtonItem: UIBarButtonItem!
@IBOutlet private weak var commitBarButtonItem: 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!
override func viewDidLoad() {
super.viewDidLoad()
configureView()
}
fileprivate func configureView() {
guard isViewLoaded else { return }
nameTextField.text = player.name
if player.score == 0 && player.id == nil {
scoreTextField.text = ""
} else {
scoreTextField.text = "\(player.score)"
}
switch presentation! {
case .modal:
navigationItem.leftBarButtonItem = cancelBarButtonItem
navigationItem.rightBarButtonItem = commitBarButtonItem
case .push:
navigationItem.leftBarButtonItem = nil
navigationItem.rightBarButtonItem = nil
}
configureForm()
configureNavigationItem()
}
}
// MARK: - Navigation
extension PlayerEditionViewController {
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
// Force keyboard to dismiss early
view.endEditing(true)
@@ -66,24 +55,31 @@ extension PlayerEditionViewController {
override func willMove(toParent parent: UIViewController?) {
super.willMove(toParent: parent)
switch presentation! {
case .modal:
break
case .push:
if parent == nil {
// Self is popping from its navigation controller
saveChanges()
}
if case .push = presentation, 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
}
}
}
}
// MARK: - Form
extension PlayerEditionViewController: UITextFieldDelegate {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
nameTextField.becomeFirstResponder()
@@ -106,16 +102,32 @@ extension PlayerEditionViewController: UITextFieldDelegate {
return false
}
@IBAction func textFieldDidChange(_ textField: UITextField) {
// User has edited the player: prevent interactive dismissal
if case .modal = presentation {
isModalInPresentation = true
}
}
private func configureForm() {
guard isViewLoaded else { return }
nameTextField.text = player.name
if player.score == 0 && player.id == nil {
scoreTextField.text = ""
} else {
scoreTextField.text = "\(player.score)"
}
}
private func saveChanges() {
guard var player = self.player else {
return
}
player.name = nameTextField.text ?? ""
player.score = scoreTextField.text.flatMap { Int($0) } ?? 0
try! appDatabase.savePlayer(&player)
self.player = player
try! dbQueue.inDatabase { db in
try player.save(db)
}
}
}
@@ -0,0 +1,243 @@
import UIKit
import GRDB
/// PlayerListViewController displays the list of players.
class PlayerListViewController: UITableViewController {
private enum PlayerOrdering {
case byName
case byScore
}
@IBOutlet private weak var newPlayerButtonItem: UIBarButtonItem!
private var animatesPlayersChange = false // Don't animate first update
private var players: [Player] = []
private var playersCancellable: DatabaseCancellable?
private var playerCountCancellable: DatabaseCancellable?
private var playerOrdering: PlayerOrdering = .byScore {
didSet {
configureOrderingBarButtonItem()
configureTableView()
}
}
override func viewDidLoad() {
super.viewDidLoad()
configureToolbar()
configureNavigationItem()
configureTableView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.isToolbarHidden = false
}
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(title: "💣", style: .plain, target: self, action: #selector(stressTest)),
]
}
private func configureNavigationItem() {
navigationItem.backBarButtonItem = UIBarButtonItem(
title: "Players", style: .plain,
target: nil, action: nil)
navigationItem.leftBarButtonItems = [editButtonItem, newPlayerButtonItem]
configureOrderingBarButtonItem()
configureTitle()
}
private func configureOrderingBarButtonItem() {
switch playerOrdering {
case .byScore:
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Score ▼",
style: .plain,
target: self, action: #selector(sortByName))
case .byName:
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Name ▲",
style: .plain,
target: self, action: #selector(sortByScore))
}
}
private func configureTitle() {
playerCountCancellable = appDatabase.observePlayerCount(
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] count in
guard let self = self else { return }
switch count {
case 0: self.navigationItem.title = "No Player"
case 1: self.navigationItem.title = "1 Player"
default: self.navigationItem.title = "\(count) Players"
}
})
}
private func configureTableView() {
switch playerOrdering {
case .byName:
playersCancellable = appDatabase.observePlayersOrderedByName(
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] players in
guard let self = self else { return }
self.updateTableView(with: players)
})
case .byScore:
playersCancellable = appDatabase.observePlayersOrderedByScore(
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] players in
guard let self = self else { return }
self.updateTableView(with: players)
})
}
}
private func updateTableView(with players: [Player]) {
if animatesPlayersChange == false {
self.players = players
tableView.reloadData()
// Future updates will be animated
animatesPlayersChange = true
return
}
// Compute difference between current and new list of players
let difference = players
.difference(from: self.players)
.inferringMoves()
// Apply those changes to the table view
tableView.performBatchUpdates({
self.players = players
for change in difference {
switch change {
case let .remove(offset, _, associatedWith):
if let associatedWith = associatedWith {
self.tableView.moveRow(
at: IndexPath(row: offset, section: 0),
to: IndexPath(row: associatedWith, section: 0))
} else {
self.tableView.deleteRows(
at: [IndexPath(row: offset, section: 0)],
with: .fade)
}
case let .insert(offset, _, associatedWith):
if associatedWith == nil {
self.tableView.insertRows(
at: [IndexPath(row: offset, section: 0)],
with: .fade)
}
}
}
}, completion: nil)
}
}
// MARK: - Navigation
extension PlayerListViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Edit" {
guard
let controller = segue.destination as? PlayerEditionViewController,
let indexPath = tableView.indexPathForSelectedRow
else { return }
let player = players[indexPath.row]
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
}
}
@IBAction func cancelPlayerEdition(_ segue: UIStoryboardSegue) {
// Player creation cancelled
}
@IBAction func commitPlayerEdition(_ segue: UIStoryboardSegue) {
// Player creation committed
}
}
// MARK: - UITableViewDataSource
extension PlayerListViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
players.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Player", for: indexPath)
configure(cell, at: indexPath)
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
// Delete the player
let player = players[indexPath.row]
try! appDatabase.deletePlayer(player)
}
private func configure(_ cell: UITableViewCell, at indexPath: IndexPath) {
let player = players[indexPath.row]
if player.name.isEmpty {
cell.textLabel?.text = "(anonymous)"
} else {
cell.textLabel?.text = player.name
}
cell.detailTextLabel?.text = abs(player.score) > 1 ? "\(player.score) points" : "0 point"
}
}
// 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.deleteAllPlayers()
}
@IBAction func refresh() {
setEditing(false, animated: true)
try! appDatabase.refreshPlayers()
}
@IBAction func stressTest() {
setEditing(false, animated: true)
for _ in 0..<50 {
DispatchQueue.global().async {
try! appDatabase.refreshPlayers()
}
}
}
}
@@ -1,8 +1,8 @@
import UIKit
import GRDB
/// PlayersViewController displays the list of players.
class PlayersViewController: UITableViewController {
/// PlayerListViewController displays the list of players.
class PlayerListViewController: UITableViewController {
private enum PlayerOrdering {
case byName
case byScore
@@ -18,14 +18,6 @@ class PlayersViewController: UITableViewController {
configureTableView()
}
}
private var playersRequest: QueryInterfaceRequest<Player> {
switch playerOrdering {
case .byName:
return Player.orderedByName()
case .byScore:
return Player.orderedByScore()
}
}
override func viewDidLoad() {
super.viewDidLoad()
@@ -71,13 +63,7 @@ class PlayersViewController: UITableViewController {
}
private func configureTitle() {
// Track changes in the number of players
let observation = ValueObservation.tracking { db in
try Player.fetchCount(db)
}
playerCountCancellable = observation.start(
in: dbQueue,
scheduling: .immediate,
playerCountCancellable = appDatabase.observePlayerCount(
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] count in
guard let self = self else { return }
@@ -90,19 +76,22 @@ class PlayersViewController: UITableViewController {
}
private func configureTableView() {
// Track changes in the list of players
let request = self.playersRequest
let observation = ValueObservation.tracking { db in
try request.fetchAll(db)
switch playerOrdering {
case .byName:
playersCancellable = appDatabase.observePlayersOrderedByName(
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] players in
guard let self = self else { return }
self.updateTableView(players)
})
case .byScore:
playersCancellable = appDatabase.observePlayersOrderedByScore(
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] players in
guard let self = self else { return }
self.updateTableView(players)
})
}
playersCancellable = observation.start(
in: dbQueue,
scheduling: .immediate,
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] players in
guard let self = self else { return }
self.updateTableView(players)
})
}
private func updateTableView(_ players: [Player]) {
@@ -141,7 +130,7 @@ class PlayersViewController: UITableViewController {
// MARK: - Navigation
extension PlayersViewController {
extension PlayerListViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Edit" {
@@ -173,7 +162,7 @@ extension PlayersViewController {
// MARK: - UITableViewDataSource
extension PlayersViewController {
extension PlayerListViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
players.count
}
@@ -187,9 +176,7 @@ extension PlayersViewController {
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
// Delete the player
let player = players[indexPath.row]
try! dbQueue.write { db in
_ = try player.delete(db)
}
try! appDatabase.deletePlayer(player)
}
private func configure(_ cell: UITableViewCell, at indexPath: IndexPath) {
@@ -206,7 +193,7 @@ extension PlayersViewController {
// MARK: - Actions
extension PlayersViewController {
extension PlayerListViewController {
@IBAction func sortByName() {
setEditing(false, animated: true)
playerOrdering = .byName
@@ -219,48 +206,19 @@ extension PlayersViewController {
@IBAction func deletePlayers() {
setEditing(false, animated: true)
try! dbQueue.write { db in
_ = try Player.deleteAll(db)
}
try! appDatabase.deleteAllPlayers()
}
@IBAction func refresh() {
setEditing(false, animated: true)
refreshPlayers()
try! appDatabase.refreshPlayers()
}
@IBAction func stressTest() {
setEditing(false, animated: true)
for _ in 0..<50 {
DispatchQueue.global().async {
self.refreshPlayers()
}
}
}
private func refreshPlayers() {
try! dbQueue.write { db in
if try Player.fetchCount(db) == 0 {
// Insert new random players
for _ in 0..<8 {
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
try player.insert(db)
}
} else {
// Insert a player
if Bool.random() {
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
try player.insert(db)
}
// Delete a random player
if Bool.random() {
try Player.order(sql: "RANDOM()").limit(1).deleteAll(db)
}
// Update some players
for var player in try Player.fetchAll(db) where Bool.random() {
player.score = Player.randomScore()
try player.update(db)
}
try! appDatabase.refreshPlayers()
}
}
}
+8 -7
View File
@@ -5,9 +5,10 @@ Demo Application
**This demo application shows you:**
- how to setup a database in an iOS app
- how to define a simple [Codable Record](../../../README.md#codable-records)
- how to track database changes and animate a table view with [ValueObservation](../../../README.md#valueobservation).
- How to setup a database in an iOS app.
- How to define a simple [Codable Record](../../../README.md#codable-records).
- How to track database changes and animate a table view with [ValueObservation](../../../README.md#valueobservation).
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
**Files of interest:**
@@ -17,15 +18,15 @@ Demo Application
- [AppDatabase.swift](GRDBDemoiOS/AppDatabase.swift)
`AppDatabase` defines the database for the whole application. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema.
`AppDatabase` grants database access for the whole application. 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.
- [Player.swift](GRDBDemoiOS/Player.swift)
`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).
`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). It defines the database requests used by the application.
- [PlayersViewController.swift](GRDBDemoiOS/PlayersViewController.swift)
- [PlayerListViewController.swift](GRDBDemoiOS/PlayerListViewController.swift)
`PlayersViewController` displays a list of players. It keeps its view up-to-date with [ValueObservation](../../../README.md#valueobservation).
`PlayerListViewController` displays the list of players.
- [PlayerEditionViewController.swift](GRDBDemoiOS/PlayerEditionViewController.swift)
+2 -2
View File
@@ -280,7 +280,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
```
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Structs/StatementArguments.html):
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
@@ -529,7 +529,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
```
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Structs/StatementArguments.html):
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
+1 -1
View File
@@ -68,7 +68,7 @@ try dbQueue.read { db in
}
```
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Structs/DatabaseMigrator.html) for more migrator methods.
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Structs/DatabaseMigrator.html) for more migrator methods.
## The `eraseDatabaseOnSchemaChange` Option
+2 -2
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '5.0.0-beta.4'
s.version = '5.0.0-beta.5'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
@@ -23,7 +23,7 @@ Pod::Spec.new do |s|
end
s.subspec 'SQLCipher' do |ss|
ss.source_files = 'GRDB/**/*.swift', 'Support/grdb_config.h'
ss.source_files = 'GRDB/**/*.swift', 'Support/SQLCipher_config.h'
ss.framework = 'Foundation'
ss.dependency 'SQLCipher', '>= 3.4.0'
ss.xcconfig = {
+2 -2
View File
@@ -2331,10 +2331,10 @@
567DAF141EAB61ED00FC0928 /* grdb_config.h */,
DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */,
DC3773F819C8CBB3004FCF85 /* GRDB.h */,
56C48E731C9A9923005DF1D9 /* module.modulemap */,
DC3773F719C8CBB3004FCF85 /* Info.plist */,
56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */,
56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */,
DC3773F719C8CBB3004FCF85 /* Info.plist */,
56C48E731C9A9923005DF1D9 /* module.modulemap */,
);
name = "Supporting Files";
path = ../Support;
+5 -1
View File
@@ -344,14 +344,18 @@ extension Database {
throws -> [String]?
where T.Iterator.Element == String
{
// Check primaryKey first, so that we fail early if the table does not exist
let lowercasedColumns = Set(columns.map { $0.lowercased() })
if lowercasedColumns.isEmpty {
// Don't hit the database for trivial case
return nil
}
// Assume "rowid" is a primary key
if lowercasedColumns == ["rowid"] {
return ["rowid"]
}
// Check primaryKey.
let primaryKey = try self.primaryKey(tableName)
if Set(primaryKey.columns.map { $0.lowercased() }).isSubset(of: lowercasedColumns) {
return primaryKey.columns
+80 -5
View File
@@ -211,9 +211,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// This method must be called after database initialization
func setup() throws {
setupBusyMode()
setupDoubleQuotedStringLiterals()
try setupForeignKeys()
setupBusyMode()
setupDefaultFunctions()
setupDefaultCollations()
setupAuthorizer()
@@ -380,6 +380,25 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
}
// MARK: - Limits
/// The maximum number of arguments accepted by an SQLite statement.
///
/// For example, requests such as the one below must make sure the `ids`
/// array does not contain more than `maximumStatementArgumentCount`
/// elements:
///
/// let ids: [Int] = ...
/// try dbQueue.write { db in
/// try Player.deleteAll(db, keys: ids)
/// }
///
/// See https://www.sqlite.org/limits.html
/// and `SQLITE_LIMIT_VARIABLE_NUMBER`.
public var maximumStatementArgumentCount: Int {
Int(sqlite3_limit(sqliteConnection, SQLITE_LIMIT_VARIABLE_NUMBER, -1))
}
// MARK: - Functions
/// Add or redefine an SQL function.
@@ -466,6 +485,38 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
finally: endReadOnly)
}
// MARK: - Snapshots
/// Returns a snapshot that must be freed with `grdb_snapshot_free`.
///
/// See https://www.sqlite.org/c3ref/snapshot.html
func takeVersionSnapshot() throws -> UnsafeMutablePointer<sqlite3_snapshot> {
var snapshot: UnsafeMutablePointer<sqlite3_snapshot>?
let code = withUnsafeMutablePointer(to: &snapshot) {
grdb_snapshot_get(sqliteConnection, "main", $0)
}
guard code == SQLITE_OK else {
// Don't grab `lastErrorMessage`, because grdb_snapshot_get may be a
// shim that does not call the missing sqlite3_snapshot_get.
throw DatabaseError(resultCode: code)
}
if let snapshot = snapshot {
return snapshot
} else {
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
}
}
func wasChanged(since initialSnapshot: UnsafeMutablePointer<sqlite3_snapshot>) throws -> Bool {
let secondSnapshot = try takeVersionSnapshot()
defer {
grdb_snapshot_free(secondSnapshot)
}
let cmp = grdb_snapshot_cmp(initialSnapshot, secondSnapshot)
assert(cmp <= 0, "Unexpected snapshot ordering")
return cmp < 0
}
// MARK: - Authorizer
func withAuthorizer<T>(_ authorizer: StatementAuthorizer?, _ block: () throws -> T) rethrows -> T {
@@ -621,11 +672,35 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
}
// MARK: - Checkpoints
// MARK: - WAL Checkpoints
func checkpoint(_ kind: Database.CheckpointMode) throws {
let code = sqlite3_wal_checkpoint_v2(sqliteConnection, nil, kind.rawValue, nil, nil)
guard code == SQLITE_OK else {
/// Runs a WAL checkpoint.
///
/// See https://www.sqlite.org/wal.html and
/// https://www.sqlite.org/c3ref/wal_checkpoint_v2.html for
/// more information.
///
/// - parameter kind: The checkpoint mode (default passive)
/// - parameter dbName: The database name (default "main")
/// - returns: A tuple:
/// - `walFrameCount`: the total number of frames in the log file
/// - `checkpointedFrameCount`: the total number of checkpointed frames
/// in the log file
@discardableResult
public func checkpoint(_ kind: Database.CheckpointMode = .passive, on dbName: String? = "main") throws
-> (walFrameCount: Int, checkpointedFrameCount: Int)
{
SchedulingWatchdog.preconditionValidQueue(self)
var walFrameCount: CInt = -1
var checkpointedFrameCount: CInt = -1
let code = sqlite3_wal_checkpoint_v2(sqliteConnection, dbName, kind.rawValue,
&walFrameCount, &checkpointedFrameCount)
switch code {
case SQLITE_OK:
return (walFrameCount: Int(walFrameCount), checkpointedFrameCount: Int(checkpointedFrameCount))
case SQLITE_MISUSE:
throw DatabaseError(resultCode: code)
default:
throw DatabaseError(resultCode: code, message: lastErrorMessage)
}
}
+99 -65
View File
@@ -167,24 +167,6 @@ public final class DatabasePool: DatabaseWriter {
}
}
extension DatabasePool {
// MARK: - WAL Checkpoints
/// Runs a WAL checkpoint
///
/// See https://www.sqlite.org/wal.html and
/// https://www.sqlite.org/c3ref/wal_checkpoint_v2.html) for
/// more information.
///
/// - parameter kind: The checkpoint mode (default passive)
public func checkpoint(_ kind: Database.CheckpointMode = .passive) throws {
try writer.sync { db in
try db.checkpoint(kind)
}
}
}
extension DatabasePool {
// MARK: - Memory management
@@ -884,69 +866,121 @@ extension DatabasePool: DatabaseReader {
onError: onError,
onChange: onChange)
// Starting a concurrent observation means that we'll fetch the initial
// value right away, without waiting for an access to the writer queue,
// and the opportunity to install a transaction observer.
//
// This is how DatabasePool can start an observation and promptly notify
// an initial value, even when there is a long-running write transaction
// in the background.
//
// We thus have to deal with the fact that between this initial fetch,
// and the beginning of transaction tracking, any number of untracked
// writes may occur.
//
// We must notify changes that happen during this untracked window. But
// how do we spot them, since we're not tracking database changes yet?
//
// A safe solution is to always perform a second fetch. We may fetch the
// same initial value, if no change did happen. But we don't miss
// possible changes.
//
// We can avoid this second fetch when SQLite is compiled with the
// SQLITE_ENABLE_SNAPSHOT option:
//
// 1. Perform the initial fetch in a DatabaseSnapshot. The snapshot
// acquires a lock that will prevent checkpointing until we get a writer
// access, so that we can reliably compare database versions with
// `sqlite3_snapshot`: https://www.sqlite.org/c3ref/snapshot.html.
//
// 2. Get a writer access, and compare the versions of the initial
// snapshot, and the current state of the database: if versions are
// identical, we can avoid the second fetch. If they are not, we perform
// the second fetch, even if the actual changes are unrelated to the
// tracked database region (we have no way to know).
//
// 3. Install the transaction observer.
if scheduler.immediateInitialValue() {
do {
// Fetch the initial value without waiting for the writer.
let initialValue = try unsafeReentrantRead(observer.fetchInitialValue)
let initialSnapshot = try makeSnapshot()
let initialValue = try initialSnapshot.read(observer.fetchInitialValue)
onChange(initialValue)
// Now wait for the writer
_weakAsyncWriteWithoutTransaction { db in
guard let db = db else { return }
if observer.isCompleted { return }
do {
// Don't miss eventual changes between the
// initial fetch and the writer access.
if let value = try observer.fetchValue(db) {
observer.notifyChange(value)
}
// Now we can start observation
db.add(transactionObserver: observer, extent: .observerLifetime)
} catch {
observer.notifyErrorAndComplete(error)
}
}
add(observer: observer, from: initialSnapshot)
} catch {
observer.cancel()
onError(error)
}
} else {
// Fetch the initial value without waiting for the writer.
_weakAsyncRead { [weak self] dbResult in
guard let dbResult = dbResult else { return }
guard let self = self else { return }
if observer.isCompleted { return }
do {
let initialValue = try observer.fetchInitialValue(dbResult.get())
observer.notifyChange(initialValue)
let label = configuration.identifier(
defaultLabel: "GRDB.DatabasePool",
purpose: "ValueObservation")
configuration
.makeDispatchQueue(label: label)
.async { [weak self] in
guard let self = self else { return }
if observer.isCompleted { return }
// Now wait for the writer
self._weakAsyncWriteWithoutTransaction { db in
guard let db = db else { return }
if observer.isCompleted { return }
do {
// Don't miss eventual changes between the
// initial fetch and the writer access.
if let value = try observer.fetchValue(db) {
observer.notifyChange(value)
}
// Now we can start observation
db.add(transactionObserver: observer, extent: .observerLifetime)
} catch {
observer.notifyErrorAndComplete(error)
}
do {
let initialSnapshot = try self.makeSnapshot()
let initialValue = try initialSnapshot.read(observer.fetchInitialValue)
observer.notifyChange(initialValue)
self.add(observer: observer, from: initialSnapshot)
} catch {
observer.notifyErrorAndComplete(error)
}
} catch {
observer.notifyErrorAndComplete(error)
}
}
}
return observer
}
// Support for _addConcurrent(observation:)
private func add<Reducer: _ValueReducer>(
observer: ValueObserver<Reducer>,
from initialSnapshot: DatabaseSnapshot)
{
_weakAsyncWriteWithoutTransaction { db in
guard let db = db else { return }
if observer.isCompleted { return }
do {
// Transaction is needed for version snapshotting
try db.inTransaction(.deferred) {
// Keep DatabaseSnaphot alive until we have compared
// database versions. It prevents database checkpointing,
// and keeps versions (`sqlite3_snapshot`) valid
// and comparable.
let fetchNeeded: Bool = withExtendedLifetime(initialSnapshot) {
// Version is nil if SQLite is not compiled with
// SQLITE_ENABLE_SNAPSHOT, or if the DatabaseSnaphot
// could not grab its version. In this case, we don't
// care, and just fetch a fresh value.
guard let initialVersion = initialSnapshot.version else {
return true
}
do {
return try db.wasChanged(since: initialVersion)
} catch {
// ignore: we'll just re-fetch
return true
}
}
if fetchNeeded, let value = try observer.fetchValue(db) {
observer.notifyChange(value)
}
return .commit
}
// Now we can start observation
db.add(transactionObserver: observer, extent: .observerLifetime)
} catch {
observer.notifyErrorAndComplete(error)
}
}
}
// MARK: - Custom FTS5 Tokenizers
#if SQLITE_ENABLE_FTS5
+8 -1
View File
@@ -14,6 +14,9 @@ public class DatabaseSnapshot: DatabaseReader {
serializedDatabase.configuration
}
/// Not nil iff SQLite was compiled with `SQLITE_ENABLE_SNAPSHOT`.
private(set) var version: UnsafeMutablePointer<sqlite3_snapshot>?
init(path: String, configuration: Configuration = Configuration(), defaultLabel: String, purpose: String) throws {
var configuration = configuration
configuration.readonly = true
@@ -33,12 +36,16 @@ public class DatabaseSnapshot: DatabaseReader {
throw DatabaseError(message: "WAL mode is not activated at path: \(path)")
}
try db.beginSnapshotTransaction()
version = try? db.takeVersionSnapshot()
}
}
deinit {
// Leave snapshot isolation
serializedDatabase.sync { db in
serializedDatabase.reentrantSync { db in
if let version = version {
grdb_snapshot_free(version)
}
try? db.commit()
}
}
+12
View File
@@ -283,6 +283,17 @@ class DatabaseObservationBroker {
}
}
switch transactionState {
case .none:
break
default:
// May happen after "PRAGMA journal_mode = WAL" executed with a
// SelectStatement.
// TODO: Maybe this state machine should be run for *all* statements,
// not ony update statements.
transactionState = .none
}
if observesRowDeletion {
return TruncateOptimizationBlocker()
} else {
@@ -496,6 +507,7 @@ class DatabaseObservationBroker {
/// Remove transaction observers that have stopped observing transaction,
/// and uninstall SQLite update hooks if there is no remaining observers.
private func databaseDidEndTransaction() {
assert(!database.isInsideTransaction)
transactionObservations = transactionObservations.filter(\.isObserving)
// Undo disableUntilNextTransaction(transactionObserver:)
+3
View File
@@ -86,6 +86,9 @@ extension DatabaseMigrator {
}
extension DatabasePool {
@available(*, unavailable, message: "Use pool.writeWithoutTransaction { $0.checkpoint() } instead")
public func checkpoint(_ kind: Database.CheckpointMode = .passive) throws { preconditionFailure() }
#if os(iOS)
@available(*, unavailable, message: "Memory management is now enabled by default. This method does nothing.")
public func setupMemoryManagement(in application: UIApplication) { preconditionFailure() }
@@ -38,10 +38,9 @@ extension AssociationToMany {
///
/// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db)
public var count: AssociationAggregate<OriginRowDecoder> {
let expression = DatabasePromise<SQLExpression> { db in
let primaryKey = try db.primaryKeyExpression(self.databaseTableName)
return SQLExpressionCountDistinct(primaryKey)
}
let expression = SQLExpressionCountDistinct(
SQLPrimaryKeyExpression(
tableName: self.databaseTableName))
return makeAggregate(expression).forKey("\(key.singularizedName)Count")
}
@@ -61,10 +60,10 @@ extension AssociationToMany {
/// let teams: [Team] = try Team.having(!Team.players.isEmpty())
/// let teams: [Team] = try Team.having(Team.players.isEmpty() == false)
public var isEmpty: AssociationAggregate<OriginRowDecoder> {
let expression = DatabasePromise<SQLExpression> { db in
let primaryKey = try db.primaryKeyExpression(self.databaseTableName)
return SQLExpressionIsEmpty(SQLExpressionCountDistinct(primaryKey))
}
let expression = SQLExpressionIsEmpty(
SQLExpressionCountDistinct(
SQLPrimaryKeyExpression(
tableName: self.databaseTableName)))
return makeAggregate(expression).forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)")
}
@@ -192,6 +192,30 @@ extension QueryInterfaceRequest: SelectionRequest {
public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest {
map(\.query) { $0.annotated(with: selection) }
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Creates a request which selects the primary key of the table.
///
/// For example:
///
/// struct Player: TableRecord { ... }
///
/// let playerIds = dbQueue.read { db in
/// try Player.all().selectPrimaryKey(as: Int64.self).fetchAll(db)
/// }
///
/// For tables that have no explicit primary key, the request selects the
/// `rowid` column.
///
/// For tables whose primary key spans several columns, the current
/// implementation also returns a request that selects the `rowid` column.
/// Future GRDB versions may return a [row value](https://www.sqlite.org/rowvalue.html).
public func selectPrimaryKey<RowDecoder>(as type: RowDecoder.Type = RowDecoder.self)
-> QueryInterfaceRequest<RowDecoder>
{
select(SQLPrimaryKeyExpression(tableName: databaseTableName), as: RowDecoder.self)
}
}
extension QueryInterfaceRequest: FilteredRequest {
@@ -779,3 +779,68 @@ struct SQLExpressionCollate: SQLExpression {
SQLExpressionCollate(expression.qualifiedExpression(with: alias), collationName: collationName)
}
}
// MARK: - SQLPrimaryKeyExpression
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// SQLPrimaryKeyExpression is the primary key of a table.
///
/// For tables that have no explicit primary key, SQLPrimaryKeyExpression is the
/// `rowid` column.
///
/// For tables whose primary key spans several columns, the current
/// implementation of SQLPrimaryKeyExpression also is the `rowid` column. Future
/// GRDB versions may return a [row value](https://www.sqlite.org/rowvalue.html).
///
/// For example:
///
/// struct Player: TableRecord { ... }
///
/// let player = dbQueue.read { db in
/// try Player.filter(Player.primaryKey == 12).fetchOne(db)
/// }
public struct SQLPrimaryKeyExpression: SQLExpression {
let tableName: String
/// Support for SQLPrimaryKeyExpression and SQLQualifiedPrimaryKeyExpression
fileprivate static func primaryKeyColumn(_ db: Database, tableName: String) throws -> Column {
let columns = try db.primaryKey(tableName).columns
if columns.count == 1 {
return Column(columns[0])
} else {
return Column.rowID
}
}
public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
try SQLPrimaryKeyExpression
.primaryKeyColumn(context.db, tableName: tableName)
.expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis)
}
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
SQLQualifiedPrimaryKeyExpression(tableName: tableName, alias: alias)
}
}
struct SQLQualifiedPrimaryKeyExpression: SQLExpression {
let tableName: String
let alias: TableAlias
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
GRDBPrecondition(
tableName.lowercased() == alias.tableName.lowercased(),
"Table names don't match: \(tableName) and \(alias.tableName)")
return try SQLPrimaryKeyExpression
.primaryKeyColumn(context.db, tableName: tableName)
.qualifiedExpression(with: alias)
.expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis)
}
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
// Never requalify
self
}
}
@@ -169,22 +169,3 @@ struct SQLExpressionNot: SQLExpression {
SQLExpressionNot(expression.qualifiedExpression(with: alias))
}
}
// MARK: -
extension Database {
/// Returns an expression for the primary key of this table.
///
/// When the table as a primary key made of several columns, we return
/// the rowid column. Eventually we'll support
/// [row values](https://www.sqlite.org/rowvalue.html) and be able to deal
/// with WITHOUT ROWID tables.
func primaryKeyExpression(_ tableName: String) throws -> SQLExpression {
let columns = try primaryKey(tableName).columns
if columns.count == 1 {
return Column(columns[0])
} else {
return Column.rowID
}
}
}
-12
View File
@@ -184,18 +184,6 @@ struct SQLRelation {
}
}
}
/// Returns nil if there is no way to express the primary key of the
/// relation as an expression.
func primaryKeyExpression(_ db: Database) throws -> SQLExpression? {
switch source {
case .subquery:
// No primary key for subquery
return nil
case let .table(tableName: tableName, alias: _):
return try db.primaryKeyExpression(tableName)
}
}
}
extension SQLRelation: Refinable {
@@ -347,7 +347,7 @@ struct SQLQueryGenerator: Refinable {
}
let context = SQLGenerationContext(db)
let primaryKey = try db.primaryKeyExpression(tableName)
let primaryKey = SQLPrimaryKeyExpression(tableName: tableName)
var sql = "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE "
sql += try primaryKey.expressionSQL(context, wrappedInParenthesis: false)
@@ -451,7 +451,7 @@ struct SQLQueryGenerator: Refinable {
}
let context = SQLGenerationContext(db)
let primaryKey = try db.primaryKeyExpression(tableName)
let primaryKey = SQLPrimaryKeyExpression(tableName: tableName)
// UPDATE table...
var sql = "UPDATE "
@@ -126,6 +126,31 @@ extension TableRecord {
all().select(literal: sqlLiteral, as: type)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Creates a request which selects the primary key of the table.
///
/// For example:
///
/// struct Player: TableRecord { ... }
///
/// let playerIds = dbQueue.read { db in
/// try Player.selectPrimaryKey(as: Int64.self).fetchAll(db)
/// }
///
/// For tables that have no explicit primary key, the request selects the
/// `rowid` column.
///
/// For tables whose primary key spans several columns, the current
/// implementation also returns a request that selects the `rowid` column.
/// Future GRDB versions may return a [row value](https://www.sqlite.org/rowvalue.html).
public static func selectPrimaryKey<RowDecoder>(
as type: RowDecoder.Type = RowDecoder.self)
-> QueryInterfaceRequest<RowDecoder>
{
all().selectPrimaryKey(as: type)
}
/// Creates a request which appends *selection*.
///
/// // SELECT id, email, name FROM player
+26
View File
@@ -140,6 +140,32 @@ extension TableRecord {
}
}
extension TableRecord {
// MARK: - Primary Key
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The primary key of the table.
///
/// For example:
///
/// struct Player: TableRecord { ... }
///
/// let player = dbQueue.read { db in
/// try Player.filter(Player.primaryKey == 12).fetchOne(db)
/// }
///
/// For tables that have no explicit primary key, this property returns the
/// `rowid` column.
///
/// For tables whose primary key spans several columns, the current
/// implementation also returns the `rowid` column. Future GRDB versions
/// may return a [row value](https://www.sqlite.org/rowvalue.html).
public static var primaryKey: SQLPrimaryKeyExpression {
SQLPrimaryKeyExpression(tableName: databaseTableName)
}
}
/// Calculating `defaultDatabaseTableName` is somewhat expensive due to the regular expression evaluation
///
/// This cache mitigates the cost of the calculation by storing the name for later retrieval
+11 -17
View File
@@ -313,8 +313,6 @@
56781B09243F7B5300650A83 /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = 56781B06243F7B4B00650A83 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; };
567A80561D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; };
567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; };
567DAF1E1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
567DAF211EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; };
567DAF3C1EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; };
567E4209242AB3CB00CAAD2C /* FailableTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567E4207242AB3CB00CAAD2C /* FailableTestCase.swift */; };
@@ -426,6 +424,8 @@
56C0539D22ACEECD0029D27D /* RemoveDuplicates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538F22ACEECD0029D27D /* RemoveDuplicates.swift */; };
56C0539E22ACEECD0029D27D /* RemoveDuplicates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538F22ACEECD0029D27D /* RemoveDuplicates.swift */; };
56C7A6AE1D2DFF6100EFB0C2 /* FoundationNSDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */; };
56C9EB9B2495324700FE5D55 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 56C9EB9A2495324700FE5D55 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
56C9EB9C2495324700FE5D55 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 56C9EB9A2495324700FE5D55 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
56CC9234201E009000CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */; };
56CC9235201E009100CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */; };
56CC923B201E033400CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC923A201E033400CB597E /* PrefixWhileCursorTests.swift */; };
@@ -905,7 +905,6 @@
5676FBA822F5CEB8004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = "<group>"; };
56781B06243F7B4B00650A83 /* GRDB-Bridging.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "GRDB-Bridging.h"; path = "SQLiteCustom/GRDB-Bridging.h"; sourceTree = "<group>"; };
567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = "<group>"; };
567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = "<group>"; };
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = "<group>"; };
567E4207242AB3CB00CAAD2C /* FailableTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FailableTestCase.swift; sourceTree = "<group>"; };
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = "<group>"; };
@@ -994,7 +993,6 @@
56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = "<group>"; };
56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = "<group>"; };
56B86E6E220FF4C800524C16 /* SQLLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLLiteralTests.swift; sourceTree = "<group>"; };
56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDB.xcconfig; sourceTree = "<group>"; };
56B9649C1DA51B4C0002DA19 /* FTS5.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5.swift; sourceTree = "<group>"; };
56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TokenizerDescriptor.swift; sourceTree = "<group>"; };
56B964B81DA51D0A0002DA19 /* FTS5Pattern.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5Pattern.swift; sourceTree = "<group>"; };
@@ -1008,9 +1006,8 @@
56C0538E22ACEECD0029D27D /* Map.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Map.swift; sourceTree = "<group>"; };
56C0538F22ACEECD0029D27D /* RemoveDuplicates.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RemoveDuplicates.swift; sourceTree = "<group>"; };
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSavepointTests.swift; sourceTree = "<group>"; };
56C48E731C9A9923005DF1D9 /* module.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; path = module.modulemap; sourceTree = "<group>"; };
56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDBDeploymentTarget.xcconfig; sourceTree = "<group>"; };
56C494421ED726C500CC72AF /* GRDBDeploymentTarget.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = GRDBDeploymentTarget.xcconfig; path = SQLiteCustom/GRDBDeploymentTarget.xcconfig; sourceTree = "<group>"; };
56C9EB9A2495324700FE5D55 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = grdb_config.h; path = SQLiteCustom/grdb_config.h; sourceTree = "<group>"; };
56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropWhileCursorTests.swift; sourceTree = "<group>"; };
56CC923A201E033400CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = "<group>"; };
56CC9248201E058900CB597E /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = "<group>"; };
@@ -1821,13 +1818,9 @@
DC37743319C8CFCE004FCF85 /* Supporting Files */ = {
isa = PBXGroup;
children = (
567DAF141EAB61ED00FC0928 /* grdb_config.h */,
DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */,
DC3773F819C8CBB3004FCF85 /* GRDB.h */,
56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */,
56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */,
DC3773F719C8CBB3004FCF85 /* Info.plist */,
56C48E731C9A9923005DF1D9 /* module.modulemap */,
);
name = "Supporting Files";
path = ../Support;
@@ -1845,15 +1838,16 @@
F3BA7FED1CFB21F8003DC1BA /* GRDBCustomSQLite */ = {
isa = PBXGroup;
children = (
EED476F41CFD174D0026A4EC /* Customize */,
56C9EB9A2495324700FE5D55 /* grdb_config.h */,
56781B06243F7B4B00650A83 /* GRDB-Bridging.h */,
F3BA7FF11CFB23D3003DC1BA /* GRDB.h */,
F3BA7FF01CFB23C9003DC1BA /* sqlite3.h */,
F3BA7FEF1CFB23BF003DC1BA /* module.modulemap */,
F3BA7FEE1CFB23B7003DC1BA /* GRDB.xcconfig */,
F3BA813B1CFB3770003DC1BA /* GRDBCustomSQLite-Testing.xcconfig */,
56C494421ED726C500CC72AF /* GRDBDeploymentTarget.xcconfig */,
F3BA7FEF1CFB23BF003DC1BA /* module.modulemap */,
F3BA7FF01CFB23C9003DC1BA /* sqlite3.h */,
F3BA7FF11CFB23D3003DC1BA /* GRDB.h */,
56781B06243F7B4B00650A83 /* GRDB-Bridging.h */,
F3BA7FF31CFB23E4003DC1BA /* SQLiteLib.xcodeproj */,
EED476F41CFD174D0026A4EC /* Customize */,
);
name = GRDBCustomSQLite;
sourceTree = "<group>";
@@ -1874,9 +1868,9 @@
buildActionMask = 2147483647;
files = (
F3BA80381CFB2932003DC1BA /* GRDB.h in Headers */,
56C9EB9C2495324700FE5D55 /* grdb_config.h in Headers */,
56781B09243F7B5300650A83 /* GRDB-Bridging.h in Headers */,
F3BA803A1CFB293A003DC1BA /* sqlite3.h in Headers */,
567DAF211EAB61ED00FC0928 /* grdb_config.h in Headers */,
EED476F31CFD172C0026A4EC /* GRDBCustomSQLite-USER.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -1886,9 +1880,9 @@
buildActionMask = 2147483647;
files = (
F3BA80931CFB2F13003DC1BA /* GRDB.h in Headers */,
56C9EB9B2495324700FE5D55 /* grdb_config.h in Headers */,
56781B08243F7B5300650A83 /* GRDB-Bridging.h in Headers */,
F3BA80951CFB2F18003DC1BA /* sqlite3.h in Headers */,
567DAF1E1EAB61ED00FC0928 /* grdb_config.h in Headers */,
EED476F21CFD17270026A4EC /* GRDBCustomSQLite-USER.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
+9 -9
View File
@@ -115,7 +115,7 @@ test_framework_GRDBOSX_maxSwift:
-scheme GRDBOSX \
SWIFT_VERSION=$(MAX_SWIFT_VERSION) \
'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 GRDB_SQLITE_ENABLE_SNAPSHOT=1' \
$(TEST_ACTIONS) \
$(XCPRETTY)
@@ -126,7 +126,7 @@ ifdef MIN_SWIFT_VERSION
-scheme GRDBOSX \
SWIFT_VERSION=$(MIN_SWIFT_VERSION) \
'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 GRDB_SQLITE_ENABLE_SNAPSHOT=1' \
$(TEST_ACTIONS) \
$(XCPRETTY)
endif
@@ -150,7 +150,7 @@ test_framework_GRDBiOS_maxTarget_maxSwift:
-destination $(MAX_IOS_DESTINATION) \
SWIFT_VERSION=$(MAX_SWIFT_VERSION) \
'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 GRDB_SQLITE_ENABLE_SNAPSHOT=1' \
$(TEST_ACTIONS) \
$(XCPRETTY)
@@ -162,7 +162,7 @@ ifdef MIN_SWIFT_VERSION
-destination $(MAX_IOS_DESTINATION) \
SWIFT_VERSION=$(MIN_SWIFT_VERSION) \
'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 GRDB_SQLITE_ENABLE_SNAPSHOT=1' \
$(TEST_ACTIONS) \
$(XCPRETTY)
endif
@@ -186,7 +186,7 @@ test_framework_GRDBtvOS_maxTarget_maxSwift:
-destination $(MAX_TVOS_DESTINATION) \
SWIFT_VERSION=$(MAX_SWIFT_VERSION) \
'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 GRDB_SQLITE_ENABLE_SNAPSHOT=1' \
$(TEST_ACTIONS) \
$(XCPRETTY)
@@ -198,7 +198,7 @@ ifdef MIN_SWIFT_VERSION
-destination $(MAX_TVOS_DESTINATION) \
SWIFT_VERSION=$(MIN_SWIFT_VERSION) \
'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 GRDB_SQLITE_ENABLE_SNAPSHOT=1' \
$(TEST_ACTIONS) \
$(XCPRETTY)
endif
@@ -394,10 +394,10 @@ ifdef JAZZY
--author 'Gwendal Roué' \
--author_url https://github.com/groue \
--github_url https://github.com/groue/GRDB.swift \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.0.0-beta.4 \
--module-version 5.0.0-beta.4 \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.0.0-beta.5 \
--module-version 5.0.0-beta.5 \
--module GRDB \
--root-url http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/ \
--root-url http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/ \
--output Documentation/Reference \
--xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS
else
+241 -36
View File
@@ -11,13 +11,13 @@
---
**Latest release**: June 6, 2020 • version 5.0.0-beta.4 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
**Latest release**: June 15, 2020 • version 5.0.0-beta.5 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
**Requirements**: iOS 10.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ &bull; Swift 5.2+ / Xcode 11.4+
| Swift version | GRDB version |
| ------------- | ----------------------------------------------------------- |
| **Swift 5.2** | **v5.0.0-beta.4**, [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0)|
| **Swift 5.2** | **v5.0.0-beta.5**, [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0)|
| Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
| Swift 5 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
| Swift 4.2 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
@@ -262,9 +262,14 @@ Documentation
**GRDB runs on top of SQLite**: you should get familiar with the [SQLite FAQ](http://www.sqlite.org/faq.html). For general and detailed information, jump to the [SQLite Documentation](http://www.sqlite.org/docs.html).
#### Frequently Asked Questions
- [FAQ]: [Opening Connections](#faq-opening-connections), [Associations](#faq-associations), etc.
#### Reference
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
#### Getting Started
@@ -313,7 +318,7 @@ Documentation
- :blue_book: [Unexpected SQLite with Swift](https://hackernoon.com/unexpected-sqlite-with-swift-ddc6343bcbfc)
**[FAQ](#faq)**
**[FAQ]**
**[Sample Code](#sample-code)**
@@ -477,7 +482,7 @@ let dbQueue = try DatabaseQueue(
configuration: config)
```
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Structs/Configuration.html) for more details.
## Database Pools
@@ -557,7 +562,7 @@ let dbPool = try DatabasePool(
configuration: config)
```
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Structs/Configuration.html) for more details.
Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information.
@@ -617,7 +622,7 @@ try dbQueue.write { db in
}
```
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/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.
@@ -815,7 +820,7 @@ Both arrays and cursors can iterate over database results. How do you choose one
- **Cursors are granted with direct access to SQLite,** unlike arrays that have to take the time to copy database values. If you look after extra performance, you may prefer cursors over arrays.
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/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
@@ -897,7 +902,7 @@ let rows = try Row.fetchAll(db,
arguments: ["name": "Arthur"])
```
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/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:
@@ -1180,7 +1185,7 @@ GRDB ships with built-in support for the following value types:
- Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol.
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Structs/StatementArguments.html):
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Structs/StatementArguments.html):
```swift
let url: URL = ...
@@ -1587,7 +1592,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction
}
```
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Structs/Configuration.html) configuration flag:
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Structs/Configuration.html) configuration flag:
```swift
// fatal error: A transaction has been left opened at the end of a database access
@@ -1701,7 +1706,7 @@ try dbQueue.write { db in
}
```
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
```swift
updateStatement.arguments = ["name": "Arthur", "score": 1000]
@@ -1960,7 +1965,7 @@ row["consumed"] // "Hello"
row["produced"] // nil
```
Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters, described below.
Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters, described below.
To see how row adapters can be used, see [Joined Queries Support](#joined-queries-support).
@@ -2415,7 +2420,7 @@ try Place.fetchAll(db, sql: "SELECT ...", arguments:...) // [Place]
try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place?
```
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Structs/StatementArguments.html) for more information about the query arguments.
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/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()`.
@@ -2794,7 +2799,7 @@ protocol EncodableRecord {
}
```
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
> :point_up: **Note**: there is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs, and uuid strings).
@@ -3628,6 +3633,7 @@ This is the list of record methods, along with their required protocols. The [Re
| `Type.none()` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
| `Type.select(...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
| `Type.select(..., as:...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
| `Type.selectPrimaryKey(as:...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
| `Type.annotated(with:...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
| `Type.filter(...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
| `Type.matching(...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
@@ -3636,9 +3642,11 @@ This is the list of record methods, along with their required protocols. The [Re
| `Type.including(required:)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
| `Type.joining(optional:)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
| `Type.joining(required:)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
| `Type.group(...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
| `Type.groupByPrimaryKey()` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
| `Type.having(...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
| `Type.order(...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
| `Type.orderByPrimaryKey()` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
| `Type.having(...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
| `Type.limit(...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
| **[Record Comparison]** | | |
| `record.databaseEquals(...)` | [EncodableRecord] | |
@@ -4112,19 +4120,6 @@ You can now build requests with the following methods: `all`, `none`, `select`,
Player.order(scoreColumn).order(nameColumn)
```
- `orderByPrimaryKey()` sorts by primary key:
```swift
// SELECT * FROM player ORDER BY id
Player.orderByPrimaryKey()
// SELECT * FROM country ORDER BY code
Country.orderByPrimaryKey()
// SELECT * FROM citizenship ORDER BY citizenId, countryCode
Citizenship.orderByPrimaryKey()
```
- `reversed()` reverses the eventual orderings.
```swift
@@ -4158,6 +4153,40 @@ You can now build requests with the following methods: `all`, `none`, `select`,
Player.including(required: Player.team)
```
- Other requests that involve the primary key:
- `selectPrimaryKey(as:)` selects the primary key.
```swift
// SELECT id FROM player
Player.selectPrimaryKey(as: Int64.self)
```
It is equivalent to:
```swift
// SELECT id FROM player
Player.select(Player.primaryKey, as: Int64.self)
```
> :point_up: **Note**: `selectPrimaryKey` and `primaryKey` are [experimental](#what-are-experimental-features) and currently pick the `rowid` column for tables that have a composite primary key that spans several columns. Future GRDB version may change this behavior.
- `orderByPrimaryKey()` sorts by primary key.
```swift
// SELECT * FROM player ORDER BY id
Player.orderByPrimaryKey()
// SELECT * FROM country ORDER BY code
Country.orderByPrimaryKey()
// SELECT * FROM citizenship ORDER BY citizenId, countryCode
Citizenship.orderByPrimaryKey()
```
- `groupByPrimaryKey()` groups rows by primary key.
You can refine requests by chaining those methods:
```swift
@@ -4179,7 +4208,7 @@ Player // SELECT * FROM player
```
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Structs/StatementArguments.html):
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Structs/StatementArguments.html):
```swift
// SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate)
@@ -4785,7 +4814,7 @@ try Player.customRequest().fetchAll(db) // [Player]
**To build custom requests**, you can use one of the built-in requests or derive requests from other requests.
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example:
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example:
```swift
extension Player {
@@ -4828,7 +4857,7 @@ try Player.customRequest().fetchAll(db) // [Player]
- The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method.
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Structs/AnyFetchRequest.html): a type-erased request.
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Structs/AnyFetchRequest.html): a type-erased request.
## Joined Queries Support
@@ -5935,7 +5964,7 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan
### DatabaseRegion
**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**.
**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/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.
@@ -5945,7 +5974,7 @@ DatabaseRegion fuels, for example, [ValueObservation and DatabaseRegionObservati
For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table.
For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF).
For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF).
#### The DatabaseRegionConvertible Protocol
@@ -7042,7 +7071,7 @@ try snapshot2.read { db in
### DatabaseWriter and DatabaseReader Protocols
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only.
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only.
These protocols provide a unified API that let you write generic code that targets all concurrency modes. They fuel, for example:
@@ -7278,17 +7307,41 @@ try writer.asyncWriteWithoutTransaction { db in
FAQ
===
**[FAQ: Opening Connections](#faq-opening-connections)**
- [How do I create a database in my application?](#how-do-i-create-a-database-in-my-application)
- [How do I open a database stored as a resource of my application?](#how-do-i-open-a-database-stored-as-a-resource-of-my-application)
- [How do I close a database connection?](#how-do-i-close-a-database-connection)
**[FAQ: SQL](#faq-sql)**
- [How do I print a request as SQL?](#how-do-i-print-a-request-as-sql)
**[FAQ: General](#faq-general)**
- [How do I monitor the duration of database statements execution?](#how-do-i-monitor-the-duration-of-database-statements-execution)
- [What Are Experimental Features?](#what-are-experimental-features)
**[FAQ: Associations](#faq-associations)**
- [How do I filter records and only keep those that are associated to another record?](#how-do-i-filter-records-and-only-keep-those-that-are-associated-to-another-record)
- [How do I filter records and only keep those that are NOT associated to another record?](#how-do-i-filter-records-and-only-keep-those-that-are-not-associated-to-another-record)
- [How do I select only one column of an associated record?](#how-do-i-select-only-one-column-of-an-associated-record)
**[FAQ: Errors](#faq-errors)**
- [Generic parameter 'T' could not be inferred](#generic-parameter-t-could-not-be-inferred)
- [SQLite error 10 "disk I/O error", SQLite error 23 "not authorized"](#sqlite-error-10-disk-io-error-sqlite-error-23-not-authorized)
- [SQLite error 21 "wrong number of statement arguments" with LIKE queries](#sqlite-error-21-wrong-number-of-statement-arguments-with-like-queries)
- [What Are Experimental Features?](#what-are-experimental-features)
## FAQ: Opening Connections
- :arrow_up: [FAQ]
- [How do I create a database in my application?](#how-do-i-create-a-database-in-my-application)
- [How do I open a database stored as a resource of my application?](#how-do-i-open-a-database-stored-as-a-resource-of-my-application)
- [How do I close a database connection?](#how-do-i-close-a-database-connection)
### How do I create a database in my application?
This question assumes that your application has to create a new database from scratch. If your app has to open an existing database that is embedded inside your application as a resource, see [How do I open a database stored as a resource of my application?](#how-do-i-open-a-database-stored-as-a-resource-of-my-application) instead.
@@ -7337,6 +7390,11 @@ Database connections are managed by [database queues](#database-queues) and [poo
Database accesses that run in background threads postpone the closing of connections.
## FAQ: SQL
- :arrow_up: [FAQ]
- [How do I print a request as SQL?](#how-do-i-print-a-request-as-sql)
### How do I print a request as SQL?
When you want to debug a request that does not deliver the expected results, you may want to print the SQL that is actually executed.
@@ -7382,6 +7440,12 @@ db.trace { event in
> :point_up: **Note**: the generated SQL may change between GRDB releases, without notice: don't have your application rely on any specific SQL output.
## FAQ: General
- :arrow_up: [FAQ]
- [How do I monitor the duration of database statements execution?](#how-do-i-monitor-the-duration-of-database-statements-execution)
- [What Are Experimental Features?](#what-are-experimental-features)
### How do I monitor the duration of database statements execution?
Use the `trace(options:_:)` method, with the `.profile` option:
@@ -7408,6 +7472,146 @@ try dbQueue.read { db in
```
## FAQ: Associations
- :arrow_up: [FAQ]
- [How do I filter records and only keep those that are associated to another record?](#how-do-i-filter-records-and-only-keep-those-that-are-associated-to-another-record)
- [How do I filter records and only keep those that are NOT associated to another record?](#how-do-i-filter-records-and-only-keep-those-that-are-not-associated-to-another-record)
- [How do I select only one column of an associated record?](#how-do-i-select-only-one-column-of-an-associated-record)
### How do I filter records and only keep those that are associated to another record?
Let's say you have two record types, `Book` and `Author`, and you want to only fetch books that have an author, and discard anonymous books.
We start by defining the association between books and authors:
```swift
struct Book: TableRecord {
...
static let author = belongsTo(Author.self)
}
struct Author: TableRecord {
...
}
```
And then we can write our request and only fetch books that have an author, discarding anonymous ones:
```swift
let books: [Book] = try dbQueue.read { db in
// SELECT book.* FROM book
// JOIN author ON author.id = book.authorID
let request = Book.joining(required: Book.author)
return try request.fetchAll(db)
}
```
Note how this request does not use the `filter` method. Indeed, we don't have any condition to express on any column. Instead, we just need to "require that a book can be joined to its author".
See [How do I filter records and only keep those that are NOT associated to another record?](#how-do-i-filter-records-and-only-keep-those-that-are-not-associated-to-another-record) below for the opposite question.
### How do I filter records and only keep those that are NOT associated to another record?
Let's say you have two record types, `Book` and `Author`, and you want to only fetch anonymous books that do not have any author.
We start by defining the association between books and authors:
```swift
struct Book: TableRecord {
...
static let author = belongsTo(Author.self)
}
struct Author: TableRecord {
...
}
```
And then we can write our request and only fetch anonymous books that don't have any author:
```swift
let books: [Book] = try dbQueue.read { db in
// SELECT book.* FROM book
// LEFT JOIN author ON author.id = book.authorID
// WHERE author.id IS NULL
let authorAlias = TableAlias()
let request = Book
.joining(optional: Book.author.aliased(authorAlias))
.filter(authorAlias[Author.primaryKey] == nil)
return try request.fetchAll(db)
}
```
This request uses a TableAlias in order to be able to filter on the eventual associated author. We make sure that the `Author.primaryKey` is nil, which is another way to say it does not exist: the book has no author.
See [How do I filter records and only keep those that are associated to another record?](#how-do-i-filter-records-and-only-keep-those-that-are-associated-to-another-record) above for the opposite question.
### How do I select only one column of an associated record?
Let's say you have two record types, `Book` and `Author`, and you want to fetch all books with their author name, but not the full associated author records.
We start by defining the association between books and authors:
```swift
struct Book: Decodable, TableRecord {
...
static let author = belongsTo(Author.self)
}
struct Author: Decodable, TableRecord {
...
enum Columns {
static let name = Column(CodingKeys.name)
}
}
```
And then we can write our request and the ad-hoc record that decodes it:
```swift
struct BookInfo: Decodable, FetchableRecord {
var book: Book
var authorName: String? // nil when the book is anonymous
static func all() -> QueryInterfaceRequest<BookInfo> {
// SELECT book.*, author.name AS authorName
// FROM book
// LEFT JOIN author ON author.id = book.authorID
let authorAlias = TableAlias()
let authorName = authorAlias[Author.Columns.name].forKey(CodingKeys.authorName)
return Book
.annotated(with: authorName)
.joining(optional: Book.author.aliased(authorAlias))
.asRequest(of: BookInfo.self)
}
}
let bookInfos: [BookInfo] = try dbQueue.read { db in
BookInfo.all().fetchAll(db)
}
```
By using a TableAlias, you can refer to an author column from a request of books.
By defining the request as a static method of BookInfo, you have access to the private `CodingKeys.authorName`, and a compiler-checked SQL column name.
By using the `annotated(with:)` method, you append the author name to the top-level selection that can be decoded by the ad-hoc record.
By using the `joining()` method, you make sure no author column is selected, but the one declared in `annotated(with:)`.
By using `asRequest(of:)`, you enhance the type-safety of your request.
## FAQ: Errors
- :arrow_up: [FAQ]
- [Generic parameter 'T' could not be inferred](#generic-parameter-t-could-not-be-inferred)
- [SQLite error 10 "disk I/O error", SQLite error 23 "not authorized"](#sqlite-error-10-disk-io-error-sqlite-error-23-not-authorized)
- [SQLite error 21 "wrong number of statement arguments" with LIKE queries](#sqlite-error-21-wrong-number-of-statement-arguments-with-like-queries)
### Generic parameter 'T' could not be inferred
You may get this error when using the `read` and `write` methods of database queues and pools:
@@ -7595,3 +7799,4 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv
[Combine]: https://developer.apple.com/documentation/combine
[Demo Application]: Documentation/DemoApps/GRDBDemoiOS/README.md
[Sharing a Database]: Documentation/SharingADatabase.md
[FAQ]: #faq
+91
View File
@@ -0,0 +1,91 @@
#ifndef grdb_config_h
#define grdb_config_h
typedef void(*errorLogCallback)(void *pArg, int iErrCode, const char *zMsg);
/// Wrapper around sqlite3_config(SQLITE_CONFIG_LOG, ...) which is a variadic
/// function that can't be used from Swift.
static inline void registerErrorLogCallback(errorLogCallback callback) {
sqlite3_config(SQLITE_CONFIG_LOG, callback, 0);
}
#if SQLITE_VERSION_NUMBER >= 3029000
/// Wrapper around sqlite3_db_config() which is a variadic function that can't
/// be used from Swift.
static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) {
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 0, (void *)0);
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 0, (void *)0);
}
/// Wrapper around sqlite3_db_config() which is a variadic function that can't
/// be used from Swift.
static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) {
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 1, (void *)0);
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 1, (void *)0);
}
#else
static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) { }
static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) { }
#endif
/*
Snapshots
=========
We have a linker/C-interop difficulty here:
- Not all SQLite versions ship with the sqlite3_snapshot_get function.
- Not all iOS/macOS versions ship a <sqlite3.h> header that contains
the declaration for sqlite3_snapshot_get(), even when SQLite is
actually compiled with SQLITE_ENABLE_SNAPSHOT.
This makes it really difficult to deal with system SQLite, custom
SQLite builds, SQLCipher, and SPM.
To avoid those problems, we add grdb_snapshot_xxx shim functions in the
following header files:
- SQLiteCustom/grdb_config.h
- Sources/CSQLite/shim.h
- Support/grdb_config.h
*/
#ifdef SQLITE_ENABLE_SNAPSHOT
static inline int grdb_snapshot_get(
sqlite3 *db,
const char *zSchema,
sqlite3_snapshot **ppSnapshot)
{
return sqlite3_snapshot_get(db, zSchema, ppSnapshot);
}
static inline void grdb_snapshot_free(sqlite3_snapshot* ppSnapshot) {
sqlite3_snapshot_free(ppSnapshot);
}
static inline int grdb_snapshot_cmp(
sqlite3_snapshot *p1,
sqlite3_snapshot *p2)
{
return sqlite3_snapshot_cmp(p1, p2);
}
#else
static inline int grdb_snapshot_get(
sqlite3 *db,
const char *zSchema,
sqlite3_snapshot **ppSnapshot)
{
return SQLITE_MISUSE;
}
static inline void grdb_snapshot_free(sqlite3_snapshot* ppSnapshot) {
}
static inline int grdb_snapshot_cmp(
sqlite3_snapshot *p1,
sqlite3_snapshot *p2)
{
return 0;
}
#endif /* SQLITE_ENABLE_SNAPSHOT */
#endif /* grdb_config_h */
+79
View File
@@ -26,3 +26,82 @@ static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) {
static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) { }
static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) { }
#endif
/*
Snapshots
=========
We have a linker/C-interop difficulty here:
- Not all SQLite versions ship with the sqlite3_snapshot_get function.
- Not all iOS/macOS versions ship a <sqlite3.h> header that contains
the declaration for sqlite3_snapshot_get(), even when SQLite is
actually compiled with SQLITE_ENABLE_SNAPSHOT.
This makes it really difficult to deal with system SQLite, custom
SQLite builds, SQLCipher, and SPM.
To avoid those problems, we add grdb_snapshot_xxx shim functions in the
following header files:
- SQLiteCustom/grdb_config.h
- Sources/CSQLite/shim.h
- Support/grdb_config.h
*/
#ifdef SQLITE_ENABLE_SNAPSHOT
static inline int grdb_snapshot_get(
sqlite3 *db,
const char *zSchema,
sqlite3_snapshot **ppSnapshot)
{
return sqlite3_snapshot_get(db, zSchema, ppSnapshot);
}
static inline void grdb_snapshot_free(sqlite3_snapshot* ppSnapshot) {
sqlite3_snapshot_free(ppSnapshot);
}
static inline int grdb_snapshot_cmp(
sqlite3_snapshot *p1,
sqlite3_snapshot *p2)
{
return sqlite3_snapshot_cmp(p1, p2);
}
#else
// Assume snapshot apis *are* defined, but not exposed.
typedef struct sqlite3_snapshot {
unsigned char hidden[48];
} sqlite3_snapshot;
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
sqlite3 *db,
const char *zSchema,
sqlite3_snapshot **ppSnapshot
);
SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
sqlite3_snapshot *p1,
sqlite3_snapshot *p2
);
static inline int grdb_snapshot_get(
sqlite3 *db,
const char *zSchema,
sqlite3_snapshot **ppSnapshot)
{
return sqlite3_snapshot_get(db, zSchema, ppSnapshot);
}
static inline void grdb_snapshot_free(sqlite3_snapshot* ppSnapshot) {
sqlite3_snapshot_free(ppSnapshot);
}
static inline int grdb_snapshot_cmp(
sqlite3_snapshot *p1,
sqlite3_snapshot *p2)
{
return sqlite3_snapshot_cmp(p1, p2);
}
#endif /* SQLITE_ENABLE_SNAPSHOT */
-4
View File
@@ -2,7 +2,3 @@ IPHONEOS_DEPLOYMENT_TARGET = 10.0
MACOSX_DEPLOYMENT_TARGET = 10.10
TVOS_DEPLOYMENT_TARGET = 9.0
WATCHOS_DEPLOYMENT_TARGET = 2.0
//// Compile with all opt-in APIs
//GCC_PREPROCESSOR_DEFINITIONS = $(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1
//OTHER_SWIFT_FLAGS = $(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>5.0.0-beta.4</string>
<string>5.0.0-beta.5</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+93
View File
@@ -0,0 +1,93 @@
#ifndef grdb_config_h
#define grdb_config_h
#include <SQLCipher/sqlite3.h>
typedef void(*errorLogCallback)(void *pArg, int iErrCode, const char *zMsg);
/// Wrapper around sqlite3_config(SQLITE_CONFIG_LOG, ...) which is a variadic
/// function that can't be used from Swift.
static inline void registerErrorLogCallback(errorLogCallback callback) {
sqlite3_config(SQLITE_CONFIG_LOG, callback, 0);
}
#if SQLITE_VERSION_NUMBER >= 3029000
/// Wrapper around sqlite3_db_config() which is a variadic function that can't
/// be used from Swift.
static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) {
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 0, (void *)0);
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 0, (void *)0);
}
/// Wrapper around sqlite3_db_config() which is a variadic function that can't
/// be used from Swift.
static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) {
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 1, (void *)0);
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 1, (void *)0);
}
#else
static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) { }
static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) { }
#endif
/*
Snapshots
=========
We have a linker/C-interop difficulty here:
- Not all SQLite versions ship with the sqlite3_snapshot_get function.
- Not all iOS/macOS versions ship a <sqlite3.h> header that contains
the declaration for sqlite3_snapshot_get(), even when SQLite is
actually compiled with SQLITE_ENABLE_SNAPSHOT.
This makes it really difficult to deal with system SQLite, custom
SQLite builds, SQLCipher, and SPM.
To avoid those problems, we add grdb_snapshot_xxx shim functions in the
following header files:
- SQLiteCustom/grdb_config.h
- Sources/CSQLite/shim.h
- Support/grdb_config.h
*/
#ifdef SQLITE_ENABLE_SNAPSHOT
static inline int grdb_snapshot_get(
sqlite3 *db,
const char *zSchema,
sqlite3_snapshot **ppSnapshot)
{
return sqlite3_snapshot_get(db, zSchema, ppSnapshot);
}
static inline void grdb_snapshot_free(sqlite3_snapshot* ppSnapshot) {
sqlite3_snapshot_free(ppSnapshot);
}
static inline int grdb_snapshot_cmp(
sqlite3_snapshot *p1,
sqlite3_snapshot *p2)
{
return sqlite3_snapshot_cmp(p1, p2);
}
#else
static inline int grdb_snapshot_get(
sqlite3 *db,
const char *zSchema,
sqlite3_snapshot **ppSnapshot)
{
return SQLITE_MISUSE;
}
static inline void grdb_snapshot_free(sqlite3_snapshot* ppSnapshot) {
}
static inline int grdb_snapshot_cmp(
sqlite3_snapshot *p1,
sqlite3_snapshot *p2)
{
return 0;
}
#endif /* SQLITE_ENABLE_SNAPSHOT */
#endif /* grdb_config_h */
+79 -12
View File
@@ -1,18 +1,7 @@
#ifndef grdb_config_h
#define grdb_config_h
#if defined(COCOAPODS)
#if defined(GRDBCIPHER)
#include <SQLCipher/sqlite3.h>
#else
#include <sqlite3.h>
#endif
#else
// Assume custom SQLite build otherwize
#if !defined(SQLITE_VERSION_NUMBER)
#include <sqlite3.h>
#endif
#endif
#include <sqlite3.h>
typedef void(*errorLogCallback)(void *pArg, int iErrCode, const char *zMsg);
@@ -62,4 +51,82 @@ SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);
SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
#endif /* GRDB_SQLITE_ENABLE_PREUPDATE_HOOK */
/*
Snapshots
=========
We have a linker/C-interop difficulty here:
- Not all SQLite versions ship with the sqlite3_snapshot_get function.
- Not all iOS/macOS versions ship a <sqlite3.h> header that contains
the declaration for sqlite3_snapshot_get(), even when SQLite is
actually compiled with SQLITE_ENABLE_SNAPSHOT.
This makes it really difficult to deal with system SQLite, custom
SQLite builds, SQLCipher, and SPM.
To avoid those problems, we add grdb_snapshot_xxx shim functions in the
following header files:
- SQLiteCustom/grdb_config.h
- Sources/CSQLite/shim.h
- Support/grdb_config.h
*/
#ifdef SQLITE_ENABLE_SNAPSHOT
static inline int grdb_snapshot_get(
sqlite3 *db,
const char *zSchema,
sqlite3_snapshot **ppSnapshot)
{
return sqlite3_snapshot_get(db, zSchema, ppSnapshot);
}
static inline void grdb_snapshot_free(sqlite3_snapshot* ppSnapshot) {
sqlite3_snapshot_free(ppSnapshot);
}
static inline int grdb_snapshot_cmp(
sqlite3_snapshot *p1,
sqlite3_snapshot *p2)
{
return sqlite3_snapshot_cmp(p1, p2);
}
#else
// Assume snapshot apis *are* defined, but not exposed.
typedef struct sqlite3_snapshot {
unsigned char hidden[48];
} sqlite3_snapshot;
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
sqlite3 *db,
const char *zSchema,
sqlite3_snapshot **ppSnapshot
);
SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
sqlite3_snapshot *p1,
sqlite3_snapshot *p2
);
static inline int grdb_snapshot_get(
sqlite3 *db,
const char *zSchema,
sqlite3_snapshot **ppSnapshot)
{
return sqlite3_snapshot_get(db, zSchema, ppSnapshot);
}
static inline void grdb_snapshot_free(sqlite3_snapshot* ppSnapshot) {
sqlite3_snapshot_free(ppSnapshot);
}
static inline int grdb_snapshot_cmp(
sqlite3_snapshot *p1,
sqlite3_snapshot *p2)
{
return sqlite3_snapshot_cmp(p1, p2);
}
#endif /* SQLITE_ENABLE_SNAPSHOT */
#endif /* grdb_config_h */
+2
View File
@@ -16,6 +16,8 @@
## Features
- [ ] Handle SQLITE_LIMIT_VARIABLE_NUMBER in deleteAll(_:keys:) and similar APIs. https://www.sqlite.org/limits.html
- [ ] Concurrent migrator / or not
- [ ] Subqueries: request.isEmpty / request.exists
- [ ] Subqueries: request.count
- [ ] Extract one row from a hasMany association (the one with the maximum date, the one with a flag set, etc.) https://stackoverflow.com/questions/43188771/sqlite-join-query-most-recent-posts-by-each-user (failed PR: https://github.com/groue/GRDB.swift/pull/767)
@@ -1127,4 +1127,64 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
}
}
}
// Test for the "How do I filter records and only keep those that are
// associated to another record?" FAQ
func testRecordsFilteredByExistingAssociatedRecord() throws {
struct Book: TableRecord {
static let author = belongsTo(Author.self)
}
struct Author: TableRecord {
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "author") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("authorID", .integer).references("author")
}
let request = Book.joining(required: Book.author)
try assertEqualSQL(db, request, """
SELECT "book".* FROM "book" \
JOIN "author" ON "author"."id" = "book"."authorID"
""")
}
}
// Test for the "How do I filter records and only keep those that are NOT
// associated to another record?" FAQ
func testRecordsFilteredByNonExistingAssociatedRecord() throws {
struct Book: TableRecord {
static let author = belongsTo(Author.self)
}
struct Author: TableRecord {
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "author") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("authorID", .integer).references("author")
}
let authorAlias = TableAlias()
let request = Book
.joining(optional: Book.author.aliased(authorAlias))
.filter(authorAlias[Author.primaryKey] == nil)
try assertEqualSQL(db, request, """
SELECT "book".* FROM "book" \
LEFT JOIN "author" ON "author"."id" = "book"."authorID" \
WHERE "author"."id" IS NULL
""")
}
}
}
@@ -442,8 +442,8 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
defer { s2.signal() }
try dbPool.writeWithoutTransaction { db in
try db.execute(sql: "DELETE FROM items")
try db.checkpoint()
}
try dbPool.checkpoint()
} catch {
XCTFail("error: \(error)")
}
@@ -538,8 +538,8 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
defer { s2.signal() }
try dbPool.writeWithoutTransaction { db in
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
try db.checkpoint()
}
try dbPool.checkpoint()
} catch {
XCTFail("error: \(error)")
}
@@ -759,8 +759,8 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
defer { s2.signal() }
try dbPool.writeWithoutTransaction { db in
try db.execute(sql: "DELETE FROM items")
try db.checkpoint()
}
try dbPool.checkpoint()
} catch {
XCTFail("error: \(error)")
}
@@ -803,8 +803,8 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
defer { s2.signal() }
try dbPool.writeWithoutTransaction { db in
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
try db.checkpoint()
}
try dbPool.checkpoint()
} catch {
XCTFail("error: \(error)")
}
+4 -4
View File
@@ -270,7 +270,7 @@ class DatabaseSnapshotTests: GRDBTestCase {
let counter = try Counter(dbPool: dbPool)
try dbPool.write(counter.increment)
let snapshot = try dbPool.makeSnapshot()
try? dbPool.checkpoint(.passive) // ignore if error or not, that's not the point
try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.passive) } // ignore if error or not, that's not the point
try XCTAssertEqual(snapshot.read(counter.value), 1)
try dbPool.write(counter.increment)
try XCTAssertEqual(snapshot.read(counter.value), 1)
@@ -281,7 +281,7 @@ class DatabaseSnapshotTests: GRDBTestCase {
let counter = try Counter(dbPool: dbPool)
try dbPool.write(counter.increment)
let snapshot = try dbPool.makeSnapshot()
try? dbPool.checkpoint(.full) // ignore if error or not, that's not the point
try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.full) } // ignore if error or not, that's not the point
try XCTAssertEqual(snapshot.read(counter.value), 1)
try dbPool.write(counter.increment)
try XCTAssertEqual(snapshot.read(counter.value), 1)
@@ -292,7 +292,7 @@ class DatabaseSnapshotTests: GRDBTestCase {
let counter = try Counter(dbPool: dbPool)
try dbPool.write(counter.increment)
let snapshot = try dbPool.makeSnapshot()
try? dbPool.checkpoint(.restart) // ignore if error or not, that's not the point
try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.restart) } // ignore if error or not, that's not the point
try XCTAssertEqual(snapshot.read(counter.value), 1)
try dbPool.write(counter.increment)
try XCTAssertEqual(snapshot.read(counter.value), 1)
@@ -303,7 +303,7 @@ class DatabaseSnapshotTests: GRDBTestCase {
let counter = try Counter(dbPool: dbPool)
try dbPool.write(counter.increment)
let snapshot = try dbPool.makeSnapshot()
try? dbPool.checkpoint(.truncate) // ignore if error or not, that's not the point
try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.truncate) } // ignore if error or not, that's not the point
try XCTAssertEqual(snapshot.read(counter.value), 1)
try dbPool.write(counter.increment)
try XCTAssertEqual(snapshot.read(counter.value), 1)
+37
View File
@@ -345,4 +345,41 @@ class DatabaseTests : GRDBTestCase {
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
}
func testCheckpoint() throws {
do {
// Not a WAL database
let dbQueue = try makeDatabaseQueue()
let result = try dbQueue.inDatabase {
try $0.checkpoint()
}
XCTAssertEqual(result.walFrameCount, -1)
XCTAssertEqual(result.checkpointedFrameCount, -1)
}
do {
// WAL database
let dbPool = try makeDatabasePool()
let result = try dbPool.writeWithoutTransaction {
try $0.checkpoint()
}
XCTAssertGreaterThanOrEqual(result.walFrameCount, 0)
XCTAssertGreaterThanOrEqual(result.checkpointedFrameCount, 0)
}
do {
// WAL database + TRUNCATE
let dbPool = try makeDatabasePool()
let result = try dbPool.writeWithoutTransaction {
try $0.checkpoint(.truncate)
}
XCTAssertEqual(result.walFrameCount, 0)
XCTAssertEqual(result.checkpointedFrameCount, 0)
}
}
func testMaximumStatementArgumentCount() throws {
let dbQueue = try makeDatabaseQueue()
let count = dbQueue.read { $0.maximumStatementArgumentCount }
// 999 should be safe: https://www.sqlite.org/limits.html
XCTAssertGreaterThanOrEqual(count, 999)
}
}
@@ -58,7 +58,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testInsertWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -70,7 +70,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testInsertWithNotNilPrimaryKeyThatMatchesARowThrowsDatabaseError() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -84,7 +84,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
}
}
}
func testInsertAfterDeleteInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -97,10 +97,10 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
// MARK: - Update
func testUpdateWithNotNilPrimaryKeyThatDoesNotMatchAnyRowThrowsRecordNotFound() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -116,7 +116,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
}
}
}
func testUpdateWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -128,7 +128,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testUpdateAfterDeleteThrowsRecordNotFound() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -145,10 +145,10 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
}
}
}
// MARK: - Save
func testSaveWithNilPrimaryKeyInsertsARowAndSetsPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -161,7 +161,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testSaveWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -173,7 +173,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testSaveWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -185,7 +185,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testSaveAfterDeleteInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -198,10 +198,10 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
// MARK: - Delete
func testDeleteWithNotNilPrimaryKeyThatDoesNotMatchAnyRowDoesNothing() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -211,7 +211,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
XCTAssertFalse(deleted)
}
}
func testDeleteWithNotNilPrimaryKeyThatMatchesARowDeletesThatRow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -224,7 +224,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
XCTAssertTrue(row == nil)
}
}
func testDeleteAfterDeleteDoesNothing() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -236,8 +236,8 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
XCTAssertFalse(deleted)
}
}
// MARK: - Fetch With Key
func testFetchCursorWithKeys() throws {
@@ -268,7 +268,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
}
}
}
func testFetchAllWithKeys() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -295,7 +295,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
}
}
}
func testFetchOneWithKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -307,7 +307,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalRowIDs\" WHERE \"id\" = \(record.id!)")
}
}
// MARK: - Fetch With Key Request
@@ -390,7 +390,18 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
}
}
// MARK: - Select Primary Key
func testSelectPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request: QueryInterfaceRequest<Int64> = MinimalRowID.selectPrimaryKey()
try assertEqualSQL(db, request, "SELECT \"id\" FROM \"minimalRowIDs\"")
}
}
// MARK: - Fetch With Primary Key
func testFetchCursorWithPrimaryKeys() throws {
@@ -416,7 +427,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
}
}
}
func testFetchAllWithPrimaryKeys() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -439,7 +450,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
}
}
}
func testFetchOneWithPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -459,7 +470,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
}
}
}
// MARK: - Fetch With Primary Key Request
@@ -529,10 +540,10 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
}
}
}
// MARK: - Exists
func testExistsWithNotNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -541,7 +552,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
XCTAssertFalse(try record.exists(db))
}
}
func testExistsWithNotNilPrimaryKeyThatMatchesARowReturnsTrue() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -550,7 +561,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
XCTAssertTrue(try record.exists(db))
}
}
func testExistsAfterDeleteReturnsTrue() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -55,7 +55,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
}
}
}
func testInsertWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -67,7 +67,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testInsertWithNotNilPrimaryKeyThatMatchesARowThrowsDatabaseError() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -82,7 +82,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
}
}
}
func testInsertAfterDeleteInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -96,10 +96,10 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
// MARK: - Update
func testUpdateWithNotNilPrimaryKeyThatDoesNotMatchAnyRowThrowsRecordNotFound() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -115,7 +115,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
}
}
}
func testUpdateWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -128,7 +128,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testUpdateAfterDeleteThrowsRecordNotFound() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -146,10 +146,10 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
}
}
}
// MARK: - Save
func testSaveWithNilPrimaryKeyThrowsDatabaseError() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -163,7 +163,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
}
}
}
func testSaveWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -175,7 +175,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testSaveWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -188,7 +188,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testSaveAfterDeleteInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -202,10 +202,10 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
// MARK: - Delete
func testDeleteWithNotNilPrimaryKeyThatDoesNotMatchAnyRowDoesNothing() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -215,7 +215,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
XCTAssertFalse(deleted)
}
}
func testDeleteWithNotNilPrimaryKeyThatMatchesARowDeletesThatRow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -229,7 +229,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
XCTAssertTrue(row == nil)
}
}
func testDeleteAfterDeleteDoesNothing() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -242,8 +242,8 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
XCTAssertFalse(deleted)
}
}
// MARK: - Fetch With Key
func testFetchCursorWithKeys() throws {
@@ -276,7 +276,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
}
}
}
func testFetchAllWithKeys() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -305,7 +305,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
}
}
}
func testFetchOneWithKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -318,7 +318,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"UUID\" = '\(record.UUID!)'")
}
}
// MARK: - Fetch With Key Request
@@ -407,6 +407,17 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
}
// MARK: - Select Primary Key
func testSelectPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request: QueryInterfaceRequest<UUID> = MinimalSingle.selectPrimaryKey()
try assertEqualSQL(db, request, "SELECT \"UUID\" FROM \"minimalSingles\"")
}
}
// MARK: - Fetch With Primary Key
func testFetchCursorWithPrimaryKeys() throws {
@@ -434,7 +445,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
}
}
}
func testFetchAllWithPrimaryKeys() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -459,7 +470,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
}
}
}
func testFetchOneWithPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -480,7 +491,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
}
}
}
// MARK: - Fetch With Primary Key Request
@@ -555,10 +566,10 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
}
}
}
// MARK: - Exists
func testExistsWithNotNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -567,7 +578,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
XCTAssertFalse(try record.exists(db))
}
}
func testExistsWithNotNilPrimaryKeyThatMatchesARowReturnsTrue() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -577,7 +588,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
XCTAssertTrue(try record.exists(db))
}
}
func testExistsAfterDeleteReturnsTrue() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -87,7 +87,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testRollbackedInsertWithNilPrimaryKeyDoesNotResetPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
let record = Person(name: "Arthur")
@@ -103,7 +103,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
// This is debatable, actually.
XCTAssertTrue(record.id != nil)
}
func testInsertWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -114,7 +114,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testRollbackedInsertWithNotNilPrimaryKeyDoeNotResetPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
let record = Person(id: 123456, name: "Arthur")
@@ -125,7 +125,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
}
XCTAssertEqual(record.id!, 123456)
}
func testInsertWithNotNilPrimaryKeyThatMatchesARowThrowsDatabaseError() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -139,7 +139,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
}
}
}
func testInsertAfterDeleteInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -152,10 +152,10 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
// MARK: - Update
func testUpdateWithNilPrimaryKeyThrowsRecordNotFound() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -170,7 +170,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
}
}
}
func testUpdateWithNotNilPrimaryKeyThatDoesNotMatchAnyRowThrowsRecordNotFound() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -185,7 +185,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
}
}
}
func testUpdateWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -198,7 +198,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testUpdateAfterDeleteThrowsRecordNotFound() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -215,10 +215,10 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
}
}
}
// MARK: - Save
func testSaveWithNilPrimaryKeyInsertsARowAndSetsPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -231,7 +231,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testSaveWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -242,8 +242,8 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testSaveWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -257,7 +257,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testSaveAfterDeleteInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -270,10 +270,10 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
// MARK: - Delete
func testDeleteWithNilPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -282,7 +282,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
XCTAssertFalse(deleted)
}
}
func testDeleteWithNotNilPrimaryKeyThatDoesNotMatchAnyRowDoesNothing() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -291,7 +291,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
XCTAssertFalse(deleted)
}
}
func testDeleteWithNotNilPrimaryKeyThatMatchesARowDeletesThatRow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -304,7 +304,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
XCTAssertTrue(row == nil)
}
}
func testDeleteAfterDeleteDoesNothing() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -316,8 +316,8 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
XCTAssertFalse(deleted)
}
}
// MARK: - Fetch With Key
func testFetchCursorWithKeys() throws {
@@ -348,7 +348,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
}
}
}
func testFetchAllWithKeys() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -375,7 +375,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
}
}
}
func testFetchOneWithKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -390,7 +390,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
XCTAssertEqual(lastSQLQuery, "SELECT *, \"rowid\" FROM \"persons\" WHERE \"rowid\" = \(record.id!)")
}
}
// MARK: - Fetch With Key Request
@@ -477,6 +477,17 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
}
// MARK: - Select Primary Key
func testSelectPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request: QueryInterfaceRequest<Int64> = Person.selectPrimaryKey()
try assertEqualSQL(db, request, "SELECT \"rowid\" FROM \"persons\"")
}
}
// MARK: - Fetch With Primary Key
func testFetchCursorWithPrimaryKeys() throws {
@@ -502,7 +513,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
}
}
}
func testFetchAllWithPrimaryKeys() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -525,7 +536,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
}
}
}
func testFetchOneWithPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -548,7 +559,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
}
}
}
// MARK: - Fetch With Primary Key Request
@@ -621,10 +632,10 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
}
}
}
// MARK: - Exists
func testExistsWithNilPrimaryKeyReturnsFalse() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -632,7 +643,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
XCTAssertFalse(try record.exists(db))
}
}
func testExistsWithNotNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -640,7 +651,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
XCTAssertFalse(try record.exists(db))
}
}
func testExistsWithNotNilPrimaryKeyThatMatchesARowReturnsTrue() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -649,7 +660,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
XCTAssertTrue(try record.exists(db))
}
}
func testExistsAfterDeleteReturnsTrue() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -659,8 +670,8 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
XCTAssertFalse(try record.exists(db))
}
}
// MARK: - RowID
func testRowIdIsSelectedByDefault() throws {
@@ -690,10 +701,10 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
XCTAssertTrue(try Person.limit(1).fetchOne(db)!.id != nil)
}
}
// MARK: - FetchedRecordsController
func testFetchedRecordsController() throws {
let dbQueue = try makeDatabaseQueue()
let person = Person(name: "Arthur")
@@ -69,7 +69,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
}
}
}
func testInsertWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -80,7 +80,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testInsertWithNotNilPrimaryKeyThatMatchesARowThrowsDatabaseError() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -94,7 +94,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
}
}
}
func testInsertAfterDeleteInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -107,10 +107,10 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
// MARK: - Update
func testUpdateWithNilPrimaryKeyThrowsRecordNotFound() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -125,7 +125,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
}
}
}
func testUpdateWithNotNilPrimaryKeyThatDoesNotMatchAnyRowThrowsRecordNotFound() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -140,7 +140,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
}
}
}
func testUpdateWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -153,7 +153,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testUpdateAfterDeleteThrowsRecordNotFound() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -170,10 +170,10 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
}
}
}
// MARK: - Save
func testSaveWithNilPrimaryKeyThrowsDatabaseError() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -187,7 +187,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
}
}
}
func testSaveWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -198,7 +198,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testSaveWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -212,7 +212,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testSaveAfterDeleteInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -225,10 +225,10 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
// MARK: - Delete
func testDeleteWithNilPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -237,7 +237,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
XCTAssertFalse(deleted)
}
}
func testDeleteWithNotNilPrimaryKeyThatDoesNotMatchAnyRowDoesNothing() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -246,7 +246,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
XCTAssertFalse(deleted)
}
}
func testDeleteWithNotNilPrimaryKeyThatMatchesARowDeletesThatRow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -259,7 +259,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
XCTAssertTrue(row == nil)
}
}
func testDeleteAfterDeleteDoesNothing() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -271,8 +271,8 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
XCTAssertFalse(deleted)
}
}
// MARK: - Fetch With Key
func testFetchCursorWithKeys() throws {
@@ -303,7 +303,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
}
}
}
func testFetchAllWithKeys() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -330,7 +330,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
}
}
}
func testFetchOneWithKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -344,7 +344,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"citizenships\" WHERE (\"personName\" = '\(record.personName!)') AND (\"countryName\" = '\(record.countryName!)')")
}
}
// MARK: - Fetch With Key Request
@@ -403,7 +403,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
}
}
}
func testFetchOneWithKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -430,8 +430,20 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
}
// MARK: - Select Primary Key
func testSelectPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request: QueryInterfaceRequest<Int64> = Citizenship.selectPrimaryKey()
// May change in a future release, when we support SQLite row values.
try assertEqualSQL(db, request, "SELECT \"rowid\" FROM \"citizenships\"")
}
}
// MARK: - Exists
func testExistsWithNilPrimaryKeyReturnsFalse() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -439,7 +451,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
XCTAssertFalse(try record.exists(db))
}
}
func testExistsWithNotNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -447,7 +459,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
XCTAssertFalse(try record.exists(db))
}
}
func testExistsWithNotNilPrimaryKeyThatMatchesARowReturnsTrue() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -456,7 +468,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
XCTAssertTrue(try record.exists(db))
}
}
func testExistsAfterDeleteReturnsTrue() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -67,10 +67,10 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase {
XCTAssertEqual(names, ["Table", "Table"])
}
}
// MARK: - Save
func testSaveInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -82,8 +82,8 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase {
XCTAssertEqual(names, ["Table", "Table"])
}
}
// MARK: - Fetch With Key
func testFetchOneWithKey() throws {
@@ -97,7 +97,7 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase {
XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"items\" WHERE \"email\" = 'item@example.com'")
}
}
// MARK: - Fetch With Key Request
@@ -125,6 +125,17 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase {
}
// MARK: - Select Primary Key
func testSelectPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request: QueryInterfaceRequest<Int64> = Item.selectPrimaryKey()
try assertEqualSQL(db, request, "SELECT \"rowid\" FROM \"items\"")
}
}
// MARK: - Fetch With Primary Key
func testFetchCursorWithPrimaryKeys() throws {
@@ -154,7 +165,7 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase {
}
}
}
func testFetchAllWithPrimaryKeys() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -181,7 +192,7 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase {
}
}
}
func testFetchOneWithPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -202,7 +213,7 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase {
}
}
}
// MARK: - Fetch With Primary Key Request
@@ -84,7 +84,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testRollbackedInsertWithNilPrimaryKeyDoesNotResetPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
let record = Person(name: "Arthur")
@@ -100,7 +100,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
// This is debatable, actually.
XCTAssertTrue(record.id != nil)
}
func testInsertWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -111,7 +111,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testRollbackedInsertWithNotNilPrimaryKeyDoeNotResetPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
let record = Person(id: 123456, name: "Arthur")
@@ -122,7 +122,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
}
XCTAssertEqual(record.id!, 123456)
}
func testInsertWithNotNilPrimaryKeyThatMatchesARowThrowsDatabaseError() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -136,7 +136,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
}
}
}
func testInsertAfterDeleteInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -149,10 +149,10 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
// MARK: - Update
func testUpdateWithNilPrimaryKeyThrowsRecordNotFound() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -182,7 +182,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
}
}
}
func testUpdateWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -195,7 +195,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testUpdateAfterDeleteThrowsRecordNotFound() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -212,10 +212,10 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
}
}
}
// MARK: - Save
func testSaveWithNilPrimaryKeyInsertsARowAndSetsPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -228,7 +228,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testSaveWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -239,7 +239,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testSaveWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -253,7 +253,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testSaveAfterDeleteInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -266,10 +266,10 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
// MARK: - Delete
func testDeleteWithNilPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -278,7 +278,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
XCTAssertFalse(deleted)
}
}
func testDeleteWithNotNilPrimaryKeyThatDoesNotMatchAnyRowDoesNothing() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -287,7 +287,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
XCTAssertFalse(deleted)
}
}
func testDeleteWithNotNilPrimaryKeyThatMatchesARowDeletesThatRow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -300,7 +300,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
XCTAssertTrue(row == nil)
}
}
func testDeleteAfterDeleteDoesNothing() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -312,8 +312,8 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
XCTAssertFalse(deleted)
}
}
// MARK: - Fetch With Key
func testFetchCursorWithKeys() throws {
@@ -344,7 +344,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
}
}
}
func testFetchAllWithKeys() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -371,7 +371,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
}
}
}
func testFetchOneWithKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -386,7 +386,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"persons\" WHERE \"id\" = \(record.id!)")
}
}
// MARK: - Fetch With Key Request
@@ -473,6 +473,17 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
}
// MARK: - Select Primary Key
func testSelectPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request: QueryInterfaceRequest<Int64> = Person.selectPrimaryKey()
try assertEqualSQL(db, request, "SELECT \"id\" FROM \"persons\"")
}
}
// MARK: - Fetch With Primary Key
func testFetchCursorWithPrimaryKeys() throws {
@@ -498,7 +509,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
}
}
}
func testFetchAllWithPrimaryKeys() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -521,7 +532,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
}
}
}
func testFetchOneWithPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -544,7 +555,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
}
}
}
// MARK: - Fetch With Primary Key Request
@@ -617,10 +628,10 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
}
}
}
// MARK: - Exists
func testExistsWithNilPrimaryKeyReturnsFalse() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -628,7 +639,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
XCTAssertFalse(try record.exists(db))
}
}
func testExistsWithNotNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -636,7 +647,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
XCTAssertFalse(try record.exists(db))
}
}
func testExistsWithNotNilPrimaryKeyThatMatchesARowReturnsTrue() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -645,7 +656,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
XCTAssertTrue(try record.exists(db))
}
}
func testExistsAfterDeleteReturnsTrue() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -62,7 +62,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
}
}
}
func testInsertWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -73,7 +73,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testInsertWithNotNilPrimaryKeyThatMatchesARowThrowsDatabaseError() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -87,7 +87,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
}
}
}
func testInsertAfterDeleteInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -100,10 +100,10 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
// MARK: - Update
func testUpdateWithNilPrimaryKeyThrowsRecordNotFound() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -118,7 +118,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
}
}
}
func testUpdateWithNotNilPrimaryKeyThatDoesNotMatchAnyRowThrowsRecordNotFound() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -133,7 +133,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
}
}
}
func testUpdateWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -146,7 +146,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testUpdateAfterDeleteThrowsRecordNotFound() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -163,10 +163,10 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
}
}
}
// MARK: - Save
func testSaveWithNilPrimaryKeyThrowsDatabaseError() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -180,7 +180,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
}
}
}
func testSaveWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -191,7 +191,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testSaveWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -205,7 +205,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testSaveAfterDeleteInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -218,10 +218,10 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
// MARK: - Delete
func testDeleteWithNilPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -230,7 +230,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
XCTAssertFalse(deleted)
}
}
func testDeleteWithNotNilPrimaryKeyThatDoesNotMatchAnyRowDoesNothing() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -239,7 +239,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
XCTAssertFalse(deleted)
}
}
func testDeleteWithNotNilPrimaryKeyThatMatchesARowDeletesThatRow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -252,7 +252,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
XCTAssertTrue(row == nil)
}
}
func testDeleteAfterDeleteDoesNothing() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -264,8 +264,8 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
XCTAssertFalse(deleted)
}
}
// MARK: - Fetch With Key
func testFetchCursorWithKeys() throws {
@@ -296,7 +296,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
}
}
}
func testFetchAllWithKeys() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -323,7 +323,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
}
}
}
func testFetchOneWithKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -336,7 +336,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"pets\" WHERE \"UUID\" = '\(record.UUID!)'")
}
}
// MARK: - Fetch With Key Request
@@ -421,6 +421,17 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
}
// MARK: - Select Primary Key
func testSelectPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request: QueryInterfaceRequest<UUID> = Pet.selectPrimaryKey()
try assertEqualSQL(db, request, "SELECT \"UUID\" FROM \"pets\"")
}
}
// MARK: - Fetch With Primary Key
func testFetchCursorWithPrimaryKeys() throws {
@@ -446,7 +457,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
}
}
}
func testFetchAllWithPrimaryKeys() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -469,7 +480,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
}
}
}
func testFetchOneWithPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -490,7 +501,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
}
}
}
// MARK: - Fetch With Primary Key Request
@@ -561,10 +572,10 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
}
}
}
// MARK: - Exists
func testExistsWithNilPrimaryKeyReturnsFalse() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -572,7 +583,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
XCTAssertFalse(try record.exists(db))
}
}
func testExistsWithNotNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -580,7 +591,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
XCTAssertFalse(try record.exists(db))
}
}
func testExistsWithNotNilPrimaryKeyThatMatchesARowReturnsTrue() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -589,7 +600,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
XCTAssertTrue(try record.exists(db))
}
}
func testExistsAfterDeleteReturnsTrue() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -61,7 +61,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
}
}
}
func testInsertWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -74,7 +74,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testInsertWithNotNilPrimaryKeyThatMatchesARowReplacesARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -89,7 +89,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testInsertAfterDeleteInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -103,10 +103,10 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
// MARK: - Update
func testUpdateWithNotNilPrimaryKeyThatDoesNotMatchAnyRowThrowsRecordNotFound() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -122,7 +122,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
}
}
}
func testUpdateWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -135,7 +135,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testUpdateAfterDeleteThrowsRecordNotFound() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -153,10 +153,10 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
}
}
}
// MARK: - Save
func testSaveWithNilPrimaryKeyThrowsDatabaseError() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -170,7 +170,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
}
}
}
func testSaveWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -182,7 +182,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testSaveWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -195,7 +195,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
func testSaveAfterDeleteInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -209,10 +209,10 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
assert(record, isEncodedIn: row)
}
}
// MARK: - Delete
func testDeleteWithNotNilPrimaryKeyThatDoesNotMatchAnyRowDoesNothing() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -222,7 +222,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
XCTAssertFalse(deleted)
}
}
func testDeleteWithNotNilPrimaryKeyThatMatchesARowDeletesThatRow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -236,7 +236,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
XCTAssertTrue(row == nil)
}
}
func testDeleteAfterDeleteDoesNothing() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -249,8 +249,8 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
XCTAssertFalse(deleted)
}
}
// MARK: - Fetch With Key
func testFetchCursorWithKeys() throws {
@@ -283,7 +283,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
}
}
}
func testFetchAllWithKeys() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -312,7 +312,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
}
}
}
func testFetchOneWithKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -325,7 +325,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"emails\" WHERE \"email\" = '\(record.email!)'")
}
}
// MARK: - Fetch With Key Request
@@ -388,7 +388,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
}
}
}
func testFetchOneWithKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -414,6 +414,17 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
}
// MARK: - Select Primary Key
func testSelectPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request: QueryInterfaceRequest<String> = Email.selectPrimaryKey()
try assertEqualSQL(db, request, "SELECT \"email\" FROM \"emails\"")
}
}
// MARK: - Fetch With Primary Key
func testFetchCursorWithPrimaryKeys() throws {
@@ -441,7 +452,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
}
}
}
func testFetchAllWithPrimaryKeys() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -466,7 +477,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
}
}
}
func testFetchOneWithPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -487,7 +498,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
}
}
}
// MARK: - Fetch With Primary Key Request
@@ -562,10 +573,10 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
}
}
}
// MARK: - Exists
func testExistsWithNotNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -574,7 +585,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
XCTAssertFalse(try record.exists(db))
}
}
func testExistsWithNotNilPrimaryKeyThatMatchesARowReturnsTrue() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -584,7 +595,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
XCTAssertTrue(try record.exists(db))
}
}
func testExistsAfterDeleteReturnsTrue() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
+30
View File
@@ -125,4 +125,34 @@ class TableRecordTests: GRDBTestCase {
XCTAssertEqual(lastSQLQuery, "SELECT \"a\", \"b\" FROM \"t1\"")
}
}
func testPrimaryKey() throws {
struct IntegerPrimaryKeyRecord: TableRecord { }
struct UUIDRecord: TableRecord { }
struct RowIDRecord: TableRecord { }
struct CompoundPrimaryKeyRecord: TableRecord { }
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.execute(sql: """
CREATE TABLE integerPrimaryKeyRecord (id INTEGER PRIMARY KEY);
CREATE TABLE uuidRecord (uuid TEXT PRIMARY KEY);
CREATE TABLE rowIDRecord (name TEXT);
CREATE TABLE compoundPrimaryKeyRecord (a INTEGER, b INTEGER, PRIMARY KEY (a, b));
""")
try assertEqualSQL(db, IntegerPrimaryKeyRecord.order(IntegerPrimaryKeyRecord.primaryKey), """
SELECT * FROM "integerPrimaryKeyRecord" ORDER BY "id"
""")
try assertEqualSQL(db, UUIDRecord.order(UUIDRecord.primaryKey), """
SELECT * FROM "uuidRecord" ORDER BY "uuid"
""")
try assertEqualSQL(db, RowIDRecord.order(RowIDRecord.primaryKey), """
SELECT * FROM "rowIDRecord" ORDER BY "rowid"
""")
try assertEqualSQL(db, CompoundPrimaryKeyRecord.order(CompoundPrimaryKeyRecord.primaryKey), """
SELECT * FROM "compoundPrimaryKeyRecord" ORDER BY "rowid"
""")
}
}
}
@@ -185,9 +185,14 @@ class TransactionObserverTests: GRDBTestCase {
try assertTransaction(start: "SAVEPOINT test", end: "COMMIT", isNotifiedAs: .commit)
try assertTransaction(start: "SAVEPOINT test; CREATE TABLE t(a)", end: "COMMIT", isNotifiedAs: .commit)
try assertTransaction(start: "SAVEPOINT test; ROLLBACK TRANSACTION TO SAVEPOINT test", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit)
try assertTransaction(start: "SAVEPOINT test; CREATE TABLE t(a); ROLLBACK TRANSACTION TO SAVEPOINT test", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit)
try assertTransaction(start: "SAVEPOINT test", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit)
#if !SQLITE_HAS_CODEC
// These tests fail with SQLCipher 4 (both debug and release configuration)
// TODO: is it GRDB or SQLCipher?
try assertTransaction(start: "SAVEPOINT test; CREATE TABLE t(a); ROLLBACK TRANSACTION TO SAVEPOINT test", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit)
try assertTransaction(start: "SAVEPOINT test; CREATE TABLE t(a)", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit)
#endif
// explicit rollback
try assertTransaction(start: "BEGIN DEFERRED TRANSACTION", end: "ROLLBACK", isNotifiedAs: .rollback)
+217
View File
@@ -99,6 +99,223 @@ class ValueObservationTests: GRDBTestCase {
XCTAssertEqual(observer.observedRegion!.description, "t(id,name)") // view is NOT tracked
}
// MARK: - Snapshot Optimization
private func isSnapshotEnabled(_ dbPool: DatabasePool) throws -> Bool {
// Testing Database.sqliteCompileOptions.contains("ENABLE_SNAPSHOT")
// is... not enough: on iOS 10.3.1, SQLITE_ENABLE_SNAPSHOT is not
// exposed, and yet, sqlite3_snaphost_get() works :shrug:
//
// So let's perform a runtime check:
try dbPool.read { db in
do {
let version = try db.takeVersionSnapshot()
grdb_snapshot_free(version)
return true
} catch {
return false
}
}
}
func testDisallowedSnapshotOptimizationWithAsyncScheduler() throws {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
}
// Force DatabasePool to perform two initial fetches, because between
// its first read access, and its write access that installs the
// transaction observer, some write did happen.
var needsChange = true
let observation = ValueObservation.tracking { db -> Int in
if needsChange {
needsChange = false
try dbPool.write { db in
try db.execute(sql: """
INSERT INTO t DEFAULT VALUES;
DELETE FROM t;
""")
}
}
return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")!
}
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = 2
var observedCounts: [Int] = []
let cancellable = observation.start(
in: dbPool,
scheduling: .async(onQueue: .main),
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
observedCounts.append(count)
expectation.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(observedCounts, [0, 0])
}
}
func testDisallowedSnapshotOptimizationWithImmediateScheduler() throws {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
}
// Force DatabasePool to perform two initial fetches, because between
// its first read access, and its write access that installs the
// transaction observer, some write did happen.
var needsChange = true
let observation = ValueObservation.tracking { db -> Int in
if needsChange {
needsChange = false
try dbPool.write { db in
try db.execute(sql: """
INSERT INTO t DEFAULT VALUES;
DELETE FROM t;
""")
}
}
return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")!
}
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = 2
var observedCounts: [Int] = []
let cancellable = observation.start(
in: dbPool,
scheduling: .immediate,
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
observedCounts.append(count)
expectation.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(observedCounts, [0, 0])
}
}
func testAllowedSnapshotOptimizationWithAsyncScheduler() throws {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
}
// Allow pool to perform a single initial fetch, because between
// its first read access, and its write access that installs the
// transaction observer, no write did happen.
var needsChange = true
let observation = ValueObservation.tracking { db -> Int in
if needsChange {
needsChange = false
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
try! dbPool.write { db in
try db.execute(sql: """
INSERT INTO t DEFAULT VALUES;
""")
}
}
}
return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")!
}
if try isSnapshotEnabled(dbPool) {
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = 2
var observedCounts: [Int] = []
let cancellable = observation.start(
in: dbPool,
scheduling: .async(onQueue: .main),
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
observedCounts.append(count)
expectation.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(observedCounts, [0, 1])
}
} else {
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = 3
var observedCounts: [Int] = []
let cancellable = observation.start(
in: dbPool,
scheduling: .async(onQueue: .main),
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
observedCounts.append(count)
expectation.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(observedCounts, [0, 0, 1])
}
}
}
func testAllowedSnapshotOptimizationWithImmediateScheduler() throws {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
}
// Allow pool to perform a single initial fetch, because between
// its first read access, and its write access that installs the
// transaction observer, no write did happen.
var needsChange = true
let observation = ValueObservation.tracking { db -> Int in
if needsChange {
needsChange = false
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
try! dbPool.write { db in
try db.execute(sql: """
INSERT INTO t DEFAULT VALUES;
""")
}
}
}
return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")!
}
if try isSnapshotEnabled(dbPool) {
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = 2
var observedCounts: [Int] = []
let cancellable = observation.start(
in: dbPool,
scheduling: .immediate,
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
observedCounts.append(count)
expectation.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(observedCounts, [0, 1])
}
} else {
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = 3
var observedCounts: [Int] = []
let cancellable = observation.start(
in: dbPool,
scheduling: .immediate,
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
observedCounts.append(count)
expectation.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(observedCounts, [0, 0, 1])
}
}
}
// MARK: - Cancellation
func testCancellableLifetime() throws {