Compare commits

...
37 Commits
Author SHA1 Message Date
Gwendal Roué 21fdc9f350 v1.3.0 2017-08-18 13:13:24 +02:00
Gwendal Roué 398c0ef687 Documentation 2017-08-18 12:25:22 +02:00
Gwendal Roué 3b0a9aef3c No more SQLite 3.20.0 TODO 2017-08-18 08:52:48 +02:00
Gwendal Roué 48ec0916bf Use SQLITE_PREPARE_PERSISTENT flag for cached statements 2017-08-18 08:52:23 +02:00
Gwendal Roué 10af87a7d0 SQLite 3.20.0 2017-08-18 08:35:02 +02:00
Gwendal Roué 96e7996f37 SQLite 3.20.0 TODO 2017-08-03 10:19:52 +02:00
Gwendal Roué 0f7af931a9 SQLite 3.20.0 TODO 2017-08-03 10:16:17 +02:00
Gwendal Roué cfd2d80b78 Fix typo 2017-07-30 15:22:13 +02:00
Gwendal Roué 0386c01aa9 CHANGELOG 2017-07-29 14:36:02 +02:00
Gwendal Roué 2c39c91ac6 CHANGELOG 2017-07-29 13:01:49 +02:00
Gwendal Roué 0eb51e3e8b Int8, Int16, UInt, UInt8, UInt16, UInt32, UInt64 adopt DatabaseValueConvertible and StatementColumnConvertible 2017-07-29 12:58:35 +02:00
Gwendal Roué bb931e9da7 FTS5.api(_:) can now throw an error 2017-07-21 18:34:19 +02:00
Gwendal Roué 7b2e672496 Cleanup 2017-07-21 17:59:04 +02:00
Gwendal Roué cdc6370ee5 Restore column ordering in filter(db, keys: [["a": ..., "b": ...], ...]) removed in 2b2e92c810 2017-07-21 13:45:24 +02:00
Gwendal Roué cc762e4e1d TODO 2017-07-21 12:20:32 +02:00
Gwendal Roué ed525bd1d8 Cleanup 2017-07-21 12:15:35 +02:00
Gwendal Roué 2b2e92c810 Cleanup 2017-07-21 12:13:03 +02:00
Gwendal Roué 44d31ead76 Implement deleteAll(_:keys:), deleteOne(_🔑) on top of the Query Interface 2017-07-21 11:19:24 +02:00
Gwendal Roué ec163e94eb Implement fetchCursor(_:keys:), fetchAll(_:keys:), and fetchOne(_🔑) on top of the Query Interface 2017-07-21 09:13:20 +02:00
Gwendal Roué ec2ac33fec TODO.md 2017-07-21 07:58:25 +02:00
Gwendal Roué 20bda2af26 v1.2.2 2017-07-20 19:30:39 +02:00
Gwendal Roué 7a49f6293d CHANGELOG.md 2017-07-20 17:50:14 +02:00
Gwendal Roué 81b21010f1 Fix memory leak with Configuration.trace 2017-07-20 17:47:11 +02:00
Gwendal Roué 2526e0a2f7 Fix links to reference documentation 2017-07-19 19:40:19 +02:00
Gwendal Roué af1e8470c9 v1.2.1 2017-07-19 09:38:25 +02:00
Gwendal Roué dfd9da68a7 CHANGELOG 2017-07-19 08:32:21 +02:00
Gwendal Roué 5e702234f4 Upgrade SQLite to v3.19.3 2017-07-19 08:31:32 +02:00
Gwendal Roué 9020dcca9a CHANGELOG 2017-07-19 08:28:02 +02:00
Gwendal Roué 930a4e4c1d Improve implementation comments in DatabasePool.readFromCurrentState 2017-07-19 08:22:23 +02:00
Gwendal Roué 4db77f96b7 Improve implementation comments in DatabasePool.readFromCurrentState 2017-07-18 16:34:50 +02:00
Gwendal Roué cc12c046b9 func === (lhs: SQLExpressible?, rhs: SQLCollatedExpression) bugfix 2017-07-18 09:00:49 +02:00
Gwendal Roué f5c63e0997 Remove unused method 2017-07-18 07:48:43 +02:00
Gwendal Roué 29a26800b7 Cleanup 2017-07-17 20:20:20 +02:00
Gwendal Roué bc5eeb3b3a expr == DatabaseValue.null is converted to expr IS NULL. 2017-07-17 20:19:19 +02:00
Gwendal Roué 40d02518b0 Cleanup 2017-07-17 15:33:09 +02:00
Gwendal Roué a2556edc69 Use sqlite3_get_autocommit
This function knows whether the database is currently inside a
transaction or not, and provides robust rollback error handling.
2017-07-17 15:33:01 +02:00
Gwendal Roué 111970fda9 Tests for public protocols and open classes
The goal of those tests is to prevent breaking changes as the one that happened in v1.2, where the DatabaseReader protocol was added a new method without any default implementation.
2017-07-13 16:53:01 +02:00
37 changed files with 1032 additions and 435 deletions

No files matched your search

