From f04972a9024d25e3cc8c3a0d71a406f4e7e56ccd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 25 Jul 2016 09:00:57 +0200 Subject: [PATCH 01/17] Documentation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cfb072a53..089de97a8 100644 --- a/README.md +++ b/README.md @@ -750,7 +750,7 @@ for (columnName, databaseValue) in row { let row = Row(["name": "foo", "date": nil]) ``` -Yet rows are not real dictionaries, because they may contain duplicate keys: +Yet rows are not real dictionaries: they are ordered, and may contain duplicate keys: ```swift let row = Row.fetchOne(db, "SELECT 1 AS foo, 2 AS foo")! From d8ada8c9d372d0d0d83774dd5309fd82f65d634e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 26 Jul 2016 06:47:33 +0200 Subject: [PATCH 02/17] TODO.md --- TODO.md | 1 + 1 file changed, 1 insertion(+) diff --git a/TODO.md b/TODO.md index bbafadd59..2d1ffc459 100644 --- a/TODO.md +++ b/TODO.md @@ -1,3 +1,4 @@ +- [ ] Partial update. update(db) should call update(db, columns: [String]) (single point of override) - [ ] Fix "More, when you're interested in specific table columns, you're out of luck, because databaseDidChange does not know about columns: it just knows that a row has been inserted, deleted, or updated, without further detail" - [ ] GRDBCipher: remove limitations on iOS or OS X versions - [ ] FetchedRecordsController: take inspiration from https://github.com/jflinter/Dwifft From 50ce433bcb426bb4fef4d212a7705107cf24fee9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 28 Jul 2016 08:25:08 +0200 Subject: [PATCH 03/17] Partial update WIP: public API --- GRDB/Record/Persistable.swift | 44 ++++++++++++++++--- GRDB/Record/Record.swift | 8 ++-- README.md | 6 ++- .../Persistable/MutablePersistableTests.swift | 4 +- .../Core/Persistable/PersistableTests.swift | 4 +- Tests/Public/Record/RecordSubClassTests.swift | 4 +- 6 files changed, 54 insertions(+), 16 deletions(-) diff --git a/GRDB/Record/Persistable.swift b/GRDB/Record/Persistable.swift index 3a4a0e164..0a74ffa61 100644 --- a/GRDB/Record/Persistable.swift +++ b/GRDB/Record/Persistable.swift @@ -115,11 +115,13 @@ public protocol MutablePersistable : TableMapping { /// implementation of update(). In their implementation, it is recommended /// that they invoke the performUpdate() method. /// + /// TODO: columns + /// /// - parameter db: A database connection. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. /// PersistenceError.NotFound is thrown if the primary key does not /// match any row in the database. - func update(db: Database) throws + func update(db: Database, columns: Set) throws /// Executes an INSERT or an UPDATE statement so that `self` is saved in /// the database. @@ -187,9 +189,39 @@ public extension MutablePersistable { /// Executes an UPDATE statement. /// + /// TODO: columns + /// + /// The default implementation for update() invokes performUpdate(). + func update(db: Database, columns: Set) throws { + try performUpdate(db, columns: columns) + } + + /// Executes an UPDATE statement. + /// + /// TODO: columns + /// + /// The default implementation for update() invokes performUpdate(). + func update(db: Database, columns: S) throws { + try update(db, columns: Set(columns.map { $0.name })) + } + + /// Executes an UPDATE statement. + /// + /// TODO: columns + /// + /// The default implementation for update() invokes performUpdate(). + func update(db: Database, columns: S) throws { + try update(db, columns: Set(columns)) + } + + /// Executes an UPDATE statement. + /// + /// TODO: columns + /// /// The default implementation for update() invokes performUpdate(). func update(db: Database) throws { - try performUpdate(db) + // TODO + try update(db, columns: Set()) } /// Executes an INSERT or an UPDATE statement so that `self` is saved in @@ -248,12 +280,14 @@ public extension MutablePersistable { /// Don't invoke this method directly: it is an internal method for types /// that adopt MutablePersistable. /// + /// TODO: columns + /// /// performUpdate() provides the default implementation for update(). Types /// that adopt MutablePersistable can invoke performUpdate() in their /// implementation of update(). They should not provide their own /// implementation of performUpdate(). - func performUpdate(db: Database) throws { - try DataMapper(db, self).updateStatement().execute() + func performUpdate(db: Database, columns: Set) throws { + try DataMapper(db, self).updateStatement(columns: columns).execute() if db.changesCount == 0 { throw PersistenceError.NotFound(self) } @@ -499,7 +533,7 @@ final class DataMapper { return statement } - func updateStatement() -> UpdateStatement { + 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) diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index c7bc8dcc2..7bbc9e964 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -249,14 +249,16 @@ public class Record : RowConvertible, TableMapping, Persistable { /// This method is guaranteed to have updated a row in the database if it /// returns without error. /// + /// TODO: columns + /// /// - parameter db: A database connection. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. /// PersistenceError.NotFound is thrown if the primary key does not match /// any row in the database and record could not be updated. - public func update(db: Database) throws { + public func update(db: Database, columns: Set) throws { // The simplest code would be: // - // try performUpdate(db) + // try performUpdate(db, columns: columns) // hasPersistentChangedValues = false // // But this triggers two calls to persistentDictionary, and this is both @@ -266,7 +268,7 @@ 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().execute() + try dataMapper.updateStatement(columns: columns).execute() if db.changesCount == 0 { throw PersistenceError.NotFound(self) } diff --git a/README.md b/README.md index 089de97a8..64249eab3 100644 --- a/README.md +++ b/README.md @@ -1860,6 +1860,8 @@ paris.id // some value [Record](#record-class) subclasses and types that adopt [Persistable](#persistable-protocol) are given default implementations for methods that insert, update, and delete: +TODO: update columns + ```swift try pointOfInterest.insert(db) // INSERT try pointOfInterest.update(db) // UPDATE @@ -1917,9 +1919,9 @@ struct Link : Persistable { try performInsert(db) } - func update(db: Database) throws { + func update(db: Database, columns: Set) throws { try validate() - try performUpdate(db) + try performUpdate(db, columns: columns) } func validate() throws { diff --git a/Tests/Public/Core/Persistable/MutablePersistableTests.swift b/Tests/Public/Core/Persistable/MutablePersistableTests.swift index 19ff3c026..a2fa893dc 100644 --- a/Tests/Public/Core/Persistable/MutablePersistableTests.swift +++ b/Tests/Public/Core/Persistable/MutablePersistableTests.swift @@ -69,9 +69,9 @@ private struct MutablePersistableCustomizedCountry : MutablePersistable { try performInsert(db) } - func update(db: Database) throws { + func update(db: Database, columns: Set) throws { willUpdate() - try performUpdate(db) + try performUpdate(db, columns: columns) } mutating func save(db: Database) throws { diff --git a/Tests/Public/Core/Persistable/PersistableTests.swift b/Tests/Public/Core/Persistable/PersistableTests.swift index 7a58d0094..3791c76d3 100644 --- a/Tests/Public/Core/Persistable/PersistableTests.swift +++ b/Tests/Public/Core/Persistable/PersistableTests.swift @@ -79,9 +79,9 @@ private struct PersistableCustomizedCountry : Persistable { try performInsert(db) } - func update(db: Database) throws { + func update(db: Database, columns: Set) throws { willUpdate() - try performUpdate(db) + try performUpdate(db, columns: columns) } func save(db: Database) throws { diff --git a/Tests/Public/Record/RecordSubClassTests.swift b/Tests/Public/Record/RecordSubClassTests.swift index 71c7190e9..522cfb66b 100644 --- a/Tests/Public/Record/RecordSubClassTests.swift +++ b/Tests/Public/Record/RecordSubClassTests.swift @@ -104,9 +104,9 @@ private class PersonWithOverrides : Person { try super.insert(db) } - override func update(db: Database) throws { + override func update(db: Database, columns: Set) throws { lastSavingMethod = .Update - try super.update(db) + try super.update(db, columns: columns) } } From 548ff068fd8ccf81d5e6604f98b46c34adf2b1e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 28 Jul 2016 08:41:22 +0200 Subject: [PATCH 04/17] Partial update WIP: implementation --- GRDB/Core/Database.swift | 44 ++++++++++++++++++++++++++++++++++- GRDB/Record/Persistable.swift | 11 +++++---- 2 files changed, 50 insertions(+), 5 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index b17e330a4..1b3ab6bcd 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -893,6 +893,48 @@ extension Database { return primaryKey } + /// The columns in table named `tableName`. + /// + /// - throws: A DatabaseError if table does not exist. + func columns(in tableName: String) throws -> [ColumnInfo] { + // https://www.sqlite.org/pragma.html + // + // > PRAGMA database.table_info(table-name); + // > + // > This pragma returns one row for each column in the named table. + // > Columns in the result set include the column name, data type, + // > whether or not the column can be NULL, and the default value for + // > the column. The "pk" column in the result set is zero for columns + // > that are not part of the primary key, and is the index of the + // > column in the primary key for columns that are part of the primary + // > key. + // + // CREATE TABLE persons ( + // id INTEGER PRIMARY KEY, + // firstName TEXT, + // lastName TEXT) + // + // PRAGMA table_info("persons") + // + // cid | name | type | notnull | dflt_value | pk | + // 0 | id | INTEGER | 0 | NULL | 1 | + // 1 | firstName | TEXT | 0 | NULL | 0 | + // 2 | lastName | TEXT | 0 | NULL | 0 | + + if #available(iOS 8.2, OSX 10.10, *) { } else { + // Work around a bug in SQLite where PRAGMA table_info would + // return a result even after the table was deleted. + if !tableExists(tableName) { + throw DatabaseError(message: "no such table: \(tableName)") + } + } + let columnInfos = ColumnInfo.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))") + guard columnInfos.count > 0 else { + throw DatabaseError(message: "no such table: \(tableName)") + } + return columnInfos + } + /// The indexes on table named `tableName`; returns the empty array if the /// table does not exist. /// @@ -947,7 +989,7 @@ extension Database { // 0 | id | INTEGER | 0 | NULL | 1 | // 1 | firstName | TEXT | 0 | NULL | 0 | // 2 | lastName | TEXT | 0 | NULL | 0 | - private struct ColumnInfo : RowConvertible { + struct ColumnInfo : RowConvertible { let name: String let type: String let notNull: Bool diff --git a/GRDB/Record/Persistable.swift b/GRDB/Record/Persistable.swift index 0a74ffa61..ea561275b 100644 --- a/GRDB/Record/Persistable.swift +++ b/GRDB/Record/Persistable.swift @@ -220,8 +220,9 @@ public extension MutablePersistable { /// /// The default implementation for update() invokes performUpdate(). func update(db: Database) throws { - // TODO - try update(db, columns: Set()) + let databaseTableName = self.dynamicType.databaseTableName() + let columns = try db.columns(in: databaseTableName) + try update(db, columns: Set(columns.map { $0.name })) } /// Executes an INSERT or an UPDATE statement so that `self` is saved in @@ -539,8 +540,10 @@ final class DataMapper { 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((", ")))") - // Update everything but primary key - var updatedColumns = persistentDictionary.keys.removingElementsOf(primaryKeyColumns) + // Don't update primary key columns + var updatedColumns = Array(persistentDictionary.keys) + .filter { columns.contains($0.lowercaseString) } + .filter { !primaryKeyColumns.contains($0.lowercaseString) } if updatedColumns.isEmpty { // IMPLEMENTATION NOTE // From 176a23fe977feb83e813569866bd4d1cd958430a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 28 Jul 2016 08:53:17 +0200 Subject: [PATCH 05/17] Partial update WIP: tests --- GRDB/Record/Persistable.swift | 4 +- .../Persistable/MutablePersistableTests.swift | 48 +++++++ .../Core/Persistable/PersistableTests.swift | 131 ++++++++++++++++++ 3 files changed, 181 insertions(+), 2 deletions(-) diff --git a/GRDB/Record/Persistable.swift b/GRDB/Record/Persistable.swift index ea561275b..3c6f8dc08 100644 --- a/GRDB/Record/Persistable.swift +++ b/GRDB/Record/Persistable.swift @@ -542,8 +542,8 @@ final class DataMapper { // Don't update primary key columns var updatedColumns = Array(persistentDictionary.keys) - .filter { columns.contains($0.lowercaseString) } - .filter { !primaryKeyColumns.contains($0.lowercaseString) } + .filter { columns.contains($0) } + .filter { !primaryKeyColumns.contains($0) } if updatedColumns.isEmpty { // IMPLEMENTATION NOTE // diff --git a/Tests/Public/Core/Persistable/MutablePersistableTests.swift b/Tests/Public/Core/Persistable/MutablePersistableTests.swift index a2fa893dc..07b507cfb 100644 --- a/Tests/Public/Core/Persistable/MutablePersistableTests.swift +++ b/Tests/Public/Core/Persistable/MutablePersistableTests.swift @@ -149,6 +149,54 @@ class MutablePersistableTests: GRDBTestCase { } } + func testPartialUpdateMutablePersistablePerson() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var person1 = MutablePersistablePerson(id: nil, name: "Arthur") + try person1.insert(db) + var person2 = MutablePersistablePerson(id: nil, name: "Barbara") + try person2.insert(db) + + do { + person1.name = "Craig" + try person1.update(db, columns: [String]()) + + 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, "Arthur") + XCTAssertEqual(rows[1].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") + } + + do { + person1.name = "Craig" + 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[1].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") + } + + do { + person1.name = "David" + try person1.update(db, columns: ["age"]) + + 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[1].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") + } + } + } + } + func testSaveMutablePersistablePerson() { assertNoError { let dbQueue = try makeDatabaseQueue() diff --git a/Tests/Public/Core/Persistable/PersistableTests.swift b/Tests/Public/Core/Persistable/PersistableTests.swift index 3791c76d3..f54f3fe27 100644 --- a/Tests/Public/Core/Persistable/PersistableTests.swift +++ b/Tests/Public/Core/Persistable/PersistableTests.swift @@ -209,6 +209,54 @@ class PersistableTests: GRDBTestCase { } } + func testPartialUpdatePersistablePersonClass() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let person1 = PersistablePersonClass(id: nil, name: "Arthur", age: 42) + try person1.insert(db) + let person2 = PersistablePersonClass(id: nil, name: "Barbara", age: 39) + try person2.insert(db) + + do { + person1.name = "Craig" + try person1.update(db, columns: [String]()) + + 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, "Arthur") + XCTAssertEqual(rows[1].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") + } + + do { + person1.name = "Craig" + 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[1].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") + } + + do { + person1.name = "David" + try person1.update(db, columns: ["age"]) + + 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[1].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") + } + } + } + } + func testSavePersistablePersonClass() { assertNoError { let dbQueue = try makeDatabaseQueue() @@ -322,6 +370,42 @@ class PersistableTests: GRDBTestCase { } } + func testPartialUpdatePersistableCountry() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var country1 = PersistableCountry(isoCode: "FR", name: "France") + try country1.insert(db) + let country2 = PersistableCountry(isoCode: "US", name: "United States") + try country2.insert(db) + + do { + country1.name = "France Métropolitaine" + try country1.update(db, columns: [String]()) + + let rows = Row.fetchAll(db, "SELECT * FROM countries ORDER BY isoCode") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + XCTAssertEqual(rows[1].value(named: "isoCode") as String, "US") + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + } + + do { + country1.name = "France Métropolitaine" + try country1.update(db, columns: [SQLColumn("name")]) + + let rows = Row.fetchAll(db, "SELECT * FROM countries ORDER BY isoCode") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "isoCode") as String, "US") + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + } + } + } + } + func testSavePersistableCountry() { assertNoError { let dbQueue = try makeDatabaseQueue() @@ -478,6 +562,53 @@ class PersistableTests: GRDBTestCase { } } + func testPartialUpdatePersistableCustomizedCountry() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + var country1 = PersistableCustomizedCountry( + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country1.insert(db) + let country2 = PersistableCustomizedCountry( + isoCode: "US", + name: "United States", + willInsert: { }, + willUpdate: { }, + willSave: { }, + willDelete: { }, + willExists: { }) + try country2.insert(db) + + country1.name = "France Métropolitaine" + try country1.update(db, columns: ["name"]) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 1) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + let rows = Row.fetchAll(db, "SELECT * FROM countries ORDER BY isoCode") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "isoCode") as String, "US") + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + } + } + } + func testSavePersistableCustomizedCountry() { assertNoError { let dbQueue = try makeDatabaseQueue() From df7791a3e72531a4b5bf9219167b9641b2f4e7da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 28 Jul 2016 09:05:46 +0200 Subject: [PATCH 06/17] Partial update WIP: documentation --- CHANGELOG.md | 28 ++++++++++++++++++++++ GRDB/Record/Persistable.swift | 44 +++++++++++++++++++++-------------- GRDB/Record/Record.swift | 7 +++--- README.md | 13 +++++------ TODO.md | 1 + 5 files changed, 65 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 44b390710..e77569957 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,36 @@ Release Notes **New** - `Database.indexes(on:)` returns the indexes defined on a database table + - `Database.table(_:hasUniqueKey:)` returns true if a sequence of columns uniquely identifies a row, that is to say if the columns are the primary key, or if there is a unique index on them. +- MutablePersistable types, including Record subclasses, support partial updates: + + ```swift + try person.update(db) // Full update + try person.update(db, columns: ["age"]) // Only updates the age column + ``` + +**Breaking Changes** + +- MutablePersistable `update` and `performUpdate` methods have changed their signature: + + ```diff + protocol MutablePersistable : TableMapping { + -func update(db: Database) throws + +func update(db: Database, columns: Set) throws + } + + extension MutablePersistable { + func update(db: Database) throws + +func update(db: Database, columns: Set) throws + +func update(db: Database, columns: S) throws + +func update(db: Database, columns: S) throws + -func performUpdate(db: Database) throws + +func performUpdate(db: Database, columns: Set) throws + } + ``` + ## 0.76.0 diff --git a/GRDB/Record/Persistable.swift b/GRDB/Record/Persistable.swift index 3c6f8dc08..5313ec42a 100644 --- a/GRDB/Record/Persistable.swift +++ b/GRDB/Record/Persistable.swift @@ -115,9 +115,8 @@ public protocol MutablePersistable : TableMapping { /// implementation of update(). In their implementation, it is recommended /// that they invoke the performUpdate() method. /// - /// TODO: columns - /// /// - parameter db: A database connection. + /// - parameter columns: The columns to update. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. /// PersistenceError.NotFound is thrown if the primary key does not /// match any row in the database. @@ -189,36 +188,43 @@ public extension MutablePersistable { /// Executes an UPDATE statement. /// - /// TODO: columns - /// - /// The default implementation for update() invokes performUpdate(). + /// - parameter db: A database connection. + /// - parameter columns: The columns to update. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.NotFound is thrown if the primary key does not + /// match any row in the database. func update(db: Database, columns: Set) throws { try performUpdate(db, columns: columns) } /// Executes an UPDATE statement. /// - /// TODO: columns - /// - /// The default implementation for update() invokes performUpdate(). + /// - parameter db: A database connection. + /// - parameter columns: The columns to update. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.NotFound is thrown if the primary key does not + /// match any row in the database. func update(db: Database, columns: S) throws { try update(db, columns: Set(columns.map { $0.name })) } /// Executes an UPDATE statement. /// - /// TODO: columns - /// - /// The default implementation for update() invokes performUpdate(). + /// - parameter db: A database connection. + /// - parameter columns: The columns to update. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.NotFound is thrown if the primary key does not + /// match any row in the database. func update(db: Database, columns: S) throws { try update(db, columns: Set(columns)) } - /// Executes an UPDATE statement. + /// Executes an UPDATE statement that updates all table columns. /// - /// TODO: columns - /// - /// The default implementation for update() invokes performUpdate(). + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.NotFound is thrown if the primary key does not + /// match any row in the database. func update(db: Database) throws { let databaseTableName = self.dynamicType.databaseTableName() let columns = try db.columns(in: databaseTableName) @@ -281,12 +287,16 @@ public extension MutablePersistable { /// Don't invoke this method directly: it is an internal method for types /// that adopt MutablePersistable. /// - /// TODO: columns - /// /// performUpdate() provides the default implementation for update(). Types /// that adopt MutablePersistable can invoke performUpdate() in their /// implementation of update(). They should not provide their own /// implementation of performUpdate(). + /// + /// - parameter db: A database connection. + /// - parameter columns: The columns to update. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// 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() if db.changesCount == 0 { diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 7bbc9e964..9982e84f9 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -249,12 +249,11 @@ public class Record : RowConvertible, TableMapping, Persistable { /// This method is guaranteed to have updated a row in the database if it /// returns without error. /// - /// TODO: columns - /// /// - parameter db: A database connection. + /// - parameter columns: The columns to update. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.NotFound is thrown if the primary key does not match - /// any row in the database and record could not be updated. + /// PersistenceError.NotFound is thrown if the primary key does not + /// match any row in the database. public func update(db: Database, columns: Set) throws { // The simplest code would be: // diff --git a/README.md b/README.md index 64249eab3..4f5ce9bb5 100644 --- a/README.md +++ b/README.md @@ -1860,14 +1860,13 @@ paris.id // some value [Record](#record-class) subclasses and types that adopt [Persistable](#persistable-protocol) are given default implementations for methods that insert, update, and delete: -TODO: update columns - ```swift -try pointOfInterest.insert(db) // INSERT -try pointOfInterest.update(db) // UPDATE -try pointOfInterest.save(db) // Inserts or updates -try pointOfInterest.delete(db) // DELETE -pointOfInterest.exists(db) // Bool +try pointOfInterest.insert(db) // INSERT +try pointOfInterest.update(db) // UPDATE +try pointOfInterest.update(db, columns: ...) // UPDATE +try pointOfInterest.save(db) // Inserts or updates +try pointOfInterest.delete(db) // DELETE +pointOfInterest.exists(db) // Bool ``` - `insert`, `update`, `save` and `delete` can throw a [DatabaseError](#error-handling) whenever an SQLite integrity check fails. diff --git a/TODO.md b/TODO.md index 2d1ffc459..7847f404d 100644 --- a/TODO.md +++ b/TODO.md @@ -1,4 +1,5 @@ - [ ] Partial update. update(db) should call update(db, columns: [String]) (single point of override) + - [ ] cache columns - [ ] Fix "More, when you're interested in specific table columns, you're out of luck, because databaseDidChange does not know about columns: it just knows that a row has been inserted, deleted, or updated, without further detail" - [ ] GRDBCipher: remove limitations on iOS or OS X versions - [ ] FetchedRecordsController: take inspiration from https://github.com/jflinter/Dwifft From 1eac28a145dcc1506b00b9e6e0c1657565ee5f66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 28 Jul 2016 09:07:31 +0200 Subject: [PATCH 07/17] Fix typo --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4f5ce9bb5..e0765bd5b 100644 --- a/README.md +++ b/README.md @@ -103,11 +103,11 @@ try dbQueue.inDatabase { db in favorite: false, coordinate: CLLocationCoordinate2DMake(52.52437, 13.41053)) - try berlin.insert(dbQueue) + try berlin.insert(db) berlin.id // some value berlin.favorite = true - try berlin.update(dbQueue) + try berlin.update(db) // Fetch [PointOfInterest] from SQL let pois = PointOfInterest.fetchAll(db, "SELECT * FROM pointOfInterests") From faa076c1e99910a2d14cb7ec421656fa25d0769e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 28 Jul 2016 09:09:08 +0200 Subject: [PATCH 08/17] TODO.md --- TODO.md | 1 + 1 file changed, 1 insertion(+) diff --git a/TODO.md b/TODO.md index 7847f404d..86aefa283 100644 --- a/TODO.md +++ b/TODO.md @@ -1,5 +1,6 @@ - [ ] Partial update. update(db) should call update(db, columns: [String]) (single point of override) - [ ] cache columns + - [ ] columns should be case-insensitive - [ ] Fix "More, when you're interested in specific table columns, you're out of luck, because databaseDidChange does not know about columns: it just knows that a row has been inserted, deleted, or updated, without further detail" - [ ] GRDBCipher: remove limitations on iOS or OS X versions - [ ] FetchedRecordsController: take inspiration from https://github.com/jflinter/Dwifft From d2acc351a24f46a9f4a4df683d14ec8e7b696c2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 28 Jul 2016 09:59:45 +0200 Subject: [PATCH 09/17] README.md: link to the new blog post --- README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e0765bd5b..e9e3a516b 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,9 @@ GRDB.swift [![Swift](https://img.shields.io/badge/swift-2.2-orange.svg?style=flat)](https://developer.apple.com/swift/) [![Platforms](https://img.shields.io/cocoapods/p/GRDB.swift.svg)](https://developer.apple.com/swift/) [![License](https://img.shields.io/github/license/groue/GRDB.swift.svg?maxAge=2592000)](/LICENSE) ========== -GRDB.swift is an SQLite toolkit for Swift 2.2. For Swift 3, see the [Swift3](https://github.com/groue/GRDB.swift/tree/Swift3) branch. +GRDB.swift is a Swift application toolkit that provides access to SQLite databases. + +It targets Swift 2.2, and Swift 3 in the [Swift3](https://github.com/groue/GRDB.swift/tree/Swift3) branch. It ships with a **low-level SQLite API**, and high-level tools that help dealing with databases: @@ -19,9 +21,9 @@ More than a set of tools that leverage SQLite abilities, GRDB is also: - **Safer**: read the blog post [Four different ways to handle SQLite concurrency](https://medium.com/@gwendal.roue/four-different-ways-to-handle-sqlite-concurrency-db3bcc74d00e) - **Faster**: see [Comparing the Performances of Swift SQLite libraries](https://github.com/groue/GRDB.swift/wiki/Performance) - Well documented & tested -- Suited for experienced SQLite users as well as beginners. -You should give it a try. +If you have experience with other database libraries, have a read at [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3): it will show how protocol-oriented programming helps you building robust applications. + --- From 21e419ff8a2fb60c7c0e4a71782cafe85e13424a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 28 Jul 2016 10:00:10 +0200 Subject: [PATCH 10/17] Typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e9e3a516b..223b2aff4 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ More than a set of tools that leverage SQLite abilities, GRDB is also: - **Faster**: see [Comparing the Performances of Swift SQLite libraries](https://github.com/groue/GRDB.swift/wiki/Performance) - Well documented & tested -If you have experience with other database libraries, have a read at [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3): it will show how protocol-oriented programming helps you building robust applications. +If you have experience with other database libraries, have a look at [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3): it will show how protocol-oriented programming helps you building robust applications. --- From 0f987916b7fa722bff254b5bbf1825dc9519e9a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 28 Jul 2016 17:03:37 +0200 Subject: [PATCH 11/17] Redirect Core Data and Realm users to "How to build an iOS application with SQLite and GRDB.swift" --- README.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 223b2aff4..29cffee88 100644 --- a/README.md +++ b/README.md @@ -1555,10 +1555,19 @@ On top of the SQLite API described above, GRDB provides a toolkit for applicatio ## Records -**On top of the [SQLite API](#sqlite-api), GRDB provides protocols and a class** that help manipulating database rows as regular objects named "records". +**On top of the [SQLite API](#sqlite-api), GRDB provides protocols and a class** that help manipulating database rows as regular objects named "records": + +```swift +if let poi = PointOfInterest.fetchOne(db, key: 1) { + poi.isFavorite = true + try poi.update(db) +} +``` Your custom structs and classes can adopt each protocol individually, and opt in to focused sets of features. Or you can subclass the `Record` class, and get the full toolkit in one go: fetching methods, persistence methods, and changes tracking. +> :point_up: **Note**: if you are familiar with Core Data's NSManagedObject or Realm's Object, you may experience a cultural shock: GRDB records are not uniqued, and do not auto-update. This is both a purpose, and a consequence of protocol-oriented programming. You should read [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3) for a general introduction. + #### Inserting Records From b16656bd235aaf03f59c45c89e59e9084481adbc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 28 Jul 2016 19:28:46 +0200 Subject: [PATCH 12/17] Partial update WIP: cache & column case insensitivity --- GRDB.xcodeproj/project.pbxproj | 36 ++++----- GRDB/Core/Database.swift | 76 +++++++++---------- GRDB/Core/DatabaseSchemaCache.swift | 35 +++++++-- GRDB/Record/Persistable.swift | 5 +- README.md | 2 +- TODO.md | 2 - .../DatabasePoolSchemaCacheTests.swift | 14 ++++ ...eIndexTests.swift => IndexInfoTests.swift} | 2 +- 8 files changed, 102 insertions(+), 70 deletions(-) rename Tests/Public/Core/Database/{TableIndexTests.swift => IndexInfoTests.swift} (98%) diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 1309ef4db..67c4cbe04 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -395,14 +395,14 @@ 5674048A1CEF84C8003ED5CC /* RowAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567404871CEF84C8003ED5CC /* RowAdapter.swift */; }; 5674048B1CEF84C8003ED5CC /* RowAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567404871CEF84C8003ED5CC /* RowAdapter.swift */; }; 567404931CF02B56003ED5CC /* AdapterRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* AdapterRowTests.swift */; }; - 567A80531D41350C00C7DCEC /* TableIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* TableIndexTests.swift */; }; - 567A80541D41350C00C7DCEC /* TableIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* TableIndexTests.swift */; }; - 567A80551D41350C00C7DCEC /* TableIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* TableIndexTests.swift */; }; - 567A80561D41350C00C7DCEC /* TableIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* TableIndexTests.swift */; }; - 567A80571D41350C00C7DCEC /* TableIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* TableIndexTests.swift */; }; - 567A80581D41350C00C7DCEC /* TableIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* TableIndexTests.swift */; }; - 567A80591D41350C00C7DCEC /* TableIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* TableIndexTests.swift */; }; - 567A805A1D41350C00C7DCEC /* TableIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* TableIndexTests.swift */; }; + 567A80531D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; + 567A80541D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; + 567A80551D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; + 567A80561D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; + 567A80571D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; + 567A80581D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; + 567A80591D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; + 567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; 567E55ED1D2BDD3D00CC6F79 /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; }; 567E55EE1D2BDD3F00CC6F79 /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; }; 567E55F31D2BDDFE00CC6F79 /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; }; @@ -1353,7 +1353,7 @@ 5672DE581CDB72520022BA81 /* DatabaseQueueBackupTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueBackupTests.swift; sourceTree = ""; }; 5672DE661CDB751D0022BA81 /* DatabasePoolBackupTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolBackupTests.swift; sourceTree = ""; }; 567404871CEF84C8003ED5CC /* RowAdapter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowAdapter.swift; sourceTree = ""; }; - 567A80521D41350C00C7DCEC /* TableIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableIndexTests.swift; sourceTree = ""; }; + 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; 5683C2681B4D445E00296494 /* libsqlite3.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libsqlite3.dylib; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.4.sdk/usr/lib/libsqlite3.dylib; sourceTree = DEVELOPER_DIR; }; 5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 568BE5191CB035A900270F93 /* sqlite3.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = sqlite3.h; path = SQLCipher/src/sqlite3.h; sourceTree = ""; }; @@ -1910,9 +1910,9 @@ isa = PBXGroup; children = ( 56A238131B9C74A90082EB20 /* DatabaseTests.swift */, + 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */, 56A238141B9C74A90082EB20 /* InMemoryDatabaseTests.swift */, 567156151CB142AA007DC145 /* ReadOnlyDatabaseTests.swift */, - 567A80521D41350C00C7DCEC /* TableIndexTests.swift */, ); path = Database; sourceTree = ""; @@ -3100,7 +3100,7 @@ 560FC5891CB00B880014AA8E /* TransactionObserverTests.swift in Sources */, 560FC58A1CB00B880014AA8E /* DatabasePoolReleaseMemoryTests.swift in Sources */, 56C3F7541CF9F12400F6A361 /* SavepointTests.swift in Sources */, - 567A80541D41350C00C7DCEC /* TableIndexTests.swift in Sources */, + 567A80541D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 560FC58B1CB00B880014AA8E /* DatabaseValueTests.swift in Sources */, 565049061CE32543000A97D8 /* FetchedRecordsControllerTests.swift in Sources */, EED6C2C71D00B6B700F8E701 /* NSNumberTests.swift in Sources */, @@ -3214,7 +3214,7 @@ 567156441CB16729007DC145 /* RecordSubClassTests.swift in Sources */, 567156451CB16729007DC145 /* DatabasePoolConcurrencyTests.swift in Sources */, 567156461CB16729007DC145 /* TransactionObserverTests.swift in Sources */, - 567A80551D41350C00C7DCEC /* TableIndexTests.swift in Sources */, + 567A80551D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 567156471CB16729007DC145 /* DatabasePoolReleaseMemoryTests.swift in Sources */, 565049071CE32543000A97D8 /* FetchedRecordsControllerTests.swift in Sources */, 567156481CB16729007DC145 /* DatabaseValueTests.swift in Sources */, @@ -3401,7 +3401,7 @@ 56AFCA721CB1AA9900F48B96 /* FunctionTests.swift in Sources */, 56AFCA731CB1AA9900F48B96 /* InMemoryDatabaseTests.swift in Sources */, 56AFCA741CB1AA9900F48B96 /* RecordWithColumnNameManglingTests.swift in Sources */, - 567A80581D41350C00C7DCEC /* TableIndexTests.swift in Sources */, + 567A80581D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 56AFCA751CB1AA9900F48B96 /* CGFloatTests.swift in Sources */, 56AFCA761CB1AA9900F48B96 /* StatementInformationTests.swift in Sources */, 5691784A1CED9B6000E179EA /* DatabaseQueueTests.swift in Sources */, @@ -3500,7 +3500,7 @@ 56AFCACC1CB1ABC800F48B96 /* InMemoryDatabaseTests.swift in Sources */, 56AFCACD1CB1ABC800F48B96 /* RecordWithColumnNameManglingTests.swift in Sources */, 56AFCACE1CB1ABC800F48B96 /* CGFloatTests.swift in Sources */, - 567A80591D41350C00C7DCEC /* TableIndexTests.swift in Sources */, + 567A80591D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 56AFCACF1CB1ABC800F48B96 /* StatementInformationTests.swift in Sources */, 56AFCAD01CB1ABC800F48B96 /* GRDBTestCase.swift in Sources */, 565EFAF41D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */, @@ -3616,7 +3616,7 @@ 560A37AC1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift in Sources */, 5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */, 565D5D721BBC694D00DC9BD4 /* Row+FoundationTests.swift in Sources */, - 567A80571D41350C00C7DCEC /* TableIndexTests.swift in Sources */, + 567A80571D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 569178391CED8E0A00E179EA /* FetchedRecordsControllerTests.swift in Sources */, 56A2386A1B9C74A90082EB20 /* RecordSubClassTests.swift in Sources */, 56A2383E1B9C74A90082EB20 /* DatabaseValueTests.swift in Sources */, @@ -3683,7 +3683,7 @@ 56A238631B9C74A90082EB20 /* RecordAwakeFromFetchTests.swift in Sources */, 569531341C919DF200CF1A2B /* DatabasePoolCollationTests.swift in Sources */, 56A238591B9C74A90082EB20 /* PrimaryKeySingleTests.swift in Sources */, - 567A80531D41350C00C7DCEC /* TableIndexTests.swift in Sources */, + 567A80531D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 56EE573D1BB317B7007A6A95 /* StatementColumnConvertibleTests.swift in Sources */, 56A238651B9C74A90082EB20 /* RecordFetchTests.swift in Sources */, 56494C111D41F5C300529CB4 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, @@ -3917,7 +3917,7 @@ F3BA80F11CFB3019003DC1BA /* SavepointTests.swift in Sources */, F3BA81031CFB303D003DC1BA /* FetchedRecordsControlleriOSTests.swift in Sources */, F3BA80B71CFB2FCD003DC1BA /* DatabaseErrorTests.swift in Sources */, - 567A805A1D41350C00C7DCEC /* TableIndexTests.swift in Sources */, + 567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, F3BA81211CFB3063003DC1BA /* PrimaryKeyNoneTests.swift in Sources */, F3BA80F71CFB3021003DC1BA /* SelectStatementTests.swift in Sources */, F3BA80FE1CFB3024003DC1BA /* TransactionObserverTests.swift in Sources */, @@ -4037,7 +4037,7 @@ F3BA811D1CFB305F003DC1BA /* TableMapping+QueryInterfaceRequestTests.swift in Sources */, F3BA80AD1CFB2FA6003DC1BA /* NSDataMemoryTests.swift in Sources */, F3BA80C21CFB2FD2003DC1BA /* DatabasePoolFileAttributesTests.swift in Sources */, - 567A80561D41350C00C7DCEC /* TableIndexTests.swift in Sources */, + 567A80561D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, F3BA81301CFB3064003DC1BA /* PrimaryKeyRowIDTests.swift in Sources */, F3BA80AB1CFB2FA6003DC1BA /* DatabaseQueueReleaseMemoryTests.swift in Sources */, 56494C141D41F5C300529CB4 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 1b3ab6bcd..8e71f2bbe 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -834,30 +834,20 @@ extension Database { // 1 | firstName | TEXT | 0 | NULL | 0 | // 2 | lastName | TEXT | 0 | NULL | 0 | - if #available(iOS 8.2, OSX 10.10, *) { } else { - // Work around a bug in SQLite where PRAGMA table_info would - // return a result even after the table was deleted. - if !tableExists(tableName) { - throw DatabaseError(message: "no such table: \(tableName)") - } - } - let columnInfos = ColumnInfo.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))") - guard columnInfos.count > 0 else { - throw DatabaseError(message: "no such table: \(tableName)") - } + let columns = try self.columns(in: tableName) let primaryKey: PrimaryKey? - let pkColumnInfos = columnInfos + let pkColumns = columns .filter { $0.primaryKeyIndex > 0 } .sort { $0.primaryKeyIndex < $1.primaryKeyIndex } - switch pkColumnInfos.count { + switch pkColumns.count { case 0: // No primary key column primaryKey = nil case 1: // Single column - let pkColumnInfo = pkColumnInfos.first! + let pkColumn = pkColumns.first! // https://www.sqlite.org/lang_createtable.html: // @@ -879,14 +869,14 @@ extension Database { // // FIXME: We ignore the exception, and consider all INTEGER primary // keys as aliases for the rowid: - if pkColumnInfo.type.uppercaseString == "INTEGER" { - primaryKey = .rowID(pkColumnInfo.name) + if pkColumn.type.uppercaseString == "INTEGER" { + primaryKey = .rowID(pkColumn.name) } else { - primaryKey = .regular([pkColumnInfo.name]) + primaryKey = .regular([pkColumn.name]) } default: // Multi-columns primary key - primaryKey = .regular(pkColumnInfos.map { $0.name }) + primaryKey = .regular(pkColumns.map { $0.name }) } schemaCache.setPrimaryKey(primaryKey, forTableName: tableName) @@ -897,6 +887,10 @@ extension Database { /// /// - throws: A DatabaseError if table does not exist. func columns(in tableName: String) throws -> [ColumnInfo] { + if let columns = schemaCache.columns(in: tableName) { + return columns + } + // https://www.sqlite.org/pragma.html // // > PRAGMA database.table_info(table-name); @@ -928,11 +922,13 @@ extension Database { throw DatabaseError(message: "no such table: \(tableName)") } } - let columnInfos = ColumnInfo.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))") - guard columnInfos.count > 0 else { + let columns = ColumnInfo.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))") + guard columns.count > 0 else { throw DatabaseError(message: "no such table: \(tableName)") } - return columnInfos + + schemaCache.setColumns(columns, forTableName: tableName) + return columns } /// The indexes on table named `tableName`; returns the empty array if the @@ -943,19 +939,19 @@ extension Database { /// /// If you want to know if a set of columns uniquely identify a row, prefer /// table(_:hasUniqueKey:) instead. - public func indexes(on tableName: String) -> [TableIndex] { + public func indexes(on tableName: String) -> [IndexInfo] { if let indexes = schemaCache.indexes(on: tableName) { return indexes } - let indexes = Row.fetch(self, "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))").map { row -> TableIndex in + let indexes = Row.fetch(self, "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))").map { row -> IndexInfo in let indexName: String = row.value(atIndex: 1) let unique: Bool = row.value(atIndex: 2) let columns = Row.fetch(self, "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))") .map { ($0.value(atIndex: 0) as Int, $0.value(atIndex: 2) as String) } .sort { $0.0 < $1.0 } .map { $0.1 } - return TableIndex(name: indexName, columns: columns, unique: unique) + return IndexInfo(name: indexName, columns: columns, unique: unique) } schemaCache.setIndexes(indexes, forTableName: tableName) @@ -978,6 +974,10 @@ extension Database { return false } +} + +/// A column of a table +struct ColumnInfo : RowConvertible { // CREATE TABLE persons ( // id INTEGER PRIMARY KEY, // firstName TEXT, @@ -989,27 +989,25 @@ extension Database { // 0 | id | INTEGER | 0 | NULL | 1 | // 1 | firstName | TEXT | 0 | NULL | 0 | // 2 | lastName | TEXT | 0 | NULL | 0 | - struct ColumnInfo : RowConvertible { - let name: String - let type: String - let notNull: Bool - let defaultDatabaseValue: DatabaseValue - let primaryKeyIndex: Int - - init(_ row: Row) { - name = row.value(named: "name") - type = row.value(named: "type") - notNull = row.value(named: "notnull") - defaultDatabaseValue = row.databaseValue(named: "dflt_value")! - primaryKeyIndex = row.value(named: "pk") - } + let name: String + let type: String + let notNull: Bool + let defaultDatabaseValue: DatabaseValue + let primaryKeyIndex: Int + + init(_ row: Row) { + name = row.value(named: "name") + type = row.value(named: "type") + notNull = row.value(named: "notnull") + defaultDatabaseValue = row.databaseValue(named: "dflt_value")! + primaryKeyIndex = row.value(named: "pk") } } /// An index on a database table. /// /// See `Database.indexes(on:)` -public struct TableIndex { +public struct IndexInfo { /// The name of the index public let name: String diff --git a/GRDB/Core/DatabaseSchemaCache.swift b/GRDB/Core/DatabaseSchemaCache.swift index da2327932..7605f8998 100644 --- a/GRDB/Core/DatabaseSchemaCache.swift +++ b/GRDB/Core/DatabaseSchemaCache.swift @@ -9,18 +9,23 @@ protocol DatabaseSchemaCacheType { func primaryKey(tableName tableName: String) -> PrimaryKey?? mutating func setPrimaryKey(primaryKey: PrimaryKey?, forTableName tableName: String) + + func columns(in tableName: String) -> [ColumnInfo]? + mutating func setColumns(columns: [ColumnInfo], forTableName tableName: String) - func indexes(on tableName: String) -> [TableIndex]? - mutating func setIndexes(indexes: [TableIndex], forTableName tableName: String) + func indexes(on tableName: String) -> [IndexInfo]? + mutating func setIndexes(indexes: [IndexInfo], forTableName tableName: String) } /// A thread-unsafe database schema cache final class DatabaseSchemaCache: DatabaseSchemaCacheType { private var primaryKeys: [String: PrimaryKey?] = [:] - private var indexes: [String: [TableIndex]] = [:] + private var columns: [String: [ColumnInfo]] = [:] + private var indexes: [String: [IndexInfo]] = [:] func clear() { primaryKeys = [:] + columns = [:] indexes = [:] } @@ -32,11 +37,19 @@ final class DatabaseSchemaCache: DatabaseSchemaCacheType { primaryKeys[tableName] = primaryKey } - func indexes(on tableName: String) -> [TableIndex]? { + func columns(in tableName: String) -> [ColumnInfo]? { + return columns[tableName] + } + + func setColumns(columns: [ColumnInfo], forTableName tableName: String) { + self.columns[tableName] = columns + } + + func indexes(on tableName: String) -> [IndexInfo]? { return indexes[tableName] } - func setIndexes(indexes: [TableIndex], forTableName tableName: String) { + func setIndexes(indexes: [IndexInfo], forTableName tableName: String) { self.indexes[tableName] = indexes } } @@ -57,11 +70,19 @@ final class SharedDatabaseSchemaCache: DatabaseSchemaCacheType { cache.write { $0.setPrimaryKey(primaryKey, forTableName: tableName) } } - func indexes(on tableName: String) -> [TableIndex]? { + func columns(in tableName: String) -> [ColumnInfo]? { + return cache.read { $0.columns(in: tableName) } + } + + func setColumns(columns: [ColumnInfo], forTableName tableName: String) { + cache.write { $0.setColumns(columns, forTableName: tableName) } + } + + func indexes(on tableName: String) -> [IndexInfo]? { return cache.read { $0.indexes(on: tableName) } } - func setIndexes(indexes: [TableIndex], forTableName tableName: String) { + func setIndexes(indexes: [IndexInfo], forTableName tableName: String) { cache.write { $0.setIndexes(indexes, forTableName: tableName) } } } diff --git a/GRDB/Record/Persistable.swift b/GRDB/Record/Persistable.swift index 5313ec42a..b79498df9 100644 --- a/GRDB/Record/Persistable.swift +++ b/GRDB/Record/Persistable.swift @@ -552,8 +552,9 @@ final class DataMapper { // Don't update primary key columns var updatedColumns = Array(persistentDictionary.keys) - .filter { columns.contains($0) } - .filter { !primaryKeyColumns.contains($0) } + .map { $0.lowercaseString } + .filter { (lowercaseKey: String) in columns.contains { $0.lowercaseString == lowercaseKey } } + .filter { (lowercaseKey: String) in !primaryKeyColumns.contains { $0.lowercaseString == lowercaseKey } } if updatedColumns.isEmpty { // IMPLEMENTATION NOTE // diff --git a/README.md b/README.md index e0765bd5b..c1b66c8a6 100644 --- a/README.md +++ b/README.md @@ -1332,7 +1332,7 @@ GRDB provides four high-level methods as well: ```swift db.tableExists("persons") // Bool, true if the table exists -db.indexes(on: "persons") // [TableIndex], the indexes defined on the table +db.indexes(on: "persons") // [IndexInfo], the indexes defined on the table try db.table("persons", hasUniqueKey: ["id"]) // Bool, true if column(s) is a unique key try db.primaryKey("persons") // PrimaryKey? ``` diff --git a/TODO.md b/TODO.md index 86aefa283..2d1ffc459 100644 --- a/TODO.md +++ b/TODO.md @@ -1,6 +1,4 @@ - [ ] Partial update. update(db) should call update(db, columns: [String]) (single point of override) - - [ ] cache columns - - [ ] columns should be case-insensitive - [ ] Fix "More, when you're interested in specific table columns, you're out of luck, because databaseDidChange does not know about columns: it just knows that a row has been inserted, deleted, or updated, without further detail" - [ ] GRDBCipher: remove limitations on iOS or OS X versions - [ ] FetchedRecordsController: take inspiration from https://github.com/jflinter/Dwifft diff --git a/Tests/Private/DatabasePoolSchemaCacheTests.swift b/Tests/Private/DatabasePoolSchemaCacheTests.swift index 22da6838e..67fb2804f 100644 --- a/Tests/Private/DatabasePoolSchemaCacheTests.swift +++ b/Tests/Private/DatabasePoolSchemaCacheTests.swift @@ -21,12 +21,14 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase { dbPool.write { db in // Assert that the writer cache is empty XCTAssertTrue(db.schemaCache.primaryKey(tableName: "items") == nil) + XCTAssertTrue(db.schemaCache.columns(in: "items") == nil) XCTAssertTrue(db.schemaCache.indexes(on: "items") == nil) } dbPool.read { db in // Assert that a reader cache is empty XCTAssertTrue(db.schemaCache.primaryKey(tableName: "items") == nil) + XCTAssertTrue(db.schemaCache.columns(in: "items") == nil) XCTAssertTrue(db.schemaCache.indexes(on: "items") == nil) } @@ -35,6 +37,14 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase { let primaryKey = try db.primaryKey("items")! XCTAssertEqual(primaryKey.rowIDColumn, "id") + let columns = try db.columns(in: "items") + XCTAssertEqual(columns.count, 4) + // TODO: test more properties + XCTAssertEqual(columns[0].name, "id") + XCTAssertEqual(columns[1].name, "email") + XCTAssertEqual(columns[2].name, "foo") + XCTAssertEqual(columns[3].name, "bar") + let indexes = db.indexes(on: "items") XCTAssertEqual(indexes.count, 2) for index in indexes { @@ -50,12 +60,14 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase { // Assert that reader cache is warmed XCTAssertTrue(db.schemaCache.primaryKey(tableName: "items") != nil) + XCTAssertTrue(db.schemaCache.columns(in: "items") != nil) XCTAssertTrue(db.schemaCache.indexes(on: "items") != nil) } dbPool.write { db in // Assert that writer cache is warmed XCTAssertTrue(db.schemaCache.primaryKey(tableName: "items") != nil) + XCTAssertTrue(db.schemaCache.columns(in: "items") != nil) XCTAssertTrue(db.schemaCache.indexes(on: "items") != nil) } @@ -65,12 +77,14 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase { // Assert that the writer cache is empty XCTAssertTrue(db.schemaCache.primaryKey(tableName: "items") == nil) + XCTAssertTrue(db.schemaCache.columns(in: "items") == nil) XCTAssertTrue(db.schemaCache.indexes(on: "items") == nil) } dbPool.read { db in // Assert that a reader cache is empty XCTAssertTrue(db.schemaCache.primaryKey(tableName: "items") == nil) + XCTAssertTrue(db.schemaCache.columns(in: "items") == nil) XCTAssertTrue(db.schemaCache.indexes(on: "items") == nil) } diff --git a/Tests/Public/Core/Database/TableIndexTests.swift b/Tests/Public/Core/Database/IndexInfoTests.swift similarity index 98% rename from Tests/Public/Core/Database/TableIndexTests.swift rename to Tests/Public/Core/Database/IndexInfoTests.swift index 842c7cc42..e6802f15f 100644 --- a/Tests/Public/Core/Database/TableIndexTests.swift +++ b/Tests/Public/Core/Database/IndexInfoTests.swift @@ -7,7 +7,7 @@ import XCTest import GRDB #endif -class TableIndexTests: GRDBTestCase { +class IndexInfoTests: GRDBTestCase { func testIndexes() { assertNoError { db in From 447df0af1726fdf479f33dcd68b006fee38c3707 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 28 Jul 2016 19:31:02 +0200 Subject: [PATCH 13/17] Partial update WIP: changelog --- CHANGELOG.md | 2 +- TODO.md | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e77569957..e21c94d21 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,7 +18,7 @@ Release Notes **Breaking Changes** -- MutablePersistable `update` and `performUpdate` methods have changed their signature: +- MutablePersistable `update` and `performUpdate` methods have changed their signatures. You only have to care about this change if you override the default `update` method. ```diff protocol MutablePersistable : TableMapping { diff --git a/TODO.md b/TODO.md index 2d1ffc459..bbafadd59 100644 --- a/TODO.md +++ b/TODO.md @@ -1,4 +1,3 @@ -- [ ] Partial update. update(db) should call update(db, columns: [String]) (single point of override) - [ ] Fix "More, when you're interested in specific table columns, you're out of luck, because databaseDidChange does not know about columns: it just knows that a row has been inserted, deleted, or updated, without further detail" - [ ] GRDBCipher: remove limitations on iOS or OS X versions - [ ] FetchedRecordsController: take inspiration from https://github.com/jflinter/Dwifft From 42125c756ef84e4c3641dfaef7d0e0165e17508b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 28 Jul 2016 19:32:20 +0200 Subject: [PATCH 14/17] v0.77.0 --- CHANGELOG.md | 6 ++++-- GRDB.swift.podspec | 2 +- README.md | 22 +++++++++++----------- Support/Info.plist | 2 +- 4 files changed, 17 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e21c94d21..648a51f60 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,11 +1,13 @@ Release Notes ============= -## Next Version +## 0.77.0 + +Released July 28, 2016 **New** -- `Database.indexes(on:)` returns the indexes defined on a database table +- `Database.indexes(on:)` returns the indexes defined on a database table. - `Database.table(_:hasUniqueKey:)` returns true if a sequence of columns uniquely identifies a row, that is to say if the columns are the primary key, or if there is a unique index on them. diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 2f1c18387..09e21b62e 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.76.0' + s.version = '0.77.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A versatile SQLite toolkit for Swift, with WAL mode support.' s.homepage = 'https://github.com/groue/GRDB.swift' diff --git a/README.md b/README.md index 76f6324ea..7b125fee8 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ If you have experience with other database libraries, have a look at [How to bui --- -**July 19, 2016: GRDB.swift 0.76.0 is out** ([changelog](CHANGELOG.md)). Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips. +**July 28, 2016: GRDB.swift 0.77.0 is out** ([changelog](CHANGELOG.md)). Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips. **Requirements**: iOS 8.0+ / OSX 10.9+, Xcode 7.3+ @@ -145,7 +145,7 @@ Documentation **Reference** -- [GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.76.0/index.html) (on cocoadocs.org) +- [GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/index.html) (on cocoadocs.org) **Getting started** @@ -191,7 +191,7 @@ To use GRDB with CocoaPods, specify in your Podfile: source 'https://github.com/CocoaPods/Specs.git' use_frameworks! -pod 'GRDB.swift', '~> 0.76.0' +pod 'GRDB.swift', '~> 0.77.0' ``` > :point_up: **Note**: [SQLCipher](#encryption) and [custom SQLite builds](#custom-sqlite-builds) are not available via CocoaPods. @@ -204,7 +204,7 @@ pod 'GRDB.swift', '~> 0.76.0' To use GRDB with Carthage, specify in your Cartfile: ``` -github "groue/GRDB.swift" ~> 0.76.0 +github "groue/GRDB.swift" ~> 0.77.0 ``` > :point_up: **Note**: [custom SQLite builds](#custom-sqlite-builds) are not available via Carthage. @@ -313,7 +313,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.76.0/Structs/Configuration.html) for more details. +See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Structs/Configuration.html) for more details. ## Database Pools @@ -393,7 +393,7 @@ let dbPool = try DatabasePool( configuration: config) ``` -See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.76.0/Structs/Configuration.html) for more details. +See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Structs/Configuration.html) for more details. Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information. @@ -1481,10 +1481,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.76.0/Protocols/RowAdapter.html): the protocol that lets you define your custom row adapters -- [ColumnMapping](http://cocoadocs.org/docsets/GRDB.swift/0.76.0/Structs/ColumnMapping.html): a row adapter that renames row columns -- [SuffixRowAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.76.0/Structs/SuffixRowAdapter.html): a row adapter that hides the first columns of a row -- [ScopeAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.76.0/Structs/ScopeAdapter.html): the row adapter that groups several adapters together to define scopes +- [RowAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Protocols/RowAdapter.html): the protocol that lets you define your custom row adapters +- [ColumnMapping](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Structs/ColumnMapping.html): a row adapter that renames row columns +- [SuffixRowAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Structs/SuffixRowAdapter.html): a row adapter that hides the first columns of a row +- [ScopeAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Structs/ScopeAdapter.html): the row adapter that groups several adapters together to define scopes ## Raw SQLite Pointers @@ -3407,7 +3407,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.76.0/Classes/DatabaseQueue.html) and [DatabasePool](http://cocoadocs.org/docsets/GRDB.swift/0.76.0/Classes/DatabasePool.html). Both adopt the [DatabaseReader](http://cocoadocs.org/docsets/GRDB.swift/0.76.0/Protocols/DatabaseReader.html) and [DatabaseWriter](http://cocoadocs.org/docsets/GRDB.swift/0.76.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.77.0/Classes/DatabaseQueue.html) and [DatabasePool](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Classes/DatabasePool.html). Both adopt the [DatabaseReader](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Protocols/DatabaseReader.html) and [DatabaseWriter](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/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 1a9f30e9f..0564988c3 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 0.76.0 + 0.77.0 CFBundleSignature ???? CFBundleVersion From 8393cd4b865b012a95edc7265fcc72ea03ff2194 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 29 Jul 2016 03:57:25 +0200 Subject: [PATCH 15/17] CHANGELOG.md --- CHANGELOG.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 648a51f60..df1080eed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,13 +14,13 @@ Released July 28, 2016 - MutablePersistable types, including Record subclasses, support partial updates: ```swift - try person.update(db) // Full update - try person.update(db, columns: ["age"]) // Only updates the age column + try person.update(db) // Full update + try person.update(db, columns: ["name"]) // Only updates the name column ``` **Breaking Changes** -- MutablePersistable `update` and `performUpdate` methods have changed their signatures. You only have to care about this change if you override the default `update` method. +- MutablePersistable `update` and `performUpdate` methods have changed their signatures. You only have to care about this change if you customize the protocol `update` method. ```diff protocol MutablePersistable : TableMapping { From c67997083244ca17648faaeb87aa6cace6abcf31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 29 Jul 2016 08:31:49 +0200 Subject: [PATCH 16/17] README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7b125fee8..0aa2b674b 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ More than a set of tools that leverage SQLite abilities, GRDB is also: - **Faster**: see [Comparing the Performances of Swift SQLite libraries](https://github.com/groue/GRDB.swift/wiki/Performance) - Well documented & tested -If you have experience with other database libraries, have a look at [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3): it will show how protocol-oriented programming helps you building robust applications. +For a general overview of how a protocol-oriented library impacts database acesses, have a look at [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3). --- From d922961112d9bffb8e6b0cd560e78b5138a8671e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 29 Jul 2016 09:03:40 +0200 Subject: [PATCH 17/17] Remove documentation for DatabaseValue.value() --- README.md | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 0aa2b674b..def1d190e 100644 --- a/README.md +++ b/README.md @@ -710,28 +710,27 @@ case .Blob(let data): print("NSData: \(data)") } ``` -You can extract [values](#values) (Bool, Int, String, NSDate, Swift enums, etc.) from DatabaseValue, just like you do from [rows](#column-values): +You can extract [values](#values) (Bool, Int, String, NSDate, Swift enums, etc.) from DatabaseValue with the [DatabaseValueConvertible.fromDatabaseValue()](#custom-value-types) method: ```swift let dbv = row.databaseValue(named: "bookCount") -let bookCount: Int = dbv.value() -let bookCount64: Int64 = dbv.value() -let hasBooks: Bool = dbv.value() // false when 0 +let bookCount = Int.fromDatabaseValue(dbv) // Int? +let bookCount64 = Int64.fromDatabaseValue(dbv) // Int64? +let hasBooks = Bool.fromDatabaseValue(dbv) // Bool?, false when 0 let dbv = row.databaseValue(named: "date") -let string: String = dbv.value() // "2015-09-11 18:14:15.123" -let date: NSDate = dbv.value() // NSDate -self.date = dbv.value() // Depends on the type of the property. +let string = String.fromDatabaseValue(dbv) // "2015-09-11 18:14:15.123" +let date = NSDate.fromDatabaseValue(dbv) // NSDate? ``` -Invalid conversions from non-NULL values raise a fatal error. This fatal error can be avoided with the [DatabaseValueConvertible.fromDatabaseValue()](#custom-value-types) method: +`fromDatabaseValue` returns nil for invalid conversions: ```swift let row = Row.fetchOne(db, "SELECT 'foo'")! let dbv = row.databaseValue(at: 0) -let string = dbv.value() as String // "foo" -let date = dbv.value() as NSDate? // fatal error: could not convert "foo" to NSDate. -let date = NSDate.fromDatabaseValue(dbv) // nil +let string = String.fromDatabaseValue(dbv) // "foo" +let int = Int.fromDatabaseValue(dbv) // nil +let date = NSDate.fromDatabaseValue(dbv) // nil ```