diff --git a/CHANGELOG.md b/CHANGELOG.md index f6468573a..3fd88e5f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,21 @@ Release Notes ============= +## 0.33.0 + +Released December 11, 2015 + +**New** + +- The `DatabasePersistable` and `MutableDatabasePersistable` protocols grant any adopting type the persistence methods that used to be reserved to subclasses of `Record` ([#12](https://github.com/groue/GRDB.swift/issues/12)) +- `Database.clearSchemaCache()` + +**Breaking Changes** + +- `RecordError` has been renamed `PersistenceError` +- `Record.databaseTableName()` now returns a non-optional String. + + ## 0.32.2 Released December 3, 2015 diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Person.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Person.swift index c21750d52..bb75f34d8 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Person.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Person.swift @@ -16,7 +16,7 @@ class Person : Record { // MARK: - Record - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "persons" } diff --git a/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7/Person.swift b/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7/Person.swift index 855d857a6..f45f1f056 100644 --- a/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7/Person.swift +++ b/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7/Person.swift @@ -14,7 +14,7 @@ class Person : Record { // MARK: - Record - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "persons" } diff --git a/GRDB Tests/Experimental/MappingTests.swift b/GRDB Tests/Experimental/MappingTests.swift index 4fabae0d1..601020fe7 100644 --- a/GRDB Tests/Experimental/MappingTests.swift +++ b/GRDB Tests/Experimental/MappingTests.swift @@ -114,7 +114,7 @@ class MappedRecord : Record { // Record overrides - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "persons" } diff --git a/GRDB Tests/GRDBTestCase.swift b/GRDB Tests/GRDBTestCase.swift index 509919b28..598e3ef41 100644 --- a/GRDB Tests/GRDBTestCase.swift +++ b/GRDB Tests/GRDBTestCase.swift @@ -33,12 +33,8 @@ class GRDBTestCase: XCTestCase { func assertNoError(@noescape test: (Void) throws -> Void) { do { try test() - } catch let error as DatabaseError { - XCTFail(error.description) - } catch let error as RecordError { - XCTFail(error.description) } catch { - XCTFail("error: \(error)") + XCTFail("unexpected error: \(error)") } } } diff --git a/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift b/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift new file mode 100644 index 000000000..63965adf2 --- /dev/null +++ b/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift @@ -0,0 +1,595 @@ +import XCTest +import GRDB + +struct PersistablePerson : DatabasePersistable { + var name: String? + + static func databaseTableName() -> String { + return "persons" + } + + var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { + return ["name": name] + } +} + +class PersistablePersonClass : DatabasePersistable { + var id: Int64? + var name: String? + + init(id: Int64?, name: String?) { + self.id = id + self.name = name + } + + static func databaseTableName() -> String { + return "persons" + } + + var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { + return ["id": id, "name": name] + } + + func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + self.id = rowID + } +} + +struct PersistableCountry : DatabasePersistable { + var isoCode: String + var name: String + + static func databaseTableName() -> String { + return "countries" + } + + var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { + return ["isoCode": isoCode, "name": name] + } +} + +struct PersistableCustomizedCountry : DatabasePersistable { + var isoCode: String + var name: String + let willInsert: Void -> Void + let willUpdate: Void -> Void + let willSave: Void -> Void + let willDelete: Void -> Void + let willExists: Void -> Void + + static func databaseTableName() -> String { + return "countries" + } + + var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { + return ["isoCode": isoCode, "name": name] + } + + func insert(db: Database) throws { + willInsert() + try performInsert(db) + } + + func update(db: Database) throws { + willUpdate() + try performUpdate(db) + } + + func save(db: Database) throws { + willSave() + try performSave(db) + } + + func delete(db: Database) throws { + willDelete() + try performDelete(db) + } + + func exists(db: Database) -> Bool { + willExists() + return performExists(db) + } +} + +class DatabasePersistableTests: GRDBTestCase { + + override func setUp() { + super.setUp() + + var migrator = DatabaseMigrator() + migrator.registerMigration("setUp") { db in + try db.execute( + "CREATE TABLE persons (" + + "id INTEGER PRIMARY KEY, " + + "name NOT NULL " + + ")") + try db.execute( + "CREATE TABLE countries (" + + "isoCode TEXT NOT NULL PRIMARY KEY, " + + "name TEXT NOT NULL " + + ")") + } + + assertNoError { + try migrator.migrate(dbQueue) + } + } + + + // MARK: - PersistablePerson + + func testInsertPersistablePerson() { + assertNoError { + try dbQueue.inDatabase { db in + let person = PersistablePerson(name: "Arthur") + try person.insert(db) + + let rows = Row.fetchAll(db, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + } + } + } + + func testSavePersistablePerson() { + assertNoError { + try dbQueue.inDatabase { db in + let person = PersistablePerson(name: "Arthur") + try person.save(db) + + let rows = Row.fetchAll(db, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + } + } + } + + + // MARK: - PersistablePersonClass + + func testInsertPersistablePersonClass() { + assertNoError { + try dbQueue.inDatabase { db in + let person = PersistablePersonClass(id: nil, name: "Arthur") + try person.insert(db) + + let rows = Row.fetchAll(db, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + } + } + } + + func testUpdatePersistablePersonClass() { + assertNoError { + try dbQueue.inDatabase { db in + let person1 = PersistablePersonClass(id: nil, name: "Arthur") + try person1.insert(db) + let person2 = PersistablePersonClass(id: nil, name: "Barbara") + try person2.insert(db) + + person1.name = "Craig" + try person1.update(db) + + 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 { + try dbQueue.inDatabase { db in + let person1 = PersistablePersonClass(id: nil, name: "Arthur") + try person1.save(db) + + var rows = Row.fetchAll(db, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + + let person2 = PersistablePersonClass(id: nil, name: "Barbara") + try person2.save(db) + + person1.name = "Craig" + try person1.save(db) + + 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") + + try person1.delete(db) + try person1.save(db) + + 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 testDeletePersistablePersonClass() { + assertNoError { + try dbQueue.inDatabase { db in + let person1 = PersistablePersonClass(id: nil, name: "Arthur") + try person1.insert(db) + let person2 = PersistablePersonClass(id: nil, name: "Barbara") + try person2.insert(db) + + try person1.delete(db) + + let rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Barbara") + } + } + } + + func testExistsPersistablePersonClass() { + assertNoError { + try dbQueue.inDatabase { db in + let person = PersistablePersonClass(id: nil, name: "Arthur") + try person.insert(db) + XCTAssertTrue(person.exists(db)) + + try person.delete(db) + + XCTAssertFalse(person.exists(db)) + } + } + } + + + // MARK: - PersistableCountry + + func testInsertPersistableCountry() { + assertNoError { + try dbQueue.inDatabase { db in + let country = PersistableCountry(isoCode: "FR", name: "France") + try country.insert(db) + + let rows = Row.fetchAll(db, "SELECT * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + } + } + } + + func testUpdatePersistableCountry() { + assertNoError { + 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) + + country1.name = "France Métropolitaine" + try country1.update(db) + + 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 { + try dbQueue.inDatabase { db in + var country1 = PersistableCountry(isoCode: "FR", name: "France") + try country1.save(db) + + var rows = Row.fetchAll(db, "SELECT * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + + let country2 = PersistableCountry(isoCode: "US", name: "United States") + try country2.save(db) + + country1.name = "France Métropolitaine" + try country1.save(db) + + 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") + + try country1.delete(db) + try country1.save(db) + + 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 testDeletePersistableCountry() { + assertNoError { + try dbQueue.inDatabase { db in + let country1 = PersistableCountry(isoCode: "FR", name: "France") + try country1.insert(db) + let country2 = PersistableCountry(isoCode: "US", name: "United States") + try country2.insert(db) + + try country1.delete(db) + + let rows = Row.fetchAll(db, "SELECT * FROM countries ORDER BY isoCode") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "US") + XCTAssertEqual(rows[0].value(named: "name") as String, "United States") + } + } + } + + func testExistsPersistableCountry() { + assertNoError { + try dbQueue.inDatabase { db in + let country = PersistableCountry(isoCode: "FR", name: "France") + try country.insert(db) + XCTAssertTrue(country.exists(db)) + + try country.delete(db) + + XCTAssertFalse(country.exists(db)) + } + } + } + + + // MARK: - PersistableCustomizedCountry + + func testInsertPersistableCustomizedCountry() { + assertNoError { + 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 + let country = PersistableCustomizedCountry( + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country.insert(db) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + let rows = Row.fetchAll(db, "SELECT * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + } + } + } + + func testUpdatePersistableCustomizedCountry() { + assertNoError { + 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) + + 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 { + 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.save(db) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 1) + XCTAssertEqual(saveCount, 1) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + var rows = Row.fetchAll(db, "SELECT * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + + let country2 = PersistableCustomizedCountry( + isoCode: "US", + name: "United States", + willInsert: { }, + willUpdate: { }, + willSave: { }, + willDelete: { }, + willExists: { }) + try country2.save(db) + + country1.name = "France Métropolitaine" + try country1.save(db) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 2) + XCTAssertEqual(saveCount, 2) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + 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") + + try country1.delete(db) + try country1.save(db) + + XCTAssertEqual(insertCount, 2) + XCTAssertEqual(updateCount, 3) + XCTAssertEqual(saveCount, 3) + XCTAssertEqual(deleteCount, 1) + XCTAssertEqual(existsCount, 0) + + 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 testDeletePersistableCustomizedCountry() { + assertNoError { + 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 + let 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) + + try country1.delete(db) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 1) + XCTAssertEqual(existsCount, 0) + + let rows = Row.fetchAll(db, "SELECT * FROM countries ORDER BY isoCode") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "US") + XCTAssertEqual(rows[0].value(named: "name") as String, "United States") + } + } + } + + func testExistsPersistableCustomizedCountry() { + assertNoError { + 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 + let country = PersistableCustomizedCountry( + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country.insert(db) + + XCTAssertTrue(country.exists(db)) + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 1) + + try country.delete(db) + + XCTAssertFalse(country.exists(db)) + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 1) + XCTAssertEqual(existsCount, 2) + } + } + } +} diff --git a/GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift b/GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift new file mode 100644 index 000000000..5c30b2680 --- /dev/null +++ b/GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift @@ -0,0 +1,567 @@ +import XCTest +import GRDB + +struct MutablePersistablePerson : MutableDatabasePersistable { + var id: Int64? + var name: String? + + static func databaseTableName() -> String { + return "persons" + } + + var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { + return ["id": id, "name": name] + } + + mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + self.id = rowID + } +} + +struct MutablePersistableCountry : MutableDatabasePersistable { + var rowID: Int64? + var isoCode: String + var name: String + + static func databaseTableName() -> String { + return "countries" + } + + var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { + return ["isoCode": isoCode, "name": name] + } + + mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + self.rowID = rowID + } +} + +struct MutablePersistableCustomizedCountry : MutableDatabasePersistable { + var rowID: Int64? + var isoCode: String + var name: String + let willInsert: Void -> Void + let willUpdate: Void -> Void + let willSave: Void -> Void + let willDelete: Void -> Void + let willExists: Void -> Void + + static func databaseTableName() -> String { + return "countries" + } + + var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { + return ["isoCode": isoCode, "name": name] + } + + mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + self.rowID = rowID + } + + mutating func insert(db: Database) throws { + willInsert() + try performInsert(db) + } + + func update(db: Database) throws { + willUpdate() + try performUpdate(db) + } + + mutating func save(db: Database) throws { + willSave() + try performSave(db) + } + + func delete(db: Database) throws { + willDelete() + try performDelete(db) + } + + func exists(db: Database) -> Bool { + willExists() + return performExists(db) + } +} + +class MutableDatabasePersistableTests: GRDBTestCase { + + override func setUp() { + super.setUp() + + var migrator = DatabaseMigrator() + migrator.registerMigration("setUp") { db in + try db.execute( + "CREATE TABLE persons (" + + "id INTEGER PRIMARY KEY, " + + "name NOT NULL " + + ")") + try db.execute( + "CREATE TABLE countries (" + + "isoCode TEXT NOT NULL PRIMARY KEY, " + + "name TEXT NOT NULL " + + ")") + } + + assertNoError { + try migrator.migrate(dbQueue) + } + } + + + // MARK: - MutablePersistablePerson + + func testInsertMutablePersistablePerson() { + assertNoError { + try dbQueue.inDatabase { db in + var person = MutablePersistablePerson(id: nil, name: "Arthur") + try person.insert(db) + + let rows = Row.fetchAll(db, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + } + } + } + + func testUpdateMutablePersistablePerson() { + assertNoError { + 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) + + person1.name = "Craig" + try person1.update(db) + + 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 { + try dbQueue.inDatabase { db in + var person1 = MutablePersistablePerson(id: nil, name: "Arthur") + try person1.save(db) + + var rows = Row.fetchAll(db, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + 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") + try person2.save(db) + + person1.name = "Craig" + try person1.save(db) + + 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") + + try person1.delete(db) + try person1.save(db) + + 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 testDeleteMutablePersistablePerson() { + assertNoError { + 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) + + try person1.delete(db) + + let rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Barbara") + } + } + } + + func testExistsMutablePersistablePerson() { + assertNoError { + try dbQueue.inDatabase { db in + var person = MutablePersistablePerson(id: nil, name: "Arthur") + try person.insert(db) + XCTAssertTrue(person.exists(db)) + + try person.delete(db) + + XCTAssertFalse(person.exists(db)) + } + } + } + + + // MARK: - MutablePersistableCountry + + func testInsertMutablePersistableCountry() { + assertNoError { + try dbQueue.inDatabase { db in + var country = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") + try country.insert(db) + + let rows = Row.fetchAll(db, "SELECT rowID, * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + } + } + } + + func testUpdateMutablePersistableCountry() { + assertNoError { + try dbQueue.inDatabase { db in + var country1 = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") + try country1.insert(db) + var country2 = MutablePersistableCountry(rowID: nil, isoCode: "US", name: "United States") + try country2.insert(db) + + country1.name = "France Métropolitaine" + try country1.update(db) + + let rows = Row.fetchAll(db, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + } + } + } + + func testSaveMutablePersistableCountry() { + assertNoError { + try dbQueue.inDatabase { db in + var country1 = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") + try country1.save(db) + + var rows = Row.fetchAll(db, "SELECT rowID, * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + + var country2 = MutablePersistableCountry(rowID: nil, isoCode: "US", name: "United States") + try country2.save(db) + + country1.name = "France Métropolitaine" + try country1.save(db) + + rows = Row.fetchAll(db, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + + try country1.delete(db) + try country1.save(db) + + rows = Row.fetchAll(db, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "United States") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "France Métropolitaine") + } + } + } + + func testDeleteMutablePersistableCountry() { + assertNoError { + try dbQueue.inDatabase { db in + var country1 = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") + try country1.insert(db) + var country2 = MutablePersistableCountry(rowID: nil, isoCode: "US", name: "United States") + try country2.insert(db) + + try country1.delete(db) + + let rows = Row.fetchAll(db, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "United States") + } + } + } + + func testExistsMutablePersistableCountry() { + assertNoError { + try dbQueue.inDatabase { db in + var country = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") + try country.insert(db) + XCTAssertTrue(country.exists(db)) + + try country.delete(db) + + XCTAssertFalse(country.exists(db)) + } + } + } + + + // MARK: - MutablePersistableCustomizedCountry + + func testInsertMutablePersistableCustomizedCountry() { + assertNoError { + 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 country = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country.insert(db) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + let rows = Row.fetchAll(db, "SELECT rowID, * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + } + } + } + + func testUpdateMutablePersistableCustomizedCountry() { + assertNoError { + 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 = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country1.insert(db) + var country2 = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "US", + name: "United States", + willInsert: { }, + willUpdate: { }, + willSave: { }, + willDelete: { }, + willExists: { }) + try country2.insert(db) + + country1.name = "France Métropolitaine" + try country1.update(db) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 1) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + let rows = Row.fetchAll(db, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + } + } + } + + func testSaveMutablePersistableCustomizedCountry() { + assertNoError { + 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 = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country1.save(db) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 1) + XCTAssertEqual(saveCount, 1) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + var rows = Row.fetchAll(db, "SELECT rowID, * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + + var country2 = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "US", + name: "United States", + willInsert: { }, + willUpdate: { }, + willSave: { }, + willDelete: { }, + willExists: { }) + try country2.save(db) + + country1.name = "France Métropolitaine" + try country1.save(db) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 2) + XCTAssertEqual(saveCount, 2) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + rows = Row.fetchAll(db, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + + try country1.delete(db) + try country1.save(db) + + XCTAssertEqual(insertCount, 2) + XCTAssertEqual(updateCount, 3) + XCTAssertEqual(saveCount, 3) + XCTAssertEqual(deleteCount, 1) + XCTAssertEqual(existsCount, 0) + + rows = Row.fetchAll(db, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "United States") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "France Métropolitaine") + } + } + } + + func testDeleteMutablePersistableCustomizedCountry() { + assertNoError { + 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 = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country1.insert(db) + var country2 = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "US", + name: "United States", + willInsert: { }, + willUpdate: { }, + willSave: { }, + willDelete: { }, + willExists: { }) + try country2.insert(db) + + try country1.delete(db) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 1) + XCTAssertEqual(existsCount, 0) + + let rows = Row.fetchAll(db, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "United States") + } + } + } + + func testExistsMutablePersistableCustomizedCountry() { + assertNoError { + 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 country = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country.insert(db) + + XCTAssertTrue(country.exists(db)) + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 1) + + try country.delete(db) + + XCTAssertFalse(country.exists(db)) + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 1) + XCTAssertEqual(existsCount, 2) + } + } + } +} diff --git a/GRDB Tests/Public/CrashTests.swift b/GRDB Tests/Public/CrashTests.swift index cb8cb3344..362811712 100644 --- a/GRDB Tests/Public/CrashTests.swift +++ b/GRDB Tests/Public/CrashTests.swift @@ -11,19 +11,19 @@ import GRDB class RecordWithoutDatabaseTableName: Record { } class RecordWithInexistingDatabaseTable: Record { - override static func databaseTableName() -> String? { + override static func databaseTableName() -> String { return "foo" } } class RecordWithEmptyStoredDatabaseDictionary : Record { - override static func databaseTableName() -> String? { + override static func databaseTableName() -> String { return "records" } } class RecordWithNilPrimaryKey : Record { - override static func databaseTableName() -> String? { + override static func databaseTableName() -> String { return "records" } @@ -33,7 +33,7 @@ class RecordWithNilPrimaryKey : Record { } class RecordForTableWithoutPrimaryKey : Record { - override static func databaseTableName() -> String? { + override static func databaseTableName() -> String { return "records" } @@ -43,7 +43,7 @@ class RecordForTableWithoutPrimaryKey : Record { } class RecordForTableWithMultipleColumnsPrimaryKey : Record { - override static func databaseTableName() -> String? { + override static func databaseTableName() -> String { return "records" } @@ -53,7 +53,7 @@ class RecordForTableWithMultipleColumnsPrimaryKey : Record { } class RecordWithRowIDPrimaryKeyNotExposedInStoredDatabaseDictionary : Record { - override static func databaseTableName() -> String? { + override static func databaseTableName() -> String { return "records" } diff --git a/GRDB Tests/Public/Record/MinimalPrimaryKeyRowIDTests.swift b/GRDB Tests/Public/Record/MinimalPrimaryKeyRowIDTests.swift index ca39c8281..53a476352 100644 --- a/GRDB Tests/Public/Record/MinimalPrimaryKeyRowIDTests.swift +++ b/GRDB Tests/Public/Record/MinimalPrimaryKeyRowIDTests.swift @@ -6,7 +6,7 @@ import GRDB class MinimalRowID: Record { var id: Int64! - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "minimalRowIDs" } @@ -124,9 +124,9 @@ class MinimalPrimaryKeyRowIDTests: GRDBTestCase { record.id = 123456 do { try record.update(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -159,9 +159,9 @@ class MinimalPrimaryKeyRowIDTests: GRDBTestCase { try record.delete(db) do { try record.update(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -299,9 +299,9 @@ class MinimalPrimaryKeyRowIDTests: GRDBTestCase { record.id = 123456 do { try record.reload(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -334,9 +334,9 @@ class MinimalPrimaryKeyRowIDTests: GRDBTestCase { try record.delete(db) do { try record.reload(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } diff --git a/GRDB Tests/Public/Record/MinimalPrimaryKeySingleTests.swift b/GRDB Tests/Public/Record/MinimalPrimaryKeySingleTests.swift index e201a3c6c..f27df4340 100644 --- a/GRDB Tests/Public/Record/MinimalPrimaryKeySingleTests.swift +++ b/GRDB Tests/Public/Record/MinimalPrimaryKeySingleTests.swift @@ -6,7 +6,7 @@ import GRDB class MinimalSingle: Record { var UUID: String! - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "minimalSingles" } @@ -121,9 +121,9 @@ class MinimalPrimaryKeySingleTests: GRDBTestCase { record.UUID = "theUUID" do { try record.update(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -158,9 +158,9 @@ class MinimalPrimaryKeySingleTests: GRDBTestCase { try record.delete(db) do { try record.update(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -297,9 +297,9 @@ class MinimalPrimaryKeySingleTests: GRDBTestCase { record.UUID = "theUUID" do { try record.reload(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -334,9 +334,9 @@ class MinimalPrimaryKeySingleTests: GRDBTestCase { try record.delete(db) do { try record.reload(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } diff --git a/GRDB Tests/Public/Record/PrimaryKeyMultipleTests.swift b/GRDB Tests/Public/Record/PrimaryKeyMultipleTests.swift index dacbd816d..c9de37246 100644 --- a/GRDB Tests/Public/Record/PrimaryKeyMultipleTests.swift +++ b/GRDB Tests/Public/Record/PrimaryKeyMultipleTests.swift @@ -7,7 +7,7 @@ class Citizenship: Record { var countryName: String! var native: Bool! - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "citizenships" } @@ -140,9 +140,9 @@ class PrimaryKeyMultipleTests: GRDBTestCase { let record = Citizenship(personName: "Arthur", countryName: "France", native: true) do { try record.update(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -176,9 +176,9 @@ class PrimaryKeyMultipleTests: GRDBTestCase { try record.delete(db) do { try record.update(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -310,9 +310,9 @@ class PrimaryKeyMultipleTests: GRDBTestCase { let record = Citizenship(personName: "Arthur", countryName: "France", native: true) do { try record.reload(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -346,9 +346,9 @@ class PrimaryKeyMultipleTests: GRDBTestCase { try record.delete(db) do { try record.reload(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } diff --git a/GRDB Tests/Public/Record/PrimaryKeyNoneTests.swift b/GRDB Tests/Public/Record/PrimaryKeyNoneTests.swift index 55059916d..e2ed89383 100644 --- a/GRDB Tests/Public/Record/PrimaryKeyNoneTests.swift +++ b/GRDB Tests/Public/Record/PrimaryKeyNoneTests.swift @@ -5,7 +5,7 @@ import GRDB class Item: Record { var name: String? - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "items" } diff --git a/GRDB Tests/Public/Record/PrimaryKeyRowIDTests.swift b/GRDB Tests/Public/Record/PrimaryKeyRowIDTests.swift index ca9098f01..bacccd596 100644 --- a/GRDB Tests/Public/Record/PrimaryKeyRowIDTests.swift +++ b/GRDB Tests/Public/Record/PrimaryKeyRowIDTests.swift @@ -8,7 +8,7 @@ class Person: Record { var age: Int? var creationDate: NSDate! - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "persons" } @@ -193,9 +193,9 @@ class PrimaryKeyRowIDTests: GRDBTestCase { let record = Person(id: 123456, name: "Arthur") do { try record.update(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -229,9 +229,9 @@ class PrimaryKeyRowIDTests: GRDBTestCase { try record.delete(db) do { try record.update(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -369,9 +369,9 @@ class PrimaryKeyRowIDTests: GRDBTestCase { let record = Person(id: 123456, name: "Arthur") do { try record.reload(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -405,9 +405,9 @@ class PrimaryKeyRowIDTests: GRDBTestCase { try record.delete(db) do { try record.reload(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } diff --git a/GRDB Tests/Public/Record/PrimaryKeySingleTests.swift b/GRDB Tests/Public/Record/PrimaryKeySingleTests.swift index ed51c8565..8d0d77392 100644 --- a/GRDB Tests/Public/Record/PrimaryKeySingleTests.swift +++ b/GRDB Tests/Public/Record/PrimaryKeySingleTests.swift @@ -6,7 +6,7 @@ class Pet: Record { var UUID: String! var name: String! - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "pets" } @@ -133,9 +133,9 @@ class PrimaryKeySingleTests: GRDBTestCase { let record = Pet(UUID: "BobbyUUID", name: "Bobby") do { try record.update(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -169,9 +169,9 @@ class PrimaryKeySingleTests: GRDBTestCase { try record.delete(db) do { try record.update(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -303,9 +303,9 @@ class PrimaryKeySingleTests: GRDBTestCase { let record = Pet(UUID: "BobbyUUID", name: "Bobby") do { try record.reload(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -339,9 +339,9 @@ class PrimaryKeySingleTests: GRDBTestCase { try record.delete(db) do { try record.reload(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } diff --git a/GRDB Tests/Public/Record/PrimaryKeySingleWithReplaceConflictResolutionTests.swift b/GRDB Tests/Public/Record/PrimaryKeySingleWithReplaceConflictResolutionTests.swift index 0fc3dbd1b..28e7f459d 100644 --- a/GRDB Tests/Public/Record/PrimaryKeySingleWithReplaceConflictResolutionTests.swift +++ b/GRDB Tests/Public/Record/PrimaryKeySingleWithReplaceConflictResolutionTests.swift @@ -5,7 +5,7 @@ class Email : Record { var email: String! var label: String? - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "emails" } @@ -131,9 +131,9 @@ class PrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { record.email = "me@domain.com" do { try record.update(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -168,9 +168,9 @@ class PrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { try record.delete(db) do { try record.update(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -307,9 +307,9 @@ class PrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { record.email = "me@domain.com" do { try record.reload(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -344,9 +344,9 @@ class PrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { try record.delete(db) do { try record.reload(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } diff --git a/GRDB Tests/Public/Record/RecordAwakeFromFetchTests.swift b/GRDB Tests/Public/Record/RecordAwakeFromFetchTests.swift index ec19c3591..7a08defa0 100644 --- a/GRDB Tests/Public/Record/RecordAwakeFromFetchTests.swift +++ b/GRDB Tests/Public/Record/RecordAwakeFromFetchTests.swift @@ -5,7 +5,7 @@ class EventRecorder : Record { var id: Int64? var awakeFromFetchCount = 0 - override static func databaseTableName() -> String? { + override static func databaseTableName() -> String { return "eventRecorders" } diff --git a/GRDB Tests/Public/Record/RecordUpdateFromRowTests.swift b/GRDB Tests/Public/Record/RecordUpdateFromRowTests.swift index f7e9680b5..eeeba50de 100644 --- a/GRDB Tests/Public/Record/RecordUpdateFromRowTests.swift +++ b/GRDB Tests/Public/Record/RecordUpdateFromRowTests.swift @@ -25,7 +25,7 @@ class Placemark : Record { super.init() } - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "placemarks" } diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index d6b16e5be..f0d528d9c 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.32.2' + s.version = '0.33.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'Versatile SQLite toolkit for Swift.' s.homepage = 'https://github.com/groue/GRDB.swift' diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index ce9b8b706..2c31eab3b 100644 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -12,6 +12,8 @@ 5606AF911C0ED37000D20487 /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 56BB86301BA98AB0001F9168 /* libsqlite3.tbd */; }; 5607EFD31BB8254800605DE3 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; }; 5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; }; + 560B3FAC1C19E01000C58EC7 /* DatabasePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560B3FAB1C19E01000C58EC7 /* DatabasePersistableTests.swift */; }; + 560B3FAD1C19E01000C58EC7 /* DatabasePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560B3FAB1C19E01000C58EC7 /* DatabasePersistableTests.swift */; }; 560C97C71BFD0B8400BF8471 /* FunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560C97C61BFD0B8400BF8471 /* FunctionTests.swift */; }; 560C97C81BFD0B8400BF8471 /* FunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560C97C61BFD0B8400BF8471 /* FunctionTests.swift */; }; 560C97DA1C0E22D300BF8471 /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = 56BB86191BA988F2001F9168 /* FMDatabase.m */; }; @@ -31,8 +33,12 @@ 5614DEF01BA9DA15003163B3 /* SQLiteStatementConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5614DEEF1BA9DA15003163B3 /* SQLiteStatementConvertible.swift */; }; 5614DEF11BA9DA15003163B3 /* SQLiteStatementConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5614DEEF1BA9DA15003163B3 /* SQLiteStatementConvertible.swift */; }; 5614DEF81BAA1B43003163B3 /* DatabaseValueConversionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */; }; + 56437C841C180EDB007D6DB3 /* DatabasePersistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56437C831C180EDB007D6DB3 /* DatabasePersistable.swift */; }; + 56437C851C180EDB007D6DB3 /* DatabasePersistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56437C831C180EDB007D6DB3 /* DatabasePersistable.swift */; }; 564A50C71BFF4B7F00B3A3A2 /* CollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* CollationTests.swift */; }; 564A50C81BFF4B7F00B3A3A2 /* CollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* CollationTests.swift */; }; + 5658420E1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5658420D1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift */; }; + 5658420F1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5658420D1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift */; }; 565B0FEF1BBC7D980098DE03 /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; }; 565B0FF01BBC7D980098DE03 /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; }; 565B0FF81BBC7FE90098DE03 /* RowConvertible+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FF71BBC7FE90098DE03 /* RowConvertible+Foundation.swift */; }; @@ -139,8 +145,6 @@ 56A2389C1B9C752B0082EB20 /* DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238971B9C752B0082EB20 /* DatabaseValueConvertible.swift */; }; 56A2389D1B9C752B0082EB20 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238981B9C752B0082EB20 /* RowConvertible.swift */; }; 56A2389E1B9C752B0082EB20 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238981B9C752B0082EB20 /* RowConvertible.swift */; }; - 56A238A21B9C753B0082EB20 /* DatabaseStorable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A01B9C753B0082EB20 /* DatabaseStorable.swift */; }; - 56A238A31B9C753B0082EB20 /* DatabaseStorable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A01B9C753B0082EB20 /* DatabaseStorable.swift */; }; 56A238A41B9C753B0082EB20 /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; 56A238A51B9C753B0082EB20 /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; 56A238AA1B9C7E540082EB20 /* StatementArguments+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A91B9C7E540082EB20 /* StatementArguments+Foundation.swift */; }; @@ -303,11 +307,14 @@ /* Begin PBXFileReference section */ 31AEFE3E1C185E63003DB703 /* FetchedRecordsController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsController.swift; sourceTree = ""; }; 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = ""; }; + 560B3FAB1C19E01000C58EC7 /* DatabasePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePersistableTests.swift; sourceTree = ""; }; 560C97C61BFD0B8400BF8471 /* FunctionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FunctionTests.swift; sourceTree = ""; }; 560C981A1C0E22D300BF8471 /* GRDBOSXPerformanceTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXPerformanceTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 5614DEEF1BA9DA15003163B3 /* SQLiteStatementConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteStatementConvertible.swift; sourceTree = ""; }; 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = ""; }; + 56437C831C180EDB007D6DB3 /* DatabasePersistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePersistable.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* CollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CollationTests.swift; sourceTree = ""; }; + 5658420D1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableDatabasePersistableTests.swift; sourceTree = ""; }; 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertibleTests.swift; sourceTree = ""; }; 565B0FF71BBC7FE90098DE03 /* RowConvertible+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "RowConvertible+Foundation.swift"; sourceTree = ""; }; 565B0FFA1BBC80720098DE03 /* RowConvertible+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "RowConvertible+FoundationTests.swift"; sourceTree = ""; }; @@ -362,7 +369,6 @@ 56A238961B9C752B0082EB20 /* DatabaseTableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTableMapping.swift; sourceTree = ""; }; 56A238971B9C752B0082EB20 /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = ""; }; 56A238981B9C752B0082EB20 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = ""; }; - 56A238A01B9C753B0082EB20 /* DatabaseStorable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseStorable.swift; sourceTree = ""; }; 56A238A11B9C753B0082EB20 /* Record.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Record.swift; sourceTree = ""; }; 56A238A91B9C7E540082EB20 /* StatementArguments+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+Foundation.swift"; sourceTree = ""; }; 56A238AC1B9C90090082EB20 /* NSNull.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSNull.swift; sourceTree = ""; }; @@ -401,6 +407,7 @@ 56CA221B1BB41533009A04C5 /* StephenCelisSQLitePerformanceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StephenCelisSQLitePerformanceTests.swift; sourceTree = ""; }; 56CA22211BB41565009A04C5 /* PerformanceRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PerformanceRecord.swift; sourceTree = ""; }; 56CB92EC1BA453E500DFD5FC /* CrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CrashTests.swift; sourceTree = ""; }; + 56DBEC341C19A0020093A2EE /* CHANGELOG.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = CHANGELOG.md; sourceTree = ""; }; 56E1524B1B43FD5B00EE27AA /* TODO.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = TODO.md; sourceTree = ""; }; 56E5891E1BBA5D5400CC0140 /* NSURL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSURL.swift; sourceTree = ""; }; 56E5D7CA1B4D3FED00430942 /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -482,6 +489,15 @@ path = TransactionObserver; sourceTree = ""; }; + 560B3FA41C19DFF800C58EC7 /* DatabasePersistable */ = { + isa = PBXGroup; + children = ( + 560B3FAB1C19E01000C58EC7 /* DatabasePersistableTests.swift */, + 5658420D1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift */, + ); + path = DatabasePersistable; + sourceTree = ""; + }; 560C97BF1BFD0B5B00BF8471 /* Function */ = { isa = PBXGroup; children = ( @@ -565,6 +581,7 @@ 56AC8CCC1BA3F267009E4319 /* Concurrency */, 56A238121B9C74A90082EB20 /* Database */, 56A238151B9C74A90082EB20 /* DatabaseError */, + 560B3FA41C19DFF800C58EC7 /* DatabasePersistable */, 56A238171B9C74A90082EB20 /* DatabaseValue */, 56A238191B9C74A90082EB20 /* DatabaseValueConvertible */, 560C97BF1BFD0B5B00BF8471 /* Function */, @@ -703,6 +720,7 @@ 56A238951B9C752B0082EB20 /* Protocols */ = { isa = PBXGroup; children = ( + 56437C831C180EDB007D6DB3 /* DatabasePersistable.swift */, 56A238961B9C752B0082EB20 /* DatabaseTableMapping.swift */, 56A238971B9C752B0082EB20 /* DatabaseValueConvertible.swift */, 56A238981B9C752B0082EB20 /* RowConvertible.swift */, @@ -714,7 +732,6 @@ 56A2389F1B9C753B0082EB20 /* Record */ = { isa = PBXGroup; children = ( - 56A238A01B9C753B0082EB20 /* DatabaseStorable.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, 31AEFE3E1C185E63003DB703 /* FetchedRecordsController.swift */, ); @@ -857,6 +874,7 @@ DC3773E919C8CBB3004FCF85 = { isa = PBXGroup; children = ( + 56DBEC341C19A0020093A2EE /* CHANGELOG.md */, DC37744719C8F50B004FCF85 /* README.md */, 56E1524B1B43FD5B00EE27AA /* TODO.md */, DC37742D19C8CC90004FCF85 /* GRDB */, @@ -1207,6 +1225,7 @@ buildActionMask = 2147483647; files = ( 56A238901B9C75030082EB20 /* UpdateStatement.swift in Sources */, + 56437C851C180EDB007D6DB3 /* DatabasePersistable.swift in Sources */, 56E589201BBA5D5400CC0140 /* NSURL.swift in Sources */, 56A2388E1B9C75030082EB20 /* StatementArguments.swift in Sources */, 56A2380A1B9C6DD20082EB20 /* StandardLibraryTypes.swift in Sources */, @@ -1228,7 +1247,6 @@ 56B7F4271BE1491700E39BBF /* CGFloat.swift in Sources */, 56A2388C1B9C75030082EB20 /* Statement.swift in Sources */, 56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */, - 56A238A31B9C753B0082EB20 /* DatabaseStorable.swift in Sources */, 56A2388A1B9C75030082EB20 /* SelectStatement.swift in Sources */, 56A2389C1B9C752B0082EB20 /* DatabaseValueConvertible.swift in Sources */, 56A238801B9C75030082EB20 /* DatabaseChanges.swift in Sources */, @@ -1274,6 +1292,7 @@ 56A2385E1B9C74A90082EB20 /* RecordCopyTests.swift in Sources */, 56FC78691BBAEB8C00CA1285 /* ManagedDataControllerTests.swift in Sources */, 56A238421B9C74A90082EB20 /* DatabaseValueConversionTests.swift in Sources */, + 5658420F1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift in Sources */, 56FC78671BBAEB8C00CA1285 /* MappingTests.swift in Sources */, 56A238441B9C74A90082EB20 /* RawRepresentableTests.swift in Sources */, 5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */, @@ -1291,6 +1310,7 @@ 56CA21BB1BB3FCF7009A04C5 /* NSDataTests.swift in Sources */, 56A238B71B9CA2590082EB20 /* DatabaseTimestampTests.swift in Sources */, 565D5D751BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */, + 560B3FAD1C19E01000C58EC7 /* DatabasePersistableTests.swift in Sources */, 56F0B9921B6001C600A2F135 /* NSDateTests.swift in Sources */, 56A238381B9C74A90082EB20 /* DatabaseTests.swift in Sources */, 56F0B9901B6001C600A2F135 /* NSDateComponentsTests.swift in Sources */, @@ -1332,6 +1352,7 @@ 56EB0AB21BCD787300A3DC55 /* NSDataMemoryTests.swift in Sources */, 565B0FFB1BBC80720098DE03 /* RowConvertible+FoundationTests.swift in Sources */, 56FC78681BBAEB8C00CA1285 /* ManagedDataControllerTests.swift in Sources */, + 5658420E1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift in Sources */, 56FC78661BBAEB8C00CA1285 /* MappingTests.swift in Sources */, 56A238691B9C74A90082EB20 /* RecordSubClassTests.swift in Sources */, 5607EFD31BB8254800605DE3 /* TransactionObserverTests.swift in Sources */, @@ -1349,6 +1370,7 @@ 56CA21BA1BB3FCF7009A04C5 /* NSDataTests.swift in Sources */, 56A238B61B9CA2590082EB20 /* DatabaseTimestampTests.swift in Sources */, 565D5D741BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */, + 560B3FAC1C19E01000C58EC7 /* DatabasePersistableTests.swift in Sources */, 56F0B9911B6001C600A2F135 /* NSDateTests.swift in Sources */, 56A238371B9C74A90082EB20 /* DatabaseTests.swift in Sources */, 56F0B98F1B6001C600A2F135 /* NSDateComponentsTests.swift in Sources */, @@ -1365,6 +1387,7 @@ buildActionMask = 2147483647; files = ( 56A238AD1B9C90090082EB20 /* NSNull.swift in Sources */, + 56437C841C180EDB007D6DB3 /* DatabasePersistable.swift in Sources */, 56E5891F1BBA5D5400CC0140 /* NSURL.swift in Sources */, 56A2389D1B9C752B0082EB20 /* RowConvertible.swift in Sources */, 56A2388D1B9C75030082EB20 /* StatementArguments.swift in Sources */, @@ -1395,7 +1418,6 @@ 56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */, 56A2387D1B9C75030082EB20 /* Database.swift in Sources */, 56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */, - 56A238A21B9C753B0082EB20 /* DatabaseStorable.swift in Sources */, 56A238871B9C75030082EB20 /* Row.swift in Sources */, 56B7F4341BE4BF1600E39BBF /* DatabaseCoder.swift in Sources */, 56A2380C1B9C6E440082EB20 /* NSData.swift in Sources */, diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index f15b6a629..1451555ac 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -480,6 +480,15 @@ public final class Database { // ========================================================================= // MARK: - Database Informations + /// Clears the database schema cache. + /// + /// You may need to clear the cache if you modify the database schema + /// outside of a migration (see DatabaseMigrator). + public func clearSchemaCache() { + assertValidQueue() + columnInfosCache = [:] + } + /// The last error message var lastErrorMessage: String? { return String.fromCString(sqlite3_errmsg(sqliteConnection)) } diff --git a/GRDB/Core/Protocols/DatabasePersistable.swift b/GRDB/Core/Protocols/DatabasePersistable.swift new file mode 100644 index 000000000..3aac7d888 --- /dev/null +++ b/GRDB/Core/Protocols/DatabasePersistable.swift @@ -0,0 +1,638 @@ +// MARK: - PersistenceError + +/// An error thrown by a type that adopts DatabasePersistable. +public enum PersistenceError: ErrorType { + + /// Thrown by MutableDatabasePersistable.update() when no matching row could be + /// found in the database. + case NotFound(MutableDatabasePersistable) +} + +extension PersistenceError : CustomStringConvertible { + /// A textual representation of `self`. + public var description: String { + switch self { + case .NotFound(let persistable): + return "Not found: \(persistable)" + } + } +} + + +// MARK: - MutableDatabasePersistable + +/// Types that adopt MutableDatabasePersistable can be inserted, updated, +/// and deleted. +/// +/// This protocol is intented for types that have an INTEGER PRIMARY KEY, and +/// are interested in the inserted RowID: they can mutate themselves upon +/// successful insertion with the didInsertWithRowID(_:forColumn:) method. +/// +/// The insert() and save() methods are mutating methods. +public protocol MutableDatabasePersistable : DatabaseTableMapping { + + /// Returns the values that should be stored in the database. + /// + /// Keys of the returned dictionary must match the column names of the + /// target database table (see DatabaseTableMapping.databaseTableName()). + /// + /// In particular, primary key columns, if any, must be included. + /// + /// struct Person : MutableDatabasePersistable { + /// var id: Int64? + /// var name: String? + /// + /// var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { + /// return ["id": id, "name": name] + /// } + /// } + var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { get } + + /// Don't call this method directly: it is called upon successful insertion, + /// with the inserted RowID and the eventual INTEGER PRIMARY KEY + /// column name. + /// + /// This method is optional: the default implementation does nothing. + /// + /// struct Person : MutableDatabasePersistable { + /// var id: Int64? + /// var name: String? + /// + /// mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + /// self.id = rowID + /// } + /// } + /// + /// - parameter rowID: The inserted rowID. + /// - parameter column: The name of the eventual INTEGER PRIMARY KEY column. + mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) + + + // MARK: - CRUD + + /// Executes an INSERT statement. + /// + /// This method is guaranteed to have inserted a row in the database if it + /// returns without error. + /// + /// Upon successful insertion, the didInsertWithRowID(:forColumn:) method + /// is called with the inserted RowID and the eventual INTEGER PRIMARY KEY + /// column name. + /// + /// This method has a default implementation, so your adopting types don't + /// have to implement it. Yet your types can provide their own + /// implementation of insert(). In their implementation, it is recommended + /// that they invoke the performInsert() method. + /// + /// - parameter db: A Database. + /// - throws: A DatabaseError whenever a SQLite error occurs. + mutating func insert(db: Database) throws + + /// Executes an UPDATE statement. + /// + /// This method is guaranteed to have updated a row in the database if it + /// returns without error. + /// + /// This method has a default implementation, so your adopting types don't + /// have to implement it. Yet your types can provide their own + /// implementation of update(). In their implementation, it is recommended + /// that they invoke the performUpdate() method. + /// + /// - parameter db: A Database. + /// - throws: A DatabaseError is thrown whenever a SQLite error occurs. + /// PersistenceError.NotFound is thrown if the primary key does not + /// match any row in the database. + func update(db: Database) throws + + /// Executes an INSERT or an UPDATE statement so that `self` is saved in + /// the database. + /// + /// If the receiver has a non-nil primary key and a matching row in the + /// database, this method performs an update. + /// + /// Otherwise, performs an insert. + /// + /// This method is guaranteed to have inserted or updated a row in the + /// database if it returns without error. + /// + /// This method has a default implementation, so your adopting types don't + /// have to implement it. Yet your types can provide their own + /// implementation of save(). In their implementation, it is recommended + /// that they invoke the performSave() method. + /// + /// - parameter db: A Database. + /// - throws: A DatabaseError whenever a SQLite error occurs, or errors + /// thrown by update(). + mutating func save(db: Database) throws + + /// Executes a DELETE statement. + /// + /// This method has a default implementation, so your adopting types don't + /// have to implement it. Yet your types can provide their own + /// implementation of delete(). In their implementation, it is recommended + /// that they invoke the performDelete() method. + /// + /// - parameter db: A Database. + /// - returns: Whether a database row was deleted. + /// - throws: A DatabaseError is thrown whenever a SQLite error occurs. + func delete(db: Database) throws -> Bool + + /// Returns true if and only if the primary key matches a row in + /// the database. + /// + /// This method has a default implementation, so your adopting types don't + /// have to implement it. Yet your types can provide their own + /// implementation of exists(). In their implementation, it is recommended + /// that they invoke the performExists() method. + /// + /// - parameter db: A Database. + /// - returns: Whether the primary key matches a row in the database. + func exists(db: Database) -> Bool +} + +public extension MutableDatabasePersistable { + + /// The default implementation does nothing. + mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + } + + + // MARK: - CRUD + + /// Executes an INSERT statement. + /// + /// The default implementation for insert() invokes performInsert(). + mutating func insert(db: Database) throws { + try performInsert(db) + } + + /// Executes an UPDATE statement. + /// + /// The default implementation for update() invokes performUpdate(). + func update(db: Database) throws { + try performUpdate(db) + } + + /// Executes an INSERT or an UPDATE statement so that `self` is saved in + /// the database. + /// + /// The default implementation for save() invokes performSave(). + mutating func save(db: Database) throws { + try performSave(db) + } + + /// Executes a DELETE statement. + /// + /// The default implementation for delete() invokes performDelete(). + func delete(db: Database) throws -> Bool { + return try performDelete(db) + } + + /// Returns true if and only if the primary key matches a row in + /// the database. + /// + /// The default implementation for exists() invokes performExists(). + func exists(db: Database) -> Bool { + return performExists(db) + } + + + // MARK: - CRUD Internals + + /// Don't invoke this method directly: it is an internal method for types + /// that adopt MutableDatabasePersistable. + /// + /// performInsert() provides the default implementation for insert(). Types + /// that adopt MutableDatabasePersistable can invoke performInsert() in + /// their implementation of insert(). They should not provide their own + /// implementation of performInsert(). + mutating func performInsert(db: Database) throws { + let dataMapper = DataMapper(db, self) + let changes = try dataMapper.insertStatement().execute() + if let rowID = changes.insertedRowID { + if case .Managed(let columnName) = dataMapper.primaryKey { + didInsertWithRowID(rowID, forColumn: columnName) + } else { + didInsertWithRowID(rowID, forColumn: nil) + } + } + } + + /// Don't invoke this method directly: it is an internal method for types + /// that adopt MutableDatabasePersistable. + /// + /// performUpdate() provides the default implementation for update(). Types + /// that adopt MutableDatabasePersistable can invoke performUpdate() in + /// their implementation of update(). They should not provide their own + /// implementation of performUpdate(). + func performUpdate(db: Database) throws { + let changes = try DataMapper(db, self).updateStatement().execute() + if changes.changedRowCount == 0 { + throw PersistenceError.NotFound(self) + } + } + + /// Don't invoke this method directly: it is an internal method for types + /// that adopt MutableDatabasePersistable. + /// + /// performSave() provides the default implementation for save(). Types + /// that adopt MutableDatabasePersistable can invoke performSave() in their + /// implementation of save(). They should not provide their own + /// implementation of performSave(). + /// + /// This default implementation forwards the job to `update` or `insert`. + mutating func performSave(db: Database) throws { + // Make sure we call self.insert and self.update so that classes that + // override insert or save have opportunity to perform their custom job. + + if DataMapper(db, self).resolvingPrimaryKeyDictionary == nil { + try insert(db) + return + } + + do { + try update(db) + } catch PersistenceError.NotFound { + // TODO: check that the not persisted objet is self + // + // Why? Adopting types could override update() and update another + // object which may be the one throwing this error. + try insert(db) + } + } + + /// Don't invoke this method directly: it is an internal method for types + /// that adopt MutableDatabasePersistable. + /// + /// performDelete() provides the default implementation for deelte(). Types + /// that adopt MutableDatabasePersistable can invoke performDelete() in + /// their implementation of delete(). They should not provide their own + /// implementation of performDelete(). + func performDelete(db: Database) throws -> Bool { + return try DataMapper(db, self).deleteStatement().execute().changedRowCount > 0 + } + + /// Don't invoke this method directly: it is an internal method for types + /// that adopt MutableDatabasePersistable. + /// + /// performExists() provides the default implementation for exists(). Types + /// that adopt MutableDatabasePersistable can invoke performExists() in + /// 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) + } + +} + + +// MARK: - DatabasePersistable + +/// Types that adopt DatabasePersistable can be inserted, updated, and deleted. +/// +/// This protocol is intented for types that don't have an INTEGER PRIMARY KEY. +/// +/// Unlike MutableDatabasePersistable, the insert() and save() methods are not +/// mutating methods. +public protocol DatabasePersistable : MutableDatabasePersistable { + + /// Don't call this method directly: it is called upon successful insertion, + /// with the inserted RowID and the eventual INTEGER PRIMARY KEY + /// column name. + /// + /// This method is optional: the default implementation does nothing. + /// + /// If you need a mutating variant of this method, adopt the + /// MutableDatabasePersistable protocol instead. + /// + /// - parameter rowID: The inserted rowID. + /// - parameter column: The name of the eventual INTEGER PRIMARY KEY column. + func didInsertWithRowID(rowID: Int64, forColumn column: String?) + + /// Executes an INSERT statement. + /// + /// This method is guaranteed to have inserted a row in the database if it + /// returns without error. + /// + /// Upon successful insertion, the didInsertWithRowID(:forColumn:) method + /// is called with the inserted RowID and the eventual INTEGER PRIMARY KEY + /// column name. + /// + /// This method has a default implementation, so your adopting types don't + /// have to implement it. Yet your types can provide their own + /// implementation of insert(). In their implementation, it is recommended + /// that they invoke the performInsert() method. + /// + /// - parameter db: A Database. + /// - throws: A DatabaseError whenever a SQLite error occurs. + func insert(db: Database) throws + + /// Executes an INSERT or an UPDATE statement so that `self` is saved in + /// the database. + /// + /// If the receiver has a non-nil primary key and a matching row in the + /// database, this method performs an update. + /// + /// Otherwise, performs an insert. + /// + /// This method is guaranteed to have inserted or updated a row in the + /// database if it returns without error. + /// + /// This method has a default implementation, so your adopting types don't + /// have to implement it. Yet your types can provide their own + /// implementation of save(). In their implementation, it is recommended + /// that they invoke the performSave() method. + /// + /// - parameter db: A Database. + /// - throws: A DatabaseError whenever a SQLite error occurs, or errors + /// thrown by update(). + func save(db: Database) throws +} + +public extension DatabasePersistable { + + /// The default implementation does nothing. + func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + + } + + // MARK: - Immutable CRUD + + /// Executes an INSERT statement. + /// + /// The default implementation for insert() invokes performInsert(). + func insert(db: Database) throws { + try performInsert(db) + } + + /// Executes an INSERT or an UPDATE statement so that `self` is saved in + /// the database. + /// + /// The default implementation for save() invokes performSave(). + func save(db: Database) throws { + try performSave(db) + } + + + // MARK: - Immutable CRUD Internals + + /// Don't invoke this method directly: it is an internal method for types + /// that adopt DatabasePersistable. + /// + /// performInsert() provides the default implementation for insert(). Types + /// that adopt DatabasePersistable can invoke performInsert() in their + /// implementation of insert(). They should not provide their own + /// implementation of performInsert(). + func performInsert(db: Database) throws { + let dataMapper = DataMapper(db, self) + let changes = try dataMapper.insertStatement().execute() + if let rowID = changes.insertedRowID { + if case .Managed(let columnName) = dataMapper.primaryKey { + didInsertWithRowID(rowID, forColumn: columnName) + } else { + didInsertWithRowID(rowID, forColumn: nil) + } + } + } + + /// Don't invoke this method directly: it is an internal method for types + /// that adopt DatabasePersistable. + /// + /// performSave() provides the default implementation for save(). Types + /// that adopt DatabasePersistable can invoke performSave() in their + /// implementation of save(). They should not provide their own + /// implementation of performSave(). + /// + /// This default implementation forwards the job to `update` or `insert`. + func performSave(db: Database) throws { + // Make sure we call self.insert and self.update so that classes that + // override insert or save have opportunity to perform their custom job. + + if DataMapper(db, self).resolvingPrimaryKeyDictionary == nil { + try insert(db) + return + } + + do { + try update(db) + } catch PersistenceError.NotFound { + // TODO: check that the not persisted objet is self + // + // Why? Adopting types could override update() and update another + // object which may be the one throwing this error. + try insert(db) + } + } + +} + +// MARK: - DataMapper + +/// DataMapper takes care of DatabasePersistable CRUD +final class DataMapper { + + /// The database + let db: Database + + /// The persistable + let persistable: MutableDatabasePersistable + + /// DataMapper keeps a copy the persistable's storedDatabaseDictionary, so + /// that this dictionary is built once whatever the database operation. + /// It is guaranteed to have at least one (key, value) pair. + let storedDatabaseDictionary: [String: DatabaseValueConvertible?] + + /// The table name + let databaseTableName: String + + /// The table primary key + let primaryKey: PrimaryKey + + /// An excerpt from storedDatabaseDictionary whose keys are primary key + /// columns. + /// + /// It is nil when persistable has no primary key. + lazy var primaryKeyDictionary: [String: DatabaseValueConvertible?]? = { [unowned self] in + let columns = self.primaryKey.columns + guard columns.count > 0 else { + return nil + } + let storedDatabaseDictionary = self.storedDatabaseDictionary + var dictionary: [String: DatabaseValueConvertible?] = [:] + for column in columns { + dictionary[column] = storedDatabaseDictionary[column] + } + return dictionary + }() + + /// An excerpt from storedDatabaseDictionary whose keys are primary key + /// columns. It is able to resolve a row in the database. + /// + /// It is nil when the primaryKeyDictionary is nil or unable to identify a + /// row in the database. + lazy var resolvingPrimaryKeyDictionary: [String: DatabaseValueConvertible?]? = { [unowned self] in + // IMPLEMENTATION NOTE + // + // https://www.sqlite.org/lang_createtable.html + // + // > According to the SQL standard, PRIMARY KEY should always + // > imply NOT NULL. Unfortunately, due to a bug in some early + // > versions, this is not the case in SQLite. Unless the column + // > is an INTEGER PRIMARY KEY or the table is a WITHOUT ROWID + // > table or the column is declared NOT NULL, SQLite allows + // > NULL values in a PRIMARY KEY column. SQLite could be fixed + // > to conform to the standard, but doing so might break legacy + // > applications. Hence, it has been decided to merely document + // > the fact that SQLite allowing NULLs in most PRIMARY KEY + // > columns. + // + // What we implement: we consider that the primary key is missing if + // and only if *all* columns of the primary key are NULL. + // + // For tables with a single column primary key, we comply to the + // SQL standard. + // + // For tables with multi-column primary keys, we let the user + // store NULL in all but one columns of the primary key. + + guard let dictionary = self.primaryKeyDictionary else { + return nil + } + for case let value? in dictionary.values { + return dictionary + } + return nil + }() + + + // MARK: - Initializer + + init(_ db: Database, _ persistable: MutableDatabasePersistable) { + let databaseTableName = persistable.dynamicType.databaseTableName() + + // Fail early if database table does not exist. + guard let primaryKey = db.primaryKeyForTable(named: databaseTableName) else { + fatalError("Table \(databaseTableName.quotedDatabaseIdentifier) does not exist. See \(persistable.dynamicType).databaseTableName()") + } + + // Fail early if storedDatabaseDictionary is empty + let storedDatabaseDictionary = persistable.storedDatabaseDictionary + guard storedDatabaseDictionary.count > 0 else { + fatalError("Invalid empty dictionary returned from \(persistable.dynamicType).storedDatabaseDictionary") + } + + self.db = db + self.persistable = persistable + self.storedDatabaseDictionary = storedDatabaseDictionary + self.databaseTableName = databaseTableName + self.primaryKey = primaryKey + } + + + // MARK: - Statement builders + + func insertStatement() -> UpdateStatement { + let insertStatement = db.updateStatement(DataMapper.insertSQL(tableName: databaseTableName, insertedColumns: Array(storedDatabaseDictionary.keys))) + insertStatement.arguments = StatementArguments(storedDatabaseDictionary.values) + return insertStatement + } + + func updateStatement() -> UpdateStatement { + // Fail early if primary key does not resolve to a database row. + guard let primaryKeyDictionary = resolvingPrimaryKeyDictionary else { + fatalError("Invalid primary key in \(persistable)") + } + + // Don't update primary key columns + var updatedDictionary = storedDatabaseDictionary + for column in primaryKeyDictionary.keys { + updatedDictionary.removeValueForKey(column) + } + + // We need something to update. + if updatedDictionary.count == 0 { + // IMPLEMENTATION NOTE + // + // It is important to update something, so that + // TransactionObserverType can observe a change even though this + // change is useless. + // + // The goal is to be able to write tests with minimal tables, + // including tables made of a single primary key column. + updatedDictionary = storedDatabaseDictionary + } + + // Update + let updateStatement = db.updateStatement(DataMapper.updateSQL(tableName: databaseTableName, updatedColumns: Array(updatedDictionary.keys), conditionColumns: Array(primaryKeyDictionary.keys))) + updateStatement.arguments = StatementArguments(Array(updatedDictionary.values) + Array(primaryKeyDictionary.values)) + return updateStatement + } + + func deleteStatement() -> UpdateStatement { + // Fail early if primary key does not resolve to a database row. + guard let primaryKeyDictionary = resolvingPrimaryKeyDictionary else { + fatalError("Invalid primary key in \(persistable)") + } + + // Delete + let deleteStatement = db.updateStatement(DataMapper.deleteSQL(tableName: databaseTableName, conditionColumns: Array(primaryKeyDictionary.keys))) + deleteStatement.arguments = StatementArguments(primaryKeyDictionary.values) + return deleteStatement + } + + func reloadStatement() -> SelectStatement { + // Fail early if primary key does not resolve to a database row. + guard let primaryKeyDictionary = resolvingPrimaryKeyDictionary else { + fatalError("Invalid primary key in \(persistable)") + } + + // Fetch + let reloadStatement = db.selectStatement(DataMapper.reloadSQL(tableName: databaseTableName, conditionColumns: Array(primaryKeyDictionary.keys))) + reloadStatement.arguments = StatementArguments(primaryKeyDictionary.values) + return reloadStatement + } + + /// SELECT statement that returns a row if and only if the primary key + /// matches a row in the database. + func existsStatement() -> SelectStatement { + // Fail early if primary key does not resolve to a database row. + guard let primaryKeyDictionary = resolvingPrimaryKeyDictionary else { + fatalError("Invalid primary key in \(persistable)") + } + + // Fetch + let existsStatement = db.selectStatement(DataMapper.existsSQL(tableName: databaseTableName, conditionColumns: Array(primaryKeyDictionary.keys))) + existsStatement.arguments = StatementArguments(primaryKeyDictionary.values) + return existsStatement + } + + + // MARK: - SQL query builders + + private class func insertSQL(tableName tableName: String, insertedColumns: [String]) -> String { + let columnSQL = insertedColumns.map { $0.quotedDatabaseIdentifier }.joinWithSeparator(",") + let valuesSQL = Array(count: insertedColumns.count, repeatedValue: "?").joinWithSeparator(",") + return "INSERT INTO \(tableName.quotedDatabaseIdentifier) (\(columnSQL)) VALUES (\(valuesSQL))" + } + + private class func updateSQL(tableName tableName: String, updatedColumns: [String], conditionColumns: [String]) -> String { + let updateSQL = updatedColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joinWithSeparator(",") + return "UPDATE \(tableName.quotedDatabaseIdentifier) SET \(updateSQL) WHERE \(whereSQL(conditionColumns))" + } + + private class func deleteSQL(tableName tableName: String, conditionColumns: [String]) -> String { + return "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE \(whereSQL(conditionColumns))" + } + + private class func existsSQL(tableName tableName: String, conditionColumns: [String]) -> String { + return "SELECT 1 FROM \(tableName.quotedDatabaseIdentifier) WHERE \(whereSQL(conditionColumns))" + } + + private class func reloadSQL(tableName tableName: String, conditionColumns: [String]) -> String { + return "SELECT * FROM \(tableName.quotedDatabaseIdentifier) WHERE \(whereSQL(conditionColumns))" + } + + private class func whereSQL(conditionColumns: [String]) -> String { + return conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joinWithSeparator(" AND ") + } +} diff --git a/GRDB/Core/Protocols/DatabaseTableMapping.swift b/GRDB/Core/Protocols/DatabaseTableMapping.swift index 70230e062..4ec2e8b4d 100644 --- a/GRDB/Core/Protocols/DatabaseTableMapping.swift +++ b/GRDB/Core/Protocols/DatabaseTableMapping.swift @@ -1,18 +1,19 @@ -/// Types that adopt DatabaseTableMapping can be initialized from rows that come -/// from a particular table. +/// Types that adopt DatabaseTableMapping declare a particular relationship with +/// a database table. /// -/// The protocol comes with built-in methods that allow to fetch instances -/// identified by their primary key, or any other key: +/// Types that adopt both DatabaseTableMapping and RowConvertible are granted +/// with built-in methods that allow to fetch instances identified by key: /// /// Person.fetchOne(db, key: 123) // Person? /// Citizenship.fetchOne(db, key: ["personId": 12, "countryId": 45]) // Citizenship? /// /// DatabaseTableMapping is adopted by Record. -public protocol DatabaseTableMapping : RowConvertible { - static func databaseTableName() -> String? +public protocol DatabaseTableMapping { + /// The name of the database table + static func databaseTableName() -> String } -extension DatabaseTableMapping { +extension RowConvertible where Self: DatabaseTableMapping { // MARK: - Single-Column Primary Key @@ -66,10 +67,7 @@ extension DatabaseTableMapping { // // Returns nil if keys is empty. private static func fetchByPrimaryKeyStatement(db: Database, keys: Sequence) -> SelectStatement? { - // Fail early if databaseTable is nil - guard let databaseTableName = databaseTableName() else { - fatalError("Nil returned from \(self).databaseTableName()") - } + let databaseTableName = self.databaseTableName() // Fail early if database table does not exist. guard let primaryKey = db.primaryKeyForTable(named: databaseTableName) else { @@ -154,11 +152,6 @@ extension DatabaseTableMapping { // // Returns nil if keys is empty. private static func fetchByKeyStatement(db: Database, keys: [[String: DatabaseValueConvertible?]]) -> SelectStatement? { - // Fail early if databaseTable is nil - guard let databaseTableName = databaseTableName() else { - fatalError("Nil returned from \(self).databaseTableName()") - } - // Avoid performing useless SELECT guard keys.count > 0 else { return nil @@ -175,6 +168,7 @@ extension DatabaseTableMapping { whereClauses.append("(" + dictionary.keys.map { "\($0.quotedDatabaseIdentifier) = ?" }.joinWithSeparator(" AND ") + ")") } + let databaseTableName = self.databaseTableName() let whereClause = whereClauses.joinWithSeparator(" OR ") let sql = "SELECT * FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(whereClause)" let statement = db.selectStatement(sql) diff --git a/GRDB/Info.plist b/GRDB/Info.plist index 2e0287431..1cb93ef4a 100644 --- a/GRDB/Info.plist +++ b/GRDB/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 0.32.2 + 0.33.0 CFBundleSignature ???? CFBundleVersion diff --git a/GRDB/Migrations/DatabaseMigrator.swift b/GRDB/Migrations/DatabaseMigrator.swift index 6a41e34b1..a4f9fb980 100644 --- a/GRDB/Migrations/DatabaseMigrator.swift +++ b/GRDB/Migrations/DatabaseMigrator.swift @@ -110,6 +110,9 @@ public struct DatabaseMigrator { let appliedMigrationIdentifiers = String.fetchAll(db, "SELECT identifier FROM grdb_migrations") try migrations .filter { !appliedMigrationIdentifiers.contains($0.identifier) } - .forEach { try $0.run(db) } + .forEach { + try $0.run(db) + db.clearSchemaCache() + } } } \ No newline at end of file diff --git a/GRDB/Record/DatabaseStorable.swift b/GRDB/Record/DatabaseStorable.swift deleted file mode 100644 index 8dd6fe6cd..000000000 --- a/GRDB/Record/DatabaseStorable.swift +++ /dev/null @@ -1,220 +0,0 @@ -// MARK: - DatabaseStorable - -protocol DatabaseStorable : DatabaseTableMapping { - var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { get } -} - - -// MARK: - DataMapper - -/// DataMapper takes care of DatabaseStorable CRUD -final class DataMapper { - - /// The database - let db: Database - - /// The storable - let storable: DatabaseStorable - - /// DataMapper keeps a copy the storable's storedDatabaseDictionary, so - /// that this dictionary is built once whatever the database operation. - /// It is guaranteed to have at least one (key, value) pair. - let storedDatabaseDictionary: [String: DatabaseValueConvertible?] - - /// The table name - let databaseTableName: String - - /// The table primary key - let primaryKey: PrimaryKey - - /// An excerpt from storedDatabaseDictionary whose keys are primary key - /// columns. - /// - /// It is nil when storable has no primary key. - lazy var primaryKeyDictionary: [String: DatabaseValueConvertible?]? = { [unowned self] in - let columns = self.primaryKey.columns - guard columns.count > 0 else { - return nil - } - let storedDatabaseDictionary = self.storedDatabaseDictionary - var dictionary: [String: DatabaseValueConvertible?] = [:] - for column in columns { - dictionary[column] = storedDatabaseDictionary[column] - } - return dictionary - }() - - /// An excerpt from storedDatabaseDictionary whose keys are primary key - /// columns. It is able to resolve a row in the database. - /// - /// It is nil when the primaryKeyDictionary is nil or unable to identify a - /// row in the database. - lazy var resolvingPrimaryKeyDictionary: [String: DatabaseValueConvertible?]? = { [unowned self] in - // IMPLEMENTATION NOTE - // - // https://www.sqlite.org/lang_createtable.html - // - // > According to the SQL standard, PRIMARY KEY should always - // > imply NOT NULL. Unfortunately, due to a bug in some early - // > versions, this is not the case in SQLite. Unless the column - // > is an INTEGER PRIMARY KEY or the table is a WITHOUT ROWID - // > table or the column is declared NOT NULL, SQLite allows - // > NULL values in a PRIMARY KEY column. SQLite could be fixed - // > to conform to the standard, but doing so might break legacy - // > applications. Hence, it has been decided to merely document - // > the fact that SQLite allowing NULLs in most PRIMARY KEY - // > columns. - // - // What we implement: we consider that the primary key is missing if - // and only if *all* columns of the primary key are NULL. - // - // For tables with a single column primary key, we comply to the - // SQL standard. - // - // For tables with multi-column primary keys, we let the user - // store NULL in all but one columns of the primary key. - - guard let dictionary = self.primaryKeyDictionary else { - return nil - } - for case let value? in dictionary.values { - return dictionary - } - return nil - }() - - - // MARK: - Initializer - - init(_ db: Database, _ storable: DatabaseStorable) { - // Fail early if databaseTable is nil - guard let databaseTableName = storable.dynamicType.databaseTableName() else { - fatalError("Nil returned from \(storable.dynamicType).databaseTableName()") - } - - // Fail early if database table does not exist. - guard let primaryKey = db.primaryKeyForTable(named: databaseTableName) else { - fatalError("Table \(databaseTableName.quotedDatabaseIdentifier) does not exist. See \(storable.dynamicType).databaseTableName()") - } - - // Fail early if storedDatabaseDictionary is empty - let storedDatabaseDictionary = storable.storedDatabaseDictionary - guard storedDatabaseDictionary.count > 0 else { - fatalError("Invalid empty dictionary returned from \(storable.dynamicType).storedDatabaseDictionary") - } - - self.db = db - self.storable = storable - self.storedDatabaseDictionary = storedDatabaseDictionary - self.databaseTableName = databaseTableName - self.primaryKey = primaryKey - } - - - // MARK: - Statement builders - - func insertStatement() -> UpdateStatement { - let insertStatement = db.updateStatement(DataMapper.insertSQL(tableName: databaseTableName, insertedColumns: Array(storedDatabaseDictionary.keys))) - insertStatement.arguments = StatementArguments(storedDatabaseDictionary.values) - return insertStatement - } - - func updateStatement() -> UpdateStatement { - // Fail early if primary key does not resolve to a database row. - guard let primaryKeyDictionary = resolvingPrimaryKeyDictionary else { - fatalError("Invalid primary key in \(storable)") - } - - // Don't update primary key columns - var updatedDictionary = storedDatabaseDictionary - for column in primaryKeyDictionary.keys { - updatedDictionary.removeValueForKey(column) - } - - // We need something to update. - if updatedDictionary.count == 0 { - // IMPLEMENTATION NOTE - // - // It is important to update something, so that - // TransactionObserverType can observe a change even though this - // change is useless. - // - // The goal is to be able to write tests with minimal tables, - // including tables made of a single primary key column. - updatedDictionary = storedDatabaseDictionary - } - - // Update - let updateStatement = db.updateStatement(DataMapper.updateSQL(tableName: databaseTableName, updatedColumns: Array(updatedDictionary.keys), conditionColumns: Array(primaryKeyDictionary.keys))) - updateStatement.arguments = StatementArguments(Array(updatedDictionary.values) + Array(primaryKeyDictionary.values)) - return updateStatement - } - - func deleteStatement() -> UpdateStatement { - // Fail early if primary key does not resolve to a database row. - guard let primaryKeyDictionary = resolvingPrimaryKeyDictionary else { - fatalError("Invalid primary key in \(storable)") - } - - // Delete - let deleteStatement = db.updateStatement(DataMapper.deleteSQL(tableName: databaseTableName, conditionColumns: Array(primaryKeyDictionary.keys))) - deleteStatement.arguments = StatementArguments(primaryKeyDictionary.values) - return deleteStatement - } - - func reloadStatement() -> SelectStatement { - // Fail early if primary key does not resolve to a database row. - guard let primaryKeyDictionary = resolvingPrimaryKeyDictionary else { - fatalError("Invalid primary key in \(storable)") - } - - // Fetch - let reloadStatement = db.selectStatement(DataMapper.reloadSQL(tableName: databaseTableName, conditionColumns: Array(primaryKeyDictionary.keys))) - reloadStatement.arguments = StatementArguments(primaryKeyDictionary.values) - return reloadStatement - } - - /// SELECT statement that returns a row if and only if the primary key - /// matches a row in the database. - func existsStatement() -> SelectStatement { - // Fail early if primary key does not resolve to a database row. - guard let primaryKeyDictionary = resolvingPrimaryKeyDictionary else { - fatalError("Invalid primary key in \(storable)") - } - - // Fetch - let existsStatement = db.selectStatement(DataMapper.existsSQL(tableName: databaseTableName, conditionColumns: Array(primaryKeyDictionary.keys))) - existsStatement.arguments = StatementArguments(primaryKeyDictionary.values) - return existsStatement - } - - - // MARK: - SQL query builders - - private class func insertSQL(tableName tableName: String, insertedColumns: [String]) -> String { - let columnSQL = insertedColumns.map { $0.quotedDatabaseIdentifier }.joinWithSeparator(",") - let valuesSQL = Array(count: insertedColumns.count, repeatedValue: "?").joinWithSeparator(",") - return "INSERT INTO \(tableName.quotedDatabaseIdentifier) (\(columnSQL)) VALUES (\(valuesSQL))" - } - - private class func updateSQL(tableName tableName: String, updatedColumns: [String], conditionColumns: [String]) -> String { - let updateSQL = updatedColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joinWithSeparator(",") - return "UPDATE \(tableName.quotedDatabaseIdentifier) SET \(updateSQL) WHERE \(whereSQL(conditionColumns))" - } - - private class func deleteSQL(tableName tableName: String, conditionColumns: [String]) -> String { - return "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE \(whereSQL(conditionColumns))" - } - - private class func existsSQL(tableName tableName: String, conditionColumns: [String]) -> String { - return "SELECT 1 FROM \(tableName.quotedDatabaseIdentifier) WHERE \(whereSQL(conditionColumns))" - } - - private class func reloadSQL(tableName tableName: String, conditionColumns: [String]) -> String { - return "SELECT * FROM \(tableName.quotedDatabaseIdentifier) WHERE \(whereSQL(conditionColumns))" - } - - private class func whereSQL(conditionColumns: [String]) -> String { - return conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joinWithSeparator(" AND ") - } -} diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index cb253fbc2..50ded18db 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -9,7 +9,7 @@ /// - updateFromRow /// - databaseTable /// - storedDatabaseDictionary -public class Record : RowConvertible, DatabaseTableMapping, DatabaseStorable { +public class Record : RowConvertible, DatabaseTableMapping, DatabasePersistable { // MARK: - Initializers @@ -73,20 +73,20 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabaseStorable { /// Returns the name of a database table. /// - /// The insert, update, save, delete, exists and reload methods require it: - /// they raise a fatal error if databaseTableName is nil. + /// This table name is required by the insert, update, save, delete, exists + /// and reload methods. /// /// class Person : Record { - /// override class func databaseTableName() -> String? { + /// override class func databaseTableName() -> String { /// return "persons" /// } /// } /// - /// The implementation of the base class Record returns nil. + /// The implementation of the base class Record raises a fatal error. /// /// - returns: The name of a database table. - public class func databaseTableName() -> String? { - return nil + public class func databaseTableName() -> String { + fatalError("Subclass must override.") } /// Returns the values that should be stored in the database. @@ -148,6 +148,21 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabaseStorable { public func updateFromRow(row: Row) { } + /// Don't call this method directly: it is called upon successful insertion, + /// with the inserted RowID and the eventual INTEGER PRIMARY KEY + /// column name. + /// + /// The default implementation calls updateFromRow() if the table has an + /// INTEGER PRIMARY KEY. + /// + /// - parameter rowID: The inserted rowID. + /// - parameter column: The name of the eventual INTEGER PRIMARY KEY column. + public func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + if let column = column { + updateFromRow(Row(dictionary: [column: rowID])) + } + } + // MARK: - Copy @@ -242,7 +257,7 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabaseStorable { // MARK: - CRUD - /// Executes an INSERT statement to insert the record. + /// Executes an INSERT statement. /// /// On success, this method sets the *databaseEdited* flag to false. /// @@ -256,16 +271,11 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabaseStorable { /// - parameter db: A Database. /// - throws: A DatabaseError whenever a SQLite error occurs. public func insert(db: Database) throws { - let dataMapper = DataMapper(db, self) - let changes = try dataMapper.insertStatement().execute() - if case .Managed(let rowIDColumnName) = dataMapper.primaryKey { - // Update RowID - updateFromRow(Row(dictionary: [rowIDColumnName: changes.insertedRowID])) - } + try performInsert(db) databaseEdited = false } - /// Executes an UPDATE statement to update the record. + /// Executes an UPDATE statement. /// /// On success, this method sets the *databaseEdited* flag to false. /// @@ -274,17 +284,15 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabaseStorable { /// /// - parameter db: A Database. /// - throws: A DatabaseError is thrown whenever a SQLite error occurs. - /// RecordError.RecordNotFound is thrown if the primary key does not match + /// 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 { - let changes = try DataMapper(db, self).updateStatement().execute() - if changes.changedRowCount == 0 { - throw RecordError.RecordNotFound(self) - } + try performUpdate(db) databaseEdited = false } - /// Saves the record in the database. + /// Executes an INSERT or an UPDATE statement so that `self` is saved in + /// the database. /// /// If the record has a non-nil primary key and a matching row in the /// database, this method performs an update. @@ -300,22 +308,10 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabaseStorable { /// - throws: A DatabaseError whenever a SQLite error occurs, or errors /// thrown by update(). final public func save(db: Database) throws { - // Make sure we call self.insert and self.update so that classes that - // override insert or save have opportunity to perform their custom job. - - if DataMapper(db, self).resolvingPrimaryKeyDictionary == nil { - try insert(db) - return - } - - do { - try update(db) - } catch RecordError.RecordNotFound { - try insert(db) - } + try performSave(db) } - /// Executes a DELETE statement to delete the record. + /// Executes a DELETE statement. /// /// On success, this method sets the *databaseEdited* flag to true. /// @@ -323,38 +319,29 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabaseStorable { /// - returns: Whether a database row was deleted. /// - throws: A DatabaseError is thrown whenever a SQLite error occurs. public func delete(db: Database) throws -> Bool { - let changes = try DataMapper(db, self).deleteStatement().execute() - // Future calls to update() will throw RecordNotFound. Make the user + let deleted = try performDelete(db) + // Future calls to update() will throw NotFound. Make the user // a favor and make sure this error is thrown even if she checks the // databaseEdited flag: databaseEdited = true - return changes.changedRowCount > 0 + return deleted } - /// Executes a SELECT statetement to reload the record. + /// Executes a SELECT statetement. /// /// On success, this method sets the *databaseEdited* flag to false. /// /// - parameter db: A Database. - /// - throws: RecordError.RecordNotFound is thrown if the primary key does + /// - throws: PersistenceError.NotFound is thrown if the primary key does /// not match any row in the database and record could not be reloaded. public func reload(db: Database) throws { let statement = DataMapper(db, self).reloadStatement() guard let row = Row.fetchOne(statement) else { - throw RecordError.RecordNotFound(self) + throw PersistenceError.NotFound(self) } updateFromRow(row) awakeFromFetch(row) } - - /// Returns true if and only if the primary key matches a row in - /// the database. - /// - /// - parameter db: A Database. - /// - returns: Whether the primary key matches a row in the database. - final public func exists(db: Database) -> Bool { - return (Row.fetchOne(DataMapper(db, self).existsStatement()) != nil) - } } @@ -375,23 +362,3 @@ extension Record : CustomStringConvertible { + ">" } } - - -// MARK: - RecordError - -/// A Record-specific error -public enum RecordError: ErrorType { - - /// No matching row could be found in the database. - case RecordNotFound(Record) -} - -extension RecordError : CustomStringConvertible { - /// A textual representation of `self`. - public var description: String { - switch self { - case .RecordNotFound(let record): - return "Record not found: \(record)" - } - } -} diff --git a/Playgrounds/JSONSynchronization.playground/Contents.swift b/Playgrounds/JSONSynchronization.playground/Contents.swift index a9deefd22..05de6d8df 100644 --- a/Playgrounds/JSONSynchronization.playground/Contents.swift +++ b/Playgrounds/JSONSynchronization.playground/Contents.swift @@ -30,7 +30,7 @@ class Person : Record { var id: Int64? var name: String? - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "persons" } diff --git a/Playgrounds/Record.playground/Contents.swift b/Playgrounds/Record.playground/Contents.swift index 1deacb36e..af0625661 100644 --- a/Playgrounds/Record.playground/Contents.swift +++ b/Playgrounds/Record.playground/Contents.swift @@ -38,7 +38,7 @@ class Person : Record { // Record overrides - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "persons" } diff --git a/Playgrounds/Record.playground/contents.xcplayground b/Playgrounds/Record.playground/contents.xcplayground index a204ba673..06828af92 100644 --- a/Playgrounds/Record.playground/contents.xcplayground +++ b/Playgrounds/Record.playground/contents.xcplayground @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/README.md b/README.md index c3522684f..334aba588 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ GRDB.swift is an [SQLite](https://www.sqlite.org) toolkit for Swift 2, from the It ships with a low-level database API, plus application-level tools. -**December 3, 2015: GRDB.swift 0.32.2 is out** - [Release notes](CHANGELOG.md). Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips. +**December 11, 2015: GRDB.swift 0.33.0 is out** - [Release notes](CHANGELOG.md). Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips. **Requirements**: iOS 7.0+ / OSX 10.9+, Xcode 7+ @@ -19,7 +19,9 @@ Why GRDB, when we already have the excellent [ccgus/fmdb](https://github.com/ccg **GRDB owes a lot to FMDB.** You will use the familiar and safe [database queues](#database-queues) you are used to. Yet you may appreciate that [database errors](#error-handling) are handled in the Swift way, and that [fetching data](#fetch-queries) is somewhat easier. -**Your SQL skills are rewarded here.** You won't lose a single feature or convenience by crafting custom SQL queries, on the contrary. Without losing type safety and all niceties you expect from a real Swift library. +**Your SQL skills are rewarded here.** Complex queries are never treated differently from the simple ones. You won't lose a single feature or convenience by crafting custom SQL queries, on the contrary. And you are granted with type safety and all the niceties you expect from a real Swift library. + +**GRDB provides protocols and a Record class** that help isolating database management code into database layer types, and avoid cluterring the rest of your application. **GRDB is fast**. As fast, when not faster, than FMDB and SQLite.swift. @@ -28,7 +30,7 @@ Features -------- - **A low-level [SQLite API](#sqlite-api)** that leverages the Swift 2 standard library. -- **A [Record](#records) class** that wraps result sets, eats your custom SQL queries for breakfast, and provides basic CRUD operations. +- **A [Record](#record) class** that wraps result sets, eats your custom SQL queries for breakfast, provides persistence operations, and changes tracking. - **[Swift type freedom](#values)**: pick the right Swift type that fits your data. Use Int64 when needed, or stick with the convenient Int. Store and read NSDate or NSDateComponents. Declare Swift enums for discrete data types. Define your own database-convertible types. - **[Database migrations](#migrations)** - **[Database changes observation hooks](#database-changes-observation)** @@ -37,7 +39,7 @@ Features Documentation ============= -- **[GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.32.2/index.html)** (on cocoadocs.org) +- **[GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.33.0/index.html)** (on cocoadocs.org) - **[Installation](#installation)** @@ -51,7 +53,6 @@ Documentation - [Values](#values) - [NSData](#nsdata-and-memory-savings) - [NSDate and NSDateComponents](#nsdate-and-nsdatecomponents) - - [NSCoding](#nscoding) - [Swift enums](#swift-enums) - [Custom Value Types](#custom-value-types) - [Transactions](#transactions) @@ -64,11 +65,14 @@ Documentation - [Raw SQLite Pointers](#raw-sqlite-pointers) -- **[Application Tools](#application-tools)** - - [Migrations](#migrations): Transform your database as your application evolves. - - [Database Changes Observation](#database-changes-observation): A robust way to perform post-commit and post-rollback actions. - - [RowConvertible Protocol](#rowconvertible-protocol): Turn database rows into handy types, without sacrificing performance. - - [Records](#records): CRUD operations and changes tracking. +- **[Migrations](#migrations)**: Transform your database as your application evolves. + +- **Database protocols, and Record** + - [RowConvertible Protocol](#rowconvertible-protocol): Don't fetch rows, fetch your custom types instead. + - [DatabasePersistable Protocol](#databasepersistable-protocol): Grant any type with persistence methods. + - [Record](#record): The class that wraps a table row or the result of any query, provides persistence methods, and changes tracking. + +- **[Database Changes Observation](#database-changes-observation)**: A robust way to perform post-commit and post-rollback actions. - **[Sample Code](#sample-code)** @@ -91,7 +95,7 @@ To use GRDB.swift with Cocoapods, specify in your Podfile: source 'https://github.com/CocoaPods/Specs.git' use_frameworks! -pod 'GRDB.swift', '0.32.2' +pod 'GRDB.swift', '0.33.0' ``` @@ -102,7 +106,7 @@ pod 'GRDB.swift', '0.32.2' To use GRDB.swift with Carthage, specify in your Cartfile: ``` -github "groue/GRDB.swift" == 0.32.2 +github "groue/GRDB.swift" == 0.33.0 ``` @@ -179,7 +183,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.32.2/Structs/Configuration.html) and [Concurrency](#concurrency) for more details. +See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.33.0/Structs/Configuration.html) and [Concurrency](#concurrency) for more details. Once connected, the `inDatabase` and `inTransaction` methods perform your **database statements** in a dedicated, serial, queue: @@ -274,7 +278,7 @@ dbQueue.inDatabase { db in } ``` -**Custom models** are your application objects that can initialize themselves from rows (see the [RowConvertible protocol](#rowconvertible-protocol) and the [Record class](#records)): +**Custom models** are your application objects that can initialize themselves from rows (see the [RowConvertible protocol](#rowconvertible-protocol) and the [Record class](#record)): ```swift dbQueue.inDatabase { db in @@ -422,6 +426,7 @@ You may prefer thinking of rows as dictionaries of `DatabaseValue`, an intermedi ```swift // Test if the column `date` is present: if let databaseValue = row["date"] { + // Pick the type you need: let dateString: String = databaseValue.value() // "2015-09-11 18:14:15.123" let date: NSDate = databaseValue.value() // NSDate @@ -446,6 +451,9 @@ if let databaseValue = row["date"] { print("NSData: \(data)") } } + +// Nil if the column is not present: +let date: NSDate = row["date"]?.value() ``` Iterate all the tuples (columnName, databaseValue) in a row, from left to right: @@ -496,17 +504,20 @@ dbQueue.inDatabase { db in } ``` -For example: +There are many supported value types (Bool, Int, String, NSDate, Swift enums, etc.). See [Values](#values) for more information: ```swift dbQueue.inDatabase { db in - // The number of persons with an email ending in @domain.com: + // The number of persons with an email ending in @example.com: let count = Int.fetchOne(db, "SELECT COUNT(*) FROM persons WHERE email LIKE ?", - arguments: ["%@domain.com"])! + arguments: ["%@example.com"])! + + // All URLs: + let urls = NSURL.fetchAll(db, "SELECT url FROM links") // The emails of people who own at least two pets: - let emails = String.fetch(db, + let emails = Optional.fetchAll(db, "SELECT persons.email " + "FROM persons " + "JOIN pets ON pets.masterId = persons.id " + @@ -528,9 +539,9 @@ Both `fetch` and `fetchAll` let you iterate the full list of fetched values. The GRDB ships with built-in support for the following value types: -- **Swift**: Bool, Double, Int, Int32, Int64, String, [Swift enums](#swift-enums). +- **Swift Standard Library**: Bool, Double, Int, Int32, Int64, String, [Swift enums](#swift-enums). -- **Foundation**: [NSCoding](#nscoding), [NSData](#nsdata-and-memory-savings), [NSDate](#nsdate-and-nsdatecomponents), [NSDateComponents](#nsdate-and-nsdatecomponents), NSNull, NSNumber, NSString, NSURL. +- **Foundation**: [NSData](#nsdata-and-memory-savings), [NSDate](#nsdate-and-nsdatecomponents), [NSDateComponents](#nsdate-and-nsdatecomponents), NSNull, NSNumber, NSString, NSURL. - **CoreGraphics**: CGFloat. @@ -559,14 +570,16 @@ They can be [directly fetched](#value-queries) from the database: let urls = NSURL.fetchAll(db, "SELECT url FROM links") // [NSURL] ``` -Use them as [Record](#records) properties: +Use them in the `storedDatabaseDictionary` property of [DatabasePersistable protocol](#databasepersistable-protocol) and [Record subclasses](#record): ```swift class Link : Record { var url: NSURL? var verified: Bool - ... + override var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { + return ["url": url, "verified": verified] + } } ``` @@ -734,37 +747,6 @@ DatabaseDateComponents.fetchOne(db, "SELECT ...") // DatabaseDateComponents? See [Column Values](#column-values) and [Value Queries](#value-queries) for more information. -### NSCoding - -NSCoding is indirectly supported, through the **DatabaseCoder** helper type. - -DatabaseCoder reads and writes objects that adopt NSCoding into Blob columns. - -For example, store NSArray into the database: - -```swift -let ints = [1, 2, 3] -try db.execute( - "INSERT INTO ... (ints, ...) VALUES (?, ...)", - arguments: [DatabaseCoder(ints), ...]) -``` - -Extract NSArray from the database: - -```swift -let row = Row.fetchOne(db, "SELECT ints ...")! -let coder = row.value(named: "ints") as DatabaseCoder // DatabaseCoder -let array = coder.object as! NSArray // NSArray -let ints = array.map { $0 as! Int } // [Int] - -DatabaseCoder.fetch(db, "SELECT ...") // DatabaseSequence -DatabaseCoder.fetchAll(db, "SELECT ...") // [DatabaseCoder] -DatabaseCoder.fetchOne(db, "SELECT ...") // DatabaseCoder? -``` - -See [Column Values](#column-values) and [Value Queries](#value-queries) for more information. - - ### Swift Enums **Swift enums** get full support from GRDB.swift as long as their raw values are Int, Int32, Int64 or String. @@ -1069,7 +1051,7 @@ See [Configuration](GRDB/Core/Configuration.swift) type and [DatabaseQueue.inTra ## Custom SQL Functions -**SQLite let you define SQL functions.** +**SQLite lets you define SQL functions.** You can for example use the Unicode support of Swift strings, and go beyond the ASCII limitations of the built-in SQLite `upper()` function: @@ -1227,10 +1209,12 @@ Application Tools On top of the SQLite API described above, GRDB provides a toolkit for applications. While none of those are mandatory, all of them help dealing with the database: -- [Migrations](#migrations): Transform your database as your application evolves. -- [Database Changes Observation](#database-changes-observation): A robust way to perform post-commit and post-rollback actions. -- [RowConvertible Protocol](#rowconvertible-protocol): Turn database rows into handy types, without sacrificing performance. -- [Records](#records): CRUD operations and changes tracking. +- **[Migrations](#migrations)**: Transform your database as your application evolves. +- **Database protocols, and Record** + - [RowConvertible Protocol](#rowconvertible-protocol): Don't fetch rows, fetch your custom types instead. + - [DatabasePersistable Protocol](#databasepersistable-protocol): Grant any type with persistence methods. + - [Record](#record): The class that wraps a table row or the result of any query, provides persistence methods, and changes tracking. +- **[Database Changes Observation](#database-changes-observation)**: A robust way to perform post-commit and post-rollback actions. ## Migrations @@ -1313,126 +1297,6 @@ migrator.registerMigrationWithoutForeignKeyChecks("AddNotNullCheckOnName") { db While your migration code runs with disabled foreign key checks, those are re-enabled and checked at the end of the migration, regardless of eventual errors. -## Database Changes Observation - -The TransactionObserverType protocol lets you **observe database changes**: - -```swift -public protocol TransactionObserverType : class { - // Notifies a database change: - // - event.kind (insert, update, or delete) - // - event.tableName - // - event.rowID - func databaseDidChangeWithEvent(event: DatabaseEvent) - - // An opportunity to rollback pending changes by throwing an error. - func databaseWillCommit() throws - - // Database changes have been committed. - func databaseDidCommit(db: Database) - - // Database changes have been rollbacked. - func databaseDidRollback(db: Database) -} -``` - -**There is one transaction observer per database:** - -```swift -var config = Configuration() -config.transactionObserver = MyObserver() -let dbQueue = try DatabaseQueue(path: databasePath, configuration: config) -``` - -Protocol callbacks are all invoked on the database queue. - -**All database changes are notified** to databaseDidChangeWithEvent, inserts, updates and deletes, including indirect ones triggered by ON DELETE and ON UPDATE actions associated to [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions). - -Those changes are not actually applied until databaseDidCommit is called. On the other side, databaseDidRollback confirms their invalidation: - -```swift -try dbQueue.inTransaction { db in - try db.execute("INSERT ...") // didChange - return .Commit // willCommit, didCommit -} - -try dbQueue.inTransaction { db in - try db.execute("INSERT ...") // didChange - return .Rollback // didRollback -} -``` - -Database statements that are executed outside of an explicit transaction do not drop off the radar: - -```swift -try dbQueue.inDatabase { db in - try db.execute("INSERT ...") // didChange, willCommit, didCommit - try db.execute("UPDATE ...") // didChange, willCommit, didCommit -} -``` - -**Eventual errors** thrown from databaseWillCommit are exposed to the application code: - -```swift -do { - try dbQueue.inTransaction { db in - ... - return .Commit // willCommit (throws), didRollback - } -} catch { - // The error thrown by the transaction observer. -} -``` - -> :point_up: **Note**: The databaseDidChangeWithEvent and databaseWillCommit callbacks must not touch the SQLite database. This limitation does not apply to databaseDidCommit and databaseDidRollback which can use their database argument. - - -### Sample Transaction Observer: TableChangeObserver - -Let's write an object that notifies, on the main thread, of modified database tables. Your view controllers can listen to those notifications and update their views accordingly. - -```swift -/// The notification posted when database tables have changed: -let DatabaseTablesDidChangeNotification = "DatabaseTablesDidChangeNotification" -let ChangedTableNamesKey = "ChangedTableNames" - -/// TableChangeObserver posts a DatabaseTablesDidChangeNotification on the main -/// thread after database tables have changed. -class TableChangeObserver : NSObject, TransactionObserverType { - private var changedTableNames: Set = [] - - func databaseDidChangeWithEvent(event: DatabaseEvent) { - // Remember the name of the changed table: - changedTableNames.insert(event.tableName) - } - - func databaseWillCommit() throws { - // Let go - } - - func databaseDidCommit(db: Database) { - // Extract the names of changed tables, and reset until next - // database event: - let changedTableNames = self.changedTableNames - self.changedTableNames = [] - - // Notify - dispatch_async(dispatch_get_main_queue()) { - NSNotificationCenter.defaultCenter().postNotificationName( - DatabaseTablesDidChangeNotification, - object: self, - userInfo: [ChangedTableNamesKey: changedTableNames]) - } - } - - func databaseDidRollback(db: Database) { - // Reset until next database event: - self.changedTableNames = [] - } -} -``` - - ## RowConvertible Protocol **The `RowConvertible` protocol grants fetching methods to any type** that can be initialized from a database row: @@ -1485,10 +1349,298 @@ PointOfInterest(dictionary: [ "title": "Rome"]) ``` -See also the [Record](#records) class, which builds on top of RowConvertible and adds a few extra features like CRUD operations, and changes tracking. +See also the [Record](#record) class, which builds on top of RowConvertible and adds a few extra features like persistence methods, and changes tracking. -## Records +### Fetching by Key + +**Adopt the `DatabaseTableMapping` protocol** on top of `RowConvertible`: + +```swift +public protocol DatabaseTableMapping { + /// The name of the database table + static func databaseTableName() -> String +} +``` + +For example: + +```swift +// CREATE TABLE persons ( +// id INTEGER PRIMARY KEY, +// name TEXT, +// email TEXT UNIQUE COLLATE NOCASE +// ) +struct Person : RowConvertible, DatabaseTableMapping { + var id: Int64? + var name: String? + var email: String? + + static func databaseTableName() -> String { + return "persons" + } + + init(row: Row) { + id = row.value(named: "id") + name = row.value(named: "name") + email = row.value(named: "email") + } +} +``` + +You are then granted with fetching methods based on database keys: + +```swift +Person.fetch(db, keys: ...) // DatabaseSequence +Person.fetchAll(db, keys: ...) // [Person] +Person.fetchOne(db, key: ...) // Person? +``` + +Both `fetch` and `fetchAll` let you iterate the full list of fetched objects. The differences are: + +- The array returned by `fetchAll` can take a lot of memory. Yet it can be iterated on any thread. +- The sequence returned by `fetch` only goes to the database as you iterate it, and is thus more memory efficient. The price for this efficiency is that the sequence must be iterated in the database queue (you'll get a fatal error if you do otherwise). +- The sequence returned by `fetch` will return a different set of results if the database has been modified between two sequence iterations. + +The order of sequences and arrays returned by the key-based methods is undefined. To specify the order of returned elements, use a raw SQL query. + + +**When the database table has a single column primary key**, you can fetch given key values: + +```swift +// SELECT * FROM persons WHERE id = 1 +Person.fetchOne(db, key: 1) + +// SELECT * FROM persons WHERE id IN (1,2,3) +Person.fetch(db, keys: [1,2,3]) + +// SELECT * FROM countries WHERE isoCode = 'FR' +Country.fetchOne(db, key: "FR") + +// SELECT * FROM countries WHERE isoCode IN ('FR', 'ES', 'US') +Country.fetchAll(db, keys: ["FR", "ES", "US"]) +``` + +**For multi-column primary keys and secondary keys**, use a key dictionary: + +```swift +// SELECT * FROM persons WHERE email = 'me@example.com' +Person.fetchOne(db, key: ["email": "me@example.com"]) + +// SELECT * FROM citizenships WHERE personId = 1 AND countryIsoCode = 'FR' +Citizenship.fetchOne(db, key: ["personId": 1, "countryIsoCode": "FR"]) +``` + + +### Optional Columns + +**Your RowConvertible type can accept rows that do not always contain the same columns.** + +This allows you to load only a subset of a table columns, or to load extra columns joined from other tables. For example: + +```swift +struct Person : RowConvertible { + let id: Int64? + let name: String + let bookCount: Int? // Only set when person is fetched from fetchAllWithBookCount() + + init(row: Row) { + // mandatory columns: + id = row.value(named: "id") + name = row.value(named: "name") + + // bookCount may not always be present: + bookCount = row["bookCount"]?.value() + } + + // The returned persons have a value in their bookCount property: + static func fetchAllWithBookCount(db: Database) -> [Person] { + return fetchAll(db, + "SELECT persons.*, COUNT(books.id) AS bookCount " + + "FROM persons " + + "LEFT JOIN books ON books.ownerId = persons.id " + + "GROUP BY persons.id") + } +} +``` + +See [Rows as Dictionaries](#rows-as-dictionaries) for more information about the `row["bookCount"]?.value()` expression. + + +## DatabasePersistable Protocol + +**GRDB provides two protocols that let adopting types store themselves in the database:** + +```swift +public protocol MutableDatabasePersistable : DatabaseTableMapping { + /// The name of the database table (from DatabaseTableMapping) + static func databaseTableName() -> String + + /// Returns the values that should be stored in the database. + var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { get } + + /// Optional method that lets your adopting type store its rowID upon + /// successful insertion: + mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) +} + +public protocol DatabasePersistable : MutableDatabasePersistable { + /// Non-mutating version of the optional didInsertWithRowID(:forColumn:) + func didInsertWithRowID(rowID: Int64, forColumn column: String?) +} +``` + +That's one more protocol that one could expect, and `MutableDatabasePersistable` may sound intimidating. + +Yet, here is the rule: + +- If your type is a struct that mutates on insertion, choose `MutableDatabasePersistable`. For example, if your table has an INTEGER PRIMARY KEY, you want to store the inserted id on successful insertion. +- Otherwise, stick with `DatabasePersistable`. + +For example, the Country struct below has no INTEGER PRIMARY KEY, and is not mutated on insertion. On the other side, the Person struct is interested in its rowID, and mutates itself on insertion: + +```swift +// CREATE TABLE countries ( +// isoCode TEXT NOT NULL PRIMARY KEY, +// name TEXT NOT NULL +// ) +struct Country : DatabasePersistable { + let isoCode: String + let name: String + + static func databaseTableName() -> String { + return "countries" + } + + var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { + return ["isoCode": isoCode, "name": name] + } +} + +// Declare the country as `let`, since its insertion does not mutate it: +let country = Country(isoCode: "FR", name: "France") +try country.insert(db) + +// CREATE TABLE persons ( +// id INTEGER PRIMARY KEY, +// name TEXT +// ) +struct Person : MutableDatabasePersistable { + let id: Int64? + let name: String? + + static func databaseTableName() -> String { + return "persons" + } + + var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { + return ["id": id, "name": name] + } + + // Update self.id upon successful insertion: + mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + self.id = rowID + } +} + +// Declare the person as `var`, since its insertion mutates it: +var person = Person(id: nil, name: "Arthur") +person.id // nil +try person.insert(db) +person.id // some value +``` + +The `storedDatabaseDictionary` property returns a dictionary whose keys are column names, and values any DatabaseValueConvertible value (Bool, Int, String, NSDate, Swift enums, etc.) See [Values](#values) for more information. + +> :point_up: **Note**: Classes should always prefer adopting `DatabasePersistable` over `MutableDatabasePersistable`, even if they mutate on insertion. This will prevent strange compiler errors when they insert an instance stored in a `let` variable (see [SR-142](https://bugs.swift.org/browse/SR-142)). + + +### Persistence Methods + +Types that adopt DatabasePersistable or MutableDatabasePersistable are given default implementations for methods that insert, update, and delete: + +```swift +try object.insert(db) // INSERT +try object.update(db) // UPDATE +try object.save(db) // Inserts or updates +try object.delete(db) // DELETE +object.exists(db) // Bool +``` + +- `insert`, `update`, `save` and `delete` can throw a [DatabaseError](#error-handling) whenever an SQLite integrity check fails. + +- `update` can also throw a PersistenceError of type NotFound, should the update fail because there is no matching row in the database. + + When saving an object that may or may not already exist in the database, prefer the `save` method: it performs the UPDATE or INSERT statement that makes sure your values are saved in the database. + +- `delete` returns whether a database row was deleted or not. + +The differences between `DatabasePersistable` and `MutableDatabasePersistable` only lie in insertion-related methods: + +```swift +protocol MutableDatabasePersistable { + // Insertion can mutate: + mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) + mutating func insert(db: Database) throws + mutating func save(db: Database) throws +} + +protocol DatabasePersistable : MutableDatabasePersistable { + // Insertion can not mutate: + func didInsertWithRowID(rowID: Int64, forColumn column: String?) + func insert(db: Database) throws + func save(db: Database) throws +} +``` + + +### Customizing the Persistence Methods + +Your custom type may want to perform extra work when the persistence methods are invoked. + +For example, it may want to have its UUID automatically set before inserting. Or it may want to validate its values before saving. + +The protocol exposes *special methods* for this exact purpose: `performInsert`, `performUpdate`, `performSave`, `performDelete`, and `performExists`. + +```swift +struct Person : MutableDatabasePersistable { + var uuid: String? + + mutating func insert(db: Database) throws { + if uuid == nil { + uuid = NSUUID().UUIDString + } + try performInsert(db) + } +} + +struct Link : DatabasePersistable { + var url: NSURL + + func insert(db: Database) throws { + try validate() + try performInsert(db) + } + + func update(db: Database) throws { + try validate() + try performUpdate(db) + } + + func validate() throws { + if url.host == nil { + throw ValidationError("url must be absolute.") + } + } +} +``` + +> :point_up: **Note**: The special methods `performInsert`, `performUpdate`, etc. are reserved for your custom implementations. Do not use them elsewhere. Do not provide another implementation for those methods. +> +> :point_up: **Note**: It is recommended that you do not implement your own version of the `save` method. Its default implementation forwards the job to `update` or `insert`: these are the methods that may need customization, not `save`. + + +## Record - [Overview](#record-overview) - [Subclassing Record](#subclassing-record) @@ -1501,7 +1653,7 @@ See also the [Record](#records) class, which builds on top of RowConvertible and ### Record Overview -**Record** is a class that wraps a table row or the result of any query, provides CRUD operations, and changes tracking. It is designed to be subclassed. +**Record** is a class that wraps a table row or the result of any query, provides persistence methods, and changes tracking. It is designed to be subclassed. ```swift // Define Record subclass @@ -1519,6 +1671,8 @@ try dbQueue.inDatabase { db in } ``` +It builds on top of the [RowConvertible](#rowconvertible-protocol) and [DatabasePersistable](#databasepersistable-protocol) protocols. + **Record is not a smart class.** It is no replacement for Core Data’s NSManagedObject, [Realm](https://realm.io)’s Object, or for an Active Record pattern. It does not provide any uniquing, automatic refresh, or synthesized properties. It has no knowledge of external references and table relationships, and will not generate JOIN queries for you. Yet, it does a few things well: @@ -1537,7 +1691,7 @@ Yet, it does a few things well: (person.name, person.citizenshipsCount) ``` -- **It provides the classic CRUD operations.** All primary keys are supported (auto-incremented INTEGER PRIMARY KEY, single column, multiple columns). +- **It provides the classic CRUD persistence methods.** All primary keys are supported (auto-incremented INTEGER PRIMARY KEY, single column, multiple columns). ```swift let person = Person(...) @@ -1568,7 +1722,7 @@ Yet, it does a few things well: ```swift class Record { /// The table name - class func databaseTableName() -> String? + class func databaseTableName() -> String /// The values stored in the database var storedDatabaseDictionary: [String: DatabaseValueConvertible?] @@ -1593,7 +1747,7 @@ class Person { var databaseEdited: Bool var databaseChanges: [String: (old: DatabaseValue?, new: DatabaseValue)] - // CRUD + // Persistence func insert(db: Database) throws func update(db: Database) throws func save(db: Database) throws // inserts or updates @@ -1639,12 +1793,14 @@ Person overrides `databaseTableName()` to return the name of the table that shou ```swift /// The table name - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "persons" } ``` -Person overrides `storedDatabaseDictionary` to return the dictionary of values that should be stored in the database when a person is saved. `DatabaseValueConvertible` is the protocol adopted by all supported values (Bool, Int, String, NSDate, Swift enums, etc.) See [Values](#values) for more information: +Person overrides `storedDatabaseDictionary` to return the dictionary of values that should be stored in the database when a person is saved. + +Person overrides `storedDatabaseDictionary` and returns a dictionary whose keys are column names, and values any `DatabaseValueConvertible` value (Bool, Int, String, NSDate, Swift enums, etc.) See [Values](#values) for more information: ```swift /// The values stored in the database @@ -1721,10 +1877,10 @@ For example: ```swift dbQueue.inDatabase { db in - // All persons with an email ending in @domain.com: + // All persons with an email ending in @example.com: Person.fetch(db, "SELECT * FROM persons WHERE email LIKE ?", - arguments: ["%@domain.com"]) + arguments: ["%@example.com"]) // All persons who have a single citizenship: Person.fetch(db, @@ -1746,8 +1902,8 @@ dbQueue.inDatabase { db in // SELECT * FROM countries WHERE isoCode IN ('FR', 'ES', 'US') Country.fetchAll(db, keys: ["FR", "ES", "US"]) - // SELECT * FROM persons WHERE email = 'me@domain.com' - Person.fetchOne(db, key: ["email": "me@domain.com"]) + // SELECT * FROM persons WHERE email = 'me@example.com' + Person.fetchOne(db, key: ["email": "me@example.com"]) // SELECT * FROM citizenships WHERE personId = 1 AND countryIsoCode = 'FR' Citizenship.fetchOne(db, key: ["personId": 1, "countryIsoCode": "FR"]) @@ -1793,7 +1949,7 @@ try dbQueue.inDatabase { db in - `insert`, `update`, `save` and `delete` can throw a [DatabaseError](#error-handling) whenever an SQLite integrity check fails. -- `update` and `reload` methods can also throw a RecordError of type RecordNotFound, should the update or reload fail because the record does not exist in the database. +- `update` and `reload` methods can also throw a PersistenceError of type NotFound, should the update or reload fail because the record does not exist in the database. When saving a record that may or may not already exist in the database, prefer the `save` method: it performs the UPDATE or INSERT statement that makes sure your values are saved in the database. @@ -1900,7 +2056,7 @@ class Person : Record { id: Int64? /// The table definition. - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "persons" } @@ -2068,6 +2224,126 @@ person.insert(db) // Replace any existing person named "Arthur" ``` +## Database Changes Observation + +The `TransactionObserverType` protocol lets you **observe database changes**: + +```swift +public protocol TransactionObserverType : class { + // Notifies a database change: + // - event.kind (insert, update, or delete) + // - event.tableName + // - event.rowID + func databaseDidChangeWithEvent(event: DatabaseEvent) + + // An opportunity to rollback pending changes by throwing an error. + func databaseWillCommit() throws + + // Database changes have been committed. + func databaseDidCommit(db: Database) + + // Database changes have been rollbacked. + func databaseDidRollback(db: Database) +} +``` + +**There is one transaction observer per database:** + +```swift +var config = Configuration() +config.transactionObserver = MyObserver() +let dbQueue = try DatabaseQueue(path: databasePath, configuration: config) +``` + +Protocol callbacks are all invoked on the database queue. + +**All database changes are notified** to databaseDidChangeWithEvent, inserts, updates and deletes, including indirect ones triggered by ON DELETE and ON UPDATE actions associated to [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions). + +Those changes are not actually applied until databaseDidCommit is called. On the other side, databaseDidRollback confirms their invalidation: + +```swift +try dbQueue.inTransaction { db in + try db.execute("INSERT ...") // didChange + return .Commit // willCommit, didCommit +} + +try dbQueue.inTransaction { db in + try db.execute("INSERT ...") // didChange + return .Rollback // didRollback +} +``` + +Database statements that are executed outside of an explicit transaction do not drop off the radar: + +```swift +try dbQueue.inDatabase { db in + try db.execute("INSERT ...") // didChange, willCommit, didCommit + try db.execute("UPDATE ...") // didChange, willCommit, didCommit +} +``` + +**Eventual errors** thrown from databaseWillCommit are exposed to the application code: + +```swift +do { + try dbQueue.inTransaction { db in + ... + return .Commit // willCommit (throws), didRollback + } +} catch { + // The error thrown by the transaction observer. +} +``` + +> :point_up: **Note**: The databaseDidChangeWithEvent and databaseWillCommit callbacks must not touch the SQLite database. This limitation does not apply to databaseDidCommit and databaseDidRollback which can use their database argument. + + +### Sample Transaction Observer: TableChangeObserver + +Let's write an object that notifies, on the main thread, of modified database tables. Your view controllers can listen to those notifications and update their views accordingly. + +```swift +/// The notification posted when database tables have changed: +let DatabaseTablesDidChangeNotification = "DatabaseTablesDidChangeNotification" +let ChangedTableNamesKey = "ChangedTableNames" + +/// TableChangeObserver posts a DatabaseTablesDidChangeNotification on the main +/// thread after database tables have changed. +class TableChangeObserver : NSObject, TransactionObserverType { + private var changedTableNames: Set = [] + + func databaseDidChangeWithEvent(event: DatabaseEvent) { + // Remember the name of the changed table: + changedTableNames.insert(event.tableName) + } + + func databaseWillCommit() throws { + // Let go + } + + func databaseDidCommit(db: Database) { + // Extract the names of changed tables, and reset until next + // database event: + let changedTableNames = self.changedTableNames + self.changedTableNames = [] + + // Notify + dispatch_async(dispatch_get_main_queue()) { + NSNotificationCenter.defaultCenter().postNotificationName( + DatabaseTablesDidChangeNotification, + object: self, + userInfo: [ChangedTableNamesKey: changedTableNames]) + } + } + + func databaseDidRollback(db: Database) { + // Reset until next database event: + self.changedTableNames = [] + } +} +``` + + Sample Code =========== diff --git a/TODO.md b/TODO.md index 4c09df4ec..05672ef90 100644 --- a/TODO.md +++ b/TODO.md @@ -1,10 +1,9 @@ - [ ] #2: this commit may be how stephencelis fixed it: https://github.com/stephencelis/SQLite.swift/commit/8f64e357c3a6668c5f011c91ba33be3e8d4b88d0 - [ ] Study SQLCipher -- [ ] Study custom collations - [ ] `IN (?)` sql snippet, with an array argument. - [ ] Write sample code around NSFetchedResultsController: fetch and output a list of TableView sections & row differences. - [ ] Compare DatabaseCoder with http://mjtsai.com/blog/2015/11/08/the-java-deserialization-bug-and-nssecurecoding/ - +- [ ] Now that DatabasePersistable is out, Record has this didInsertWithRowID(:forColumn:) which calls updateFromRow. When we document "The updateFromRow method MUST NOT assume the presence of particular columns. The Record class itself reserves the right to call updateFromRow with arbitrary columns", we are actually talking about didInsertWithRowID, which is now exposed. Users may be confused. Not sure: