From 08f84bdc071946f36611c2a753a5510e7d815fcb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 9 Aug 2016 14:36:56 +0200 Subject: [PATCH 01/20] TODO.md --- TODO.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/TODO.md b/TODO.md index 0e6964352..857927f86 100644 --- a/TODO.md +++ b/TODO.md @@ -1,3 +1,5 @@ +- [ ] @hdlj: FetchedRecordsController throttling +- [ ] @hdlj: Check RAM pressure - [ ] Fatal Error when MutablePersistable.update(_:columns:) is given columns that do not exist in the database. - [ ] What is the behavior inTransaction and inSavepoint behaviors in case of commit error? Code looks like we do not rollback, leaving the app in a weird state (out of Swift transaction block with a SQLite transaction that may still be opened). - [ ] GRDBCipher: remove limitations on iOS or OS X versions From c1b85c0d21378e039a8191e3d34624a9c423386a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 9 Aug 2016 18:35:50 +0200 Subject: [PATCH 02/20] TODO.md --- TODO.md | 1 + 1 file changed, 1 insertion(+) diff --git a/TODO.md b/TODO.md index 857927f86..f3a4d8a17 100644 --- a/TODO.md +++ b/TODO.md @@ -1,3 +1,4 @@ +- [ ] @hdlj: Extensibility of the Query Interface - [ ] @hdlj: FetchedRecordsController throttling - [ ] @hdlj: Check RAM pressure - [ ] Fatal Error when MutablePersistable.update(_:columns:) is given columns that do not exist in the database. From b510bff195ae7521a66a3d844bbed615666f5356 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 9 Aug 2016 18:41:30 +0200 Subject: [PATCH 03/20] Documentation --- GRDB/Record/FetchedRecordsController.swift | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index 175b4f81b..c857524ce 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -10,7 +10,7 @@ public final class FetchedRecordsController { // MARK: - Initialization - /// Returns a fetched records controller initialized from a SQL query and + /// Creates a fetched records controller initialized from a SQL query and /// its eventual arguments. /// /// let controller = FetchedRecordsController( @@ -40,7 +40,7 @@ public final class FetchedRecordsController { self.init(databaseWriter, request: SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter), queue: queue, isSameRecord: isSameRecord) } - /// Returns a fetched records controller initialized from a fetch request + /// Creates a fetched records controller initialized from a fetch request /// from the [Query Interface](https://github.com/groue/GRDB.swift#the-query-interface). /// /// let request = Wine.order(SQLColumn("name")) @@ -363,13 +363,9 @@ extension FetchedRecordsController where Record: TableMapping { // MARK: - Initialization - /// Returns a fetched records controller initialized from a SQL query and + /// Creates a fetched records controller initialized from a SQL query and /// its eventual arguments. /// - /// The type of the fetched records must be a subclass of the Record class, - /// or adopt both RowConvertible, and Persistable or MutablePersistable - /// protocols. - /// /// let controller = FetchedRecordsController( /// dbQueue, /// sql: "SELECT * FROM wines WHERE color = ? ORDER BY name", @@ -395,7 +391,8 @@ extension FetchedRecordsController where Record: TableMapping { self.init(databaseWriter, request: SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter), queue: queue, compareRecordsByPrimaryKey: compareRecordsByPrimaryKey) } - /// Returns a fetched records controller initialized from a fetch request. + /// Creates a fetched records controller initialized from a fetch request. + /// from the [Query Interface](https://github.com/groue/GRDB.swift#the-query-interface). /// /// let request = Wine.order(SQLColumn("name")) /// let controller = FetchedRecordsController( From f42186f7c98121619ffa50b4d34d9f831df2a8ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Aug 2016 06:10:59 +0200 Subject: [PATCH 04/20] TODO.md --- TODO.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/TODO.md b/TODO.md index f3a4d8a17..dd9e0a6fc 100644 --- a/TODO.md +++ b/TODO.md @@ -1,6 +1,8 @@ - [ ] @hdlj: Extensibility of the Query Interface - [ ] @hdlj: FetchedRecordsController throttling - [ ] @hdlj: Check RAM pressure +- [ ] Table builder: allow several foreign keys on a columns +- [ ] Table builder: allow checks on a columns - [ ] Fatal Error when MutablePersistable.update(_:columns:) is given columns that do not exist in the database. - [ ] What is the behavior inTransaction and inSavepoint behaviors in case of commit error? Code looks like we do not rollback, leaving the app in a weird state (out of Swift transaction block with a SQLite transaction that may still be opened). - [ ] GRDBCipher: remove limitations on iOS or OS X versions From b9ea94e9be3c6d734c1cf4fca6bc2db4a4874439 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Aug 2016 06:15:53 +0200 Subject: [PATCH 05/20] TODO.md --- TODO.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/TODO.md b/TODO.md index dd9e0a6fc..3bd53b60a 100644 --- a/TODO.md +++ b/TODO.md @@ -3,6 +3,8 @@ - [ ] @hdlj: Check RAM pressure - [ ] Table builder: allow several foreign keys on a columns - [ ] Table builder: allow checks on a columns +- [ ] Record.exists(db) should return false when primary key is nil +- [ ] Record.update(db) should throw, not crash, when primary key is nil - [ ] Fatal Error when MutablePersistable.update(_:columns:) is given columns that do not exist in the database. - [ ] What is the behavior inTransaction and inSavepoint behaviors in case of commit error? Code looks like we do not rollback, leaving the app in a weird state (out of Swift transaction block with a SQLite transaction that may still be opened). - [ ] GRDBCipher: remove limitations on iOS or OS X versions @@ -25,7 +27,6 @@ Not sure -- [ ] Record.exists(db) should return false when primary key is nil - [X] Have Row adopt LiteralDictionaryConvertible - [ ] ... allowing non unique column names - [ ] Remove DatabaseValue.value() From ff5e171d4a6eda879f08e74218727cbe107352b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Aug 2016 07:45:04 +0200 Subject: [PATCH 06/20] Date format documentation (addresses #97) --- README.md | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 61782fe20..d416e2ce6 100644 --- a/README.md +++ b/README.md @@ -942,18 +942,27 @@ Here is the support provided by GRDB for the various [date formats](https://www. #### NSDate -**GRDB stores NSDate using the format "yyyy-MM-dd HH:mm:ss.SSS" in the UTC time zone.** It is precise to the millisecond. - -This format may not fit your needs. We provide below some sample code for [storing dates as timestamps](#custom-value-types) that you can adapt for your application. - -NSDate can be stored and fetched from the database just like other [value types](#values): +**NSDate** can be stored and fetched from the database just like other [value types](#values): ```swift try db.execute( "INSERT INTO persons (creationDate, ...) VALUES (?, ...)", arguments: [NSDate(), ...]) + +let creationDate: NSDate = row.value(named: "creationDate") ``` +Dates are stored using the format "YYYY-MM-DD HH:MM:SS.SSS" in the UTC time zone. It is precise to the millisecond. + +> :point_up: **Note**: this format was chosen because it is the only format that is: +> +> - Comparable (`ORDER BY date` works) +> - Comparable with the SQLite keyword NOW (`WHERE date > NOW` works) +> - Able to feed [SQLite date & time functions](https://www.sqlite.org/lang_datefunc.html) +> - Precise enough +> +> Yet this format may not fit your needs. For example, you may want to store dates as timestamps. In this case, store and load Doubles instead of Date, and perform the required conversions. + #### NSDateComponents @@ -1204,8 +1213,6 @@ The `databaseValue` property returns [DatabaseValue](#databasevalue), a type tha The `fromDatabaseValue()` factory method returns an instance of your custom type if the databaseValue contains a suitable value. If the databaseValue does not contain a suitable value, such as "foo" for NSDate, the method returns nil. -As an example, see [DatabaseTimestamp.playground](Playgrounds/DatabaseTimestamp.playground/Contents.swift): it shows how to store dates as timestamps, unlike the built-in [NSDate](#nsdate-and-nsdatecomponents). - ## Prepared Statements @@ -3987,7 +3994,6 @@ Sample Code - The [Documentation](#documentation) is full of GRDB snippets. - [GRDBDemoiOS](DemoApps/GRDBDemoiOS): A sample iOS application. - Check `GRDB.xcworkspace`: it contains GRDB-enabled playgrounds to play with. -- How to read and write NSDate as timestamp: [DatabaseTimestamp.playground](Playgrounds/DatabaseTimestamp.playground/Contents.swift) - How to synchronize a database table with a JSON payload: [JSONSynchronization.playground](Playgrounds/JSONSynchronization.playground/Contents.swift) - A class that behaves like NSUserDefaults, but backed by SQLite: [UserDefaults.playground](Playgrounds/UserDefaults.playground/Contents.swift) - How to notify view controllers of database changes: [TableChangeObserver.swift](https://gist.github.com/groue/2e21172719e634657dfd) From e61550841b46616c5cb029a08ae356105ea3fcb7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Aug 2016 08:00:27 +0200 Subject: [PATCH 07/20] Failing tests that exists() returns false when primary key is nil --- Tests/Public/Record/PrimaryKeyMultipleTests.swift | 10 ++++++++++ Tests/Public/Record/PrimaryKeyRowIDTests.swift | 10 ++++++++++ Tests/Public/Record/PrimaryKeySingleTests.swift | 10 ++++++++++ 3 files changed, 30 insertions(+) diff --git a/Tests/Public/Record/PrimaryKeyMultipleTests.swift b/Tests/Public/Record/PrimaryKeyMultipleTests.swift index c09fd6b26..3c7fdf761 100644 --- a/Tests/Public/Record/PrimaryKeyMultipleTests.swift +++ b/Tests/Public/Record/PrimaryKeyMultipleTests.swift @@ -394,6 +394,16 @@ class PrimaryKeyMultipleTests: GRDBTestCase { // MARK: - Exists + func testExistsWithNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + dbQueue.inDatabase { db in + let record = Citizenship(personName: nil, countryName: nil, native: true) + XCTAssertFalse(record.exists(db)) + } + } + } + func testExistsWithNotNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() { assertNoError { let dbQueue = try makeDatabaseQueue() diff --git a/Tests/Public/Record/PrimaryKeyRowIDTests.swift b/Tests/Public/Record/PrimaryKeyRowIDTests.swift index 1f5058839..2303b74d7 100644 --- a/Tests/Public/Record/PrimaryKeyRowIDTests.swift +++ b/Tests/Public/Record/PrimaryKeyRowIDTests.swift @@ -537,6 +537,16 @@ class PrimaryKeyRowIDTests: GRDBTestCase { // MARK: - Exists + func testExistsWithNilPrimaryKeyReturnsFalse() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + dbQueue.inDatabase { db in + let record = Person(id: nil, name: "Arthur") + XCTAssertFalse(record.exists(db)) + } + } + } + func testExistsWithNotNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() { assertNoError { let dbQueue = try makeDatabaseQueue() diff --git a/Tests/Public/Record/PrimaryKeySingleTests.swift b/Tests/Public/Record/PrimaryKeySingleTests.swift index 1ee011e9a..a09670fb4 100644 --- a/Tests/Public/Record/PrimaryKeySingleTests.swift +++ b/Tests/Public/Record/PrimaryKeySingleTests.swift @@ -459,6 +459,16 @@ class PrimaryKeySingleTests: GRDBTestCase { // MARK: - Exists + func testExistsWithNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + dbQueue.inDatabase { db in + let record = Pet(UUID: nil, name: "Bobby") + XCTAssertFalse(record.exists(db)) + } + } + } + func testExistsWithNotNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() { assertNoError { let dbQueue = try makeDatabaseQueue() From 944bdd5bba847f268c77cf9e572f0895f9268c60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Aug 2016 08:03:41 +0200 Subject: [PATCH 08/20] Failing tests that update() throws PersistenceError.NotFound when primary key is nil --- .../Public/Record/PrimaryKeyMultipleTests.swift | 17 ++++++++++++++++- Tests/Public/Record/PrimaryKeyRowIDTests.swift | 15 +++++++++++++++ Tests/Public/Record/PrimaryKeySingleTests.swift | 17 ++++++++++++++++- 3 files changed, 47 insertions(+), 2 deletions(-) diff --git a/Tests/Public/Record/PrimaryKeyMultipleTests.swift b/Tests/Public/Record/PrimaryKeyMultipleTests.swift index 3c7fdf761..431a7a829 100644 --- a/Tests/Public/Record/PrimaryKeyMultipleTests.swift +++ b/Tests/Public/Record/PrimaryKeyMultipleTests.swift @@ -138,6 +138,21 @@ class PrimaryKeyMultipleTests: GRDBTestCase { // MARK: - Update + func testUpdateWithNilPrimaryKeyThrowsRecordNotFound() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = Citizenship(personName: nil, countryName: nil, native: true) + do { + try record.update(db) + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound + } + } + } + } + func testUpdateWithNotNilPrimaryKeyThatDoesNotMatchAnyRowThrowsRecordNotFound() { assertNoError { let dbQueue = try makeDatabaseQueue() @@ -394,7 +409,7 @@ class PrimaryKeyMultipleTests: GRDBTestCase { // MARK: - Exists - func testExistsWithNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() { + func testExistsWithNilPrimaryKeyReturnsFalse() { assertNoError { let dbQueue = try makeDatabaseQueue() dbQueue.inDatabase { db in diff --git a/Tests/Public/Record/PrimaryKeyRowIDTests.swift b/Tests/Public/Record/PrimaryKeyRowIDTests.swift index 2303b74d7..a1e915892 100644 --- a/Tests/Public/Record/PrimaryKeyRowIDTests.swift +++ b/Tests/Public/Record/PrimaryKeyRowIDTests.swift @@ -197,6 +197,21 @@ class PrimaryKeyRowIDTests: GRDBTestCase { // MARK: - Update + func testUpdateWithNilPrimaryKeyThrowsRecordNotFound() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = Person(id: nil, name: "Arthur") + do { + try record.update(db) + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound + } + } + } + } + func testUpdateWithNotNilPrimaryKeyThatDoesNotMatchAnyRowThrowsRecordNotFound() { assertNoError { let dbQueue = try makeDatabaseQueue() diff --git a/Tests/Public/Record/PrimaryKeySingleTests.swift b/Tests/Public/Record/PrimaryKeySingleTests.swift index a09670fb4..00ba47715 100644 --- a/Tests/Public/Record/PrimaryKeySingleTests.swift +++ b/Tests/Public/Record/PrimaryKeySingleTests.swift @@ -129,6 +129,21 @@ class PrimaryKeySingleTests: GRDBTestCase { // MARK: - Update + func testUpdateWithNilPrimaryKeyThrowsRecordNotFound() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = Pet(UUID: nil, name: "Bobby") + do { + try record.update(db) + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound + } + } + } + } + func testUpdateWithNotNilPrimaryKeyThatDoesNotMatchAnyRowThrowsRecordNotFound() { assertNoError { let dbQueue = try makeDatabaseQueue() @@ -459,7 +474,7 @@ class PrimaryKeySingleTests: GRDBTestCase { // MARK: - Exists - func testExistsWithNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() { + func testExistsWithNilPrimaryKeyReturnsFalse() { assertNoError { let dbQueue = try makeDatabaseQueue() dbQueue.inDatabase { db in From d96b1bb9f8f067edb172bf0d65cea7106815ad1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Aug 2016 08:14:37 +0200 Subject: [PATCH 09/20] Passing tests for update() and exists() when primary key is nil --- GRDB/Record/Persistable.swift | 22 ++++++++++++++++------ GRDB/Record/Record.swift | 6 +++++- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/GRDB/Record/Persistable.swift b/GRDB/Record/Persistable.swift index dece528bf..5c6372cf8 100644 --- a/GRDB/Record/Persistable.swift +++ b/GRDB/Record/Persistable.swift @@ -298,7 +298,11 @@ public extension MutablePersistable { /// PersistenceError.NotFound is thrown if the primary key does not /// match any row in the database. func performUpdate(db: Database, columns: Set) throws { - try DataMapper(db, self).updateStatement(columns: columns).execute() + guard let statement = DataMapper(db, self).updateStatement(columns: columns) else { + // Nil primary key + throw PersistenceError.NotFound(self) + } + try statement.execute() if db.changesCount == 0 { throw PersistenceError.NotFound(self) } @@ -353,7 +357,11 @@ public extension MutablePersistable { /// their implementation of exists(). They should not provide their own /// implementation of performExists(). func performExists(db: Database) -> Bool { - return (Row.fetchOne(DataMapper(db, self).existsStatement()) != nil) + guard let statement = DataMapper(db, self).existsStatement() else { + // Nil primary key + return false + } + return Row.fetchOne(statement) != nil } } @@ -544,11 +552,12 @@ final class DataMapper { return statement } - func updateStatement(columns columns: Set) -> UpdateStatement { + /// Returns nil if and only if primary key is nil + func updateStatement(columns columns: Set) -> UpdateStatement? { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey?.columns ?? [] let primaryKeyValues = databaseValues(forColumns: primaryKeyColumns, inDictionary: persistentDictionary) - GRDBPrecondition(primaryKeyValues.contains { !$0.isNull }, "record can not be identified. persistentDictionary must contain non-nil value(s) for the key(s) \(primaryKeyColumns.joinWithSeparator((", ")))") + guard primaryKeyValues.contains({ !$0.isNull }) else { return nil } // Don't update primary key columns var updatedColumns = Array(persistentDictionary.keys) @@ -591,11 +600,12 @@ final class DataMapper { return statement } - func existsStatement() -> SelectStatement { + /// Returns nil if and only if primary key is nil + func existsStatement() -> SelectStatement? { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey?.columns ?? [] let primaryKeyValues = databaseValues(forColumns: primaryKeyColumns, inDictionary: persistentDictionary) - GRDBPrecondition(primaryKeyValues.contains { !$0.isNull }, "record can not be identified. persistentDictionary must contain non-nil value(s) for the key(s) \(primaryKeyColumns.joinWithSeparator((", ")))") + guard primaryKeyValues.contains({ !$0.isNull }) else { return nil } let query = ExistsQuery( tableName: databaseTableName, diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 9982e84f9..ecde92f3e 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -267,7 +267,11 @@ public class Record : RowConvertible, TableMapping, Persistable { // So let's provide our custom implementation of insert, which uses the // same persistentDictionary for both update, and change tracking. let dataMapper = DataMapper(db, self) - try dataMapper.updateStatement(columns: columns).execute() + guard let statement = dataMapper.updateStatement(columns: columns) else { + // Nil primary key + throw PersistenceError.NotFound(self) + } + try statement.execute() if db.changesCount == 0 { throw PersistenceError.NotFound(self) } From aeca4c0f9c7823f511b3792d96e882415eaf734c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Aug 2016 08:16:32 +0200 Subject: [PATCH 10/20] Failing tests that delete() returns false when primary key is nil --- Tests/Public/Record/PrimaryKeyMultipleTests.swift | 11 +++++++++++ Tests/Public/Record/PrimaryKeyRowIDTests.swift | 11 +++++++++++ Tests/Public/Record/PrimaryKeySingleTests.swift | 11 +++++++++++ 3 files changed, 33 insertions(+) diff --git a/Tests/Public/Record/PrimaryKeyMultipleTests.swift b/Tests/Public/Record/PrimaryKeyMultipleTests.swift index 431a7a829..cb85f8a92 100644 --- a/Tests/Public/Record/PrimaryKeyMultipleTests.swift +++ b/Tests/Public/Record/PrimaryKeyMultipleTests.swift @@ -290,6 +290,17 @@ class PrimaryKeyMultipleTests: GRDBTestCase { // MARK: - Delete + func testDeleteWithNilPrimaryKey() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = Citizenship(personName: nil, countryName: nil, native: true) + let deleted = try record.delete(db) + XCTAssertFalse(deleted) + } + } + } + func testDeleteWithNotNilPrimaryKeyThatDoesNotMatchAnyRowDoesNothing() { assertNoError { let dbQueue = try makeDatabaseQueue() diff --git a/Tests/Public/Record/PrimaryKeyRowIDTests.swift b/Tests/Public/Record/PrimaryKeyRowIDTests.swift index a1e915892..df9db7713 100644 --- a/Tests/Public/Record/PrimaryKeyRowIDTests.swift +++ b/Tests/Public/Record/PrimaryKeyRowIDTests.swift @@ -355,6 +355,17 @@ class PrimaryKeyRowIDTests: GRDBTestCase { // MARK: - Delete + func testDeleteWithNilPrimaryKey() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = Person(id: nil, name: "Arthur") + let deleted = try record.delete(db) + XCTAssertFalse(deleted) + } + } + } + func testDeleteWithNotNilPrimaryKeyThatDoesNotMatchAnyRowDoesNothing() { assertNoError { let dbQueue = try makeDatabaseQueue() diff --git a/Tests/Public/Record/PrimaryKeySingleTests.swift b/Tests/Public/Record/PrimaryKeySingleTests.swift index 00ba47715..a14a1f66b 100644 --- a/Tests/Public/Record/PrimaryKeySingleTests.swift +++ b/Tests/Public/Record/PrimaryKeySingleTests.swift @@ -281,6 +281,17 @@ class PrimaryKeySingleTests: GRDBTestCase { // MARK: - Delete + func testDeleteWithNilPrimaryKey() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = Pet(UUID: nil, name: "Bobby") + let deleted = try record.delete(db) + XCTAssertFalse(deleted) + } + } + } + func testDeleteWithNotNilPrimaryKeyThatDoesNotMatchAnyRowDoesNothing() { assertNoError { let dbQueue = try makeDatabaseQueue() From cd776e4b649c0fc60175fe112dbec64d6536ee05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Aug 2016 08:20:15 +0200 Subject: [PATCH 11/20] Passing tests for delete() when primary key is nil --- GRDB/Record/Persistable.swift | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/GRDB/Record/Persistable.swift b/GRDB/Record/Persistable.swift index 5c6372cf8..fea778a6b 100644 --- a/GRDB/Record/Persistable.swift +++ b/GRDB/Record/Persistable.swift @@ -345,7 +345,11 @@ public extension MutablePersistable { /// their implementation of delete(). They should not provide their own /// implementation of performDelete(). func performDelete(db: Database) throws -> Bool { - try DataMapper(db, self).deleteStatement().execute() + guard let statement = DataMapper(db, self).deleteStatement() else { + // Nil primary key + return false + } + try statement.execute() return db.changesCount > 0 } @@ -586,11 +590,12 @@ final class DataMapper { return statement } - func deleteStatement() -> UpdateStatement { + /// Returns nil if and only if primary key is nil + func deleteStatement() -> UpdateStatement? { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey?.columns ?? [] let primaryKeyValues = databaseValues(forColumns: primaryKeyColumns, inDictionary: persistentDictionary) - GRDBPrecondition(primaryKeyValues.contains { !$0.isNull }, "record can not be identified. persistentDictionary must contain non-nil value(s) for the key(s) \(primaryKeyColumns.joinWithSeparator((", ")))") + guard primaryKeyValues.contains({ !$0.isNull }) else { return nil } let query = DeleteQuery( tableName: databaseTableName, From 548b2f4b77ab35664ba957af44193268c25e9f44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Aug 2016 08:24:31 +0200 Subject: [PATCH 12/20] Rename DataMapper to DAO --- GRDB/Record/Persistable.swift | 30 +++++++++++++++--------------- GRDB/Record/Record.swift | 14 +++++++------- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/GRDB/Record/Persistable.swift b/GRDB/Record/Persistable.swift index fea778a6b..399c4f75d 100644 --- a/GRDB/Record/Persistable.swift +++ b/GRDB/Record/Persistable.swift @@ -279,9 +279,9 @@ public extension MutablePersistable { /// implementation of insert(). They should not provide their own /// implementation of performInsert(). mutating func performInsert(db: Database) throws { - let dataMapper = DataMapper(db, self) - try dataMapper.insertStatement().execute() - didInsertWithRowID(db.lastInsertedRowID, forColumn: dataMapper.primaryKey?.rowIDColumn) + let dao = DAO(db, self) + try dao.insertStatement().execute() + didInsertWithRowID(db.lastInsertedRowID, forColumn: dao.primaryKey?.rowIDColumn) } /// Don't invoke this method directly: it is an internal method for types @@ -298,7 +298,7 @@ public extension MutablePersistable { /// PersistenceError.NotFound is thrown if the primary key does not /// match any row in the database. func performUpdate(db: Database, columns: Set) throws { - guard let statement = DataMapper(db, self).updateStatement(columns: columns) else { + guard let statement = DAO(db, self).updateStatement(columns: columns) else { // Nil primary key throw PersistenceError.NotFound(self) } @@ -345,7 +345,7 @@ public extension MutablePersistable { /// their implementation of delete(). They should not provide their own /// implementation of performDelete(). func performDelete(db: Database) throws -> Bool { - guard let statement = DataMapper(db, self).deleteStatement() else { + guard let statement = DAO(db, self).deleteStatement() else { // Nil primary key return false } @@ -361,7 +361,7 @@ public extension MutablePersistable { /// their implementation of exists(). They should not provide their own /// implementation of performExists(). func performExists(db: Database) -> Bool { - guard let statement = DataMapper(db, self).existsStatement() else { + guard let statement = DAO(db, self).existsStatement() else { // Nil primary key return false } @@ -473,9 +473,9 @@ public extension Persistable { /// implementation of insert(). They should not provide their own /// implementation of performInsert(). func performInsert(db: Database) throws { - let dataMapper = DataMapper(db, self) - try dataMapper.insertStatement().execute() - didInsertWithRowID(db.lastInsertedRowID, forColumn: dataMapper.primaryKey?.rowIDColumn) + let dao = DAO(db, self) + try dao.insertStatement().execute() + didInsertWithRowID(db.lastInsertedRowID, forColumn: dao.primaryKey?.rowIDColumn) } /// Don't invoke this method directly: it is an internal method for types @@ -509,10 +509,10 @@ public extension Persistable { } -// MARK: - DataMapper +// MARK: - DAO -/// DataMapper takes care of Persistable CRUD -final class DataMapper { +/// DAO takes care of Persistable CRUD +final class DAO { /// The database let db: Database @@ -520,9 +520,9 @@ final class DataMapper { /// The persistable let persistable: MutablePersistable - /// DataMapper keeps a copy the persistable's persistentDictionary, so - /// that this dictionary is built once whatever the database operation. - /// It is guaranteed to have at least one (key, value) pair. + /// DAO keeps a copy the persistable's persistentDictionary, so that this + /// dictionary is built once whatever the database operation. It is + /// guaranteed to have at least one (key, value) pair. let persistentDictionary: [String: DatabaseValueConvertible?] /// The table name diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index ecde92f3e..6a7d47bb2 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -216,11 +216,11 @@ public class Record : RowConvertible, TableMapping, Persistable { // So let's provide our custom implementation of insert, which uses the // same persistentDictionary for both insertion, and change tracking. - let dataMapper = DataMapper(db, self) - var persistentDictionary = dataMapper.persistentDictionary - try dataMapper.insertStatement().execute() + let dao = DAO(db, self) + var persistentDictionary = dao.persistentDictionary + try dao.insertStatement().execute() let rowID = db.lastInsertedRowID - let rowIDColumn = dataMapper.primaryKey?.rowIDColumn + let rowIDColumn = dao.primaryKey?.rowIDColumn didInsertWithRowID(rowID, forColumn: rowIDColumn) // Update persistentDictionary with inserted id, so that we can @@ -266,8 +266,8 @@ public class Record : RowConvertible, TableMapping, Persistable { // // So let's provide our custom implementation of insert, which uses the // same persistentDictionary for both update, and change tracking. - let dataMapper = DataMapper(db, self) - guard let statement = dataMapper.updateStatement(columns: columns) else { + let dao = DAO(db, self) + guard let statement = dao.updateStatement(columns: columns) else { // Nil primary key throw PersistenceError.NotFound(self) } @@ -277,7 +277,7 @@ public class Record : RowConvertible, TableMapping, Persistable { } // Set hasPersistentChangedValues to false - referenceRow = Row(dataMapper.persistentDictionary) + referenceRow = Row(dao.persistentDictionary) } /// Executes an INSERT or an UPDATE statement so that `self` is saved in From 0f2854fe17b81a0f83dbbd154a2aeca49b50e256 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Aug 2016 08:26:43 +0200 Subject: [PATCH 13/20] CHANGELOG.md --- CHANGELOG.md | 7 +++++++ TODO.md | 4 ++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c9c955f54..eec65bc98 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,13 @@ Release Notes ============= +## Next Version + +**New** + +- Persistable `update`, `exists` and `delete` methods now work with objects that have a nil primary key. They used to crash. + + ## 0.79.0 Released August 8, 2016 diff --git a/TODO.md b/TODO.md index 3bd53b60a..87e44a73c 100644 --- a/TODO.md +++ b/TODO.md @@ -3,8 +3,8 @@ - [ ] @hdlj: Check RAM pressure - [ ] Table builder: allow several foreign keys on a columns - [ ] Table builder: allow checks on a columns -- [ ] Record.exists(db) should return false when primary key is nil -- [ ] Record.update(db) should throw, not crash, when primary key is nil +- [X] Record.exists(db) should return false when primary key is nil +- [X] Record.update(db) should throw, not crash, when primary key is nil - [ ] Fatal Error when MutablePersistable.update(_:columns:) is given columns that do not exist in the database. - [ ] What is the behavior inTransaction and inSavepoint behaviors in case of commit error? Code looks like we do not rollback, leaving the app in a weird state (out of Swift transaction block with a SQLite transaction that may still be opened). - [ ] GRDBCipher: remove limitations on iOS or OS X versions From 7bb586616420c1f53c7526b9e86daccc41fa4632 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Aug 2016 08:48:06 +0200 Subject: [PATCH 14/20] Failing test for multiple check constraints on a column --- Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift index 81e7afb27..04cd5697c 100644 --- a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -125,17 +125,19 @@ class SQLTableBuilderTests: GRDBTestCase { try db.create(table: "test") { t in t.column("a", .Integer).check { $0 > 0 } t.column("b", .Integer).check(sql: "b <> 2") + t.column("c", .Integer).check { $0 > 0 }.check { $0 < 10 } } XCTAssertEqual(self.lastSQLQuery, "CREATE TABLE \"test\" (" + "\"a\" INTEGER CHECK ((\"a\" > 0)), " + - "\"b\" INTEGER CHECK (b <> 2)" + + "\"b\" INTEGER CHECK (b <> 2), " + + "\"c\" INTEGER CHECK ((\"c\" > 0)) CHECK ((\"c\" < 10))" + ")") // Sanity check - try db.execute("INSERT INTO test (a, b) VALUES (1, 0)") + try db.execute("INSERT INTO test (a, b, c) VALUES (1, 0, 1)") do { - try db.execute("INSERT INTO test (a, b) VALUES (0, 0)") + try db.execute("INSERT INTO test (a, b, c) VALUES (0, 0, 1)") XCTFail() } catch { } From 4be192392184bf9df256009dcb8a5ee2df17ff1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Aug 2016 08:48:24 +0200 Subject: [PATCH 15/20] Pass test for multiple check constraints on a column --- GRDB/QueryInterface/SQLTableBuilder.swift | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/GRDB/QueryInterface/SQLTableBuilder.swift b/GRDB/QueryInterface/SQLTableBuilder.swift index bc9d97cd5..782f13656 100644 --- a/GRDB/QueryInterface/SQLTableBuilder.swift +++ b/GRDB/QueryInterface/SQLTableBuilder.swift @@ -428,7 +428,7 @@ public final class ColumnDefinition { private var primaryKey: (conflictResolution: SQLConflictResolution?, autoincrement: Bool)? private var notNullConflictResolution: SQLConflictResolution? private var uniqueConflictResolution: SQLConflictResolution? - private var checkExpression: _SQLExpression? + private var checkConstraints: [_SQLExpression] = [] private var defaultExpression: _SQLExpression? private var collationName: String? private var reference: (table: String, column: String?, deleteAction: SQLForeignKeyAction?, updateAction: SQLForeignKeyAction?, deferred: Bool)? @@ -501,7 +501,7 @@ public final class ColumnDefinition { /// represents the defined column, and returns the expression to check. /// - returns: Self so that you can further refine the column definition. public func check(@noescape condition: (SQLColumn) -> SQLExpressible) -> ColumnDefinition { - checkExpression = condition(SQLColumn(name)).sqlExpression + checkConstraints.append(condition(SQLColumn(name)).sqlExpression) return self } @@ -516,7 +516,7 @@ public final class ColumnDefinition { /// - parameter sql: An SQL snippet. /// - returns: Self so that you can further refine the column definition. public func check(sql sql: String) -> ColumnDefinition { - checkExpression = _SQLExpression.Literal(sql, nil) + checkConstraints.append(_SQLExpression.Literal(sql, nil)) return self } @@ -638,10 +638,10 @@ public final class ColumnDefinition { chunks.append(conflictResolution.rawValue) } - if let checkExpression = checkExpression { + for checkConstraint in checkConstraints { chunks.append("CHECK") - var arguments: StatementArguments? = nil // nil so that checkExpression.sql(&arguments) embeds literals - chunks.append("(" + checkExpression.sql(&arguments) + ")") + var arguments: StatementArguments? = nil // nil so that checkConstraint.sql(&arguments) embeds literals + chunks.append("(" + checkConstraint.sql(&arguments) + ")") } if let defaultExpression = defaultExpression { From 936d2e56ea10cbc8c973c51ffd2d74f798ae509c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Aug 2016 09:08:06 +0200 Subject: [PATCH 16/20] CHANGELOG.md --- CHANGELOG.md | 13 +++++++++++++ TODO.md | 2 +- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index eec65bc98..c73f4459a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,19 @@ Release Notes ## Next Version +**Fixed** + +- `ColumnDefinition.check()` can now define several constraints: + + ```swift + try db.create(table: "users") { t in + t.column("name", .Text).notNull() + .check { length($0) > 0 } + .check { !["root", "admin"].contains($0) } + } + ``` + + **New** - Persistable `update`, `exists` and `delete` methods now work with objects that have a nil primary key. They used to crash. diff --git a/TODO.md b/TODO.md index 87e44a73c..bc803908e 100644 --- a/TODO.md +++ b/TODO.md @@ -2,7 +2,7 @@ - [ ] @hdlj: FetchedRecordsController throttling - [ ] @hdlj: Check RAM pressure - [ ] Table builder: allow several foreign keys on a columns -- [ ] Table builder: allow checks on a columns +- [X] Table builder: allow checks on a columns - [X] Record.exists(db) should return false when primary key is nil - [X] Record.update(db) should throw, not crash, when primary key is nil - [ ] Fatal Error when MutablePersistable.update(_:columns:) is given columns that do not exist in the database. From 4d9c7d0dcbcf852435cc3965ed74c6b24cff07c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Aug 2016 13:23:19 +0200 Subject: [PATCH 17/20] Failing test for multiple foreign keys on a column --- Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift index 04cd5697c..c0b998632 100644 --- a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -213,11 +213,13 @@ class SQLTableBuilderTests: GRDBTestCase { try db.create(table: "child") { t in t.column("parentName", .Text).references("parent", onDelete: .Cascade, onUpdate: .Cascade) t.column("parentEmail", .Text).references("parent", column: "email", onDelete: .Restrict, deferred: true) + t.column("weird", .Text).references("parent", column: "name").references("parent", column: "email") } XCTAssertEqual(self.lastSQLQuery, "CREATE TABLE \"child\" (" + "\"parentName\" TEXT REFERENCES \"parent\"(\"name\") ON DELETE CASCADE ON UPDATE CASCADE, " + - "\"parentEmail\" TEXT REFERENCES \"parent\"(\"email\") ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED" + + "\"parentEmail\" TEXT REFERENCES \"parent\"(\"email\") ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED, " + + "\"weird\" TEXT REFERENCES \"parent\"(\"name\") REFERENCES \"parent\"(\"email\")" + ")") } } From d9e77284c1218e8e2077b49a54745e8ad5a3d8ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Aug 2016 13:23:24 +0200 Subject: [PATCH 18/20] Pass test for multiple foreign keys on a column --- CHANGELOG.md | 2 +- GRDB/QueryInterface/SQLTableBuilder.swift | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c73f4459a..71144c76c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ Release Notes **Fixed** -- `ColumnDefinition.check()` can now define several constraints: +- ColumnDefinition `check` and `references` methods can now define several constraints: ```swift try db.create(table: "users") { t in diff --git a/GRDB/QueryInterface/SQLTableBuilder.swift b/GRDB/QueryInterface/SQLTableBuilder.swift index 782f13656..a9af9a287 100644 --- a/GRDB/QueryInterface/SQLTableBuilder.swift +++ b/GRDB/QueryInterface/SQLTableBuilder.swift @@ -429,9 +429,9 @@ public final class ColumnDefinition { private var notNullConflictResolution: SQLConflictResolution? private var uniqueConflictResolution: SQLConflictResolution? private var checkConstraints: [_SQLExpression] = [] + private var foreignKeyConstraints: [(table: String, column: String?, deleteAction: SQLForeignKeyAction?, updateAction: SQLForeignKeyAction?, deferred: Bool)] = [] private var defaultExpression: _SQLExpression? private var collationName: String? - private var reference: (table: String, column: String?, deleteAction: SQLForeignKeyAction?, updateAction: SQLForeignKeyAction?, deferred: Bool)? init(name: String, type: SQLColumnType) { self.name = name @@ -598,7 +598,7 @@ public final class ColumnDefinition { /// See https://www.sqlite.org/foreignkeys.html#fk_deferred. /// - returns: Self so that you can further refine the column definition. public func references(table: String, column: String? = nil, onDelete deleteAction: SQLForeignKeyAction? = nil, onUpdate updateAction: SQLForeignKeyAction? = nil, deferred: Bool = false) -> ColumnDefinition { - reference = (table: table, column: column, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred) + foreignKeyConstraints.append((table: table, column: column, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred)) return self } @@ -655,7 +655,7 @@ public final class ColumnDefinition { chunks.append(collationName) } - if let (table, column, deleteAction, updateAction, deferred) = reference { + for (table, column, deleteAction, updateAction, deferred) in foreignKeyConstraints { chunks.append("REFERENCES") if let column = column { chunks.append("\(table.quotedDatabaseIdentifier)(\(column.quotedDatabaseIdentifier))") @@ -704,7 +704,7 @@ private struct IndexDefinition { chunks.append("\(table.quotedDatabaseIdentifier)(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joinWithSeparator(", ")))") if let condition = condition { chunks.append("WHERE") - var arguments: StatementArguments? = nil // nil so that checkExpression.sql(&arguments) embeds literals + var arguments: StatementArguments? = nil // nil so that condition.sql(&arguments) embeds literals chunks.append(condition.sql(&arguments)) } return chunks.joinWithSeparator(" ") From 60e0a731ad89e94ad6d254b01e8e58bdc69316ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Aug 2016 18:54:32 +0200 Subject: [PATCH 19/20] Partial updates now requires updated columns to be present in the persistentDictionary. --- CHANGELOG.md | 7 ++-- GRDB/Record/Persistable.swift | 33 ++++++++++------- TODO.md | 5 --- .../Persistable/MutablePersistableTests.swift | 35 ++++++++++++------- 4 files changed, 45 insertions(+), 35 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 71144c76c..8226cbb18 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ Release Notes **Fixed** -- ColumnDefinition `check` and `references` methods can now define several constraints: +- [ColumnDefinition](https://github.com/groue/GRDB.swift#database-schema) `check` and `references` methods can now define several constraints: ```swift try db.create(table: "users") { t in @@ -15,10 +15,9 @@ Release Notes } ``` +- [Persistable](https://github.com/groue/GRDB.swift#persistable-protocol) `update`, `exists` and `delete` methods now work with objects that have a nil primary key. They used to crash. -**New** - -- Persistable `update`, `exists` and `delete` methods now work with objects that have a nil primary key. They used to crash. +- The `update(_:columns:)` method, which performs partial updates, no longer ignores unknown columns. ## 0.79.0 diff --git a/GRDB/Record/Persistable.swift b/GRDB/Record/Persistable.swift index 399c4f75d..c3dea2e71 100644 --- a/GRDB/Record/Persistable.swift +++ b/GRDB/Record/Persistable.swift @@ -517,10 +517,10 @@ final class DAO { /// The database let db: Database - /// The persistable - let persistable: MutablePersistable + /// The record + let record: MutablePersistable - /// DAO keeps a copy the persistable's persistentDictionary, so that this + /// DAO keeps a copy the record's persistentDictionary, so that this /// dictionary is built once whatever the database operation. It is /// guaranteed to have at least one (key, value) pair. let persistentDictionary: [String: DatabaseValueConvertible?] @@ -531,17 +531,17 @@ final class DAO { /// The table primary key let primaryKey: PrimaryKeyInfo? - init(_ db: Database, _ persistable: MutablePersistable) { + init(_ db: Database, _ record: MutablePersistable) { // Fail early if database table does not exist. - let databaseTableName = persistable.dynamicType.databaseTableName() + let databaseTableName = record.dynamicType.databaseTableName() let primaryKey = try! db.primaryKey(databaseTableName) // Fail early if persistentDictionary is empty - let persistentDictionary = persistable.persistentDictionary - GRDBPrecondition(persistentDictionary.count > 0, "\(persistable.dynamicType).persistentDictionary: invalid empty dictionary") + let persistentDictionary = record.persistentDictionary + GRDBPrecondition(persistentDictionary.count > 0, "\(record.dynamicType).persistentDictionary: invalid empty dictionary") self.db = db - self.persistable = persistable + self.record = record self.persistentDictionary = persistentDictionary self.databaseTableName = databaseTableName self.primaryKey = primaryKey @@ -563,11 +563,18 @@ final class DAO { let primaryKeyValues = databaseValues(forColumns: primaryKeyColumns, inDictionary: persistentDictionary) guard primaryKeyValues.contains({ !$0.isNull }) else { return nil } - // Don't update primary key columns - var updatedColumns = Array(persistentDictionary.keys) - .map { $0.lowercaseString } - .filter { (lowercaseKey: String) in columns.contains { $0.lowercaseString == lowercaseKey } } - .filter { (lowercaseKey: String) in !primaryKeyColumns.contains { $0.lowercaseString == lowercaseKey } } + let lowercasePersistentColumns = Set(persistentDictionary.keys.map { $0.lowercaseString }) + let lowercasePrimaryKeyColumns = Set(primaryKeyColumns.map { $0.lowercaseString }) + var updatedColumns: [String] = [] + for column in columns { + let lowercaseColumn = column.lowercaseString + // Make sure the requested column is present in persistentDictionary + GRDBPrecondition(lowercasePersistentColumns.contains(lowercaseColumn), "column \(column) can't be updated because it is missing from persistentDictionary") + // Don't update primary key columns + guard !lowercasePrimaryKeyColumns.contains(column) else { continue } + updatedColumns.append(column) + } + if updatedColumns.isEmpty { // IMPLEMENTATION NOTE // diff --git a/TODO.md b/TODO.md index bc803908e..c638fbfe1 100644 --- a/TODO.md +++ b/TODO.md @@ -1,11 +1,6 @@ - [ ] @hdlj: Extensibility of the Query Interface - [ ] @hdlj: FetchedRecordsController throttling - [ ] @hdlj: Check RAM pressure -- [ ] Table builder: allow several foreign keys on a columns -- [X] Table builder: allow checks on a columns -- [X] Record.exists(db) should return false when primary key is nil -- [X] Record.update(db) should throw, not crash, when primary key is nil -- [ ] Fatal Error when MutablePersistable.update(_:columns:) is given columns that do not exist in the database. - [ ] What is the behavior inTransaction and inSavepoint behaviors in case of commit error? Code looks like we do not rollback, leaving the app in a weird state (out of Swift transaction block with a SQLite transaction that may still be opened). - [ ] GRDBCipher: remove limitations on iOS or OS X versions - [ ] FetchedRecordsController: take inspiration from https://github.com/jflinter/Dwifft diff --git a/Tests/Public/Core/Persistable/MutablePersistableTests.swift b/Tests/Public/Core/Persistable/MutablePersistableTests.swift index 07b507cfb..c0cc061a7 100644 --- a/Tests/Public/Core/Persistable/MutablePersistableTests.swift +++ b/Tests/Public/Core/Persistable/MutablePersistableTests.swift @@ -10,13 +10,14 @@ import XCTest private struct MutablePersistablePerson : MutablePersistable { var id: Int64? var name: String? + var age: Int? static func databaseTableName() -> String { return "persons" } var persistentDictionary: [String: DatabaseValueConvertible?] { - return ["id": id, "name": name] + return ["id": id, "name": name, "age": age] } mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) { @@ -98,7 +99,8 @@ class MutablePersistableTests: GRDBTestCase { try db.execute( "CREATE TABLE persons (" + "id INTEGER PRIMARY KEY, " + - "name NOT NULL " + + "name NOT NULL, " + + "age INTEGER" + ")") try db.execute( "CREATE TABLE countries (" + @@ -116,7 +118,7 @@ class MutablePersistableTests: GRDBTestCase { assertNoError { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var person = MutablePersistablePerson(id: nil, name: "Arthur") + var person = MutablePersistablePerson(id: nil, name: "Arthur", age: 24) try person.insert(db) let rows = Row.fetchAll(db, "SELECT * FROM persons") @@ -131,9 +133,9 @@ class MutablePersistableTests: GRDBTestCase { assertNoError { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var person1 = MutablePersistablePerson(id: nil, name: "Arthur") + var person1 = MutablePersistablePerson(id: nil, name: "Arthur", age: 24) try person1.insert(db) - var person2 = MutablePersistablePerson(id: nil, name: "Barbara") + var person2 = MutablePersistablePerson(id: nil, name: "Barbara", age: 24) try person2.insert(db) person1.name = "Craig" @@ -153,9 +155,9 @@ class MutablePersistableTests: GRDBTestCase { assertNoError { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var person1 = MutablePersistablePerson(id: nil, name: "Arthur") + var person1 = MutablePersistablePerson(id: nil, name: "Arthur", age: 24) try person1.insert(db) - var person2 = MutablePersistablePerson(id: nil, name: "Barbara") + var person2 = MutablePersistablePerson(id: nil, name: "Barbara", age: 36) try person2.insert(db) do { @@ -166,32 +168,39 @@ class MutablePersistableTests: GRDBTestCase { XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + XCTAssertEqual(rows[0].value(named: "age") as Int, 24) XCTAssertEqual(rows[1].value(named: "id") as Int64, person2.id!) XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") + XCTAssertEqual(rows[1].value(named: "age") as Int, 36) } do { person1.name = "Craig" + person1.age = 25 try person1.update(db, columns: [SQLColumn("name")]) let rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) XCTAssertEqual(rows[0].value(named: "name") as String, "Craig") + XCTAssertEqual(rows[0].value(named: "age") as Int, 24) XCTAssertEqual(rows[1].value(named: "id") as Int64, person2.id!) XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") + XCTAssertEqual(rows[1].value(named: "age") as Int, 36) } do { person1.name = "David" - try person1.update(db, columns: ["age"]) + try person1.update(db, columns: ["AgE"]) // case insensitivity let rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) XCTAssertEqual(rows[0].value(named: "name") as String, "Craig") + XCTAssertEqual(rows[0].value(named: "age") as Int, 25) XCTAssertEqual(rows[1].value(named: "id") as Int64, person2.id!) XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") + XCTAssertEqual(rows[1].value(named: "age") as Int, 36) } } } @@ -201,7 +210,7 @@ class MutablePersistableTests: GRDBTestCase { assertNoError { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var person1 = MutablePersistablePerson(id: nil, name: "Arthur") + var person1 = MutablePersistablePerson(id: nil, name: "Arthur", age: 24) try person1.save(db) var rows = Row.fetchAll(db, "SELECT * FROM persons") @@ -209,7 +218,7 @@ class MutablePersistableTests: GRDBTestCase { XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") - var person2 = MutablePersistablePerson(id: nil, name: "Barbara") + var person2 = MutablePersistablePerson(id: nil, name: "Barbara", age: 24) try person2.save(db) person1.name = "Craig" @@ -239,9 +248,9 @@ class MutablePersistableTests: GRDBTestCase { assertNoError { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var person1 = MutablePersistablePerson(id: nil, name: "Arthur") + var person1 = MutablePersistablePerson(id: nil, name: "Arthur", age: 24) try person1.insert(db) - var person2 = MutablePersistablePerson(id: nil, name: "Barbara") + var person2 = MutablePersistablePerson(id: nil, name: "Barbara", age: 24) try person2.insert(db) // TODO: test delete return value @@ -259,7 +268,7 @@ class MutablePersistableTests: GRDBTestCase { assertNoError { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var person = MutablePersistablePerson(id: nil, name: "Arthur") + var person = MutablePersistablePerson(id: nil, name: "Arthur", age: 24) try person.insert(db) XCTAssertTrue(person.exists(db)) From ceb73730c2a1a5d8914a8a844a1a745e7e8562b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Aug 2016 18:56:23 +0200 Subject: [PATCH 20/20] v0.79.1 --- CHANGELOG.md | 4 +++- GRDB.swift.podspec | 2 +- README.md | 24 ++++++++++++------------ Support/Info.plist | 2 +- 4 files changed, 17 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8226cbb18..2841d2af3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,9 @@ Release Notes ============= -## Next Version +## 0.79.1 + +Released August 10, 2016 **Fixed** diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 74b849a1f..37a25465e 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '0.79.0' + s.version = '0.79.1' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A Swift application toolkit for SQLite databases.' s.homepage = 'https://github.com/groue/GRDB.swift' diff --git a/README.md b/README.md index d416e2ce6..f53eb30f6 100644 --- a/README.md +++ b/README.md @@ -3,9 +3,9 @@ GRDB.swift [![Swift](https://img.shields.io/badge/swift-2.2-orange.svg?style=fla ### A Swift application toolkit for SQLite databases. -**Requirements**: iOS 8.0+ / OSX 10.9+ • Xcode 7.3+ • Swift 2.2 (see the [Swift3](https://github.com/groue/GRDB.swift/tree/Swift3) branch for Swift 3). +**Latest release**: August 10, 2016 • version 0.79.1 • [CHANGELOG](CHANGELOG.md) -**Latest release**: August 8, 2016 • version 0.79.0 • [CHANGELOG](CHANGELOG.md) +**Requirements**: iOS 8.0+ / OSX 10.9+ • Xcode 7.3+ • Swift 2.2 (see the [Swift3](https://github.com/groue/GRDB.swift/tree/Swift3) branch for Swift 3). Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips. @@ -163,7 +163,7 @@ Documentation **Reference** -- [GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.79.0/index.html) (on cocoadocs.org) +- [GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.79.1/index.html) (on cocoadocs.org) **Getting Started** @@ -213,7 +213,7 @@ To use GRDB with CocoaPods, specify in your Podfile: source 'https://github.com/CocoaPods/Specs.git' use_frameworks! -pod 'GRDB.swift', '~> 0.79.0' +pod 'GRDB.swift' ``` > :point_up: **Note**: [SQLCipher](#encryption) and [custom SQLite builds](#custom-sqlite-builds) are not available via CocoaPods. @@ -226,7 +226,7 @@ pod 'GRDB.swift', '~> 0.79.0' To use GRDB with Carthage, specify in your Cartfile: ``` -github "groue/GRDB.swift" ~> 0.79.0 +github "groue/GRDB.swift" ``` > :point_up: **Note**: [custom SQLite builds](#custom-sqlite-builds) are not available via Carthage. @@ -335,7 +335,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.79.0/Structs/Configuration.html) for more details. +See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.79.1/Structs/Configuration.html) for more details. ## Database Pools @@ -415,7 +415,7 @@ let dbPool = try DatabasePool( configuration: config) ``` -See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.79.0/Structs/Configuration.html) for more details. +See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.79.1/Structs/Configuration.html) for more details. Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information. @@ -1514,10 +1514,10 @@ for person in Person.fetch(db, sql, adapter: adapter) { For more information about row adapters, see the documentation of: -- [RowAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.79.0/Protocols/RowAdapter.html): the protocol that lets you define your custom row adapters -- [ColumnMapping](http://cocoadocs.org/docsets/GRDB.swift/0.79.0/Structs/ColumnMapping.html): a row adapter that renames row columns -- [SuffixRowAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.79.0/Structs/SuffixRowAdapter.html): a row adapter that hides the first columns of a row -- [ScopeAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.79.0/Structs/ScopeAdapter.html): the row adapter that groups several adapters together to define scopes +- [RowAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.79.1/Protocols/RowAdapter.html): the protocol that lets you define your custom row adapters +- [ColumnMapping](http://cocoadocs.org/docsets/GRDB.swift/0.79.1/Structs/ColumnMapping.html): a row adapter that renames row columns +- [SuffixRowAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.79.1/Structs/SuffixRowAdapter.html): a row adapter that hides the first columns of a row +- [ScopeAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.79.1/Structs/ScopeAdapter.html): the row adapter that groups several adapters together to define scopes ## Raw SQLite Pointers @@ -3669,7 +3669,7 @@ let count2 = dbQueue.inDatabase { db in SQLite concurrency is a wiiide topic. -First have a detailed look at the full API of [DatabaseQueue](http://cocoadocs.org/docsets/GRDB.swift/0.79.0/Classes/DatabaseQueue.html) and [DatabasePool](http://cocoadocs.org/docsets/GRDB.swift/0.79.0/Classes/DatabasePool.html). Both adopt the [DatabaseReader](http://cocoadocs.org/docsets/GRDB.swift/0.79.0/Protocols/DatabaseReader.html) and [DatabaseWriter](http://cocoadocs.org/docsets/GRDB.swift/0.79.0/Protocols/DatabaseWriter.html) protocols, so that you can write code that targets both classes. +First have a detailed look at the full API of [DatabaseQueue](http://cocoadocs.org/docsets/GRDB.swift/0.79.1/Classes/DatabaseQueue.html) and [DatabasePool](http://cocoadocs.org/docsets/GRDB.swift/0.79.1/Classes/DatabasePool.html). Both adopt the [DatabaseReader](http://cocoadocs.org/docsets/GRDB.swift/0.79.1/Protocols/DatabaseReader.html) and [DatabaseWriter](http://cocoadocs.org/docsets/GRDB.swift/0.79.1/Protocols/DatabaseWriter.html) protocols, so that you can write code that targets both classes. If the built-in queues and pools do not fit your needs, or if you can not guarantee that a single queue or pool is accessing your database file, you may have a look at: diff --git a/Support/Info.plist b/Support/Info.plist index b16de5fb6..69379b2f6 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 0.79.0 + 0.79.1 CFBundleSignature ???? CFBundleVersion