Compare commits

...
6 Commits
13 changed files with 242 additions and 92 deletions

No files matched your search

+8 -1
View File
@@ -1,6 +1,13 @@
Release Notes
=============
## 2.0.3
Released October 9, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.0.2...v2.0.3)
**Fixed**: Record types that conform to Encodable now encode their null columns.
## 2.0.2
Released October 5, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.0.1...v2.0.2)
@@ -114,7 +121,7 @@ New features have been added in order to plug a few holes and support the [RxGRD
- Query interface requests learned how to limit the number of deleted rows:
```swift
// Delete the worse ten players:
// Delete the last ten players:
// DELETE FROM players ORDER BY score LIMIT 10
let request = Player.order(scoreColumn).limit(10)
try request.deleteAll(db)
+1 -1
View File
@@ -15,7 +15,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
```sh
cd [GRDB directory]
git checkout v2.0.2
git checkout v2.0.3
git submodule update --init SQLiteCustom/src
````
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '2.0.2'
s.version = '2.0.3'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A Swift application toolkit for SQLite databases.'
+18
View File
@@ -743,6 +743,14 @@
567E55EE1D2BDD3F00CC6F79 /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; };
567E55F31D2BDDFE00CC6F79 /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; };
567E55F41D2BDDFF00CC6F79 /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; };
567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
567F45A91F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
567F45AA1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
567F45AB1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
567F45AD1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
567F45AE1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
567F45AF1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
568068321EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
568068331EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
@@ -2071,6 +2079,7 @@
567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = "<group>"; };
567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = "<group>"; };
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = "<group>"; };
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = "<group>"; };
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Fixits-1.2.swift"; sourceTree = "<group>"; };
@@ -2466,6 +2475,7 @@
children = (
5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */,
5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */,
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */,
);
name = TransactionObserver;
sourceTree = "<group>";
@@ -4098,6 +4108,7 @@
56176C631EACCCC7000F3F2B /* FTS5TokenizerTests.swift in Sources */,
5623934F1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */,
560FC57C1CB00B880014AA8E /* StatementArgumentsTests.swift in Sources */,
567F45A91F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
5634B1081CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */,
560FC57D1CB00B880014AA8E /* RecordInitializersTests.swift in Sources */,
56176C5F1EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */,
@@ -4368,6 +4379,7 @@
56176C691EACCCC8000F3F2B /* FTS5TokenizerTests.swift in Sources */,
562393501DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */,
5671563A1CB16729007DC145 /* StatementArgumentsTests.swift in Sources */,
567F45AA1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
5657AB601D108BA9006283EF /* FoundationNSURLTests.swift in Sources */,
5671563B1CB16729007DC145 /* RecordInitializersTests.swift in Sources */,
56176C651EACCCC8000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */,
@@ -4596,6 +4608,7 @@
56176C751EACCCCA000F3F2B /* FTS5TokenizerTests.swift in Sources */,
56AFCA4D1CB1AA9900F48B96 /* DatabasePoolReadOnlyTests.swift in Sources */,
5657AB631D108BA9006283EF /* FoundationNSURLTests.swift in Sources */,
567F45AD1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
5657AB6B1D108BA9006283EF /* FoundationURLTests.swift in Sources */,
56AFCA4F1CB1AA9900F48B96 /* DataMemoryTests.swift in Sources */,
56176C711EACCCCA000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */,
@@ -4734,6 +4747,7 @@
56176C7B1EACCCCB000F3F2B /* FTS5TokenizerTests.swift in Sources */,
566AD8CC1D531BEE002EC1A8 /* TableDefinitionTests.swift in Sources */,
56AFCAA41CB1ABC800F48B96 /* MutablePersistableTests.swift in Sources */,
567F45AE1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
56AFCAA51CB1ABC800F48B96 /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */,
56AFCAA61CB1ABC800F48B96 /* DatabasePoolReadOnlyTests.swift in Sources */,
56176C771EACCCCB000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */,
@@ -4961,6 +4975,7 @@
56176C6B1EACCCC9000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */,
56300B621C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */,
56EA869F1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift in Sources */,
567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
5657AB621D108BA9006283EF /* FoundationNSURLTests.swift in Sources */,
5657AB6A1D108BA9006283EF /* FoundationURLTests.swift in Sources */,
56F3E74D1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */,
@@ -5099,6 +5114,7 @@
56176C591EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */,
56D4968A1D81316E008276D7 /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
56D496601D81304E008276D7 /* FoundationNSUUIDTests.swift in Sources */,
567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
56D4968D1D81316E008276D7 /* DatabaseFunctionTests.swift in Sources */,
56D496661D813086008276D7 /* QueryInterfaceRequestTests.swift in Sources */,
56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */,
@@ -5417,6 +5433,7 @@
5657AB651D108BA9006283EF /* FoundationNSURLTests.swift in Sources */,
F3BA80F31CFB301D003DC1BA /* StatementColumnConvertibleTests.swift in Sources */,
5657AB6D1D108BA9006283EF /* FoundationURLTests.swift in Sources */,
567F45AF1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
F3BA804C1CFB2B24003DC1BA /* GRDBTestCase.swift in Sources */,
5698ACBD1DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */,
5623931F1DECC02000A6B01F /* RowFetchTests.swift in Sources */,
@@ -5645,6 +5662,7 @@
F3BA80B01CFB2FB2003DC1BA /* DatabaseCollationTests.swift in Sources */,
56C7A6AE1D2DFF6100EFB0C2 /* FoundationNSDateTests.swift in Sources */,
F3BA80F51CFB301E003DC1BA /* StatementColumnConvertibleTests.swift in Sources */,
567F45AB1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
F3BA80A61CFB2F91003DC1BA /* GRDBTestCase.swift in Sources */,
5657AB411D108BA9006283EF /* FoundationNSDataTests.swift in Sources */,
56B964C61DA521450002DA19 /* FTS5PatternTests.swift in Sources */,
+21 -2
View File
@@ -28,7 +28,6 @@ private struct PersistableKeyedEncodingContainer<Key: CodingKey> : KeyedEncoding
mutating func encode(_ value: Float, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: Double, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: String, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encodeNil(forKey key: Key) throws { encode(nil, key.stringValue) }
/// Encodes the given value for the given key.
///
@@ -45,6 +44,24 @@ private struct PersistableKeyedEncodingContainer<Key: CodingKey> : KeyedEncoding
}
}
// Provide explicit encoding of optionals, because default implementation does not encode nil values.
mutating func encodeNil(forKey key: Key) throws { encode(nil, key.stringValue) }
mutating func encodeIfPresent(_ value: Bool?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: Int?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: Int8?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: Int16?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: Int32?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: Int64?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: UInt?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: UInt8?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: UInt16?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: UInt32?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: UInt64?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: Float?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: Double?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: String?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent<T>(_ value: T?, forKey key: Key) throws where T : Encodable { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
/// Stores a keyed encoding container for the given key and returns it.
///
/// - parameter keyType: The key type to use for the container.
@@ -189,6 +206,8 @@ extension MutablePersistable where Self: Encodable {
try! self.encode(to: encoder)
}
}
encode { (value, key) in container[key] = value }
encode { (value, key) in
container[key] = value
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDBCipher'
s.version = '2.0.2'
s.version = '2.0.3'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A Swift application toolkit for SQLite databases.'
+5 -5
View File
@@ -3,7 +3,7 @@ GRDB 2.0 [![Swift](https://img.shields.io/badge/swift-4-orange.svg?style=flat)](
### A toolkit for SQLite databases, with a focus on application development
**Latest release**: October 5, 2017 • version 2.0.2 • [CHANGELOG](CHANGELOG.md)
**Latest release**: October 9, 2017 • version 2.0.3 • [CHANGELOG](CHANGELOG.md)
**Requirements**: iOS 8.0+ / OSX 10.9+ / watchOS 2.0+ &bull; Swift 4.0 / Xcode 9+
@@ -14,7 +14,7 @@ GRDB 2.0 [![Swift](https://img.shields.io/badge/swift-4-orange.svg?style=flat)](
| Swift 3 | [v1.0](https://github.com/groue/GRDB.swift/tree/v1.0) |
| Swift 3.1 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) |
| Swift 3.2 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) |
| **Swift 4** | **v2.0.2** |
| **Swift 4** | **v2.0.3** |
Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips.
@@ -265,7 +265,7 @@ The [Swift Package Manager](https://swift.org/package-manager/) automates the di
```swift
let package = Package(
dependencies: [
.package(url: "https://github.com/groue/GRDB.swift.git", from: "2.0.2")
.package(url: "https://github.com/groue/GRDB.swift.git", from: "2.0.3")
]
)
```
@@ -282,7 +282,7 @@ Any pull request that has the `make test_CarthageBuild` command successfully com
## Manually
1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v2.0.2) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v2.0.2` command.
1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v2.0.3) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v2.0.3` command.
2. Embed the `GRDB.xcodeproj` project in your own project.
@@ -5021,7 +5021,7 @@ Alternatively, perform a manual installation of GRDB and SQLCipher:
```sh
cd [GRDB directory]
git checkout v2.0.2
git checkout v2.0.3
git submodule update --init SQLCipher/src
```
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>2.0.2</string>
<string>2.0.3</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+4 -9
View File
@@ -119,15 +119,10 @@ class GRDBTestCase: XCTestCase {
XCTAssertTrue(sqlQueries.contains(sql), "Did not execute \(sql)")
}
func assert(_ record: MutablePersistable, isEncodedIn row: Row) {
let recordContent = AnySequence({ PersistenceContainer(record).makeIterator() })
for (column, value) in recordContent {
if let dbValue: DatabaseValue = row[column] {
XCTAssertEqual(dbValue, value?.databaseValue ?? .null)
} else {
XCTFail("Missing column \(column) in fetched row")
}
}
func assert(_ record: MutablePersistable, isEncodedIn row: Row, file: StaticString = #file, line: UInt = #line) {
let recordDict = record.databaseDictionary
let rowDict = Dictionary(row, uniquingKeysWith: { (left, _) in left })
XCTAssertEqual(recordDict, rowDict, file: file, line: line)
}
// Compare SQL strings (ignoring leading and trailing white space and semicolons.
@@ -27,8 +27,9 @@ extension MutablePersistableEncodableTests {
}
var value = Struct(value: "foo")
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo"])
try value.insert(db)
let string = try String.fetchOne(db, "SELECT value FROM t1")!
XCTAssertEqual(string, "foo")
}
@@ -56,8 +57,9 @@ extension MutablePersistableEncodableTests {
}
var value = Struct(value: "foo")
try value.insert(db)
assert(value, isEncodedIn: ["someColumn": "foo (Encodable)"])
try value.insert(db)
let string = try String.fetchOne(db, "SELECT someColumn FROM t1")!
XCTAssertEqual(string, "foo (Encodable)")
}
@@ -80,8 +82,9 @@ extension MutablePersistableEncodableTests {
}
var value = Struct(value: "foo")
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo (MutablePersistable)"])
try value.insert(db)
let string = try String.fetchOne(db, "SELECT value FROM t1")!
XCTAssertEqual(string, "foo (MutablePersistable)")
}
@@ -109,8 +112,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(int64: 123, optionalInt64: 456)
try value.insert(db)
assert(value, isEncodedIn: ["int64": 123, "optionalInt64": 456])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["int64": 123, "optionalInt64": 456])
return .rollback
@@ -118,8 +122,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(int64: 123, optionalInt64: nil)
try value.insert(db)
assert(value, isEncodedIn: ["int64": 123, "optionalInt64": nil])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["int64": 123, "optionalInt64": nil])
return .rollback
@@ -152,8 +157,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(value: Value(string: "foo"), optionalValue: Value(string: "bar"))
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo", "optionalValue": "bar"])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["value": "foo", "optionalValue": "bar"])
return .rollback
@@ -161,8 +167,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(value: Value(string: "foo"), optionalValue: nil)
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo", "optionalValue": nil])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["value": "foo", "optionalValue": nil])
return .rollback
@@ -204,8 +211,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(value: Value(nestedValue: NestedValue(string: "foo")), optionalValue: Value(nestedValue: NestedValue(string: "bar")))
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo", "optionalValue": "bar"])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["value": "foo", "optionalValue": "bar"])
return .rollback
@@ -213,8 +221,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(value: Value(nestedValue: NestedValue(string: "foo")), optionalValue: nil)
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo", "optionalValue": nil])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["value": "foo", "optionalValue": nil])
return .rollback
@@ -247,8 +256,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(value: .foo, optionalValue: .bar)
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo", "optionalValue": "bar"])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["value": "foo", "optionalValue": "bar"])
return .rollback
@@ -256,8 +266,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(value: .foo, optionalValue: nil)
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo", "optionalValue": nil])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["value": "foo", "optionalValue": nil])
return .rollback
@@ -308,8 +319,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(value: Value(string: "foo"), optionalValue: Value(string: "bar"))
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo (DatabaseValueConvertible)", "optionalValue": "bar (DatabaseValueConvertible)"])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["value": "foo (DatabaseValueConvertible)", "optionalValue": "bar (DatabaseValueConvertible)"])
return .rollback
@@ -317,8 +329,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(value: Value(string: "foo"), optionalValue: nil)
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo (DatabaseValueConvertible)", "optionalValue": nil])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["value": "foo (DatabaseValueConvertible)", "optionalValue": nil])
return .rollback
@@ -370,8 +383,9 @@ extension MutablePersistableEncodableTests {
}
let value = StructWithURL(url: URL(string: "https://github.com")!)
try value.insert(db)
assert(value, isEncodedIn: ["url": value.url])
try value.insert(db)
let dbValue = try DatabaseValue.fetchOne(db, "SELECT url FROM t1")!
XCTAssert(dbValue.storage.value is String)
let fetchedURL = URL.fromDatabaseValue(dbValue)!
@@ -392,8 +406,9 @@ extension MutablePersistableEncodableTests {
}
let value = StructWithUUID(uuid: UUID())
try value.insert(db)
assert(value, isEncodedIn: ["uuid": value.uuid])
try value.insert(db)
let dbValue = try DatabaseValue.fetchOne(db, "SELECT uuid FROM t1")!
XCTAssert(dbValue.storage.value is Data)
let fetchedUUID = UUID.fromDatabaseValue(dbValue)!
@@ -315,46 +315,6 @@ class TransactionObserverTests: GRDBTestCase {
}
}
func testTruncateOptimization() throws {
// https://www.sqlite.org/c3ref/update_hook.html
//
// > In the current implementation, the update hook is not invoked [...]
// > when rows are deleted using the truncate optimization.
//
// https://www.sqlite.org/lang_delete.html#truncateopt
//
// > When the WHERE is omitted from a DELETE statement and the table
// > being deleted has no triggers, SQLite uses an optimization to erase
// > the entire table content without having to visit each row of the
// > table individually.
//
// Here we test that the truncate optimization does not prevent
// transaction observers from observing individual deletions.
let dbQueue = try makeDatabaseQueue()
let observer = Observer()
dbQueue.add(transactionObserver: observer)
try dbQueue.inDatabase { db in
let artist1 = Artist(name: "Gerhard Richter")
let artist2 = Artist(name: "Vincent Fournier")
try artist1.insert(db)
try artist2.insert(db)
try db.execute("DELETE FROM artists")
XCTAssertEqual(observer.lastCommittedEvents.count, 2)
let artist1DeleteEvent = observer.lastCommittedEvents.filter {
self.match(event: $0, kind: .delete, tableName: "artists", rowId: artist1.id!)
}.first
XCTAssertTrue(artist1DeleteEvent != nil)
let artist2DeleteEvent = observer.lastCommittedEvents.filter {
self.match(event: $0, kind: .delete, tableName: "artists", rowId: artist1.id!)
}.first
XCTAssertTrue(artist2DeleteEvent != nil)
}
}
func testCascadingDeleteEvents() throws {
let dbQueue = try makeDatabaseQueue()
let observer = Observer()
@@ -0,0 +1,152 @@
import XCTest
#if GRDBCIPHER
import GRDBCipher
#elseif GRDBCUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
class TruncateOptimizationTests: GRDBTestCase {
// https://www.sqlite.org/c3ref/update_hook.html
//
// > In the current implementation, the update hook is not invoked [...]
// > when rows are deleted using the truncate optimization.
//
// https://www.sqlite.org/lang_delete.html#truncateopt
//
// > When the WHERE is omitted from a DELETE statement and the table
// > being deleted has no triggers, SQLite uses an optimization to erase
// > the entire table content without having to visit each row of the
// > table individually.
//
// Here we test that the truncate optimization does not prevent
// transaction observers from observing individual deletions.
class DeletionObserver : TransactionObserver {
private var notify: ([String: Int]) -> Void
private var deletionEvents: [String: Int] = [:]
// Notifies table names with the number of deleted rows
init(_ notify: @escaping ([String: Int]) -> Void) {
self.notify = notify
}
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
return true
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
func databaseWillChange(with event: DatabasePreUpdateEvent) { }
#endif
func databaseDidChange(with event: DatabaseEvent) {
if case .delete = event.kind {
deletionEvents[event.tableName, default: 0] += 1
}
}
func databaseWillCommit() throws { }
func databaseDidCommit(_ db: Database) {
if !deletionEvents.isEmpty {
notify(deletionEvents)
}
deletionEvents = [:]
}
func databaseDidRollback(_ db: Database) {
deletionEvents = [:]
}
}
func testExecuteDelete() throws {
let dbQueue = try makeDatabaseQueue()
var deletionEvents: [[String: Int]] = []
let observer = DeletionObserver { deletionEvents.append($0) }
dbQueue.add(transactionObserver: observer, extent: .databaseLifetime)
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE t(a)")
try db.execute("INSERT INTO t VALUES (NULL)")
try db.execute("INSERT INTO t VALUES (NULL)")
deletionEvents = []
try db.execute("DELETE FROM t")
XCTAssertEqual(deletionEvents.count, 1)
XCTAssertEqual(deletionEvents[0], ["t": 2])
try db.execute("INSERT INTO t VALUES (NULL)")
deletionEvents = []
try db.execute("DELETE FROM t")
XCTAssertEqual(deletionEvents.count, 1)
XCTAssertEqual(deletionEvents[0], ["t": 1])
}
}
func testExecuteDeleteWithPreparedStatement() throws {
let dbQueue = try makeDatabaseQueue()
var deletionEvents: [[String: Int]] = []
let observer = DeletionObserver { deletionEvents.append($0) }
dbQueue.add(transactionObserver: observer, extent: .databaseLifetime)
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE t(a)")
let deleteStatement = try db.makeUpdateStatement("DELETE FROM t")
try db.execute("INSERT INTO t VALUES (NULL)")
try db.execute("INSERT INTO t VALUES (NULL)")
deletionEvents = []
try deleteStatement.execute()
XCTAssertEqual(deletionEvents.count, 1)
XCTAssertEqual(deletionEvents[0], ["t": 2])
try db.execute("INSERT INTO t VALUES (NULL)")
deletionEvents = []
try deleteStatement.execute()
XCTAssertEqual(deletionEvents.count, 1)
XCTAssertEqual(deletionEvents[0], ["t": 1])
}
}
func testDropTable() throws {
// Preventing the truncate optimization requires GRDB to fiddle with
// sqlite3_set_authorizer. When badly done, this can prevent DROP TABLE
// statements from dropping tables.
//
// SQLite3 authorizers can perform during both compilation and
// execution of statements.
//
// Here we test that grouping compilation and execution of DROP TABLE
// statement does the right thing.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE t(a)")
try db.execute("INSERT INTO t VALUES (NULL)")
try db.execute("DROP TABLE t") // compile + execute
try XCTAssertFalse(db.tableExists("t"))
}
}
func testDropTableWithPreparedStatement() throws {
// Preventing the truncate optimization requires GRDB to fiddle with
// sqlite3_set_authorizer. When badly done, this can prevent DROP TABLE
// statements from dropping tables.
//
// SQLite3 authorizers can perform during both compilation and
// execution of statements.
//
// Here we test that splitting compilation from execution of DROP TABLE
// statement does the right thing.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE t(a)")
try db.execute("INSERT INTO t VALUES (NULL)")
let dropStatement = try db.makeUpdateStatement("DROP TABLE t") // compile...
try dropStatement.execute() // ... then execute
try XCTAssertFalse(db.tableExists("t"))
}
}
}
@@ -307,20 +307,4 @@ class UpdateStatementTests : GRDBTestCase {
}
}
}
func testDropTablePreparedStatement() throws {
// In v2.0.1...
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
XCTAssertFalse(try db.tableExists("t"))
try db.execute("CREATE TABLE t(a)")
XCTAssertTrue(try db.tableExists("t"))
try db.execute("DROP TABLE t") // ... this would drop the table
XCTAssertFalse(try db.tableExists("t"))
try db.execute("CREATE TABLE t(a)")
XCTAssertTrue(try db.tableExists("t"))
try db.makeUpdateStatement("DROP TABLE t").execute() // ... but this would not. WTF??? Hence this regression test.
XCTAssertFalse(try db.tableExists("t"))
}
}
}