Compare commits

...
43 Commits
Author SHA1 Message Date
Gwendal Roué 99b143a55c v2.1.0 2017-10-24 08:34:10 +02:00
Gwendal Roué 8401f42f3e Documentation 2017-10-24 08:20:33 +02:00
Gwendal Roué f69949edea Explain why Carthage test is commented out in .travis.yml 2017-10-24 08:18:06 +02:00
Gwendal Roué 62e33f294e ReleaseProcess.md 2017-10-24 08:11:13 +02:00
Gwendal Roué 2a8e48ba63 Minor 2017-10-24 08:11:05 +02:00
Gwendal Roué 6372bf663f Update Carthage information 2017-10-23 20:27:46 +02:00
Gwendal Roué ac7cc09bfe CHANGELOG.md 2017-10-23 19:54:38 +02:00
Gwendal Roué c9f0d473cf New FAQ: How do I print a request as SQL? 2017-10-23 19:54:30 +02:00
Gwendal Roué 8a7ffdbb67 CHANGELOG.md 2017-10-23 19:21:38 +02:00
Gwendal Roué d30baaf16c Fix default cached argument value for Request.asSQLRequest(_:cached:) 2017-10-23 19:21:30 +02:00
Gwendal Roué 1981adeb22 Request.asSQLRequest(_:cached:) 2017-10-23 19:20:38 +02:00
Gwendal Roué 8427b8b668 Remove test_CarthageBuild from the test make target 2017-10-23 19:02:09 +02:00
Gwendal Roué 6db590a31b Remove Carthage test from .travis.yml 2017-10-23 19:01:07 +02:00
Gwendal Roué 22faa03a48 Update sample code that create databases
The Application Support directory should generally be preferred.
2017-10-23 18:58:32 +02:00
Gwendal Roué d3cd0ae85a TODO.md 2017-10-23 09:42:40 +02:00
Gwendal Roué b624955bf3 Merge branch 'master' of github.com:groue/GRDB.swift into development 2017-10-15 12:19:35 +02:00
Gwendal Roué 1b20cd14d1 Fix link to SQLite documentation for the "pre-update hook" 2017-10-14 17:54:38 +02:00
Gwendal Roué baf2f780c9 Document that FetchedRecordsController is not suited for large data sets (#263) 2017-10-13 13:16:46 +02:00
Gwendal Roué 9d1997b6cd Typo 2017-10-12 21:54:46 +02:00
Gwendal Roué 313baa0064 Typo 2017-10-12 21:52:51 +02:00
Gwendal Roué 006eee9f51 Document that Record subclasses have to override database methods 2017-10-12 21:51:15 +02:00
Gwendal Roué 2720caf945 Documentation 2017-10-12 20:51:14 +02:00
Gwendal Roué 62faa57bf0 Documentation 2017-10-12 20:50:36 +02:00
Gwendal Roué abbdb995e6 Documentation 2017-10-12 20:46:01 +02:00
Gwendal Roué fd2ae60a65 Fix sample code of conversion from Row to Dictionary 2017-10-12 20:41:48 +02:00
Gwendal Roué 2c4cf2d06b Improve documentation of Codable support, and decrease focus on the Record class. 2017-10-12 20:40:33 +02:00
Gwendal Roué 0f5ec15d47 Test for Carthage integration in an iOS app 2017-10-12 08:26:36 +02:00
Gwendal Roué 1c3dfb346f Travis: move make test_CarthageBuild to the "Test Installation" stage 2017-10-11 22:02:02 +02:00
Darren Clark b76013d60b Travis - re-enable Carthage 2017-10-11 21:45:53 +02:00
Gwendal Roué e3ed95571c Upgrade custom SQLite builds to v3.20.1 2017-10-11 21:43:41 +02:00
Gwendal Roué c749893858 Update sqlcipher from https://github.com/groue/sqlcipher/pull/1 2017-10-11 21:26:37 +02:00
Gwendal Roué 9135be3da6 CHANGELOG 2017-10-11 08:20:34 +02:00
Gwendal Roué 9930fd3938 Fix failing test for drop temporary table 2017-10-11 08:17:57 +02:00
Gwendal Roué c62c3df00d Failing test for drop temporary table 2017-10-11 08:10:22 +02:00
Gwendal Roué 0419d67533 More fiddling with the deadly truncate optimization 2017-10-10 09:01:50 +02:00
Gwendal Roué 32d69c5be0 TODO.md 2017-10-10 08:20:27 +02:00
Gwendal Roué c2fb23c69c Stop using String.characters view 2017-10-10 08:15:28 +02:00
Gwendal Roué 47611e14f7 v2.0.3 2017-10-09 08:11:06 +02:00
Gwendal Roué b90f876b5b Records that adopt Encodable encode null columns 2017-10-09 08:06:46 +02:00
Gwendal Roué 9037d51bc7 Failing test for Encodable+Persistable (null values are not encoded) 2017-10-09 08:03:43 +02:00
Gwendal Roué fb8c68f5e0 Fix compiler error 2017-10-07 07:41:17 +02:00
Gwendal Roué 4995b5bb8c Group truncate optimization tests together 2017-10-07 06:51:13 +02:00
Gwendal Roué c87ebfd4eb CHANGELOG.md 2017-10-07 05:49:46 +02:00
32 changed files with 721 additions and 234 deletions

No files matched your search

+10 -7
View File
@@ -141,11 +141,14 @@ jobs:
- TID=SPM
script: make test_install_SPM
## The following doesn’t work, as `make test_CarthageBuild` does not yet work.
## Carthage Build
#- stage: Carthage
# osx_image: xcode9
# before_install:
# - brew update
# - brew outdated carthage || brew upgrade carthage
# script: make test_CarthageBuild
## Commented out until `make test_CarthageBuild` performs *reliably*.
## See https://github.com/groue/GRDB.swift/pull/262
# - stage: Test Installation
# osx_image: xcode9
# before_install:
# - brew update
# - brew outdated carthage || brew upgrade carthage
# env:
# - TID=Carthages
# script: make test_CarthageBuild
+54 -2
View File
@@ -1,6 +1,58 @@
Release Notes
=============
## 2.1.0
Released October 24, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.0.3...v2.1.0)
### New
- GRDBCipher can now build from command line ([groue/sqlcipher/pull/1](https://github.com/groue/sqlcipher/pull/1) by [Darren Clark](https://github.com/darrenclark))
- Upgrade custom SQLite builds to [v3.20.1](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- The new method `Request.asSQLRequest` allows to inspect the sql and arguments of any request:
```swift
let request = Player.all()
let sql = try request.asSQLRequest().sql
print(sql) // Prints "SELECT * FROM players"
```
- StatementArguments adopts Equatable
### Fixed
- `DROP TABLE` statements would not drop temporary tables.
### Documentation Diff
- New FAQ: [How do I create a database in my application?](https://github.com/groue/GRDB.swift/blob/master/README.md#how-do-i-create-a-database-in-my-application)
- New FAQ: [How do I print a request as SQL?](https://github.com/groue/GRDB.swift/blob/master/README.md#how-do-i-print-a-request-as-sql)
- The [Codable Record](https://github.com/groue/GRDB.swift/blob/master/README.md#codable-records) chapter has been enhanced with more information and sample code.
### API diff
```diff
extension Request {
+ func asSQLRequest(_ db: Database, cached: Bool = false) throws -> SQLRequest
}
struct SQLRequest {
+ let sql: String
+ let arguments: StatementArguments?
+ let adapter: RowAdapter?
}
```
## 2.0.3
Released October 9, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.0.2...v2.0.3)
**Fixed**: Record types that conform to Encodable now encode their null columns.
## 2.0.2
Released October 5, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.0.1...v2.0.2)
@@ -114,7 +166,7 @@ New features have been added in order to plug a few holes and support the [RxGRD
- Query interface requests learned how to limit the number of deleted rows:
```swift
// Delete the worse ten players:
// Delete the last ten players:
// DELETE FROM players ORDER BY score LIMIT 10
let request = Player.order(scoreColumn).limit(10)
try request.deleteAll(db)
@@ -186,7 +238,7 @@ New features have been added in order to plug a few holes and support the [RxGRD
- The deprecated `TableMapping.primaryKeyRowComparator` method has been removed.
### Documentation diff
### Documentation Diff
- [WatchOS installation procedure](https://github.com/groue/GRDB.swift#installation) has been updated with new instructions.
- The [introduction to multithreading with database pools](https://github.com/groue/GRDB.swift#database-pools) has been enhanced.
@@ -14,9 +14,10 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
}
private func setupDatabase(_ application: UIApplication) throws {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString
let databasePath = documentsPath.appendingPathComponent("db.sqlite")
dbQueue = try AppDatabase.openDatabase(atPath: databasePath)
let databaseURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("db.sqlite")
dbQueue = try AppDatabase.openDatabase(atPath: databaseURL.path)
// Be a nice iOS citizen, and don't consume too much memory
// See https://github.com/groue/GRDB.swift/#memory-management
+2 -2
View File
@@ -3,7 +3,7 @@ Custom SQLite Builds
By default, GRDB uses the version of SQLite that ships with the target operating system.
**You can build GRDB with a custom build of [SQLite 3.20.0](https://www.sqlite.org/changes.html).**
**You can build GRDB with a custom build of [SQLite 3.20.1](https://www.sqlite.org/changes.html).**
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](../../../#support-for-sqlite-pre-update-hooks).
@@ -15,7 +15,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
```sh
cd [GRDB directory]
git checkout v2.0.2
git checkout v2.1.0
git submodule update --init SQLiteCustom/src
````
+2 -2
View File
@@ -497,7 +497,7 @@ Build a `value BETWEEN min AND max` expression from Swift ranges:
#### The COUNT Function
Build a `COUNT(...)` expression from the [count](http://groue.github.io/GRDB.swift/docs/2.0/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/2.0/Functions.html) functions:
Build a `COUNT(...)` expression from the [count](http://groue.github.io/GRDB.swift/docs/2.1/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/2.1/Functions.html) functions:
```swift
// SQLExpression: COUNT(email)
@@ -588,4 +588,4 @@ You may want to compare it to another protocol, SQLSpecificExpressible, which ha
> :point_up: **Note**: whenever you extend GRDB with a Swift function, method, or operator, you should generally make sure that its signature contains at least one GRDB-specific type. In the `cast` function, it is Database.ColumnType.
**If SQLExpressionLiteral reveals too limited for your purpose**, you may have to implement a new type that adopts the [SQLExpression](http://groue.github.io/GRDB.swift/docs/2.0/Protocols/SQLExpression.html) protocol.
**If SQLExpressionLiteral reveals too limited for your purpose**, you may have to implement a new type that adopts the [SQLExpression](http://groue.github.io/GRDB.swift/docs/2.1/Protocols/SQLExpression.html) protocol.
+1 -1
View File
@@ -24,7 +24,7 @@ To release a new GRDB version:
- Commit and tag
- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
- Push to the master branch
- Push to the Swift3 branch
- Push to the Swift4 branch
- `pod trunk push --allow-warnings GRDB.swift.podspec`
- `pod trunk push --allow-warnings GRDBCipher.podspec`
- `make doc`, and update index.html in the `gh-pages` branch
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '2.0.2'
s.version = '2.1.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A Swift application toolkit for SQLite databases.'
+18
View File
@@ -743,6 +743,14 @@
567E55EE1D2BDD3F00CC6F79 /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; };
567E55F31D2BDDFE00CC6F79 /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; };
567E55F41D2BDDFF00CC6F79 /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; };
567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
567F45A91F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
567F45AA1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
567F45AB1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
567F45AD1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
567F45AE1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
567F45AF1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
568068321EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
568068331EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
@@ -2071,6 +2079,7 @@
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>"; };
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = "<group>"; };
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Fixits-1.2.swift"; sourceTree = "<group>"; };
@@ -2466,6 +2475,7 @@
children = (
5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */,
5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */,
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */,
);
name = TransactionObserver;
sourceTree = "<group>";
@@ -4098,6 +4108,7 @@
56176C631EACCCC7000F3F2B /* FTS5TokenizerTests.swift in Sources */,
5623934F1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */,
560FC57C1CB00B880014AA8E /* StatementArgumentsTests.swift in Sources */,
567F45A91F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
5634B1081CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */,
560FC57D1CB00B880014AA8E /* RecordInitializersTests.swift in Sources */,
56176C5F1EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */,
@@ -4368,6 +4379,7 @@
56176C691EACCCC8000F3F2B /* FTS5TokenizerTests.swift in Sources */,
562393501DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */,
5671563A1CB16729007DC145 /* StatementArgumentsTests.swift in Sources */,
567F45AA1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
5657AB601D108BA9006283EF /* FoundationNSURLTests.swift in Sources */,
5671563B1CB16729007DC145 /* RecordInitializersTests.swift in Sources */,
56176C651EACCCC8000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */,
@@ -4596,6 +4608,7 @@
56176C751EACCCCA000F3F2B /* FTS5TokenizerTests.swift in Sources */,
56AFCA4D1CB1AA9900F48B96 /* DatabasePoolReadOnlyTests.swift in Sources */,
5657AB631D108BA9006283EF /* FoundationNSURLTests.swift in Sources */,
567F45AD1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
5657AB6B1D108BA9006283EF /* FoundationURLTests.swift in Sources */,
56AFCA4F1CB1AA9900F48B96 /* DataMemoryTests.swift in Sources */,
56176C711EACCCCA000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */,
@@ -4734,6 +4747,7 @@
56176C7B1EACCCCB000F3F2B /* FTS5TokenizerTests.swift in Sources */,
566AD8CC1D531BEE002EC1A8 /* TableDefinitionTests.swift in Sources */,
56AFCAA41CB1ABC800F48B96 /* MutablePersistableTests.swift in Sources */,
567F45AE1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
56AFCAA51CB1ABC800F48B96 /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */,
56AFCAA61CB1ABC800F48B96 /* DatabasePoolReadOnlyTests.swift in Sources */,
56176C771EACCCCB000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */,
@@ -4961,6 +4975,7 @@
56176C6B1EACCCC9000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */,
56300B621C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */,
56EA869F1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift in Sources */,
567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
5657AB621D108BA9006283EF /* FoundationNSURLTests.swift in Sources */,
5657AB6A1D108BA9006283EF /* FoundationURLTests.swift in Sources */,
56F3E74D1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */,
@@ -5099,6 +5114,7 @@
56176C591EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */,
56D4968A1D81316E008276D7 /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
56D496601D81304E008276D7 /* FoundationNSUUIDTests.swift in Sources */,
567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
56D4968D1D81316E008276D7 /* DatabaseFunctionTests.swift in Sources */,
56D496661D813086008276D7 /* QueryInterfaceRequestTests.swift in Sources */,
56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */,
@@ -5417,6 +5433,7 @@
5657AB651D108BA9006283EF /* FoundationNSURLTests.swift in Sources */,
F3BA80F31CFB301D003DC1BA /* StatementColumnConvertibleTests.swift in Sources */,
5657AB6D1D108BA9006283EF /* FoundationURLTests.swift in Sources */,
567F45AF1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
F3BA804C1CFB2B24003DC1BA /* GRDBTestCase.swift in Sources */,
5698ACBD1DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */,
5623931F1DECC02000A6B01F /* RowFetchTests.swift in Sources */,
@@ -5645,6 +5662,7 @@
F3BA80B01CFB2FB2003DC1BA /* DatabaseCollationTests.swift in Sources */,
56C7A6AE1D2DFF6100EFB0C2 /* FoundationNSDateTests.swift in Sources */,
F3BA80F51CFB301E003DC1BA /* StatementColumnConvertibleTests.swift in Sources */,
567F45AB1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
F3BA80A61CFB2F91003DC1BA /* GRDBTestCase.swift in Sources */,
5657AB411D108BA9006283EF /* FoundationNSDataTests.swift in Sources */,
56B964C61DA521450002DA19 /* FTS5PatternTests.swift in Sources */,
+10 -7
View File
@@ -1549,10 +1549,11 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
// print("StatementCompilationAuthorizer: \(actionCode) \([cString1, cString2, cString3, cString4].flatMap { $0.map({ String(cString: $0) }) })")
switch actionCode {
case SQLITE_DROP_TABLE, SQLITE_DROP_TEMP_TABLE, SQLITE_DROP_TEMP_VIEW, SQLITE_DROP_VIEW, SQLITE_DETACH, SQLITE_ALTER_TABLE, SQLITE_DROP_VTABLE, SQLITE_CREATE_INDEX, SQLITE_CREATE_TEMP_INDEX, SQLITE_DROP_INDEX, SQLITE_DROP_TEMP_INDEX:
if actionCode == SQLITE_DROP_TABLE || actionCode == SQLITE_DROP_VTABLE {
isDropTableStatement = true
}
case SQLITE_DROP_TABLE, SQLITE_DROP_VTABLE, SQLITE_DROP_TEMP_TABLE:
isDropTableStatement = true
invalidatesDatabaseSchemaCache = true
return SQLITE_OK
case SQLITE_DROP_TEMP_VIEW, SQLITE_DROP_VIEW, SQLITE_DETACH, SQLITE_ALTER_TABLE, SQLITE_CREATE_INDEX, SQLITE_CREATE_TEMP_INDEX, SQLITE_DROP_INDEX, SQLITE_DROP_TEMP_INDEX:
invalidatesDatabaseSchemaCache = true
return SQLITE_OK
case SQLITE_READ:
@@ -1572,10 +1573,12 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
return SQLITE_OK
case SQLITE_DELETE:
guard !isDropTableStatement else { return SQLITE_OK }
guard let tableName = cString1.map({ String(cString: $0) }), tableName != "sqlite_master" else { return SQLITE_OK }
databaseEventKinds.append(.delete(tableName: tableName))
guard let cString1 = cString1 else { return SQLITE_OK }
guard strcmp(cString1, "sqlite_master") != 0 else { return SQLITE_OK }
guard strcmp(cString1, "sqlite_temp_master") != 0 else { return SQLITE_OK }
databaseEventKinds.append(.delete(tableName: String(cString: cString1)))
// Prevent the [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
// See TruncateOptimizationBlocker
// See also TruncateOptimizationBlocker
needsTruncateOptimizationPreventionDuringExecution = true
return SQLITE_IGNORE
case SQLITE_UPDATE:
+17 -5
View File
@@ -36,6 +36,18 @@ extension Request {
let sql = "SELECT COUNT(*) FROM (\(statement.sql))"
return try Int.fetchOne(db, sql, arguments: statement.arguments)!
}
/// Returns an equivalent SQLRequest.
///
/// - parameters:
/// - db: A database connection.
/// - cached: Defaults to false. If true, the request reuses a cached
/// prepared statement.
/// - returns: An SQLRequest
public func asSQLRequest(_ db: Database, cached: Bool = false) throws -> SQLRequest {
let (statement, adapter) = try prepare(db)
return SQLRequest(statement.sql, arguments: statement.arguments, adapter: adapter, cached: cached)
}
}
extension Request {
@@ -126,6 +138,11 @@ public struct AnyRequest : Request {
/// A Request built from raw SQL.
public struct SQLRequest : Request {
public let sql: String
public let arguments: StatementArguments?
public let adapter: RowAdapter?
private let statementCacheName: Database.StatementCacheName?
/// Creates a new request from an SQL string, optional arguments, and
/// optional row adapter.
///
@@ -178,11 +195,6 @@ public struct SQLRequest : Request {
}
return (statement, adapter)
}
private let sql: String
private let arguments: StatementArguments?
private let adapter: RowAdapter?
private let statementCacheName: Database.StatementCacheName?
}
/// The protocol for requests that know how to decode database rows.
+11 -4
View File
@@ -105,7 +105,7 @@ public class Statement {
guard let cString = sqlite3_bind_parameter_name(self.sqliteStatement, Int32($0 + 1)) else {
return nil
}
return String(String(cString: cString).characters.dropFirst()) // Drop initial ":", "@", "$"
return String(String(cString: cString).dropFirst()) // Drop initial ":", "@", "$"
}
}()
@@ -574,6 +574,8 @@ public final class UpdateStatement : Statement {
/// print(row)
/// // Prints <Row two:2 foo:"foo" one:1 foo2:"foo" bar:"bar">
public struct StatementArguments {
var values: [DatabaseValue] = []
var namedValues: [String: DatabaseValue] = [:]
public var isEmpty: Bool {
return values.isEmpty && namedValues.isEmpty
@@ -831,9 +833,6 @@ public struct StatementArguments {
// MARK: Not Public
var values: [DatabaseValue] = []
var namedValues: [String: DatabaseValue] = [:]
mutating func consume(_ statement: Statement, allowingRemainingValues: Bool) throws -> [DatabaseValue] {
let initialValuesCount = values.count
let bindings = try statement.sqliteArgumentNames.map { argumentName -> DatabaseValue in
@@ -889,6 +888,14 @@ extension StatementArguments : CustomStringConvertible {
}
}
extension StatementArguments : Equatable {
public static func == (lhs: StatementArguments, rhs: StatementArguments) -> Bool {
if lhs.values != rhs.values { return false }
if lhs.namedValues != rhs.namedValues { return false }
return true
}
}
/// A thread-unsafe statement cache
struct StatementCache {
unowned let db: Database
@@ -462,9 +462,8 @@ struct SQLExpressionCollate : SQLExpression {
func expressionSQL(_ arguments: inout StatementArguments?) -> String {
let sql = expression.expressionSQL(&arguments)
let chars = sql.characters
if chars.last! == ")" {
return String(chars.prefix(upTo: chars.index(chars.endIndex, offsetBy: -1))) + " COLLATE " + collationName.rawValue + ")"
if sql.last! == ")" {
return String(sql.prefix(upTo: sql.index(sql.endIndex, offsetBy: -1))) + " COLLATE " + collationName.rawValue + ")"
} else {
return sql + " COLLATE " + collationName.rawValue
}
+21 -2
View File
@@ -28,7 +28,6 @@ private struct PersistableKeyedEncodingContainer<Key: CodingKey> : KeyedEncoding
mutating func encode(_ value: Float, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: Double, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: String, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encodeNil(forKey key: Key) throws { encode(nil, key.stringValue) }
/// Encodes the given value for the given key.
///
@@ -45,6 +44,24 @@ private struct PersistableKeyedEncodingContainer<Key: CodingKey> : KeyedEncoding
}
}
// Provide explicit encoding of optionals, because default implementation does not encode nil values.
mutating func encodeNil(forKey key: Key) throws { encode(nil, key.stringValue) }
mutating func encodeIfPresent(_ value: Bool?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: Int?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: Int8?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: Int16?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: Int32?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: Int64?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: UInt?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: UInt8?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: UInt16?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: UInt32?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: UInt64?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: Float?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: Double?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: String?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent<T>(_ value: T?, forKey key: Key) throws where T : Encodable { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
/// Stores a keyed encoding container for the given key and returns it.
///
/// - parameter keyType: The key type to use for the container.
@@ -189,6 +206,8 @@ extension MutablePersistable where Self: Encodable {
try! self.encode(to: encoder)
}
}
encode { (value, key) in container[key] = value }
encode { (value, key) in
container[key] = value
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDBCipher'
s.version = '2.0.2'
s.version = '2.1.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A Swift application toolkit for SQLite databases.'
+10 -3
View File
@@ -222,6 +222,13 @@ test_CarthageBuild: SQLiteCustom SQLCipher
ifdef CARTHAGE
rm -rf Carthage
$(CARTHAGE) build --no-skip-current
$(XCODEBUILD) \
-project Tests/Carthage/GRDBiOS/iOS.xcodeproj \
-scheme iOS \
-configuration Release \
-destination $(MAX_IOS_DESTINATION) \
clean build \
$(XCPRETTY)
else
@echo Carthage must be installed for test_CarthageBuild
@exit 1
@@ -285,10 +292,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/v2.0 \
--module-version 2.0 \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v2.1.0 \
--module-version 2.1 \
--module GRDB \
--root-url http://groue.github.io/GRDB.swift/docs/2.0/ \
--root-url http://groue.github.io/GRDB.swift/docs/2.1/ \
--output Documentation/Reference \
--podspec GRDB.swift.podspec
else
+215 -95
View File
@@ -3,7 +3,7 @@ GRDB 2.0 [![Swift](https://img.shields.io/badge/swift-4-orange.svg?style=flat)](
### A toolkit for SQLite databases, with a focus on application development
**Latest release**: October 5, 2017 • version 2.0.2 • [CHANGELOG](CHANGELOG.md)
**Latest release**: October 24, 2017 • version 2.1.0 • [CHANGELOG](CHANGELOG.md)
**Requirements**: iOS 8.0+ / OSX 10.9+ / watchOS 2.0+ &bull; Swift 4.0 / Xcode 9+
@@ -14,7 +14,7 @@ GRDB 2.0 [![Swift](https://img.shields.io/badge/swift-4-orange.svg?style=flat)](
| Swift 3 | [v1.0](https://github.com/groue/GRDB.swift/tree/v1.0) |
| Swift 3.1 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) |
| Swift 3.2 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) |
| **Swift 4** | **v2.0.2** |
| **Swift 4** | **v2.1.0** |
Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips.
@@ -197,7 +197,7 @@ Documentation
**Reference**
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/2.0/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/2.1/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
**Getting Started**
@@ -245,7 +245,7 @@ Installation
See [Encryption](#encryption) for the installation procedure of GRDB with SQLCipher.
See [Custom SQLite builds](Documentation/CustomSQLiteBuilds.md) for the installation procedure of GRDB with a customized build of SQLite 3.20.0.
See [Custom SQLite builds](Documentation/CustomSQLiteBuilds.md) for the installation procedure of GRDB with a customized build of SQLite 3.20.1.
## CocoaPods
@@ -265,7 +265,7 @@ The [Swift Package Manager](https://swift.org/package-manager/) automates the di
```swift
let package = Package(
dependencies: [
.package(url: "https://github.com/groue/GRDB.swift.git", from: "2.0.2")
.package(url: "https://github.com/groue/GRDB.swift.git", from: "2.1.0")
]
)
```
@@ -275,14 +275,14 @@ Note that Linux is not currently supported.
## Carthage
Carthage does not support the variety of frameworks built by GRDB (standard SQLite, custom SQLite, SQLCipher).
Carthage can build GRDB frameworks, but it can also inexplicably fail. This installation method is thus *unsupported*.
Any pull request that has the `make test_CarthageBuild` command successfully complete will be greatly appreciated, though. Bring your local Xcode guru!
If you decide to use Carthage despite this warning, and get any Carthage-related error, please open an issue in the [Carthage repo](https://github.com/Carthage/Carthage/issues), ask [Stack Overflow](http://stackoverflow.com), summon your local Xcode guru, or submit a pull request that has the `make test_CarthageBuild` command succeed 100% of the time (one time is not enough). See [#262](https://github.com/groue/GRDB.swift/pull/262) for more information.
## Manually
1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v2.0.2) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v2.0.2` command.
1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v2.1.0) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v2.1.0` command.
2. Embed the `GRDB.xcodeproj` project in your own project.
@@ -379,7 +379,7 @@ let dbQueue = try DatabaseQueue(
configuration: config)
```
See [Configuration](http://groue.github.io/GRDB.swift/docs/2.0/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/2.1/Structs/Configuration.html) for more details.
## Database Pools
@@ -460,7 +460,7 @@ let dbPool = try DatabasePool(
configuration: config)
```
See [Configuration](http://groue.github.io/GRDB.swift/docs/2.0/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/2.1/Structs/Configuration.html) for more details.
Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information.
@@ -650,7 +650,7 @@ Both arrays and cursors can iterate over database results. How do you choose one
- Cursors can not be used on any thread: you must consume them in a protected database queue.
- Cursors iterate database results in a lazy fashion, and don't consume much memory.
- Cursors can be iterated only one time.
- Cursors are granted with direct access to SQLite: you can especially expect the best performance from cursors of raw database rows and some primitive types like `Int`, `String`, or `Bool` that adopt the [StatementColumnConvertible](http://groue.github.io/GRDB.swift/docs/2.0/Protocols/StatementColumnConvertible.html) protocol.
- Cursors are granted with direct access to SQLite: you can especially expect the best performance from cursors of raw database rows and some primitive types like `Int`, `String`, or `Bool` that adopt the [StatementColumnConvertible](http://groue.github.io/GRDB.swift/docs/2.1/Protocols/StatementColumnConvertible.html) protocol.
If you don't see, or don't care about the difference, use arrays. If you care about memory and performance, use cursors when appropriate.
@@ -663,7 +663,7 @@ Date.fetchCursor(...) // DatabaseValueCursor<Date>
Player.fetchCursor(...) // RecordCursor<Player>
```
All cursor types adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/2.0/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift. As such, cursors come with many methods: `contains`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `map`, `reduce`:
All cursor types adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/2.1/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 methods: `contains`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `map`, `reduce`:
```swift
// Iterate all Github links
@@ -734,7 +734,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/2.0/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/2.1/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:
@@ -933,7 +933,7 @@ for (columnName, dbValue) in row { ... } // ("foo", 1), ("foo", 2)
- A `[String: DatabaseValue]` dictionary that keeps leftmost value in case of duplicated column name:
```swift
let dict = Dictionary(row, uniquingKeysWith: { $0 })
let dict = Dictionary(row, uniquingKeysWith: { (left, _) in left })
```
- A `[String: AnyObject]` dictionary which keeps rightmost value in case of duplicated column name. This dictionary is identical to FMResultSet's resultDictionary from FMDB. It contains NSNull values for null columns, and can be shared with Objective-C:
@@ -943,7 +943,7 @@ for (columnName, dbValue) in row { ... } // ("foo", 1), ("foo", 2)
row.map { (column, dbValue) in
(column, dbValue.storage.value as AnyObject)
},
uniquingKeysWith: { $1 })
uniquingKeysWith: { (_, right) in right })
```
- A `[String: Any]` dictionary that can feed, for example, JSONSerialization:
@@ -953,7 +953,7 @@ for (columnName, dbValue) in row { ... } // ("foo", 1), ("foo", 2)
row.map { (column, dbValue) in
(column, dbValue.storage.value)
},
uniquingKeysWith: { $0 })
uniquingKeysWith: { (left, _) in left })
```
See the documentation of [`Dictionary.init(_:uniquingKeysWith:)`](https://developer.apple.com/documentation/swift/dictionary/2892961-init) for more information.
@@ -1005,7 +1005,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/2.0/Structs/StatementArguments.html):
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/2.1/Structs/StatementArguments.html):
```swift
let url: URL = ...
@@ -1397,7 +1397,7 @@ try dbQueue.inDatabase { 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/2.0/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/2.1/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
```swift
updateStatement.arguments = ["name": "Arthur", "score": 1000]
@@ -1659,7 +1659,7 @@ row["consumed"] // "Hello"
row["produced"] // nil
```
Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/2.0/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:
Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/2.1/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:
### ColumnMapping
@@ -1786,8 +1786,8 @@ Before jumping in the low-level wagon, here is the list of all SQLite APIs used
- `sqlite3_aggregate_context`, `sqlite3_create_function_v2`, `sqlite3_result_blob`, `sqlite3_result_double`, `sqlite3_result_error`, `sqlite3_result_error_code`, `sqlite3_result_int64`, `sqlite3_result_null`, `sqlite3_result_text`, `sqlite3_user_data`, `sqlite3_value_blob`, `sqlite3_value_bytes`, `sqlite3_value_double`, `sqlite3_value_int64`, `sqlite3_value_text`, `sqlite3_value_type`: see [Custom SQL Functions and Aggregates](#custom-sql-functions-and-aggregates)
- `sqlite3_backup_finish`, `sqlite3_backup_init`, `sqlite3_backup_step`: see [Backup](#backup)
- `sqlite3_bind_blob`, `sqlite3_bind_double`, `sqlite3_bind_int64`, `sqlite3_bind_null`, `sqlite3_bind_parameter_count`, `sqlite3_bind_parameter_name`, `sqlite3_bind_text`, `sqlite3_clear_bindings`, `sqlite3_column_blob`, `sqlite3_column_bytes`, `sqlite3_column_count`, `sqlite3_column_double`, `sqlite3_column_int64`, `sqlite3_column_name`, `sqlite3_column_text`, `sqlite3_column_type`, `sqlite3_exec`, `sqlite3_finalize`, `sqlite3_prepare_v2`, `sqlite3_reset`, `sqlite3_step`: see [Executing Updates](#executing-updates), [Fetch Queries](#fetch-queries), [Prepared Statements](#prepared-statements), [Values](#values)
- `sqlite3_busy_handler`, `sqlite3_busy_timeout`: see [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/2.0/Structs/Configuration.html)
- `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/2.0/Classes/Database.html)
- `sqlite3_busy_handler`, `sqlite3_busy_timeout`: see [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/2.1/Structs/Configuration.html)
- `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/2.1/Classes/Database.html)
- `sqlite3_close`, `sqlite3_close_v2`, `sqlite3_next_stmt`, `sqlite3_open_v2`: see [Database Connections](#database-connections)
- `sqlite3_commit_hook`, `sqlite3_rollback_hook`, `sqlite3_update_hook`: see [TransactionObserver Protocol](#transactionobserver-protocol), [FetchedRecordsController](#fetchedrecordscontroller)
- `sqlite3_config`: see [Error Log](#error-log)
@@ -1798,9 +1798,9 @@ Before jumping in the low-level wagon, here is the list of all SQLite APIs used
- `sqlite3_last_insert_rowid`: see [Executing Updates](#executing-updates)
- `sqlite3_preupdate_count`, `sqlite3_preupdate_depth`, `sqlite3_preupdate_hook`, `sqlite3_preupdate_new`, `sqlite3_preupdate_old`: see [Support for SQLite Pre-Update Hooks](#support-for-sqlite-pre-update-hooks)
- `sqlite3_set_authorizer`: **reserved by GRDB**
- `sqlite3_sql`: see [Statement.sql](http://groue.github.io/GRDB.swift/docs/2.0/Classes/Statement.html)
- `sqlite3_trace`: see [Configuration.trace](http://groue.github.io/GRDB.swift/docs/2.0/Structs/Configuration.html)
- `sqlite3_wal_checkpoint_v2`: see [DatabasePool.checkpoint](http://groue.github.io/GRDB.swift/docs/2.0/Classes/DatabasePool.html)
- `sqlite3_sql`: see [Statement.sql](http://groue.github.io/GRDB.swift/docs/2.1/Classes/Statement.html)
- `sqlite3_trace`: see [Configuration.trace](http://groue.github.io/GRDB.swift/docs/2.1/Structs/Configuration.html)
- `sqlite3_wal_checkpoint_v2`: see [DatabasePool.checkpoint](http://groue.github.io/GRDB.swift/docs/2.1/Classes/DatabasePool.html)
Records
@@ -1840,14 +1840,12 @@ Your custom structs and classes can adopt each protocol individually, and opt in
- [Persistence Methods](#persistence-methods)
- [Customizing the Persistence Methods](#customizing-the-persistence-methods)
- [Conflict Resolution](#conflict-resolution)
- [Codable Records](#codable-records)
- [Record Class](#record-class)
- [Changes Tracking](#changes-tracking)
- [The Implicit RowID Primary Key](#the-implicit-rowid-primary-key)
- **[List of Record Methods](#list-of-record-methods)**
**Records, Swift Archival & Serialization**
- [Codable Records](#codable-records)
- [List of Record Methods](#list-of-record-methods)
- [The Query Interface](#the-query-interface)
### Inserting Records
@@ -1944,13 +1942,15 @@ let playerWithEmailCount = try Player.filter(emailColumn != nil).fetchCount(db)
```
You can now jump to:
Details follow:
- [Record Protocols Overview](#record-protocols-overview)
- [RowConvertible Protocol](#rowconvertible-protocol)
- [TableMapping Protocol](#tablemapping-protocol)
- [Persistable Protocol](#persistable-protocol)
- [Codable Records](#codable-records)
- [Record Class](#record-class)
- [The Implicit RowID Primary Key](#the-implicit-rowid-primary-key)
- [List of Record Methods](#list-of-record-methods)
- [The Query Interface](#the-query-interface)
@@ -2125,7 +2125,7 @@ try Place.fetchAll(db, "SELECT ...", arguments:...) // [Place]
try Place.fetchOne(db, "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/2.0/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/2.1/Structs/StatementArguments.html) for more information about the query arguments.
## TableMapping Protocol
@@ -2432,13 +2432,98 @@ try player.insert(db)
> :warning: **Warning**: [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) may delete rows so that inserts and updates can succeed. Those deletions are not reported to [transaction observers](#transactionobserver-protocol) (this might change in a future release of SQLite).
## Codable Records
[Swift Archival & Serialization](https://github.com/apple/swift-evolution/blob/master/proposals/0166-swift-archival-serialization.md) was introduced with Swift 4.
GRDB provides default implementations for [`RowConvertible.init(row:)`](#rowconvertible-protocol) and [`Persistable.encode(to:)`](#persistable-protocol) for record types that also adopt an archival protocol (`Codable`, `Encodable` or `Decodable`). When all their properties are themselves codable, Swift generates the archiving methods, and you don't need to write them down:
```swift
// This is just enough...
struct Player: RowConvertible, Persistable, Codable {
static let databaseTableName = "players"
let name: String
let score: Int
}
// ... so that you can save and fetch players:
try dbQueue.inDatabase { db in
try Player(name: "Arthur", score: 100).insert(db)
let players = try Player.fetchAll(db)
}
```
GRDB support for Codable only works for "flat" records, whose stored properties are all simple [values](#values) (Bool, Int, String, Date, Swift enums, etc.) For example, the following record is not flat:
```swift
// Can't take profit from Codable code generation:
struct Place: RowConvertible, Persistable, Codable {
static let databaseTableName = "places"
var title: String
var coordinate: CLLocationCoordinate2D // <- Not a simple value
}
```
Make it flat, as below, and you'll be granted with all Codable and GRDB advantages:
```swift
struct Place: RowConvertible, Persistable, Codable {
static let databaseTableName = "places"
// Stored properties are all plain values:
var title: String
var latitude: CLLocationDegrees
var longitude: CLLocationDegrees
// Complex properties are computed properties:
var coordinate: CLLocationCoordinate2D {
get {
return CLLocationCoordinate2D(
latitude: latitude,
longitude: longitude)
}
set {
latitude = newValue.latitude
longitude = newValue.longitude
}
}
}
```
As documented with the [Persistable](#persistable-protocol) protocol, have you struct records use MutablePersistable instead of Persistable when they store their automatically incremented row id:
```swift
struct Place: RowConvertible, MutablePersistable, Codable {
static let databaseTableName = "places"
var id: Int64? // <- the row id
var title: String
var latitude: CLLocationDegrees
var longitude: CLLocationDegrees
var coordinate: CLLocationCoordinate2D { ... }
mutating func didInsert(with rowID: Int64, for column: String?) {
// Update id after insertion
id = rowID
}
}
var place = Place(id: nil, ...)
try place.insert(db)
place.id // A unique id
```
> :point_up: **Note**: Some values have a different way to encode and decode themselves in a standard archive vs. the database. For example, [Date](#date-and-datecomponents) saves itself as a numerical timestamp (archive) or a string (database). When such an ambiguity happens, GRDB always favors customized database encoding and decoding.
## Record Class
**Record** is a class that is designed to be subclassed, and provides the full toolkit in one go: fetching and persistence methods, as well as changes tracking (see the [list of record methods](#list-of-record-methods) for an overview).
**Record** is a class that is designed to be subclassed. It inherits its features from the [RowConvertible, TableMapping, and Persistable](#record-protocols-overview) protocols. On top of that, it adds [changes tracking](#changes-tracking).
Record subclasses inherit their features from the [RowConvertible, TableMapping, and Persistable](#record-protocols-overview) protocols. Check their documentation for more information.
For example, here is a fully functional Record subclass:
Record subclasses define their custom database relationship by overriding database methods:
```swift
class Place : Record {
@@ -2469,7 +2554,7 @@ class Place : Record {
container["longitude"] = coordinate.longitude
}
/// Update record ID after a successful insertion
/// When relevant, update record ID after a successful insertion
override func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
@@ -2479,7 +2564,7 @@ class Place : Record {
### Changes Tracking
**The [Record](#record-class) class provides changes tracking.**
**Record instances know if they have been modified since they were last fetched.**
The `update()` [method](#persistence-methods) always executes an UPDATE statement. When the record has not been edited, this costly database access is generally useless.
@@ -2721,31 +2806,6 @@ let player = try Player.fetchOne(statement, arguments: [1]) // Player?
```
## Codable Records
[Swift Archival & Serialization](https://github.com/apple/swift-evolution/blob/master/proposals/0166-swift-archival-serialization.md) was introduced with Swift 4.
GRDB provides default implementations for [`RowConvertible.init(row:)`](#rowconvertible-protocol) and [`Persistable.encode(to:)`](#persistable-protocol) for record types that also adopt an archival protocol (`Codable`, `Encodable` or `Decodable`). When all their properties are themselves codable, Swift generates the archiving methods, and you don't need to write them down:
```swift
// This is just enough...
struct Player: RowConvertible, Persistable, Codable {
static let databaseTableName = "players"
let name: String
let score: Int
}
// ... so that you can save and fetch players:
try dbQueue.inDatabase { db in
try Player(name: "Arthur", score: 100).insert(db)
let players = try Player.fetchAll(db)
}
```
> :point_up: **Note**: Some types have a different way to encode and decode themselves in a standard archive vs. the database. For example, [Date](#date-and-datecomponents) saves itself as a numerical timestamp (archive) or a string (database). When such an ambiguity happens, GRDB always favors customized database encoding and decoding.
The Query Interface
===================
@@ -3121,7 +3181,7 @@ Player // SELECT * FROM players
```
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/2.0/Structs/StatementArguments.html):
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/2.1/Structs/StatementArguments.html):
```swift
// SELECT DATE(creationDate), COUNT(*) FROM players WHERE name = 'Arthur' GROUP BY date(creationDate)
@@ -3590,9 +3650,9 @@ try request.fetchOne(db) // Player?
**To build custom requests**, you can create your own type that adopts the protocols, or derive requests from other requests, or use one of the built-in concrete types:
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/2.0/Structs/SQLRequest.html): a Request built from raw SQL
- [AnyRequest](http://groue.github.io/GRDB.swift/docs/2.0/Structs/AnyRequest.html): a type-erased Request
- [AnyTypedRequest](http://groue.github.io/GRDB.swift/docs/2.0/Structs/AnyTypedRequest.html): a type-erased TypedRequest
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/2.1/Structs/SQLRequest.html): a Request built from raw SQL
- [AnyRequest](http://groue.github.io/GRDB.swift/docs/2.1/Structs/AnyRequest.html): a type-erased Request
- [AnyTypedRequest](http://groue.github.io/GRDB.swift/docs/2.1/Structs/AnyTypedRequest.html): a type-erased TypedRequest
Use the `asRequest(of:)` method to define the type fetched by the request:
@@ -4022,7 +4082,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
```
FTS3Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/2.0/Structs/StatementArguments.html):
FTS3Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/2.1/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
@@ -4235,7 +4295,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
```
FTS5Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/2.0/Structs/StatementArguments.html):
FTS5Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/2.1/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
@@ -4657,7 +4717,7 @@ dbQueue.inDatabase { db in
#### Support for SQLite Pre-Update Hooks
A [custom SQLite build](Documentation/CustomSQLiteBuilds.md) can activate [SQLite "preupdate hooks"](http://www.sqlite.org/sessions/c3ref/preupdate_count.html). In this case, TransactionObserverType gets an extra callback which lets you observe individual column values in the rows modified by a transaction:
A [custom SQLite build](Documentation/CustomSQLiteBuilds.md) can activate [SQLite "preupdate hooks"](https://sqlite.org/c3ref/preupdate_count.html). In this case, TransactionObserverType gets an extra callback which lets you observe individual column values in the rows modified by a transaction:
```swift
protocol TransactionObserverType : class {
@@ -4797,6 +4857,8 @@ controller.trackChanges { controller in
}
```
> :warning: **Warning**: notification of individual record changes (the `onChange` callback) has FetchedRecordsController use a diffing algorithm that has a high complexity, a high memory consumption, and is thus **not suited for large result sets**. One hundred rows is probably OK, but one thousand is probably not. If your application experiences problems with large lists, see [Issue 263](https://github.com/groue/GRDB.swift/issues/263) for more information.
Callbacks have the fetched record controller itself as an argument: use it in order to avoid memory leaks:
```swift
@@ -4969,7 +5031,9 @@ controller.trackChanges(
})
```
See [GRDBDemoiOS](DemoApps/GRDBDemoiOS/GRDBDemoiOS) for an sample app that uses FetchedRecordsController.
> :warning: **Warning**: notification of individual record changes (the `onChange` callback) has FetchedRecordsController use a diffing algorithm that has a high complexity, a high memory consumption, and is thus **not suited for large result sets**. One hundred rows is probably OK, but one thousand is probably not. If your application experiences problems with large lists, see [Issue 263](https://github.com/groue/GRDB.swift/issues/263) for more information.
See [GRDBDemoiOS](DemoApps/GRDBDemoiOS/GRDBDemoiOS) for an sample app that uses FetchedRecordsController to animate a table view.
> :point_up: **Note**: our sample code above uses `unowned` references to the table view controller. This is a safe pattern as long as the table view controller owns the fetched records controller, and is deallocated from the main thread (this is usually the case). In other situations, prefer weak references.
@@ -5021,7 +5085,7 @@ Alternatively, perform a manual installation of GRDB and SQLCipher:
```sh
cd [GRDB directory]
git checkout v2.0.2
git checkout v2.1.0
git submodule update --init SQLCipher/src
```
@@ -5128,7 +5192,7 @@ DROP TABLE students;
--' WHERE id = 1
```
To avoid those problems, **never embed raw values in your SQL queries**. The only correct technique is to provide [arguments](http://groue.github.io/GRDB.swift/docs/2.0/Structs/StatementArguments.html) to your SQL queries:
To avoid those problems, **never embed raw values in your SQL queries**. The only correct technique is to provide [arguments](http://groue.github.io/GRDB.swift/docs/2.1/Structs/StatementArguments.html) to your SQL queries:
```swift
// Good
@@ -5489,24 +5553,25 @@ For example, to explicitely use [complete](https://developer.apple.com/reference
```swift
// Paths
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let directoryPath = (documentsPath as NSString).appendingPathComponent("database")
let databasePath = (directoryPath as NSString).appendingPathComponent("db.sqlite")
let fileManager = FileManager.default
let directoryURL = try fileManager
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("database", isDirectory: true)
let databaseURL = directoryURL.appendingPathComponent("db.sqlite")
// Create directory if needed
let fm = FileManager.default
var isDirectory: ObjCBool = false
if !fm.fileExists(atPath: directoryPath, isDirectory: &isDirectory) {
try fm.createDirectory(atPath: directoryPath, withIntermediateDirectories: false)
if !fileManager.fileExists(atPath: directoryURL.path, isDirectory: &isDirectory) {
try fileManager.createDirectory(atPath: directoryURL.path, withIntermediateDirectories: false)
} else if !isDirectory.boolValue {
throw NSError(domain: NSCocoaErrorDomain, code: NSFileWriteFileExistsError, userInfo: nil)
}
// Enable data protection
try fm.setAttributes([.protectionKey : FileProtectionType.complete], ofItemAtPath: directoryPath)
try fileManager.setAttributes([.protectionKey : FileProtectionType.complete], ofItemAtPath: directoryURL.path)
// Open database
let dbQueue = try DatabaseQueue(path: databasePath)
let dbQueue = try DatabaseQueue(path: databaseURL.path)
```
When a database is protected, an application that runs in the background on a locked device won't be able to read or write from it. Instead, it will get [DatabaseError](#error-handling) with code [`SQLITE_IOERR`](https://www.sqlite.org/rescode.html#ioerr) (10) "disk I/O error", or [`SQLITE_AUTH`](https://www.sqlite.org/rescode.html#auth) (23) "not authorized".
@@ -5706,7 +5771,7 @@ try dbPool.write { db in
### DatabaseWriter and DatabaseReader Protocols
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/2.0/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/2.0/Protocols/DatabaseWriter.html) protocols.
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/2.1/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/2.1/Protocols/DatabaseWriter.html) protocols.
These protocols provide a unified API that lets you write safe concurrent code that targets both classes.
@@ -5714,7 +5779,7 @@ However, database queues are not database pools, and DatabaseReader and Database
- Pools are less forgiving than queues when one overlooks a transaction (see [concurrency rule 3](#guarantees-and-rules)).
- DatabaseWriter.readFromCurrentState is synchronous, or asynchronous, depending on whether it is run by a queue or a pool (see [advanced DatabasePool](#advanced-databasepool)). It thus requires higher libDispatch skills, and more complex synchronization code.
- The definition of "current state" in DatabaseWriter.readFromCurrentState is [delicate](http://groue.github.io/GRDB.swift/docs/2.0/Protocols/DatabaseWriter.html#/s:FP4GRDB14DatabaseWriter20readFromCurrentStateFzFCS_8DatabaseT_T_).
- The definition of "current state" in DatabaseWriter.readFromCurrentState is [delicate](http://groue.github.io/GRDB.swift/docs/2.1/Protocols/DatabaseWriter.html#/s:FP4GRDB14DatabaseWriter20readFromCurrentStateFzFCS_8DatabaseT_T_).
DatabaseReader and DatabaseWriter are not a tool for applications that hesitate between DatabaseQueue and DatabasePool, and look for a common API. As seen above, the protocols actually make applications harder to write correctly. Instead, they target generic code that has *both* queues and pools in mind. The built-in AnyDatabaseReader and AnyDatabaseWriter type erasers serve the same purpose.
@@ -5801,7 +5866,7 @@ If you absolutely need multiple connections, then:
- Read about [isolation in SQLite](https://www.sqlite.org/isolation.html)
- Learn about [locks and transactions](https://www.sqlite.org/lang_transaction.html)
- Become a master of the [WAL mode](https://www.sqlite.org/wal.html)
- Prepare to setup a [busy handler](https://www.sqlite.org/c3ref/busy_handler.html) with [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/2.0/Structs/Configuration.html)
- Prepare to setup a [busy handler](https://www.sqlite.org/c3ref/busy_handler.html) with [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/2.1/Structs/Configuration.html)
- [Ask questions](https://github.com/groue/GRDB.swift/issues)
@@ -6040,18 +6105,27 @@ for player in players {
FAQ
===
- [How do I close a database connection?](#how-do-i-close-a-database-connection)
- [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 print a request as SQL?](#how-do-i-print-a-request-as-sql)
- [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)
- [What Are Experimental Features?](#what-are-experimental-features)
### How do I close a database connection?
Database connections are managed by [database queues](#database-queues) and [pools](#database-pools). A connection is closed when its database queue or pool is deallocated, and all usages of this connection are completed.
### How do I create a database in my application?
Database accesses that run in background threads postpone the closing of connections.
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.
The database has to be stored in a valid place where it can be created and modified. For example, in the [Application Support directory](https://developer.apple.com/library/content/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html):
```swift
let databaseURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("db.sqlite")
let dbQueue = try DatabaseQueue(path: databaseURL.path)
```
### How do I open a database stored as a resource of my application?
@@ -6065,20 +6139,66 @@ let dbPath = Bundle.main.path(forResource: "db", ofType: "sqlite")!
let dbQueue = try DatabaseQueue(path: dbPath, configuration: configuration)
```
If the application should modify the database, you need to copy it to a place where it can be modified. For example, in the Documents folder. Only then, open a [connection](#database-connections):
If the application should modify the database, you need to copy it to a place where it can be modified. For example, in the [Application Support directory](https://developer.apple.com/library/content/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html). Only then, open a [connection](#database-connections):
```swift
let fm = FileManager.default
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let dbPath = (documentsPath as NSString).appendingPathComponent("db.sqlite")
if !fm.fileExists(atPath: dbPath) {
let fileManager = FileManager.default
let dbPath = try fileManager
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("db.sqlite")
.path
if !fileManager.fileExists(atPath: dbPath) {
let dbResourcePath = Bundle.main.path(forResource: "db", ofType: "sqlite")!
try fm.copyItem(atPath: dbResourcePath, toPath: dbPath)
try fileManager.copyItem(atPath: dbResourcePath, toPath: dbPath)
}
let dbQueue = try DatabaseQueue(path: dbPath)
```
### How do I close a database connection?
Database connections are managed by [database queues](#database-queues) and [pools](#database-pools). A connection is closed when its database queue or pool is deallocated, and all usages of this connection are completed.
Database accesses that run in background threads postpone the closing of connections.
### 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.
Use the `asSQLRequest` method:
```swift
try dbQueue.inDatabase { db in
let request = Wine
.filter(Column("origin") == "Burgundy")
.order(Column("price")
let sqlRequest = try request.asSQLRequest(db)
print(sqlRequest.sql)
// Prints SELECT * FROM wines WHERE origin = ? ORDER BY price
print(sqlRequest.arguments)
// Prints ["Burgundy"]
}
```
Another option is to setup a tracing function that will print out all SQL requests executed by your application. You provide the trace function when you connect to the database:
```swift
var config = Configuration()
config.trace = { print("SQL: \($0)") } // Prints all SQL statements
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
try dbQueue.inDatabase { db in
let wines = Wine
.filter(Column("origin") == "Burgundy")
.order(Column("price")
.fetchAll(db)
// Prints SELECT * FROM wines WHERE origin = 'Burgundy' ORDER BY price
}
```
### Generic parameter 'T' could not be inferred
You may get this error when using DatabaseQueue.inDatabase, DatabasePool.read, or DatabasePool.write:
@@ -6146,6 +6266,6 @@ Sample Code
**Thanks**
- [Pierlis](http://pierlis.com), where we write great software.
- [Vladimir Babin](https://github.com/Chiliec), [Pascal Edmond](https://github.com/pakko972), [Andrey Fidrya](https://github.com/zmeyc), [Cristian Filipov](https://github.com/cfilipov), [David Hart](https://github.com/hartbit), [Brad Lindsay](https://github.com/bfad), [@peter-ss](https://github.com/peter-ss), [Pierre-Loïc Raynaud](https://github.com/pierlo), [Stefano Rodriguez](https://github.com/sroddy) [Steven Schveighoffer](https://github.com/schveiguy), [@swiftlyfalling](https://github.com/swiftlyfalling), and [Kevin Wooten](https://github.com/kdubb) for their contributions, help, and feedback on GRDB.
- [Vladimir Babin](https://github.com/Chiliec), [Darren Clark](https://github.com/darrenclark), [Pascal Edmond](https://github.com/pakko972), [Andrey Fidrya](https://github.com/zmeyc), [Cristian Filipov](https://github.com/cfilipov), [David Hart](https://github.com/hartbit), [Brad Lindsay](https://github.com/bfad), [@peter-ss](https://github.com/peter-ss), [Pierre-Loïc Raynaud](https://github.com/pierlo), [Stefano Rodriguez](https://github.com/sroddy) [Steven Schveighoffer](https://github.com/schveiguy), [@swiftlyfalling](https://github.com/swiftlyfalling), and [Kevin Wooten](https://github.com/kdubb) for their contributions, help, and feedback on GRDB.
- [@aymerick](https://github.com/aymerick) and [Mathieu "Kali" Poumeyrol](https://github.com/kali) because SQL.
- [ccgus/fmdb](https://github.com/ccgus/fmdb) for its excellency.
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>2.0.2</string>
<string>2.1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+4 -3
View File
@@ -12,11 +12,12 @@
- [ ] REGEXP https://www.sqlite.org/lang_expr.html
- [ ] CASE x WHEN w1 THEN r1 WHEN w2 THEN r2 ELSE r3 END https://www.sqlite.org/lang_expr.html
- [ ] Write regression tests for #156 and #157
- [ ] Truncate optimization: tests for drop temp table, drop view, drop temp view
- [ ] "Documents" and "Application Support" directories: see https://github.com/ccgus/fmdb/commit/7ebbfd055c48d75dfb0119abbd9b5fc2f9001b9f#diff-2f831b88cf9e6758355acd8f88f7d996R16
GRDB 2.0
GRDB 3.0
- [ ] Document Record.updateChanges(_:)
- [ ] WIP on diff algorithms in RxGRDB needs access to MutablePersistable.databaseDictionary. The problem is that one should not need a writing protocol just to read. So consider introducing a new DatabaseEncodable protocol above MutablePersistable. It does not grant any writing methods. But it has encode(to:) and databaseDictionary.
- [ ] Rename Request to DatabaseRequest, SQLiteRequest, SQLRequest, because Request is a bad name: https://github.com/swift-server/http/pull/7#issuecomment-308448528
Not sure
+6 -6
View File
@@ -14,7 +14,7 @@
567374481B4D46600089DE44 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567374461B4D46600089DE44 /* LaunchScreen.storyboard */; };
568E2B991CACE4ED00426E7B /* SimplePersonsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568E2B981CACE4ED00426E7B /* SimplePersonsViewController.swift */; };
56AEC9D91CAA985700452D96 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AEC9D21CAA985700452D96 /* AppDelegate.swift */; };
56AEC9DA1CAA985700452D96 /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AEC9D31CAA985700452D96 /* Database.swift */; };
56AEC9DA1CAA985700452D96 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AEC9D31CAA985700452D96 /* AppDatabase.swift */; };
56AEC9DB1CAA985700452D96 /* DemoViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AEC9D41CAA985700452D96 /* DemoViewController.swift */; };
56AEC9DD1CAA985700452D96 /* Person.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AEC9D61CAA985700452D96 /* Person.swift */; };
56AEC9DE1CAA985700452D96 /* PersonEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AEC9D71CAA985700452D96 /* PersonEditionViewController.swift */; };
@@ -44,7 +44,7 @@
567374491B4D46600089DE44 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
568E2B981CACE4ED00426E7B /* SimplePersonsViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SimplePersonsViewController.swift; sourceTree = "<group>"; };
56AEC9D21CAA985700452D96 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
56AEC9D31CAA985700452D96 /* Database.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Database.swift; sourceTree = "<group>"; };
56AEC9D31CAA985700452D96 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
56AEC9D41CAA985700452D96 /* DemoViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DemoViewController.swift; sourceTree = "<group>"; };
56AEC9D61CAA985700452D96 /* Person.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Person.swift; sourceTree = "<group>"; };
56AEC9D71CAA985700452D96 /* PersonEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersonEditionViewController.swift; sourceTree = "<group>"; };
@@ -85,7 +85,7 @@
children = (
56AEC9D21CAA985700452D96 /* AppDelegate.swift */,
567374441B4D46600089DE44 /* Assets.xcassets */,
56AEC9D31CAA985700452D96 /* Database.swift */,
56AEC9D31CAA985700452D96 /* AppDatabase.swift */,
56AEC9D41CAA985700452D96 /* DemoViewController.swift */,
567374491B4D46600089DE44 /* Info.plist */,
567374461B4D46600089DE44 /* LaunchScreen.storyboard */,
@@ -193,7 +193,7 @@
56AEC9DD1CAA985700452D96 /* Person.swift in Sources */,
56AEC9DF1CAA985700452D96 /* PersonsViewController.swift in Sources */,
56AEC9DB1CAA985700452D96 /* DemoViewController.swift in Sources */,
56AEC9DA1CAA985700452D96 /* Database.swift in Sources */,
56AEC9DA1CAA985700452D96 /* AppDatabase.swift in Sources */,
568E2B991CACE4ED00426E7B /* SimplePersonsViewController.swift in Sources */,
56AEC9DE1CAA985700452D96 /* PersonEditionViewController.swift in Sources */,
56AEC9D91CAA985700452D96 /* AppDelegate.swift in Sources */,
@@ -263,7 +263,7 @@
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0;
SWIFT_VERSION = 4.0;
};
name = Debug;
};
@@ -300,7 +300,7 @@
IPHONEOS_DEPLOYMENT_TARGET = 9.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SWIFT_VERSION = 3.0;
SWIFT_VERSION = 4.0;
VALIDATE_PRODUCT = YES;
};
name = Release;
@@ -0,0 +1,93 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0900"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "567374371B4D46600089DE44"
BuildableName = "iOS.app"
BlueprintName = "iOS"
ReferencedContainer = "container:iOS.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "567374371B4D46600089DE44"
BuildableName = "iOS.app"
BlueprintName = "iOS"
ReferencedContainer = "container:iOS.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "567374371B4D46600089DE44"
BuildableName = "iOS.app"
BlueprintName = "iOS"
ReferencedContainer = "container:iOS.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "567374371B4D46600089DE44"
BuildableName = "iOS.app"
BlueprintName = "iOS"
ReferencedContainer = "container:iOS.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
+1 -1
View File
@@ -120,7 +120,7 @@ class FTS3TableBuilderTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", using: FTS3()) { t in
t.tokenizer = .unicode61(tokenCharacters: Set(".-".characters))
t.tokenizer = .unicode61(tokenCharacters: Set(".-"))
}
assertDidExecute(sql: "CREATE VIRTUAL TABLE \"documents\" USING fts3(tokenize=unicode61 \"tokenchars=-.\")")
}
+1 -1
View File
@@ -143,7 +143,7 @@ class FTS3TokenizerTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", using: FTS3()) { t in
t.tokenizer = .unicode61(tokenCharacters: Set(".-".characters))
t.tokenizer = .unicode61(tokenCharacters: Set(".-"))
}
XCTAssertTrue(match(db, "2016-10-04.txt", "2016-10-04.txt"))
+1 -1
View File
@@ -120,7 +120,7 @@ class FTS4TableBuilderTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", using: FTS4()) { t in
t.tokenizer = .unicode61(tokenCharacters: Set(".-".characters))
t.tokenizer = .unicode61(tokenCharacters: Set(".-"))
}
assertDidExecute(sql: "CREATE VIRTUAL TABLE \"documents\" USING fts4(tokenize=unicode61 \"tokenchars=-.\")")
}
@@ -615,7 +615,7 @@ class FetchedRecordsControllerTests: GRDBTestCase {
for step in steps {
recorder.transactionExpectation = expectation(description: "expectation")
try dbQueue.inTransaction { db in
try synchronizePersons(db, step.word.characters.enumerated().map { Person(id: Int64($0), name: String($1)) })
try synchronizePersons(db, step.word.enumerated().map { Person(id: Int64($0), name: String($1)) })
return .commit
}
waitForExpectations(timeout: 1, handler: nil)
+4 -9
View File
@@ -119,15 +119,10 @@ class GRDBTestCase: XCTestCase {
XCTAssertTrue(sqlQueries.contains(sql), "Did not execute \(sql)")
}
func assert(_ record: MutablePersistable, isEncodedIn row: Row) {
let recordContent = AnySequence({ PersistenceContainer(record).makeIterator() })
for (column, value) in recordContent {
if let dbValue: DatabaseValue = row[column] {
XCTAssertEqual(dbValue, value?.databaseValue ?? .null)
} else {
XCTFail("Missing column \(column) in fetched row")
}
}
func assert(_ record: MutablePersistable, isEncodedIn row: Row, file: StaticString = #file, line: UInt = #line) {
let recordDict = record.databaseDictionary
let rowDict = Dictionary(row, uniquingKeysWith: { (left, _) in left })
XCTAssertEqual(recordDict, rowDict, file: file, line: line)
}
// Compare SQL strings (ignoring leading and trailing white space and semicolons.
@@ -27,8 +27,9 @@ extension MutablePersistableEncodableTests {
}
var value = Struct(value: "foo")
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo"])
try value.insert(db)
let string = try String.fetchOne(db, "SELECT value FROM t1")!
XCTAssertEqual(string, "foo")
}
@@ -56,8 +57,9 @@ extension MutablePersistableEncodableTests {
}
var value = Struct(value: "foo")
try value.insert(db)
assert(value, isEncodedIn: ["someColumn": "foo (Encodable)"])
try value.insert(db)
let string = try String.fetchOne(db, "SELECT someColumn FROM t1")!
XCTAssertEqual(string, "foo (Encodable)")
}
@@ -80,8 +82,9 @@ extension MutablePersistableEncodableTests {
}
var value = Struct(value: "foo")
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo (MutablePersistable)"])
try value.insert(db)
let string = try String.fetchOne(db, "SELECT value FROM t1")!
XCTAssertEqual(string, "foo (MutablePersistable)")
}
@@ -109,8 +112,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(int64: 123, optionalInt64: 456)
try value.insert(db)
assert(value, isEncodedIn: ["int64": 123, "optionalInt64": 456])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["int64": 123, "optionalInt64": 456])
return .rollback
@@ -118,8 +122,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(int64: 123, optionalInt64: nil)
try value.insert(db)
assert(value, isEncodedIn: ["int64": 123, "optionalInt64": nil])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["int64": 123, "optionalInt64": nil])
return .rollback
@@ -152,8 +157,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(value: Value(string: "foo"), optionalValue: Value(string: "bar"))
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo", "optionalValue": "bar"])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["value": "foo", "optionalValue": "bar"])
return .rollback
@@ -161,8 +167,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(value: Value(string: "foo"), optionalValue: nil)
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo", "optionalValue": nil])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["value": "foo", "optionalValue": nil])
return .rollback
@@ -204,8 +211,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(value: Value(nestedValue: NestedValue(string: "foo")), optionalValue: Value(nestedValue: NestedValue(string: "bar")))
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo", "optionalValue": "bar"])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["value": "foo", "optionalValue": "bar"])
return .rollback
@@ -213,8 +221,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(value: Value(nestedValue: NestedValue(string: "foo")), optionalValue: nil)
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo", "optionalValue": nil])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["value": "foo", "optionalValue": nil])
return .rollback
@@ -247,8 +256,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(value: .foo, optionalValue: .bar)
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo", "optionalValue": "bar"])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["value": "foo", "optionalValue": "bar"])
return .rollback
@@ -256,8 +266,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(value: .foo, optionalValue: nil)
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo", "optionalValue": nil])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["value": "foo", "optionalValue": nil])
return .rollback
@@ -308,8 +319,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(value: Value(string: "foo"), optionalValue: Value(string: "bar"))
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo (DatabaseValueConvertible)", "optionalValue": "bar (DatabaseValueConvertible)"])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["value": "foo (DatabaseValueConvertible)", "optionalValue": "bar (DatabaseValueConvertible)"])
return .rollback
@@ -317,8 +329,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(value: Value(string: "foo"), optionalValue: nil)
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo (DatabaseValueConvertible)", "optionalValue": nil])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["value": "foo (DatabaseValueConvertible)", "optionalValue": nil])
return .rollback
@@ -370,8 +383,9 @@ extension MutablePersistableEncodableTests {
}
let value = StructWithURL(url: URL(string: "https://github.com")!)
try value.insert(db)
assert(value, isEncodedIn: ["url": value.url])
try value.insert(db)
let dbValue = try DatabaseValue.fetchOne(db, "SELECT url FROM t1")!
XCTAssert(dbValue.storage.value is String)
let fetchedURL = URL.fromDatabaseValue(dbValue)!
@@ -392,8 +406,9 @@ extension MutablePersistableEncodableTests {
}
let value = StructWithUUID(uuid: UUID())
try value.insert(db)
assert(value, isEncodedIn: ["uuid": value.uuid])
try value.insert(db)
let dbValue = try DatabaseValue.fetchOne(db, "SELECT uuid FROM t1")!
XCTAssert(dbValue.storage.value is Data)
let fetchedUUID = UUID.fromDatabaseValue(dbValue)!
+15
View File
@@ -50,4 +50,19 @@ class SQLRequestTests: GRDBTestCase {
XCTAssertTrue(statement1 === statement2)
}
}
func testAsSQLRequest() throws {
struct CustomRequest: Request {
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try SQLRequest("SELECT ?, ?", arguments: [1, "foo"]).prepare(db)
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = CustomRequest()
let sqlRequest = try request.asSQLRequest(db)
XCTAssertEqual(sqlRequest.sql, "SELECT ?, ?")
XCTAssertEqual(sqlRequest.arguments, [1, "foo"])
}
}
}
@@ -315,46 +315,6 @@ class TransactionObserverTests: GRDBTestCase {
}
}
func testTruncateOptimization() throws {
// https://www.sqlite.org/c3ref/update_hook.html
//
// > In the current implementation, the update hook is not invoked [...]
// > when rows are deleted using the truncate optimization.
//
// https://www.sqlite.org/lang_delete.html#truncateopt
//
// > When the WHERE is omitted from a DELETE statement and the table
// > being deleted has no triggers, SQLite uses an optimization to erase
// > the entire table content without having to visit each row of the
// > table individually.
//
// Here we test that the truncate optimization does not prevent
// transaction observers from observing individual deletions.
let dbQueue = try makeDatabaseQueue()
let observer = Observer()
dbQueue.add(transactionObserver: observer)
try dbQueue.inDatabase { db in
let artist1 = Artist(name: "Gerhard Richter")
let artist2 = Artist(name: "Vincent Fournier")
try artist1.insert(db)
try artist2.insert(db)
try db.execute("DELETE FROM artists")
XCTAssertEqual(observer.lastCommittedEvents.count, 2)
let artist1DeleteEvent = observer.lastCommittedEvents.filter {
self.match(event: $0, kind: .delete, tableName: "artists", rowId: artist1.id!)
}.first
XCTAssertTrue(artist1DeleteEvent != nil)
let artist2DeleteEvent = observer.lastCommittedEvents.filter {
self.match(event: $0, kind: .delete, tableName: "artists", rowId: artist1.id!)
}.first
XCTAssertTrue(artist2DeleteEvent != nil)
}
}
func testCascadingDeleteEvents() throws {
let dbQueue = try makeDatabaseQueue()
let observer = Observer()
@@ -0,0 +1,183 @@
import XCTest
#if GRDBCIPHER
import GRDBCipher
#elseif GRDBCUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
class TruncateOptimizationTests: GRDBTestCase {
// https://www.sqlite.org/c3ref/update_hook.html
//
// > In the current implementation, the update hook is not invoked [...]
// > when rows are deleted using the truncate optimization.
//
// https://www.sqlite.org/lang_delete.html#truncateopt
//
// > When the WHERE is omitted from a DELETE statement and the table
// > being deleted has no triggers, SQLite uses an optimization to erase
// > the entire table content without having to visit each row of the
// > table individually.
//
// We will thus test that the truncate optimization does not prevent
// transaction observers from observing individual deletions.
//
// But that's not enough: preventing the truncate optimization requires GRDB
// to fiddle with sqlite3_set_authorizer. When badly done, this can prevent
// DROP TABLE statements from dropping tables. SQLite3 authorizers are
// invoked during both compilation and execution of SQL statements. We will
// thus test that DROP TABLE statements perform as expected when compilation
// and execution are grouped, and when they are performed separately.
class DeletionObserver : TransactionObserver {
private var notify: ([String: Int]) -> Void
private var deletionEvents: [String: Int] = [:]
// Notifies table names with the number of deleted rows
init(_ notify: @escaping ([String: Int]) -> Void) {
self.notify = notify
}
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
return true
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
func databaseWillChange(with event: DatabasePreUpdateEvent) { }
#endif
func databaseDidChange(with event: DatabaseEvent) {
if case .delete = event.kind {
deletionEvents[event.tableName, default: 0] += 1
}
}
func databaseWillCommit() throws { }
func databaseDidCommit(_ db: Database) {
if !deletionEvents.isEmpty {
notify(deletionEvents)
}
deletionEvents = [:]
}
func databaseDidRollback(_ db: Database) {
deletionEvents = [:]
}
}
func testExecuteDelete() throws {
let dbQueue = try makeDatabaseQueue()
var deletionEvents: [[String: Int]] = []
let observer = DeletionObserver { deletionEvents.append($0) }
dbQueue.add(transactionObserver: observer, extent: .databaseLifetime)
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE t(a)")
try db.execute("INSERT INTO t VALUES (NULL)")
try db.execute("INSERT INTO t VALUES (NULL)")
deletionEvents = []
try db.execute("DELETE FROM t")
XCTAssertEqual(deletionEvents.count, 1)
XCTAssertEqual(deletionEvents[0], ["t": 2])
try db.execute("INSERT INTO t VALUES (NULL)")
deletionEvents = []
try db.execute("DELETE FROM t")
XCTAssertEqual(deletionEvents.count, 1)
XCTAssertEqual(deletionEvents[0], ["t": 1])
}
}
func testExecuteDeleteWithPreparedStatement() throws {
let dbQueue = try makeDatabaseQueue()
var deletionEvents: [[String: Int]] = []
let observer = DeletionObserver { deletionEvents.append($0) }
dbQueue.add(transactionObserver: observer, extent: .databaseLifetime)
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE t(a)")
let deleteStatement = try db.makeUpdateStatement("DELETE FROM t")
try db.execute("INSERT INTO t VALUES (NULL)")
try db.execute("INSERT INTO t VALUES (NULL)")
deletionEvents = []
try deleteStatement.execute()
XCTAssertEqual(deletionEvents.count, 1)
XCTAssertEqual(deletionEvents[0], ["t": 2])
try db.execute("INSERT INTO t VALUES (NULL)")
deletionEvents = []
try deleteStatement.execute()
XCTAssertEqual(deletionEvents.count, 1)
XCTAssertEqual(deletionEvents[0], ["t": 1])
}
}
func testDropTable() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE t(a)")
try db.execute("INSERT INTO t VALUES (NULL)")
try db.execute("DROP TABLE t") // compile + execute
try XCTAssertFalse(db.tableExists("t"))
}
}
func testDropTableWithPreparedStatement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE t(a)")
try db.execute("INSERT INTO t VALUES (NULL)")
let dropStatement = try db.makeUpdateStatement("DROP TABLE t") // compile...
try dropStatement.execute() // ... then execute
try XCTAssertFalse(db.tableExists("t"))
}
}
func testDropTemporaryTable() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TEMPORARY TABLE t(a)")
try db.execute("INSERT INTO t VALUES (NULL)")
try db.execute("DROP TABLE t") // compile + execute
try XCTAssertFalse(db.tableExists("t"))
}
}
func testDropTemporaryTableWithPreparedStatement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TEMPORARY TABLE t(a)")
try db.execute("INSERT INTO t VALUES (NULL)")
let dropStatement = try db.makeUpdateStatement("DROP TABLE t") // compile...
try dropStatement.execute() // ... then execute
try XCTAssertFalse(db.tableExists("t"))
}
}
func testDropVirtualTable() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE VIRTUAL TABLE t USING fts3(a)")
try db.execute("INSERT INTO t VALUES (NULL)")
try db.execute("DROP TABLE t") // compile + execute
try XCTAssertFalse(db.tableExists("t"))
}
}
func testDropVirtualTableWithPreparedStatement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE VIRTUAL TABLE t USING fts3(a)")
try db.execute("INSERT INTO t VALUES (NULL)")
let dropStatement = try db.makeUpdateStatement("DROP TABLE t") // compile...
try dropStatement.execute() // ... then execute
try XCTAssertFalse(db.tableExists("t"))
}
}
}
@@ -307,20 +307,4 @@ class UpdateStatementTests : GRDBTestCase {
}
}
}
func testDropTablePreparedStatement() throws {
// In v2.0.1...
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
XCTAssertFalse(try db.tableExists("t"))
try db.execute("CREATE TABLE t(a)")
XCTAssertTrue(try db.tableExists("t"))
try db.execute("DROP TABLE t") // ... this would drop the table
XCTAssertFalse(try db.tableExists("t"))
try db.execute("CREATE TABLE t(a)")
XCTAssertTrue(try db.tableExists("t"))
try db.makeUpdateStatement("DROP TABLE t").execute() // ... but this would not. WTF??? Hence this regression test.
XCTAssertFalse(try db.tableExists("t"))
}
}
}