+48
View File
@@ -1,6 +1,54 @@
Release Notes
=============
## 1.3.0
Released August 18, 2017
**New**
- Upgrade custom SQLite builds to [v3.20.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- Complete support for all signed and unsigned integer types: from Int8 toUInt64, all integers can be stored and loaded from the database.
**API diff**
```diff
+extension Int8: DatabaseValueConvertible, StatementColumnConvertible { }
+extension Int16: DatabaseValueConvertible, StatementColumnConvertible { }
+extension UInt8: DatabaseValueConvertible, StatementColumnConvertible { }
+extension UInt16: DatabaseValueConvertible, StatementColumnConvertible { }
+extension UInt32: DatabaseValueConvertible, StatementColumnConvertible { }
+extension UInt64: DatabaseValueConvertible, StatementColumnConvertible { }
+extension UInt: DatabaseValueConvertible, StatementColumnConvertible { }
```
## 1.2.2
Released July 20, 2017
**Fixed**
- The `Configuration.trace` function no longer leaks memory.
## 1.2.1
Released July 19, 2017
**Fixed**
- Upgrade custom SQLite builds to [v3.19.3](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- The [Query Interface](https://github.com/groue/GRDB.swift/#the-query-interface) now generates `IS NULL` SQL snippets for comparisons with `DatabaseValue.null`:
```swift
// SELECT * FROM players WHERE email IS NULL
Player.filter(Column("email") == DatabaseValue.null)
```
It used to generate `= NULL` which would not behave as expected.
## 1.2
Released July 13, 2017
+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.19.2](https://www.sqlite.org/changes.html).**
**You can build GRDB with a custom build of [SQLite 3.20.0](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.swift directory]
git checkout v1.2
git checkout v1.3.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/1.2/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/1.2/Functions.html) functions:
Build a `COUNT(...)` expression from the [count](http://groue.github.io/GRDB.swift/docs/1.3/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/1.3/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/1.2/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/1.3/Protocols/SQLExpression.html) protocol.
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '1.2'
s.version = '1.3.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A Swift application toolkit for SQLite databases.'
+45 -1
View File
@@ -292,6 +292,22 @@
562756481E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
562756491E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
5627564A1E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
562EA8261F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
562EA8271F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
562EA8281F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
562EA8291F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
562EA82A1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
562EA82B1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
562EA82C1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
562EA82D1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
562EA82F1F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; };
562EA8301F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; };
562EA8311F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; };
562EA8321F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; };
562EA8331F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; };
562EA8341F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; };
562EA8351F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; };
562EA8361F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; };
56300B5F1C53C38F005A543B /* QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */; };
56300B621C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */; };
56300B691C53D25E005A543B /* QueryInterfaceExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */; };
@@ -1900,6 +1916,8 @@
562393711DEE104400A6B01F /* MapCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MapCursorTests.swift; sourceTree = "<group>"; };
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = "<group>"; };
562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = "<group>"; };
562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = "<group>"; };
562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = "<group>"; };
56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequestTests.swift; sourceTree = "<group>"; };
56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "RowConvertible+QueryInterfaceRequestTests.swift"; sourceTree = "<group>"; };
56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceExpressionsTests.swift; sourceTree = "<group>"; };
@@ -2421,10 +2439,11 @@
56176C581EACC2D8000F3F2B /* GRDBTests */ = {
isa = PBXGroup;
children = (
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */,
562EA81E1F17B26F00FA528C /* Compilation */,
56A238111B9C74A90082EB20 /* Core */,
5698AC3E1DA2BEBB0056AF8C /* FTS */,
56176CA01EACEE2A000F3F2B /* GRDBCipher */,
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */,
56A238231B9C74A90082EB20 /* Migrations */,
569978D31B539038005EBEED /* Private */,
56300B5C1C53C38F005A543B /* QueryInterface */,
@@ -2481,6 +2500,15 @@
name = GRDBCipher;
sourceTree = "<group>";
};
562EA81E1F17B26F00FA528C /* Compilation */ = {
isa = PBXGroup;
children = (
562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */,
562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */,
);
name = Compilation;
sourceTree = "<group>";
};
56300B5C1C53C38F005A543B /* QueryInterface */ = {
isa = PBXGroup;
children = (
@@ -3924,11 +3952,13 @@
560FC5621CB00B880014AA8E /* Record+QueryInterfaceRequestTests.swift in Sources */,
5698ACD81DA925420056AF8C /* RowTestCase.swift in Sources */,
56A8C2411D1918EE0096E9D4 /* FoundationNSUUIDTests.swift in Sources */,
562EA8301F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */,
562206031E420EA3005860AC /* DatabasePoolBackupTests.swift in Sources */,
5657AB571D108BA9006283EF /* FoundationNSStringTests.swift in Sources */,
564448841EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
560FC5B21CB031E30014AA8E /* StatementColumnConvertibleFetchTests.swift in Sources */,
561667021D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */,
562EA8271F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */,
569C1EB31CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */,
560FC5651CB00B880014AA8E /* RecordPrimaryKeyNoneTests.swift in Sources */,
560FC5661CB00B880014AA8E /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
@@ -4161,11 +4191,13 @@
5671561F1CB16729007DC145 /* Record+QueryInterfaceRequestTests.swift in Sources */,
5698ACD91DA925420056AF8C /* RowTestCase.swift in Sources */,
567156221CB16729007DC145 /* StatementColumnConvertibleFetchTests.swift in Sources */,
562EA8311F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */,
562206001E420EA3005860AC /* DatabasePoolBackupTests.swift in Sources */,
567156231CB16729007DC145 /* RecordPrimaryKeyNoneTests.swift in Sources */,
564448851EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
567156241CB16729007DC145 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
567156251CB16729007DC145 /* RowFromDictionaryTests.swift in Sources */,
562EA8281F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */,
565F03C41CE5D3AA00DE108F /* RowAdapterTests.swift in Sources */,
567156261CB16729007DC145 /* SelectStatementTests.swift in Sources */,
567156281CB16729007DC145 /* QueryInterfaceExpressionsTests.swift in Sources */,
@@ -4378,11 +4410,13 @@
56F26C241CEE3F34007969C4 /* RowAdapterTests.swift in Sources */,
56AFCA311CB1AA9900F48B96 /* RecordPrimaryKeyNoneTests.swift in Sources */,
56AFCA321CB1AA9900F48B96 /* DatabaseQueueConcurrencyTests.swift in Sources */,
562EA8341F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */,
5698ACD31DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */,
56AFCA331CB1AA9900F48B96 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
564448881EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
56AFCA341CB1AA9900F48B96 /* RowFromDictionaryTests.swift in Sources */,
569C1EB61CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */,
562EA82B1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */,
56DAA2D71DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */,
5698AC4E1DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */,
567E55EE1D2BDD3F00CC6F79 /* EncryptionTests.swift in Sources */,
@@ -4509,11 +4543,13 @@
56AFCA891CB1ABC800F48B96 /* Record+QueryInterfaceRequestTests.swift in Sources */,
56AFCA8A1CB1ABC800F48B96 /* RecordPrimaryKeyNoneTests.swift in Sources */,
56AFCA8B1CB1ABC800F48B96 /* DatabaseQueueConcurrencyTests.swift in Sources */,
562EA8351F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */,
5698ACD41DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */,
56AFCA8C1CB1ABC800F48B96 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
564448891EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
56AFCA8D1CB1ABC800F48B96 /* RowFromDictionaryTests.swift in Sources */,
5657AB541D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */,
562EA82C1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */,
56DAA2D81DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */,
5698AC4F1DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */,
56AFCA8F1CB1ABC800F48B96 /* DatabaseCollationTests.swift in Sources */,
@@ -4725,11 +4761,13 @@
56DAA2D61DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */,
56FF45441D2C23BA00F21EF9 /* TableMappingDeleteByKeyTests.swift in Sources */,
56A238561B9C74A90082EB20 /* RecordPrimaryKeyNoneTests.swift in Sources */,
562EA8331F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */,
563363BE1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift in Sources */,
56A238501B9C74A90082EB20 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
564448871EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
56A238461B9C74A90082EB20 /* RowFromDictionaryTests.swift in Sources */,
569C1EB51CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */,
562EA82A1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */,
564A50C81BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift in Sources */,
56E8CE111BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift in Sources */,
56300B691C53D25E005A543B /* QueryInterfaceExpressionsTests.swift in Sources */,
@@ -4856,11 +4894,13 @@
56D496591D81304E008276D7 /* FoundationNSDateTests.swift in Sources */,
56D4968B1D81316E008276D7 /* NumericOverflowTests.swift in Sources */,
56D496B31D8133E3008276D7 /* IndexInfoTests.swift in Sources */,
562EA82F1F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */,
5698AC961DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */,
56D4966D1D81309E008276D7 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */,
564448831EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
56D496811D813131008276D7 /* TransactionObserverSavepointsTests.swift in Sources */,
56D496AB1D8132CA008276D7 /* DatabasePoolFunctionTests.swift in Sources */,
562EA8261F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */,
56D496691D813086008276D7 /* QueryInterfaceExpressionsTests.swift in Sources */,
562393691DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */,
562205F21E420E47005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */,
@@ -5159,11 +5199,13 @@
F3BA810C1CFB3056003DC1BA /* StatementArguments+FoundationTests.swift in Sources */,
F3BA80B91CFB2FD1003DC1BA /* DatabasePoolBackupTests.swift in Sources */,
F3BA811E1CFB3063003DC1BA /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
562EA8361F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */,
5623934C1DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */,
F3BA80DD1CFB300E003DC1BA /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
5644488A1EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
F3BA80521CFB2B59003DC1BA /* DatabaseQueueSchemaCacheTests.swift in Sources */,
F3BA80BE1CFB2FD1003DC1BA /* DatabasePoolReadOnlyTests.swift in Sources */,
562EA82D1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */,
F3BA80C61CFB2FD8003DC1BA /* DatabaseQueueConcurrencyTests.swift in Sources */,
F3BA81161CFB305E003DC1BA /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */,
F3BA80F41CFB301D003DC1BA /* StatementColumnConvertibleFetchTests.swift in Sources */,
@@ -5376,11 +5418,13 @@
F3BA81101CFB3057003DC1BA /* Row+FoundationTests.swift in Sources */,
F3BA812C1CFB3064003DC1BA /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
5698AC991DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */,
562EA8321F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */,
56A8C2451D1918EF0096E9D4 /* FoundationNSUUIDTests.swift in Sources */,
5657AB591D108BA9006283EF /* FoundationNSStringTests.swift in Sources */,
564448861EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
5698ACCB1DA62A2D0056AF8C /* FTS5TokenizerTests.swift in Sources */,
56B14E821D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */,
562EA8291F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */,
56FF45591D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */,
56B021CC1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */,
561667041D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */,
+99 -53
View File
@@ -294,10 +294,18 @@ public final class Database {
var lastErrorMessage: String? { return String(cString: sqlite3_errmsg(sqliteConnection)) }
/// True if the database connection is currently in a transaction.
public var isInsideTransaction: Bool { return isInsideExplicitTransaction || !savepointStack.isEmpty }
/// Set by BEGIN/ROLLBACK/COMMIT transaction statements.
fileprivate var isInsideExplicitTransaction: Bool = false
public var isInsideTransaction: Bool {
// https://sqlite.org/c3ref/get_autocommit.html
//
// > The sqlite3_get_autocommit() interface returns non-zero or zero if
// > the given database connection is or is not in autocommit mode,
// > respectively.
//
// > Autocommit mode is on by default. Autocommit mode is disabled by a
// > BEGIN statement. Autocommit mode is re-enabled by a COMMIT
// > or ROLLBACK.
return sqlite3_get_autocommit(sqliteConnection) == 0
}
/// Set by SAVEPOINT/COMMIT/ROLLBACK/RELEASE savepoint statements.
fileprivate var savepointStack = SavepointStack()
@@ -471,6 +479,7 @@ public final class Database {
guard let stmt = stmt else { return SQLITE_OK }
guard let expandedSQLCString = sqlite3_expanded_sql(OpaquePointer(stmt)) else { return SQLITE_OK }
let sql = String(cString: expandedSQLCString)
sqlite3_free(expandedSQLCString)
let database = unsafeBitCast(dbPointer, to: Database.self)
database.configuration.trace!(sql)
return SQLITE_OK
@@ -487,6 +496,7 @@ public final class Database {
guard let stmt = stmt else { return SQLITE_OK }
guard let expandedSQLCString = sqlite3_expanded_sql(OpaquePointer(stmt)) else { return SQLITE_OK }
let sql = String(cString: expandedSQLCString)
sqlite3_free(expandedSQLCString)
let database = unsafeBitCast(dbPointer, to: Database.self)
database.configuration.trace!(sql)
return SQLITE_OK
@@ -683,7 +693,22 @@ extension Database {
/// - returns: A SelectStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func makeSelectStatement(_ sql: String) throws -> SelectStatement {
return try SelectStatement(database: self, sql: sql)
return try makeSelectStatement(sql, prepFlags: 0)
}
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM persons WHERE age > ?", prepFlags: 0)
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
///
/// - parameter sql: An SQL query.
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
/// - returns: A SelectStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
func makeSelectStatement(_ sql: String, prepFlags: Int32) throws -> SelectStatement {
return try SelectStatement(database: self, sql: sql, prepFlags: prepFlags)
}
/// Returns a prepared statement that can be reused.
@@ -720,7 +745,22 @@ extension Database {
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func makeUpdateStatement(_ sql: String) throws -> UpdateStatement {
return try UpdateStatement(database: self, sql: sql)
return try makeUpdateStatement(sql, prepFlags: 0)
}
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeUpdateStatement("INSERT INTO persons (name) VALUES (?)", prepFlags: 0)
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
///
/// - parameter sql: An SQL query.
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
func makeUpdateStatement(_ sql: String, prepFlags: Int32) throws -> UpdateStatement {
return try UpdateStatement(database: self, sql: sql, prepFlags: prepFlags)
}
/// Returns a prepared statement that can be reused.
@@ -1200,7 +1240,7 @@ extension Database {
/// If there exists a unique key on columns, return the columns
/// ordered as the matching index (or primay key). Case of returned columns
/// is not guaranteed.
func columnsForUniqueKey(_ columns: [String], in tableName: String) throws -> [String]? {
func columnsForUniqueKey<T: Sequence>(_ columns: T, in tableName: String) throws -> [String]? where T.Iterator.Element == String {
let primaryKey = try self.primaryKey(tableName) // first, so that we fail early and consistently should the table not exist
let lowercasedColumns = Set(columns.map { $0.lowercased() })
if let index = try indexes(on: tableName).first(where: { index in index.isUnique && Set(index.columns.map { $0.lowercased() }) == lowercasedColumns }) {
@@ -1629,7 +1669,7 @@ extension Database {
if needsRollback {
do {
try rollback(underlyingError: firstError)
try rollback()
} catch {
if firstError == nil {
firstError = error
@@ -1706,7 +1746,7 @@ extension Database {
if needsRollback {
do {
if topLevelSavepoint {
try rollback(underlyingError: firstError)
try rollback()
} else {
// Rollback, and release the savepoint.
// Rollback alone is not enough to clear the savepoint from
@@ -1737,36 +1777,48 @@ extension Database {
}
}
private func rollback(underlyingError: Error?) throws {
do {
private func rollback() throws {
// The SQLite documentation contains two related but distinct techniques
// to handle rollbacks and errors:
//
// https://www.sqlite.org/lang_transaction.html#immediate
//
// > Response To Errors Within A Transaction
// >
// > If certain kinds of errors occur within a transaction, the
// > transaction may or may not be rolled back automatically.
// > The errors that can cause an automatic rollback include:
// >
// > - SQLITE_FULL: database or disk full
// > - SQLITE_IOERR: disk I/O error
// > - SQLITE_BUSY: database in use by another process
// > - SQLITE_NOMEM: out or memory
// >
// > [...] It is recommended that applications respond to the
// > errors listed above by explicitly issuing a ROLLBACK
// > command. If the transaction has already been rolled back
// > automatically by the error response, then the ROLLBACK
// > command will fail with an error, but no harm is caused
// > by this.
//
// https://sqlite.org/c3ref/get_autocommit.html
//
// > The sqlite3_get_autocommit() interface returns non-zero or zero if
// > the given database connection is or is not in autocommit mode,
// > respectively.
// >
// > [...] If certain kinds of errors occur on a statement within a
// > multi-statement transaction (errors including SQLITE_FULL,
// > SQLITE_IOERR, SQLITE_NOMEM, SQLITE_BUSY, and SQLITE_INTERRUPT) then
// > the transaction might be rolled back automatically. The only way to
// > find out whether SQLite automatically rolled back the transaction
// > after an error is to use this function.
//
// The second technique is more robust, because we don't have to guess
// which rollback errors should be ignored, and which rollback errors
// should be exposed to the library user.
if sqlite3_get_autocommit(sqliteConnection) == 0 {
try execute("ROLLBACK TRANSACTION")
} catch {
// https://www.sqlite.org/lang_transaction.html#immediate
//
// > Response To Errors Within A Transaction
// >
// > If certain kinds of errors occur within a transaction, the
// > transaction may or may not be rolled back automatically.
// > The errors that can cause an automatic rollback include:
// >
// > - SQLITE_FULL: database or disk full
// > - SQLITE_IOERR: disk I/O error
// > - SQLITE_BUSY: database in use by another process
// > - SQLITE_NOMEM: out or memory
// >
// > [...] It is recommended that applications respond to the
// > errors listed above by explicitly issuing a ROLLBACK
// > command. If the transaction has already been rolled back
// > automatically by the error response, then the ROLLBACK
// > command will fail with an error, but no harm is caused
// > by this.
//
// TODO: test that isInsideTransaction, savepointStack, transaction
// observers, etc. are in good shape when such an implicit rollback
// happens.
guard let underlyingError = underlyingError as? DatabaseError, [.SQLITE_FULL, .SQLITE_IOERR, .SQLITE_BUSY, .SQLITE_NOMEM].contains(underlyingError.resultCode) else {
throw error
}
}
}
@@ -1884,9 +1936,11 @@ extension Database {
}
func updateStatementWillExecute(_ statement: UpdateStatement) {
// Grab the transaction observers that are interested in the actions
// performed by the statement.
let databaseEventKinds = statement.databaseEventKinds
activeTransactionObservers = transactionObservers.filter { observer in
return databaseEventKinds.index(where: observer.observes) != nil
return databaseEventKinds.contains(where: observer.observes)
}
}
@@ -1947,7 +2001,7 @@ extension Database {
case .transaction(action: let action):
switch action {
case .begin:
isInsideExplicitTransaction = true
break
case .commit:
if case .pending = self.transactionHookState {
// A COMMIT statement has ended a deferred transaction
@@ -1997,7 +2051,7 @@ extension Database {
}
}
/// Transaction hook
/// See sqlite3_commit_hook
func willCommit() throws {
let eventsBuffer = savepointStack.eventsBuffer
savepointStack.clear()
@@ -2013,12 +2067,10 @@ extension Database {
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
/// Transaction hook
/// See sqlite3_preupdate_hook
private func willChange(with event: DatabasePreUpdateEvent) {
if savepointStack.isEmpty {
// Don't notify all transactionObservers about the database event.
// Only notify those that are interested in the event, and have been
// isolated in updateStatementWillExecute().
// Notify all interested transactionObservers.
for observer in activeTransactionObservers {
observer.databaseWillChange(with: event)
}
@@ -2029,12 +2081,10 @@ extension Database {
}
#endif
/// Transaction hook
/// See sqlite3_update_hook
private func didChange(with event: DatabaseEvent) {
if savepointStack.isEmpty {
// Don't notify all transactionObservers about the database event.
// Only notify those that are interested in the event, and have been
// isolated in updateStatementWillExecute().
// Notify all interested transactionObservers.
for observer in activeTransactionObservers {
observer.databaseDidChange(with: event)
}
@@ -2044,9 +2094,7 @@ extension Database {
}
}
/// Transaction hook
private func didCommit() {
isInsideExplicitTransaction = false
savepointStack.clear()
for observer in transactionObservers {
@@ -2055,9 +2103,7 @@ extension Database {
cleanupTransactionObservers()
}
/// Transaction hook
private func didRollback(notifyTransactionObservers: Bool) {
isInsideExplicitTransaction = false
savepointStack.clear()
if notifyTransactionObservers {
+50 -34
View File
@@ -538,48 +538,64 @@ extension DatabasePool : DatabaseWriter {
/// - throws: The error thrown by the block, or any DatabaseError that would
/// happen while establishing the read access to the database.
public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws {
// https://www.sqlite.org/isolation.html
//
// > In WAL mode, SQLite exhibits "snapshot isolation". When a read
// > transaction starts, that reader continues to see an unchanging
// > "snapshot" of the database file as it existed at the moment in time
// > when the read transaction started. Any write transactions that
// > commit while the read transaction is active are still invisible to
// > the read transaction, because the reader is seeing a snapshot of
// > database file from a prior moment in time.
//
// That's exactly what we need. But what does "when read transaction
// starts" mean?
//
// http://www.sqlite.org/lang_transaction.html
//
// > Deferred [transaction] means that no locks are acquired on the
// > database until the database is first accessed. [...] Locks are not
// > acquired until the first read or write operation. [...] Because the
// > acquisition of locks is deferred until they are needed, it is
// > possible that another thread or process could create a separate
// > transaction and write to the database after the BEGIN on the
// > current thread has executed.
//
// Now that's precise enough: SQLite defers "snapshot isolation" until
// the first SELECT:
//
// Reader Writer
// BEGIN DEFERRED TRANSACTION
// UPDATE ... (1)
// Here the change (1) is visible
// SELECT ...
// UPDATE ... (2)
// Here the change (2) is not visible
//
// The readFromCurrentState method says that no change should be visible
// at all. We thus have to perform a select that establishes the
// snapshot isolation before we release the writer queue:
//
// Reader Writer
// BEGIN DEFERRED TRANSACTION
// SELECT anything
// UPDATE ...
// Here the change is not visible by GRDB user
// This method must be called from the writing dispatch queue:
writer.preconditionValidQueue()
// The semaphore that blocks the writing dispatch queue until snapshot
// isolation has been established:
let semaphore = DispatchSemaphore(value: 0)
var readError: Error? = nil
try readerPool.get { reader in
reader.async { db in
// https://www.sqlite.org/isolation.html
//
// > In WAL mode, SQLite exhibits "snapshot isolation". When a
// > read transaction starts, that reader continues to see an
// > unchanging "snapshot" of the database file as it existed at
// > the moment in time when the read transaction started.
// > Any write transactions that commit while the read
// > transaction is active are still invisible to the read
// > transaction, because the reader is seeing a snapshot of
// > database file from a prior moment in time.
//
// This documentation is NOT accurate. SQLite actually defers
// isolation until the first SELECT:
//
// Reader Writer
// BEGIN DEFERRED TRANSACTION
// UPDATE ... (1)
// Here the change (1) is visible
// SELECT ...
// UPDATE ... (2)
// Here the change (2) is not visible
//
// This is not the guarantee expected by this method: no change
// at all should be visible.
//
// Workaround: perform an initial read before releasing the
// writer queue:
//
// Reader Writer
// BEGIN DEFERRED TRANSACTION
// SELECT anything -- the work around
// UPDATE ...
// Here the change is not visible by GRDB user
do {
try db.beginTransaction(.deferred)
assert(db.isInsideTransaction)
try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").cursor().next() // doesn't work with cached statement
try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").cursor().next()
} catch {
readError = error
semaphore.signal() // Release the writer queue and rethrow error
-9
View File
@@ -95,15 +95,6 @@ public final class Row {
self.init(impl: StatementCopyRowImpl(sqliteStatement: sqliteStatement, columnNames: statementRef.takeUnretainedValue().columnNames))
}
/// Creates a row from the *current state* of the SQLite statement.
///
/// The row is implemented on top of StatementCopyRowImpl, which *copies*
/// the values from the SQLite statement so that further iteration of the
/// statement does not modify the row.
convenience init(copiedFromSQLiteStatement sqliteStatement: SQLiteStatement, columnNames: [String]) {
self.init(impl: StatementCopyRowImpl(sqliteStatement: sqliteStatement, columnNames: columnNames))
}
init(impl: RowImpl) {
self.impl = impl
self.statementRef = nil
+58 -8
View File
@@ -31,7 +31,14 @@ public class Statement {
self.sqliteStatement = sqliteStatement
}
fileprivate init(database: Database, sql: String, observer: StatementCompilationObserver) throws {
/// Creates a prepared statement.
///
/// - parameter database: A database connection.
/// - parameter sql: An SQL query.
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
/// - parameter observer: A StatementCompilationObserver
fileprivate init(database: Database, sql: String, prepFlags: Int32, observer: StatementCompilationObserver) throws {
SchedulingWatchdog.preconditionValidQueue(database)
observer.start()
@@ -44,7 +51,12 @@ public class Statement {
sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
let sqlStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
var sqlEnd: UnsafePointer<Int8>? = nil
code = sqlite3_prepare_v2(database.sqliteConnection, sqlStart, -1, &sqliteStatement, &sqlEnd)
// sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
#if GRDBCUSTOMSQLITE
code = sqlite3_prepare_v3(database.sqliteConnection, sqlStart, -1, UInt32(bitPattern: prepFlags), &sqliteStatement, &sqlEnd)
#else
code = sqlite3_prepare_v2(database.sqliteConnection, sqlStart, -1, &sqliteStatement, &sqlEnd)
#endif
let remainingData = Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: sqlEnd!), count: sqlStart + sqlCodeUnits.count - sqlEnd! - 1, deallocator: .none)
remainingSQL = String(data: remainingData, encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines)
}
@@ -211,10 +223,16 @@ public final class SelectStatement : Statement {
/// Information about the table and columns read by a SelectStatement
public private(set) var selectionInfo: SelectionInfo
init(database: Database, sql: String) throws {
/// Creates a prepared statement.
///
/// - parameter database: A database connection.
/// - parameter sql: An SQL query.
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
init(database: Database, sql: String, prepFlags: Int32) throws {
self.selectionInfo = SelectionInfo()
let observer = StatementCompilationObserver(database)
try super.init(database: database, sql: sql, observer: observer)
try super.init(database: database, sql: sql, prepFlags: prepFlags, observer: observer)
Database.preconditionValidSelectStatement(sql: sql, observer: observer)
self.selectionInfo = observer.selectionInfo
}
@@ -399,12 +417,18 @@ public final class UpdateStatement : Statement {
super.init(database: database, sqliteStatement: sqliteStatement)
}
init(database: Database, sql: String) throws {
/// Creates a prepared statement.
///
/// - parameter database: A database connection.
/// - parameter sql: An SQL query.
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
init(database: Database, sql: String, prepFlags: Int32) throws {
self.invalidatesDatabaseSchemaCache = false
self.databaseEventKinds = []
let observer = StatementCompilationObserver(database)
try super.init(database: database, sql: sql, observer: observer)
try super.init(database: database, sql: sql, prepFlags: prepFlags, observer: observer)
self.invalidatesDatabaseSchemaCache = observer.invalidatesDatabaseSchemaCache
self.transactionStatementInfo = observer.transactionStatementInfo
self.databaseEventKinds = observer.databaseEventKinds
@@ -864,7 +888,20 @@ struct StatementCache {
return statement
}
let statement = try db.makeSelectStatement(sql)
#if GRDBCUSTOMSQLITE
// http://www.sqlite.org/c3ref/c_prepare_persistent.html#sqlitepreparepersistent
// > The SQLITE_PREPARE_PERSISTENT flag is a hint to the query
// > planner that the prepared statement will be retained for a long
// > time and probably reused many times.
//
// This looks like a perfect match for cached statements.
//
// However SQLITE_PREPARE_PERSISTENT was only introduced in
// SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
let statement = try db.makeSelectStatement(sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
#else
let statement = try db.makeSelectStatement(sql)
#endif
selectStatements[sql] = statement
return statement
}
@@ -874,7 +911,20 @@ struct StatementCache {
return statement
}
let statement = try db.makeUpdateStatement(sql)
#if GRDBCUSTOMSQLITE
// http://www.sqlite.org/c3ref/c_prepare_persistent.html#sqlitepreparepersistent
// > The SQLITE_PREPARE_PERSISTENT flag is a hint to the query
// > planner that the prepared statement will be retained for a long
// > time and probably reused many times.
//
// This looks like a perfect match for cached statements.
//
// However SQLITE_PREPARE_PERSISTENT was only introduced in
// SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
let statement = try db.makeUpdateStatement(sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
#else
let statement = try db.makeUpdateStatement(sql)
#endif
updateStatements[sql] = statement
return statement
}
@@ -114,17 +114,64 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns an Int initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int? {
switch dbValue.storage {
case .int64(let int64):
return Int(exactly: int64)
case .double(let double):
guard double >= Double(Int64.min) else { return nil }
guard double < Double(Int64.max) else { return nil }
return Int(exactly: Int64(double))
default:
return nil
return Int64.fromDatabaseValue(dbValue).flatMap { Int(exactly: $0) }
}
}
/// Int8 adopts DatabaseValueConvertible and StatementColumnConvertible.
extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
///
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
if let v = Int8(exactly: int64) {
self = v
} else {
fatalError("could not convert database value \(int64) to Int8")
}
}
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Int64(self).databaseValue
}
/// Returns an Int8 initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int8? {
return Int64.fromDatabaseValue(dbValue).flatMap { Int8(exactly: $0) }
}
}
/// Int16 adopts DatabaseValueConvertible and StatementColumnConvertible.
extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
///
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
if let v = Int16(exactly: int64) {
self = v
} else {
fatalError("could not convert database value \(int64) to Int16")
}
}
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Int64(self).databaseValue
}
/// Returns an Int16 initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int16? {
return Int64.fromDatabaseValue(dbValue).flatMap { Int16(exactly: $0) }
}
}
/// Int32 adopts DatabaseValueConvertible and StatementColumnConvertible.
@@ -151,16 +198,7 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns an Int32 initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int32? {
switch dbValue.storage {
case .int64(let int64):
return Int32(exactly: int64)
case .double(let double):
guard double >= Double(Int64.min) else { return nil }
guard double < Double(Int64.max) else { return nil }
return Int32(exactly: Int64(double))
default:
return nil
}
return Int64.fromDatabaseValue(dbValue).flatMap { Int32(exactly: $0) }
}
}
@@ -196,6 +234,146 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// UInt adopts DatabaseValueConvertible and StatementColumnConvertible.
extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
///
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
if let v = UInt(exactly: int64) {
self = v
} else {
fatalError("could not convert database value \(int64) to UInt")
}
}
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Int64(self).databaseValue
}
/// Returns an Int initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt? {
return Int64.fromDatabaseValue(dbValue).flatMap { UInt(exactly: $0) }
}
}
/// UInt8 adopts DatabaseValueConvertible and StatementColumnConvertible.
extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
///
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
if let v = UInt8(exactly: int64) {
self = v
} else {
fatalError("could not convert database value \(int64) to UInt8")
}
}
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Int64(self).databaseValue
}
/// Returns an UInt8 initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt8? {
return Int64.fromDatabaseValue(dbValue).flatMap { UInt8(exactly: $0) }
}
}
/// UInt16 adopts DatabaseValueConvertible and StatementColumnConvertible.
extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
///
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
if let v = UInt16(exactly: int64) {
self = v
} else {
fatalError("could not convert database value \(int64) to UInt16")
}
}
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Int64(self).databaseValue
}
/// Returns an UInt16 initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt16? {
return Int64.fromDatabaseValue(dbValue).flatMap { UInt16(exactly: $0) }
}
}
/// UInt32 adopts DatabaseValueConvertible and StatementColumnConvertible.
extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
///
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
if let v = UInt32(exactly: int64) {
self = v
} else {
fatalError("could not convert database value \(int64) to UInt32")
}
}
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Int64(self).databaseValue
}
/// Returns an UInt32 initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt32? {
return Int64.fromDatabaseValue(dbValue).flatMap { UInt32(exactly: $0) }
}
}
/// UInt64 adopts DatabaseValueConvertible and StatementColumnConvertible.
extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
///
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
if let v = UInt64(exactly: int64) {
self = v
} else {
fatalError("could not convert database value \(int64) to UInt64")
}
}
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Int64(self).databaseValue
}
/// Returns an UInt64 initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt64? {
return Int64.fromDatabaseValue(dbValue).flatMap { UInt64(exactly: $0) }
}
}
/// Double adopts DatabaseValueConvertible and StatementColumnConvertible.
extension Double: DatabaseValueConvertible, StatementColumnConvertible {
+15 -10
View File
@@ -132,17 +132,22 @@
}
}
static func api(_ db: Database) -> UnsafePointer<fts5_api>? {
do {
return try Data.fetchOne(db, "SELECT fts5()").flatMap { data in
guard data.count == MemoryLayout<UnsafePointer<fts5_api>>.size else {
return nil
}
return data.withUnsafeBytes { $0.pointee }
}
} catch {
return nil
static func api(_ db: Database) throws -> UnsafePointer<fts5_api> {
let sqliteConnection = db.sqliteConnection
var statement: SQLiteStatement? = nil
var api: UnsafePointer<fts5_api>? = nil
let type: StaticString = "fts5_api_ptr"
let code = sqlite3_prepare_v3(db.sqliteConnection, "SELECT fts5(?)", -1, 0, &statement, nil)
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
}
defer { sqlite3_finalize(statement) }
type.utf8Start.withMemoryRebound(to: Int8.self, capacity: type.utf8CodeUnitCount) { typePointer in
_ = sqlite3_bind_pointer(statement, 1, &api, typePointer, nil)
}
sqlite3_step(statement)
return api!
}
}
+2 -4
View File
@@ -55,10 +55,8 @@
/// class MyTokenizer : FTS5CustomTokenizer { ... }
/// db.add(tokenizer: MyTokenizer.self)
public func add<Tokenizer: FTS5CustomTokenizer>(tokenizer: Tokenizer.Type) {
guard let api = FTS5.api(self) else {
// Assume a GRDB bug or an SQLite miscompilation: there is no point throwing any error.
fatalError("FTS5 is not enabled")
}
// TODO GRDB 2.0: let this method throw when FTS5 can't be loaded
let api = try! FTS5.api(self)
// Swift won't let the @convention(c) xCreate() function below create
// an instance of the generic Tokenizer type.
+1 -3
View File
@@ -188,9 +188,7 @@
/// }
/// }
public func makeTokenizer(_ descriptor: FTS5TokenizerDescriptor) throws -> FTS5Tokenizer {
guard let api = FTS5.api(self) else {
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "FTS5 API not found")
}
let api = try FTS5.api(self)
let xTokenizerPointer: UnsafeMutablePointer<fts5_tokenizer> = .allocate(capacity: 1)
defer { xTokenizerPointer.deallocate(capacity: 1) }
@@ -191,6 +191,30 @@ public struct SQLBinaryOperator : Hashable {
public static func == (lhs: SQLBinaryOperator, rhs: SQLBinaryOperator) -> Bool {
return lhs.sql == rhs.sql
}
// TODO: make it an extension of Sequence (like joined(separator:)) when Swift can better handle existentials
// TODO: make it public eventually
/// Return nil if expressions is empty.
func join(_ expressions: [SQLExpression]) -> SQLExpression? {
switch expressions.count {
case 0:
return nil
case 1:
return expressions[0]
default:
let literals = expressions.map { $0.literal }
let firstLiteral = literals[0]
var sql = firstLiteral.sql
var arguments = firstLiteral.arguments ?? StatementArguments()
for literal in literals.suffix(from: 1) {
sql += " \(self.sql) \(literal.sql)"
if let args = literal.arguments {
arguments += args
}
}
return SQLExpressionLiteral("(\(sql))", arguments: arguments.isEmpty ? nil : arguments)
}
}
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
+33 -27
View File
@@ -14,6 +14,28 @@ extension SQLBinaryOperator {
static let isNot = SQLBinaryOperator("IS NOT", negated: "IS")
}
// Outputs "x = y" or "x IS NULL"
private func isEqual(_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression {
switch (lhs, rhs) {
case (let lhs, let rhs as DatabaseValue):
switch rhs.storage {
case .null:
return SQLExpressionBinary(.is, lhs, DatabaseValue.null)
default:
return SQLExpressionBinary(.equal, lhs, rhs)
}
case (let lhs as DatabaseValue, let rhs):
switch lhs.storage {
case .null:
return SQLExpressionBinary(.is, rhs, DatabaseValue.null)
default:
return SQLExpressionBinary(.equal, lhs, rhs)
}
default:
return SQLExpressionBinary(.equal, lhs, rhs)
}
}
/// An SQL expression that compares two expressions with the `=` SQL operator.
///
/// // name = 'Arthur'
@@ -24,11 +46,7 @@ extension SQLBinaryOperator {
/// // name IS NULL
/// Column("name") == nil
public func == (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression {
if let rhs = rhs {
return SQLExpressionBinary(.equal, lhs.sqlExpression, rhs.sqlExpression)
} else {
return SQLExpressionBinary(.`is`, lhs.sqlExpression, DatabaseValue.null)
}
return isEqual(lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null)
}
/// An SQL expression that compares two expressions with the `=` SQL operator.
@@ -71,11 +89,7 @@ public func == (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression {
/// // name IS NULL
/// nil == Column("name")
public func == (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression {
if let lhs = lhs {
return SQLExpressionBinary(.equal, lhs.sqlExpression, rhs.sqlExpression)
} else {
return SQLExpressionBinary(.`is`, rhs.sqlExpression, DatabaseValue.null)
}
return isEqual(lhs?.sqlExpression ?? DatabaseValue.null, rhs.sqlExpression)
}
/// An SQL expression that compares two expressions with the `=` SQL operator.
@@ -113,7 +127,7 @@ public func == (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression {
/// // email = login
/// Column("email") == Column("login")
public func == (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
return SQLExpressionBinary(.equal, lhs.sqlExpression, rhs.sqlExpression)
return isEqual(lhs.sqlExpression, rhs.sqlExpression)
}
/// An SQL expression that compares two expressions with the `<>` SQL operator.
@@ -126,11 +140,7 @@ public func == (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL
/// // name IS NOT NULL
/// Column("name") != nil
public func != (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression {
if let rhs = rhs {
return SQLExpressionBinary(.notEqual, lhs.sqlExpression, rhs.sqlExpression)
} else {
return SQLExpressionBinary(.isNot, lhs.sqlExpression, DatabaseValue.null)
}
return isEqual(lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null).negated
}
/// An SQL expression that compares two expressions with the `<>` SQL operator.
@@ -173,11 +183,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression {
/// // name IS NOT NULL
/// nil != Column("name")
public func != (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression {
if let lhs = lhs {
return SQLExpressionBinary(.notEqual, lhs.sqlExpression, rhs.sqlExpression)
} else {
return SQLExpressionBinary(.isNot, rhs.sqlExpression, DatabaseValue.null)
}
return isEqual(lhs?.sqlExpression ?? DatabaseValue.null, rhs.sqlExpression).negated
}
/// An SQL expression that compares two expressions with the `<>` SQL operator.
@@ -215,7 +221,7 @@ public func != (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression {
/// // email <> login
/// Column("email") != Column("login")
public func != (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
return SQLExpressionBinary(.notEqual, lhs.sqlExpression, rhs.sqlExpression)
return isEqual(lhs.sqlExpression, rhs.sqlExpression).negated
}
/// An SQL expression that compares two expressions with the `IS` SQL operator.
@@ -223,7 +229,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL
/// // name IS 'Arthur'
/// Column("name") === "Arthur"
public func === (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression {
return SQLExpressionBinary(.`is`, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null)
return SQLExpressionBinary(.is, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null)
}
/// An SQL expression that compares two expressions with the `IS` SQL operator.
@@ -240,9 +246,9 @@ public func === (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpress
/// "Arthur" === Column("name")
public func === (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression {
if let lhs = lhs {
return SQLExpressionBinary(.`is`, lhs.sqlExpression, rhs.sqlExpression)
return SQLExpressionBinary(.is, lhs.sqlExpression, rhs.sqlExpression)
} else {
return SQLExpressionBinary(.`is`, rhs.sqlExpression, DatabaseValue.null)
return SQLExpressionBinary(.is, rhs.sqlExpression, DatabaseValue.null)
}
}
@@ -251,7 +257,7 @@ public func === (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpres
/// // name IS 'Arthur' COLLATE NOCASE
/// "Arthur" === Column("name").collating(.nocase)
public func === (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression {
return SQLExpressionCollate(lhs == rhs.expression, collationName: rhs.collationName)
return SQLExpressionCollate(lhs === rhs.expression, collationName: rhs.collationName)
}
/// An SQL expression that compares two expressions with the `IS` SQL operator.
@@ -259,7 +265,7 @@ public func === (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpress
/// // email IS login
/// Column("email") === Column("login")
public func === (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
return SQLExpressionBinary(.`is`, lhs.sqlExpression, rhs.sqlExpression)
return SQLExpressionBinary(.is, lhs.sqlExpression, rhs.sqlExpression)
}
/// An SQL expression that compares two expressions with the `IS NOT` SQL operator.
+15 -96
View File
@@ -48,6 +48,7 @@ extension RowConvertible where Self: TableMapping {
// MARK: Fetching by Single-Column Primary Key
// TODO GRDB 2.0: make the result non optional
/// Returns a cursor over records, given their primary keys.
///
/// let persons = try Person.fetchCursor(db, keys: [1, 2, 3]) // DatabaseCursor<Person>
@@ -63,10 +64,7 @@ extension RowConvertible where Self: TableMapping {
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> DatabaseCursor<Self>? where Sequence.Iterator.Element: DatabaseValueConvertible {
guard let statement = try makeFetchByPrimaryKeyStatement(db, keys: keys) else {
return nil
}
return try fetchCursor(statement)
return try filter(db, keys: keys).fetchCursor(db)
}
/// Returns an array of records, given their primary keys.
@@ -81,10 +79,12 @@ extension RowConvertible where Self: TableMapping {
/// - returns: An array of records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> [Self] where Sequence.Iterator.Element: DatabaseValueConvertible {
guard let statement = try makeFetchByPrimaryKeyStatement(db, keys: keys) else {
let keys = Array(keys)
if keys.isEmpty {
// Avoid hitting the database
return []
}
return try fetchAll(statement)
return try filter(db, keys: keys).fetchAll(db)
}
/// Returns a single record given its primary key.
@@ -98,43 +98,10 @@ extension RowConvertible where Self: TableMapping {
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne<PrimaryKeyType: DatabaseValueConvertible>(_ db: Database, key: PrimaryKeyType?) throws -> Self? {
guard let key = key else {
// Avoid hitting the database
return nil
}
return try fetchOne(makeFetchByPrimaryKeyStatement(db, keys: [key])!)
}
// Returns "SELECT * FROM table WHERE id IN (?,?,?)"
//
// Returns nil if values is empty.
private static func makeFetchByPrimaryKeyStatement<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> SelectStatement? where Sequence.Iterator.Element: DatabaseValueConvertible {
// Fail early if database table does not exist.
let databaseTableName = self.databaseTableName
let primaryKey = try db.primaryKey(databaseTableName)
// Fail early if database table has not one column in its primary key
let columns = primaryKey?.columns ?? []
GRDBPrecondition(columns.count <= 1, "requires single column primary key in table: \(databaseTableName)")
let column = columns.first ?? Column.rowID.name
let keys = Array(keys)
switch keys.count {
case 0:
// Avoid performing useless SELECT
return nil
case 1:
// SELECT * FROM table WHERE id = ?
let sql = "SELECT \(defaultSelection) FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) = ?"
let statement = try db.makeSelectStatement(sql)
statement.arguments = StatementArguments(keys)
return statement
case let count:
// SELECT * FROM table WHERE id IN (?,?,?)
let keysSQL = databaseQuestionMarks(count: count)
let sql = "SELECT \(defaultSelection) FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) IN (\(keysSQL))"
let statement = try db.makeSelectStatement(sql)
statement.arguments = StatementArguments(keys)
return statement
}
return try filter(db, keys: [key]).fetchOne(db)
}
}
@@ -142,6 +109,7 @@ extension RowConvertible where Self: TableMapping {
// MARK: Fetching by Key
// TODO GRDB 2.0: make the result non optional
/// Returns a cursor over records identified by the provided unique keys
/// (primary key or any key with a unique index on it).
///
@@ -158,10 +126,7 @@ extension RowConvertible where Self: TableMapping {
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> DatabaseCursor<Self>? {
guard let statement = try makeFetchByKeyStatement(db, keys: keys) else {
return nil
}
return try fetchCursor(statement)
return try filter(db, keys: keys).fetchCursor(db)
}
/// Returns an array of records identified by the provided unique keys
@@ -177,10 +142,12 @@ extension RowConvertible where Self: TableMapping {
/// - returns: An array of records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> [Self] {
guard let statement = try makeFetchByKeyStatement(db, keys: keys) else {
let keys = Array(keys)
if keys.isEmpty {
// Avoid hitting the database
return []
}
return try fetchAll(statement)
return try filter(db, keys: keys).fetchAll(db)
}
/// Returns a single record identified by a unique key (the primary key or
@@ -194,54 +161,6 @@ extension RowConvertible where Self: TableMapping {
/// - returns: An optional record.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Self? {
return try fetchOne(makeFetchByKeyStatement(db, keys: [key])!)
}
// Returns "SELECT * FROM table WHERE (a = ? AND b = ?) OR (a = ? AND b = ?) ...
//
// Returns nil if keys is empty.
//
// If there is no unique index on the columns, the method raises a fatal
// (unless fatalErrorOnMissingUniqueIndex is false, for testability).
static func makeFetchByKeyStatement(_ db: Database, keys: [[String: DatabaseValueConvertible?]], fatalErrorOnMissingUniqueIndex: Bool = true) throws -> SelectStatement? {
// Avoid performing useless SELECT
guard keys.count > 0 else {
return nil
}
let databaseTableName = self.databaseTableName
var arguments: [DatabaseValueConvertible?] = []
var whereClauses: [String] = []
for dictionary in keys {
GRDBPrecondition(dictionary.count > 0, "Invalid empty key dictionary")
let columns = Array(dictionary.keys)
guard let orderedColumns = try db.columnsForUniqueKey(columns, in: databaseTableName) else {
let error = DatabaseError(resultCode: .SQLITE_MISUSE, message: "table \(databaseTableName) has no unique index on column(s) \(columns.sorted().joined(separator: ", "))")
if fatalErrorOnMissingUniqueIndex {
// Programmer error
fatalError(error.description)
} else {
throw error
}
}
arguments.append(contentsOf: orderedColumns.map { orderedColumn in
dictionary.first { (column, value) in column.lowercased() == orderedColumn.lowercased() }!.value
})
whereClauses.append("(" + (orderedColumns.map { "\($0.quotedDatabaseIdentifier) = ?" } as [String]).joined(separator: " AND ") + ")")
}
let whereClause = whereClauses.joined(separator: " OR ")
let sql = "SELECT \(defaultSelection) FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(whereClause)"
let statement = try db.makeSelectStatement(sql)
statement.arguments = StatementArguments(arguments)
return statement
}
fileprivate static var defaultSelection: String {
if selectsRowID {
return "*, rowid"
} else {
return "*"
}
return try filter(db, keys: [key]).fetchOne(db)
}
}
+71 -79
View File
@@ -44,6 +44,69 @@ extension TableMapping {
}
}
extension TableMapping {
// MARK: Key Requests
static func filter<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> QueryInterfaceRequest<Self> where Sequence.Iterator.Element: DatabaseValueConvertible {
let primaryKey = try db.primaryKey(databaseTableName)
let columns = primaryKey?.columns.map { Column($0) } ?? [Column.rowID]
GRDBPrecondition(columns.count == 1, "table \(databaseTableName) has multiple columns in its primary key")
let column = columns[0]
let keys = Array(keys)
switch keys.count {
case 0:
return none()
case 1:
return filter(column == keys[0])
default:
return filter(keys.contains(column))
}
}
// Raises a fatal error if there is no unique index on the columns (unless
// fatalErrorOnMissingUniqueIndex is false, for testability).
//
// TODO: think about
// - allowing non unique keys in Type.fetchOne(db, key: ...) ???
// - allowing non unique keys in Type.fetchAll/Cursor(db, keys: ...)
// - forbidding Player.deleteOne(db, key: ["email": nil]) since this may delete several rows (case of a nullable unique key)
static func filter(_ db: Database, keys: [[String: DatabaseValueConvertible?]], fatalErrorOnMissingUniqueIndex: Bool = true) throws -> QueryInterfaceRequest<Self> {
// SELECT * FROM table WHERE ((a=? AND b=?) OR (c=? AND d=?) OR ...)
let keyPredicates: [SQLExpression] = try keys.map { key in
// Prevent filter(db, keys: [[:]])
GRDBPrecondition(!key.isEmpty, "Invalid empty key dictionary")
// Prevent filter(db, keys: [["foo": 1, "bar": 2]]) where
// ("foo", "bar") is not a unique key (primary key or columns of a
// unique index)
guard let orderedColumns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else {
let message = "table \(databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))"
if fatalErrorOnMissingUniqueIndex {
fatalError(message)
} else {
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: message)
}
}
let lowercaseOrderedColumns = orderedColumns.map { $0.lowercased() }
let columnPredicates: [SQLExpression] = key
// Sort key columns in the same order as the unique index
.sorted { (kv1, kv2) in lowercaseOrderedColumns.index(of: kv1.0.lowercased())! < lowercaseOrderedColumns.index(of: kv2.0.lowercased())! }
.map { (column, value) in Column(column) == value }
return SQLBinaryOperator.and.join(columnPredicates)! // not nil because columnPredicates is not empty
}
guard let predicate = SQLBinaryOperator.or.join(keyPredicates) else {
// No key
return none()
}
return filter(predicate)
}
}
extension TableMapping {
// MARK: Deleting All
@@ -74,11 +137,12 @@ extension TableMapping {
/// - returns: The number of deleted rows
@discardableResult
public static func deleteAll<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> Int where Sequence.Iterator.Element: DatabaseValueConvertible {
guard let statement = try makeDeleteByPrimaryKeyStatement(db, keys: keys) else {
let keys = Array(keys)
if keys.isEmpty {
// Avoid hitting the database
return 0
}
try statement.execute()
return db.changesCount
return try filter(db, keys: keys).deleteAll(db)
}
/// Delete a record, identified by its primary key; returns whether a
@@ -93,44 +157,11 @@ extension TableMapping {
@discardableResult
public static func deleteOne<PrimaryKeyType: DatabaseValueConvertible>(_ db: Database, key: PrimaryKeyType?) throws -> Bool {
guard let key = key else {
// Avoid hitting the database
return false
}
return try deleteAll(db, keys: [key]) > 0
}
// Returns "DELETE FROM table WHERE id IN (?,?,?)"
//
// Returns nil if keys is empty.
private static func makeDeleteByPrimaryKeyStatement<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> UpdateStatement? where Sequence.Iterator.Element: DatabaseValueConvertible {
// Fail early if database table does not exist.
let databaseTableName = self.databaseTableName
let primaryKey = try db.primaryKey(databaseTableName)
// Fail early if database table has not one column in its primary key
let columns = primaryKey?.columns ?? []
GRDBPrecondition(columns.count <= 1, "requires single column primary key in table: \(databaseTableName)")
let column = columns.first ?? Column.rowID.name
let keys = Array(keys)
switch keys.count {
case 0:
// Avoid performing useless DELETE
return nil
case 1:
// DELETE FROM table WHERE id = ?
let sql = "DELETE FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) = ?"
let statement = try db.makeUpdateStatement(sql)
statement.arguments = StatementArguments(keys)
return statement
case let count:
// DELETE FROM table WHERE id IN (?,?,?)
let keysSQL = databaseQuestionMarks(count: count)
let sql = "DELETE FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) IN (\(keysSQL))"
let statement = try db.makeUpdateStatement(sql)
statement.arguments = StatementArguments(keys)
return statement
}
}
}
extension TableMapping {
@@ -148,11 +179,11 @@ extension TableMapping {
/// - returns: The number of deleted rows
@discardableResult
public static func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int {
guard let statement = try makeDeleteByKeyStatement(db, keys: keys) else {
if keys.isEmpty {
// Avoid hitting the database
return 0
}
try statement.execute()
return db.changesCount
return try filter(db, keys: keys).deleteAll(db)
}
/// Delete a record, identified by a unique key (the primary key or any key
@@ -168,45 +199,6 @@ extension TableMapping {
public static func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool {
return try deleteAll(db, keys: [key]) > 0
}
// Returns "DELETE FROM table WHERE (a = ? AND b = ?) OR (a = ? AND b = ?) ...
//
// Returns nil if keys is empty.
//
// If there is no unique index on the columns, the method raises a fatal
// (unless fatalErrorOnMissingUniqueIndex is false, for testability).
static func makeDeleteByKeyStatement(_ db: Database, keys: [[String: DatabaseValueConvertible?]], fatalErrorOnMissingUniqueIndex: Bool = true) throws -> UpdateStatement? {
// Avoid performing useless SELECT
guard keys.count > 0 else {
return nil
}
let databaseTableName = self.databaseTableName
var arguments: [DatabaseValueConvertible?] = []
var whereClauses: [String] = []
for dictionary in keys {
GRDBPrecondition(dictionary.count > 0, "Invalid empty key dictionary")
let columns = Array(dictionary.keys)
guard let orderedColumns = try db.columnsForUniqueKey(columns, in: databaseTableName) else {
let error = DatabaseError(resultCode: .SQLITE_MISUSE, message: "table \(databaseTableName) has no unique index on column(s) \(columns.sorted().joined(separator: ", "))")
if fatalErrorOnMissingUniqueIndex {
fatalError(error.description)
} else {
throw error
}
}
arguments.append(contentsOf: orderedColumns.map { orderedColumn in
dictionary.first { (column, value) in column.lowercased() == orderedColumn.lowercased() }!.value
})
whereClauses.append("(" + (orderedColumns.map { "\($0.quotedDatabaseIdentifier) = ?" } as [String]).joined(separator: " AND ") + ")")
}
let whereClause = whereClauses.joined(separator: " OR ")
let sql = "DELETE FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(whereClause)"
let statement = try db.makeUpdateStatement(sql)
statement.arguments = StatementArguments(arguments)
return statement
}
}
extension TableMapping {
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDBCipher'
s.version = '1.2'
s.version = '1.3.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A Swift application toolkit for SQLite databases.'
+3 -3
View File
@@ -288,10 +288,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/v1.2 \
--module-version 1.2 \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v1.3.0 \
--module-version 1.3 \
--module GRDB \
--root-url http://groue.github.io/GRDB.swift/docs/1.2/ \
--root-url http://groue.github.io/GRDB.swift/docs/1.3/ \
--output Documentation/Reference \
--podspec GRDB.swift.podspec
else
+28 -28
View File
@@ -3,7 +3,7 @@ GRDB.swift [![Swift](https://img.shields.io/badge/swift-3.1-orange.svg?style=fla
### A toolkit for SQLite databases, with a focus on application development
**Latest release**: July 13, 2017 &bull; version 1.2 &bull; [CHANGELOG](CHANGELOG.md)
**Latest release**: August 18, 2017 &bull; version 1.3.0 &bull; [CHANGELOG](CHANGELOG.md)
**Requirements**: iOS 8.0+ / OSX 10.9+ / watchOS 2.0+ &bull; Xcode 8.3+ &bull; Swift 3.1
@@ -189,7 +189,7 @@ Documentation
**Reference**
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/1.2/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/1.3/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
**Getting Started**
@@ -237,7 +237,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.19.2.
See [Custom SQLite builds](Documentation/CustomSQLiteBuilds.md) for the installation procedure of GRDB with a customized build of SQLite 3.20.0.
## CocoaPods
@@ -275,7 +275,7 @@ Any pull request that has the `make test_CarthageBuild` command successfully com
## Manually
1. [Download](https://github.com/groue/GRDB.swift/releases/tag/1.2) a copy of GRDB.swift, or clone its repository and make sure you use the latest tagged version with the `git checkout v1.2` command.
1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v1.3.0) a copy of GRDB.swift, or clone its repository and make sure you use the latest tagged version with the `git checkout v1.3.0` command.
2. Embed the `GRDB.xcodeproj` project in your own project.
@@ -374,7 +374,7 @@ let dbQueue = try DatabaseQueue(
configuration: config)
```
See [Configuration](http://groue.github.io/GRDB.swift/docs/1.2/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/1.3/Structs/Configuration.html) for more details.
## Database Pools
@@ -453,7 +453,7 @@ let dbPool = try DatabasePool(
configuration: config)
```
See [Configuration](http://groue.github.io/GRDB.swift/docs/1.2/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/1.3/Structs/Configuration.html) for more details.
Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information.
@@ -701,7 +701,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/1.2/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/1.3/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:
@@ -927,7 +927,7 @@ let urls = try URL.fetchAll(db, "SELECT url FROM links") // [URL]
GRDB ships with built-in support for the following value types:
- **Swift Standard Library**: Bool, Double, Float, Int, Int32, Int64, String, [Swift enums](#swift-enums).
- **Swift Standard Library**: Bool, Double, Float, all signed and unsigned integer types, String, [Swift enums](#swift-enums).
- **Foundation**: [Data](#data-and-memory-savings), [Date](#date-and-datecomponents), [DateComponents](#date-and-datecomponents), NSNull, [NSNumber](#nsnumber-and-nsdecimalnumber), NSString, URL, [UUID](#uuid).
@@ -939,7 +939,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/1.2/Structs/StatementArguments.html):
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/1.3/Structs/StatementArguments.html):
```swift
let url: URL = ...
@@ -1331,7 +1331,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/1.2/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/1.3/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
```swift
updateStatement.arguments = ["name": "Arthur", "age": 41]
@@ -1629,7 +1629,7 @@ row.value(named: "consumed") // "Hello"
row.value(named: "produced") // nil
```
Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/1.2/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/1.3/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
@@ -1757,8 +1757,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/1.2/Structs/Configuration.html)
- `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/1.2/Classes/Database.html)
- `sqlite3_busy_handler`, `sqlite3_busy_timeout`: see [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/1.3/Structs/Configuration.html)
- `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/1.3/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)
@@ -1769,9 +1769,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/1.2/Classes/Statement.html)
- `sqlite3_trace`: see [Configuration.trace](http://groue.github.io/GRDB.swift/docs/1.2/Structs/Configuration.html)
- `sqlite3_wal_checkpoint_v2`: see [DatabasePool.checkpoint](http://groue.github.io/GRDB.swift/docs/1.2/Classes/DatabasePool.html)
- `sqlite3_sql`: see [Statement.sql](http://groue.github.io/GRDB.swift/docs/1.3/Classes/Statement.html)
- `sqlite3_trace`: see [Configuration.trace](http://groue.github.io/GRDB.swift/docs/1.3/Structs/Configuration.html)
- `sqlite3_wal_checkpoint_v2`: see [DatabasePool.checkpoint](http://groue.github.io/GRDB.swift/docs/1.3/Classes/DatabasePool.html)
Records
@@ -1982,7 +1982,7 @@ try PointOfInterest.fetchAll(db, "SELECT ...", arguments:...) // [PointOfInte
try PointOfInterest.fetchOne(db, "SELECT ...", arguments:...) // PointOfInterest?
```
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/1.2/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/1.3/Structs/StatementArguments.html) for more information about the query arguments.
### RowConvertible and Row Adapters
@@ -2962,7 +2962,7 @@ Person // SELECT * FROM persons
```
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/1.2/Structs/StatementArguments.html):
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/1.3/Structs/StatementArguments.html):
```swift
// SELECT DATE(creationDate), COUNT(*) FROM persons WHERE name = 'Arthur' GROUP BY date(creationDate)
@@ -3385,9 +3385,9 @@ try request.fetchOne(db) // Person?
**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/1.2/Structs/SQLRequest.html): a Request built from raw SQL
- [AnyRequest](http://groue.github.io/GRDB.swift/docs/1.2/Structs/AnyRequest.html): a type-erased Request
- [AnyTypedRequest](http://groue.github.io/GRDB.swift/docs/1.2/Structs/AnyTypedRequest.html): a type-erased TypedRequest
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/1.3/Structs/SQLRequest.html): a Request built from raw SQL
- [AnyRequest](http://groue.github.io/GRDB.swift/docs/1.3/Structs/AnyRequest.html): a type-erased Request
- [AnyTypedRequest](http://groue.github.io/GRDB.swift/docs/1.3/Structs/AnyTypedRequest.html): a type-erased TypedRequest
Use the `asRequest(of:)` method to define the type fetched by the request:
@@ -3816,7 +3816,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/1.2/Structs/StatementArguments.html):
FTS3Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/1.3/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
@@ -4029,7 +4029,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/1.2/Structs/StatementArguments.html):
FTS5Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/1.3/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
@@ -4811,7 +4811,7 @@ Alternatively, perform a manual installation of GRDB and SQLCipher:
```sh
cd [GRDB.swift directory]
git checkout v1.2
git checkout v1.3.0
git submodule update --init SQLCipher/src
```
@@ -4918,7 +4918,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/1.2/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/1.3/Structs/StatementArguments.html) to your SQL queries:
```swift
// Good
@@ -5493,7 +5493,7 @@ try dbPool.write { db in
### DatabaseWriter and DatabaseReader Protocols
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/1.2/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/1.2/Protocols/DatabaseWriter.html) protocols.
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/1.3/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/1.3/Protocols/DatabaseWriter.html) protocols.
These protocols provide a unified API that lets you write safe concurrent code that targets both classes.
@@ -5501,7 +5501,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/1.2/Protocols/DatabaseWriter.html#/s:FP4GRDB14DatabaseWriter20readFromCurrentStateFzFCS_8DatabaseT_T_).
- The definition of "current state" in DatabaseWriter.readFromCurrentState is [delicate](http://groue.github.io/GRDB.swift/docs/1.3/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 reusable agnostic code that has *both* queues and pools in mind. For example, GRDB uses those protocols for [migrations](#migrations) and [FetchedRecordsController](#fetchedrecordscontroller), two tools that accept both queues and pools.
@@ -5582,7 +5582,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/1.2/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/1.3/Structs/Configuration.html)
- [Ask questions](https://github.com/groue/GRDB.swift/issues)
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.2</string>
<string>1.3.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+8 -1
View File
@@ -11,9 +11,16 @@
- [ ] GLOB https://www.sqlite.org/lang_expr.html
- [ ] 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
- [ ] See how we can use [sqlite3_get_autocommit](https://www.sqlite.org/capi3ref.html#sqlite3_get_autocommit)
- [ ] Write regression tests for #156 and #157
GRDB 2.0
- [ ] Remove all writing powers from TableMapping:
- [ ] TableMapping.deleteAll(_:) -> move to MutablePersistable
- [ ] TableMapping.deleteAll(_:keys:) -> move to MutablePersistable
- [ ] TableMapping.deleteOne(_:key:) -> move to MutablePersistable
- [ ] QueryInterfaceRequest.deleteAll(_:) -> require MutablePersistable adoption
Not sure
- [ ] Support for resource values (see https://developer.apple.com/library/ios/qa/qa1719/_index.html)
@@ -0,0 +1,219 @@
#if GRDBCIPHER
import GRDBCipher
#elseif GRDBCUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
// GRDB 1.2 has shipped with a change in the DatabaseReader public protocol.
//
// This change in a public protocol has broken the semantic versioning contract,
// because userland types that adopt the protocol suddenly stop compiling. And
// indeed RxGRDB had to be modified in order to accomodate GRDB 1.2.
//
// To prevent such breaking change, this file contains types that adopt all GRBD
// public protocols, but experimental ones. Test pass if this file compiles
// without any error.
// MARK: - Cursor
private class UserCursor<T> : Cursor {
func next() throws -> T? { preconditionFailure() }
}
extension UserCursor {
// Test presence of the Element associated type
static var elementType: Element.Type { return Element.self }
}
// MARK: - DatabaseAggregate
private struct UserDatabaseAggregate1 : DatabaseAggregate {
let a: Int?
init() { a = nil }
mutating func step(_ dbValues: [DatabaseValue]) throws { }
func finalize() throws -> DatabaseValueConvertible? { preconditionFailure() }
}
private class UserDatabaseAggregate2 : DatabaseAggregate {
required init() { }
func step(_ dbValues: [DatabaseValue]) throws { }
func finalize() throws -> DatabaseValueConvertible? { preconditionFailure() }
}
// MARK: - DatabaseReader
private class UserDatabaseReader : DatabaseReader {
func read<T>(_ block: (Database) throws -> T) throws -> T { preconditionFailure() }
func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T { preconditionFailure() }
func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T { preconditionFailure() }
func add(function: DatabaseFunction) { }
func remove(function: DatabaseFunction) { }
func add(collation: DatabaseCollation) { }
func remove(collation: DatabaseCollation) { }
}
// MARK: - DatabaseValueConvertible
private struct UserDatabaseValueConvertible1 : DatabaseValueConvertible {
var databaseValue: DatabaseValue { preconditionFailure() }
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UserDatabaseValueConvertible1? { preconditionFailure() }
}
private class UserDatabaseValueConvertible2 : DatabaseValueConvertible {
var databaseValue: DatabaseValue { preconditionFailure() }
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { preconditionFailure() }
}
// MARK: - DatabaseWriter
private class UserDatabaseWriter : DatabaseWriter {
func read<T>(_ block: (Database) throws -> T) throws -> T { preconditionFailure() }
func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T { preconditionFailure() }
func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T { preconditionFailure() }
func add(function: DatabaseFunction) { }
func remove(function: DatabaseFunction) { }
func add(collation: DatabaseCollation) { }
func remove(collation: DatabaseCollation) { }
func write<T>(_ block: (Database) throws -> T) rethrows -> T { preconditionFailure() }
func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T { preconditionFailure() }
func readFromCurrentState(_ block: @escaping (Database) -> Void) throws { preconditionFailure() }
}
// MARK: - FTS5Tokenizer
#if SQLITE_ENABLE_FTS5
private class UserFTS5Tokenizer : FTS5Tokenizer {
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 { preconditionFailure() }
}
#endif
// MARK: - FTS5CustomTokenizer
#if SQLITE_ENABLE_FTS5
private class UserFTS5CustomTokenizer : FTS5CustomTokenizer {
static let name: String = "UserFTS5CustomTokenizer"
required init(db: Database, arguments: [String]) throws { preconditionFailure() }
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 { preconditionFailure() }
}
#endif
// MARK: - FTS5WrapperTokenizer
#if SQLITE_ENABLE_FTS5
private class UserFTS5WrapperTokenizer : FTS5WrapperTokenizer {
static let name: String = "UserFTS5WrapperTokenizer"
var wrappedTokenizer: FTS5Tokenizer { preconditionFailure() }
required init(db: Database, arguments: [String]) throws { preconditionFailure() }
func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: (String, FTS5TokenFlags) throws -> ()) throws { preconditionFailure() }
}
#endif
// MARK: - MutablePersistable
private struct UserMutablePersistable1 : MutablePersistable {
static let databaseTableName = "UserMutablePersistable1"
func encode(to container: inout PersistenceContainer) { }
}
private class UserMutablePersistable2 : MutablePersistable {
static let databaseTableName = "UserMutablePersistable2"
func encode(to container: inout PersistenceContainer) { }
}
// MARK: - Persistable
private struct UserPersistable1 : Persistable {
static let databaseTableName = "UserPersistable1"
func encode(to container: inout PersistenceContainer) { }
}
private class UserPersistable2 : Persistable {
static let databaseTableName = "UserPersistable2"
func encode(to container: inout PersistenceContainer) { }
}
// MARK: - Request
private struct UserRequest1 : Request {
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { preconditionFailure() }
}
private class UserRequest2 : Request {
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { preconditionFailure() }
}
// MARK: - RowConvertible
private struct UserRowConvertible1 : RowConvertible {
init(row: Row) { }
}
private class UserRowConvertible2 : RowConvertible {
required init(row: Row) { }
}
// MARK: - StatementColumnConvertible
private struct UserStatementColumnConvertible1 : StatementColumnConvertible {
init(sqliteStatement: SQLiteStatement, index: Int32) { }
}
private class UserStatementColumnConvertible2 : StatementColumnConvertible {
required init(sqliteStatement: SQLiteStatement, index: Int32) { }
}
// MARK: - TableMapping
private struct UserTableMapping1 : TableMapping {
static let databaseTableName = "UserTableMapping1"
}
private class UserTableMapping2 : TableMapping {
static let databaseTableName = "UserTableMapping2"
}
// MARK: - TypedRequest
private struct UserTypedRequest1 : TypedRequest {
struct CustomType { }
typealias RowDecoder = CustomType
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { preconditionFailure() }
}
private class UserTypedRequest2<T> : TypedRequest {
typealias RowDecoder = T
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { preconditionFailure() }
}
// MARK: - TransactionObserver
private class UserTransactionObserver : TransactionObserver {
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { return false }
func databaseDidChange(with event: DatabaseEvent) { }
func databaseWillCommit() throws { }
func databaseDidCommit(_ db: Database) { }
func databaseDidRollback(_ db: Database) { }
#if SQLITE_ENABLE_PREUPDATE_HOOK
func databaseWillChange(with event: DatabasePreUpdateEvent) { }
#endif
}
// MARK: - VirtualTableModule
private struct UserVirtualTableModule1 : VirtualTableModule {
struct CustomTableDefinition { }
let moduleName = "UserVirtualTableModule1"
func makeTableDefinition() -> CustomTableDefinition { preconditionFailure() }
func moduleArguments(for definition: CustomTableDefinition, in db: Database) throws -> [String] { preconditionFailure() }
func database(_ db: Database, didCreate tableName: String, using definition: CustomTableDefinition) throws { }
}
private class UserVirtualTableModule2 : VirtualTableModule {
struct CustomTableDefinition { }
let moduleName = "UserVirtualTableModule2"
func makeTableDefinition() -> CustomTableDefinition { preconditionFailure() }
func moduleArguments(for definition: CustomTableDefinition, in db: Database) throws -> [String] { preconditionFailure() }
func database(_ db: Database, didCreate tableName: String, using definition: CustomTableDefinition) throws { }
}
@@ -0,0 +1,26 @@
#if GRDBCIPHER
import GRDBCipher
#elseif GRDBCUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
// This file contains types that subclass GRBD open classes. Test pass if this
// file compiles without any error.
// MARK: - Record
private class UserRecord : Record {
override init() { super.init() }
required init(row: Row) { super.init(row: row) }
override class var databaseTableName: String { return super.databaseTableName }
override class var persistenceConflictPolicy: PersistenceConflictPolicy { return super.persistenceConflictPolicy }
override class var selectsRowID: Bool { return super.selectsRowID }
override func encode(to container: inout PersistenceContainer) { super.encode(to: &container) }
override func didInsert(with rowID: Int64, for column: String?) { super.didInsert(with: rowID, for: column) }
override func copy() -> Self { preconditionFailure() }
override func insert(_ db: Database) throws { try super.insert(db) }
override func update(_ db: Database, columns: Set<String>) throws { try super.update(db, columns: columns) }
override func delete(_ db: Database) throws -> Bool { return try super.delete(db) }
}
+6 -2
View File
@@ -23,9 +23,13 @@ class DatabaseQueueTests: GRDBTestCase {
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
XCTAssertEqual(error.message!.lowercased(), "file is encrypted or is not a database") // lowercased: accept multiple SQLite version
XCTAssert([
"file is encrypted or is not a database",
"file is not a database"].contains(error.message!))
XCTAssertTrue(error.sql == nil)
XCTAssertEqual(error.description.lowercased(), "sqlite error 26: file is encrypted or is not a database")
XCTAssert([
"SQLite error 26: file is encrypted or is not a database",
"SQLite error 26: file is not a database"].contains(error.description))
}
}
#endif
@@ -381,9 +381,15 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age == nil)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NULL)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age == DatabaseValue.null)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NULL)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(nil == Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NULL)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(DatabaseValue.null == Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NULL)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age == Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" = \"age\")")
@@ -436,6 +442,9 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) == nil)),
"SELECT * FROM \"readers\" WHERE (\"name\" IS NULL COLLATE NOCASE)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) == DatabaseValue.null)),
"SELECT * FROM \"readers\" WHERE (\"name\" IS NULL COLLATE NOCASE)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(collation) == "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" = 'fOo' COLLATE localized_case_insensitive)")
@@ -466,9 +475,15 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age != nil)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age != DatabaseValue.null)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(nil != Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(DatabaseValue.null != Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age != Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" <> \"age\")")
@@ -521,6 +536,9 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) != nil)),
"SELECT * FROM \"readers\" WHERE (\"name\" IS NOT NULL COLLATE NOCASE)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) != DatabaseValue.null)),
"SELECT * FROM \"readers\" WHERE (\"name\" IS NOT NULL COLLATE NOCASE)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(collation) != "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" <> 'fOo' COLLATE localized_case_insensitive)")
@@ -545,9 +563,15 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!(Col.age == nil))),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!(Col.age == DatabaseValue.null))),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!(nil == Col.age))),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!(DatabaseValue.null == Col.age))),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!(Col.age == Col.age))),
"SELECT * FROM \"readers\" WHERE (\"age\" <> \"age\")")
@@ -252,8 +252,10 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
try record2.insert(db)
do {
// This method used to return nil, but does no longer.
// In GRDB 2.0, it won't return an optional.
let cursor = try MinimalRowID.fetchCursor(db, keys: [])
XCTAssertTrue(cursor == nil)
try XCTAssertNil(cursor!.next())
}
do {
@@ -323,8 +325,10 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
do {
let ids: [Int64] = []
// This method used to return nil, but does no longer.
// In GRDB 2.0, it won't return an optional.
let cursor = try MinimalRowID.fetchCursor(db, keys: ids)
XCTAssertTrue(cursor == nil)
try XCTAssertNil(cursor!.next())
}
do {
@@ -260,8 +260,10 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
try record2.insert(db)
do {
// This method used to return nil, but does no longer.
// In GRDB 2.0, it won't return an optional.
let cursor = try MinimalSingle.fetchCursor(db, keys: [])
XCTAssertTrue(cursor == nil)
try XCTAssertNil(cursor!.next())
}
do {
@@ -336,8 +338,10 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
do {
let UUIDs: [String] = []
// This method used to return nil, but does no longer.
// In GRDB 2.0, it won't return an optional.
let cursor = try MinimalSingle.fetchCursor(db, keys: UUIDs)
XCTAssertTrue(cursor == nil)
try XCTAssertNil(cursor!.next())
}
do {
@@ -329,8 +329,10 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
try record2.insert(db)
do {
// This method used to return nil, but does no longer.
// In GRDB 2.0, it won't return an optional.
let cursor = try Person.fetchCursor(db, keys: [])
XCTAssertTrue(cursor == nil)
try XCTAssertNil(cursor!.next())
}
do {
@@ -403,8 +405,10 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
do {
let ids: [Int64] = []
// This method used to return nil, but does no longer.
// In GRDB 2.0, it won't return an optional.
let cursor = try Person.fetchCursor(db, keys: ids)
XCTAssertTrue(cursor == nil)
try XCTAssertNil(cursor!.next())
}
do {
@@ -284,8 +284,10 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
try record2.insert(db)
do {
// This method used to return nil, but does no longer.
// In GRDB 2.0, it won't return an optional.
let cursor = try Citizenship.fetchCursor(db, keys: [])
XCTAssertTrue(cursor == nil)
try XCTAssertNil(cursor!.next())
}
do {
@@ -118,8 +118,10 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase {
do {
let ids: [Int64] = []
// This method used to return nil, but does no longer.
// In GRDB 2.0, it won't return an optional.
let cursor = try Item.fetchCursor(db, keys: ids)
XCTAssertTrue(cursor == nil)
try XCTAssertNil(cursor!.next())
}
do {
@@ -325,8 +325,10 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
try record2.insert(db)
do {
// This method used to return nil, but does no longer.
// In GRDB 2.0, it won't return an optional.
let cursor = try Person.fetchCursor(db, keys: [])
XCTAssertTrue(cursor == nil)
try XCTAssertNil(cursor!.next())
}
do {
@@ -399,8 +401,10 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
do {
let ids: [Int64] = []
// This method used to return nil, but does no longer.
// In GRDB 2.0, it won't return an optional.
let cursor = try Person.fetchCursor(db, keys: ids)
XCTAssertTrue(cursor == nil)
try XCTAssertNil(cursor!.next())
}
do {
@@ -277,8 +277,10 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
try record2.insert(db)
do {
// This method used to return nil, but does no longer.
// In GRDB 2.0, it won't return an optional.
let cursor = try Pet.fetchCursor(db, keys: [])
XCTAssertTrue(cursor == nil)
try XCTAssertNil(cursor!.next())
}
do {
@@ -349,8 +351,10 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
do {
let UUIDs: [String] = []
// This method used to return nil, but does no longer.
// In GRDB 2.0, it won't return an optional.
let cursor = try Pet.fetchCursor(db, keys: UUIDs)
XCTAssertTrue(cursor == nil)
try XCTAssertNil(cursor!.next())
}
do {
@@ -266,8 +266,10 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
try record2.insert(db)
do {
// This method used to return nil, but does no longer.
// In GRDB 2.0, it won't return an optional.
let cursor = try Email.fetchCursor(db, keys: [])
XCTAssertTrue(cursor == nil)
try XCTAssertNil(cursor!.next())
}
do {
@@ -342,8 +344,10 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
do {
let emails: [String] = []
// This method used to return nil, but does no longer.
// In GRDB 2.0, it won't return an optional.
let cursor = try Email.fetchCursor(db, keys: emails)
XCTAssertTrue(cursor == nil)
try XCTAssertNil(cursor!.next())
}
do {
+5 -31
View File
@@ -15,15 +15,15 @@ private struct Person : RowConvertible, TableMapping {
class RecordUniqueIndexTests: GRDBTestCase {
func testFetchOneRequiresUniqueIndex() throws {
func testKeyFilterRequiresUniqueIndex() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE)")
_ = try Person.makeFetchByKeyStatement(db, keys: [["id": nil]])
_ = try Person.makeFetchByKeyStatement(db, keys: [["email": nil]])
_ = try Person.filter(db, keys: [["id": nil]])
_ = try Person.filter(db, keys: [["email": nil]])
do {
_ = try Person.makeFetchByKeyStatement(db, keys: [["id": nil, "email": nil]], fatalErrorOnMissingUniqueIndex: false)
_ = try Person.filter(db, keys: [["id": nil, "email": nil]], fatalErrorOnMissingUniqueIndex: false)
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_MISUSE)
@@ -31,33 +31,7 @@ class RecordUniqueIndexTests: GRDBTestCase {
XCTAssertEqual(error.description, "SQLite error 21: table persons has no unique index on column(s) email, id")
}
do {
_ = try Person.makeFetchByKeyStatement(db, keys: [["name": nil]], fatalErrorOnMissingUniqueIndex: false)
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_MISUSE)
XCTAssertEqual(error.message!, "table persons has no unique index on column(s) name")
XCTAssertEqual(error.description, "SQLite error 21: table persons has no unique index on column(s) name")
}
}
}
func testDeleteOneRequiresUniqueIndex() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE)")
_ = try Person.makeDeleteByKeyStatement(db, keys: [["id": nil]])
_ = try Person.makeDeleteByKeyStatement(db, keys: [["email": nil]])
do {
_ = try Person.makeDeleteByKeyStatement(db, keys: [["id": nil, "email": nil]], fatalErrorOnMissingUniqueIndex: false)
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_MISUSE)
XCTAssertEqual(error.message!, "table persons has no unique index on column(s) email, id")
XCTAssertEqual(error.description, "SQLite error 21: table persons has no unique index on column(s) email, id")
}
do {
_ = try Person.makeDeleteByKeyStatement(db, keys: [["name": nil]], fatalErrorOnMissingUniqueIndex: false)
_ = try Person.filter(db, keys: [["name": nil]], fatalErrorOnMissingUniqueIndex: false)
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_MISUSE)
@@ -34,7 +34,7 @@ class TableMappingDeleteByKeyTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
var deleted = try Hacker.deleteOne(db, key: 1)
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"hackers\" WHERE \"rowid\" = 1")
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"hackers\" WHERE (\"rowid\" = 1)")
XCTAssertFalse(deleted)
try db.execute("INSERT INTO hackers (rowid, name) VALUES (?, ?)", arguments: [1, "Arthur"])
@@ -46,7 +46,7 @@ class TableMappingDeleteByKeyTests: GRDBTestCase {
try db.execute("INSERT INTO hackers (rowid, name) VALUES (?, ?)", arguments: [2, "Barbara"])
try db.execute("INSERT INTO hackers (rowid, name) VALUES (?, ?)", arguments: [3, "Craig"])
let deletedCount = try Hacker.deleteAll(db, keys: [2, 3, 4])
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"hackers\" WHERE \"rowid\" IN (2,3,4)")
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"hackers\" WHERE (\"rowid\" IN (2, 3, 4))")
XCTAssertEqual(deletedCount, 2)
XCTAssertEqual(try Hacker.fetchCount(db), 1)
}
@@ -56,7 +56,7 @@ class TableMappingDeleteByKeyTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
var deleted = try Person.deleteOne(db, key: 1)
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" = 1")
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE (\"id\" = 1)")
XCTAssertFalse(deleted)
try db.execute("INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [1, "Arthur", "arthur@example.com"])
@@ -68,7 +68,7 @@ class TableMappingDeleteByKeyTests: GRDBTestCase {
try db.execute("INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [2, "Barbara", "barbara@example.com"])
try db.execute("INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [3, "Craig", "craig@example.com"])
let deletedCount = try Person.deleteAll(db, keys: [2, 3, 4])
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (2,3,4)")
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE (\"id\" IN (2, 3, 4))")
XCTAssertEqual(deletedCount, 2)
XCTAssertEqual(try Person.fetchCount(db), 1)
}
@@ -78,7 +78,7 @@ class TableMappingDeleteByKeyTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
var deleted = try Citizenship.deleteOne(db, key: ["personId": 1, "countryIsoCode": "FR"])
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"citizenships\" WHERE (\"personId\" = 1 AND \"countryIsoCode\" = 'FR')")
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"citizenships\" WHERE ((\"personId\" = 1) AND (\"countryIsoCode\" = 'FR'))")
XCTAssertFalse(deleted)
try db.execute("INSERT INTO citizenships (personId, countryIsoCode) VALUES (?, ?)", arguments: [1, "FR"])