Change RowModel.save(db) so that it inserts when no database row could be updated.

This commit is contained in:
Gwendal Roué committed 2015-07-12 13:20:58 +02:00
1 parent bd5d2c58fc
commit 554ed9fcd5
9 files changed
+599 -27

No files matched your search

@@ -0,0 +1,239 @@
//
// GRDB.swift
// https://github.com/groue/GRDB.swift
// Copyright (c) 2015 Gwendal Roué
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
import GRDB
// MinimalRowID is the most tiny class with a RowID primary key which supports
// read and write operations of RowModel.
class MinimalRowID: RowModel {
var id: Int64!
override class var databaseTable: Table? {
return Table(named: "minimalRowIDs", primaryKey: .RowID("id"))
}
override var storedDatabaseDictionary: [String: DatabaseValueConvertible?] {
return ["id": id]
}
override func setDatabaseValue(dbv: DatabaseValue, forColumn column: String) {
switch column {
case "id": id = dbv.value()
default: super.setDatabaseValue(dbv, forColumn: column)
}
}
static func setupInDatabase(db: Database) throws {
try db.execute(
"CREATE TABLE minimalRowIDs (id INTEGER PRIMARY KEY)")
}
}
class MinimalPrimaryKeyRowIDTests: RowModelTestCase {
func testInsert() {
// Models with RowID primary key should be able to be inserted with a
// nil primary key. After the insertion, they have their primary key
// set.
assertNoError {
let minimalRowID = MinimalRowID()
XCTAssertTrue(minimalRowID.id == nil)
try dbQueue.inTransaction { db in
// The tested method
try minimalRowID.insert(db)
// After insertion, ID should be set
XCTAssertTrue(minimalRowID.id != nil)
return .Commit
}
// After insertion, model should be present in the database
dbQueue.inDatabase { db in
let minimalRowIDs = db.fetchAll(MinimalRowID.self, "SELECT * FROM minimalRowIDs")
XCTAssertEqual(minimalRowIDs.count, 1)
}
}
}
func testInsertTwice() {
// Models with RowID primary key should be able to be inserted with a
// nil primary key. After the insertion, they have their primary key
// set.
//
// The second insertion should fail because the primary key is already
// taken.
assertNoError {
let minimalRowID = MinimalRowID()
XCTAssertTrue(minimalRowID.id == nil)
do {
try dbQueue.inTransaction { db in
try minimalRowID.insert(db)
try minimalRowID.insert(db)
return .Commit
}
XCTFail("Expected error")
} catch is DatabaseError {
// OK, this is expected
}
}
}
func testUpdate() {
assertNoError {
try dbQueue.inTransaction { db in
var minimalRowID = MinimalRowID()
XCTAssertTrue(minimalRowID.id == nil)
try minimalRowID.insert(db)
try minimalRowID.update(db) // object still in database
minimalRowID = db.fetchOne(MinimalRowID.self, primaryKey: minimalRowID.id)!
try minimalRowID.delete(db)
do {
try minimalRowID.update(db) // object no longer in database
XCTFail("Expected RowModelError.RowModelNotFound")
} catch RowModelError.RowModelNotFound {
} catch {
XCTFail("Expected RowModelError.RowModelNotFound, not \(error)")
}
return .Commit
}
}
}
func testSave() {
assertNoError {
let minimalRowID = MinimalRowID()
XCTAssertTrue(minimalRowID.id == nil)
try dbQueue.inTransaction { db in
try minimalRowID.save(db) // insert
let minimalRowIDCount = db.fetchOne(Int.self, "SELECT COUNT(*) FROM minimalRowIDs")!
XCTAssertEqual(minimalRowIDCount, 1)
return .Commit
}
XCTAssertTrue(minimalRowID.id != nil)
try dbQueue.inTransaction { db in
try minimalRowID.save(db) // update
let minimalRowIDCount = db.fetchOne(Int.self, "SELECT COUNT(*) FROM minimalRowIDs")!
XCTAssertEqual(minimalRowIDCount, 1)
return .Commit
}
try dbQueue.inDatabase { db in
try minimalRowID.delete(db)
try minimalRowID.save(db) // inserts
let minimalRowIDCount = db.fetchOne(Int.self, "SELECT COUNT(*) FROM minimalRowIDs")!
XCTAssertEqual(minimalRowIDCount, 1)
}
}
}
func testSelectWithPrimaryKey() {
assertNoError {
var id: Int64? = nil
try dbQueue.inTransaction { db in
let minimalRowID = MinimalRowID()
try minimalRowID.insert(db)
id = minimalRowID.id
return .Commit
}
dbQueue.inDatabase { db in
let minimalRowID = db.fetchOne(MinimalRowID.self, primaryKey: id!)! // The tested method
XCTAssertEqual(minimalRowID.id!, id!)
}
}
}
func testSelectWithKey() {
assertNoError {
try dbQueue.inDatabase { db in
var minimalRowID = MinimalRowID()
try minimalRowID.insert(db)
let id = minimalRowID.id
minimalRowID = db.fetchOne(MinimalRowID.self, key: ["id": id])! // The tested method
XCTAssertEqual(minimalRowID.id!, id!)
}
}
}
func testDelete() {
assertNoError {
var id: Int64? = nil
try dbQueue.inTransaction { db in
let minimalRowID1 = MinimalRowID()
try minimalRowID1.insert(db)
let minimalRowID2 = MinimalRowID()
try minimalRowID2.insert(db)
id = minimalRowID2.id
try minimalRowID1.delete(db) // The tested method
return .Commit
}
dbQueue.inDatabase { db in
let minimalRowIDs = db.fetchAll(MinimalRowID.self, "SELECT * FROM minimalRowIDs")
XCTAssertEqual(minimalRowIDs.count, 1)
XCTAssertEqual(minimalRowIDs.first!.id, id!)
}
}
}
func testReload() {
assertNoError {
try dbQueue.inTransaction { db in
let minimalRowID = MinimalRowID()
try minimalRowID.insert(db)
try minimalRowID.reload(db) // object still in database
try minimalRowID.delete(db)
do {
try minimalRowID.reload(db) // object no longer in database
XCTFail("Expected RowModelError.RowModelNotFound")
} catch RowModelError.RowModelNotFound {
} catch {
XCTFail("Expected RowModelError.RowModelNotFound, not \(error)")
}
return .Commit
}
}
}
}
@@ -0,0 +1,232 @@
//
// GRDB.swift
// https://github.com/groue/GRDB.swift
// Copyright (c) 2015 Gwendal Roué
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
import GRDB
// MinimalRowID is the most tiny class with a Single row primary key which
// supports read and write operations of RowModel.
class MinimalSingle: RowModel {
var UUID: String!
override class var databaseTable: Table? {
return Table(named: "minimalSingles", primaryKey: .RowID("UUID"))
}
override var storedDatabaseDictionary: [String: DatabaseValueConvertible?] {
return ["UUID": UUID]
}
override func setDatabaseValue(dbv: DatabaseValue, forColumn column: String) {
switch column {
case "UUID": UUID = dbv.value()
default: super.setDatabaseValue(dbv, forColumn: column)
}
}
static func setupInDatabase(db: Database) throws {
try db.execute(
"CREATE TABLE minimalSingles (UUID TEXT NOT NULL PRIMARY KEY)")
}
}
class MinimalPrimaryKeySingleTests: RowModelTestCase {
func testInsert() {
// Models with RowID primary key should be able to be inserted with a
// nil primary key. After the insertion, they have their primary key
// set.
assertNoError {
let minimalSingle = MinimalSingle()
minimalSingle.UUID = "foo"
try dbQueue.inTransaction { db in
// The tested method
try minimalSingle.insert(db)
return .Commit
}
// After insertion, model should be present in the database
dbQueue.inDatabase { db in
let minimalSingles = db.fetchAll(MinimalSingle.self, "SELECT * FROM minimalSingles")
XCTAssertEqual(minimalSingles.count, 1)
}
}
}
func testInsertTwice() {
// Models with RowID primary key should be able to be inserted with a
// nil primary key. After the insertion, they have their primary key
// set.
//
// The second insertion should fail because the primary key is already
// taken.
assertNoError {
let minimalSingle = MinimalSingle()
minimalSingle.UUID = "foo"
do {
try dbQueue.inTransaction { db in
try minimalSingle.insert(db)
try minimalSingle.insert(db)
return .Commit
}
XCTFail("Expected error")
} catch is DatabaseError {
// OK, this is expected
}
}
}
func testUpdate() {
assertNoError {
try dbQueue.inTransaction { db in
var minimalSingle = MinimalSingle()
minimalSingle.UUID = "foo"
try minimalSingle.insert(db)
try minimalSingle.update(db) // object still in database
minimalSingle = db.fetchOne(MinimalSingle.self, primaryKey: minimalSingle.UUID)!
try minimalSingle.delete(db)
do {
try minimalSingle.update(db) // object no longer in database
XCTFail("Expected RowModelError.RowModelNotFound")
} catch RowModelError.RowModelNotFound {
} catch {
XCTFail("Expected RowModelError.RowModelNotFound, not \(error)")
}
return .Commit
}
}
}
func testSave() {
assertNoError {
let minimalSingle = MinimalSingle()
minimalSingle.UUID = "foo"
try dbQueue.inTransaction { db in
try minimalSingle.save(db) // insert
let minimalSingleCount = db.fetchOne(Int.self, "SELECT COUNT(*) FROM minimalSingles")!
XCTAssertEqual(minimalSingleCount, 1)
return .Commit
}
try dbQueue.inTransaction { db in
try minimalSingle.save(db) // update
let minimalSingleCount = db.fetchOne(Int.self, "SELECT COUNT(*) FROM minimalSingles")!
XCTAssertEqual(minimalSingleCount, 1)
return .Commit
}
try dbQueue.inDatabase { db in
try minimalSingle.delete(db)
try minimalSingle.save(db) // inserts
let minimalSingleCount = db.fetchOne(Int.self, "SELECT COUNT(*) FROM minimalSingles")!
XCTAssertEqual(minimalSingleCount, 1)
}
}
}
func testSelectWithPrimaryKey() {
assertNoError {
try dbQueue.inDatabase { db in
let UUID = "foo"
var minimalSingle = MinimalSingle()
minimalSingle.UUID = UUID
try minimalSingle.insert(db)
minimalSingle = db.fetchOne(MinimalSingle.self, primaryKey: UUID)! // The tested method
XCTAssertEqual(minimalSingle.UUID!, UUID)
}
}
}
func testSelectWithKey() {
assertNoError {
try dbQueue.inDatabase { db in
let UUID = "foo"
var minimalSingle = MinimalSingle()
minimalSingle.UUID = UUID
try minimalSingle.insert(db)
minimalSingle = db.fetchOne(MinimalSingle.self, key: ["UUID": UUID])! // The tested method
XCTAssertEqual(minimalSingle.UUID!, UUID)
}
}
}
func testDelete() {
assertNoError {
try dbQueue.inDatabase { db in
let UUID1 = "foo"
let minimalSingle1 = MinimalSingle()
minimalSingle1.UUID = UUID1
try minimalSingle1.insert(db)
let UUID2 = "bar"
let minimalSingle2 = MinimalSingle()
minimalSingle2.UUID = UUID2
try minimalSingle2.insert(db)
try minimalSingle1.delete(db) // The tested method
let minimalSingles = db.fetchAll(MinimalSingle.self, "SELECT * FROM minimalSingles")
XCTAssertEqual(minimalSingles.count, 1)
XCTAssertEqual(minimalSingles.first!.UUID, UUID2)
}
}
}
func testReload() {
assertNoError {
try dbQueue.inTransaction { db in
let minimalSingle = MinimalSingle()
minimalSingle.UUID = "foo"
try minimalSingle.insert(db)
try minimalSingle.reload(db) // object still in database
try minimalSingle.delete(db)
do {
try minimalSingle.reload(db) // object no longer in database
XCTFail("Expected RowModelError.RowModelNotFound")
} catch RowModelError.RowModelNotFound {
} catch {
XCTFail("Expected RowModelError.RowModelNotFound, not \(error)")
}
return .Commit
}
}
}
}
@@ -25,6 +25,7 @@
import XCTest
import GRDB
// Citizenship has a multiple-column primary key.
class Citizenship: RowModel {
var personID: Int64?
var countryName: String?
@@ -172,8 +173,8 @@ class PrimaryKeyMultipleTests: RowModelTestCase {
XCTAssertEqual(citizenship.countryName!, "France")
XCTAssertEqual(calendar.component(NSCalendarUnit.Year, fromDate: citizenship.grantedDate!), 2000)
try citizenship.delete(db)
do {
try citizenship.delete(db)
try citizenship.update(db) // object no longer in database
XCTFail("Expected RowModelError.RowModelNotFound")
} catch RowModelError.RowModelNotFound {
@@ -186,6 +187,41 @@ class PrimaryKeyMultipleTests: RowModelTestCase {
}
}
func testSave() {
assertNoError {
let person = Person(name: "Arthur", age: 41)
try dbQueue.inTransaction { db in
try person.insert(db)
return .Commit
}
let citizenship = Citizenship()
citizenship.personID = person.id
citizenship.countryName = "France"
try dbQueue.inTransaction { db in
try citizenship.save(db) // insert
let citizenshipCount = db.fetchOne(Int.self, "SELECT COUNT(*) FROM citizenships")!
XCTAssertEqual(citizenshipCount, 1)
return .Commit
}
try dbQueue.inTransaction { db in
try citizenship.save(db) // update
let citizenshipCount = db.fetchOne(Int.self, "SELECT COUNT(*) FROM citizenships")!
XCTAssertEqual(citizenshipCount, 1)
return .Commit
}
try dbQueue.inDatabase { db in
try citizenship.delete(db)
try citizenship.save(db) // inserts
let citizenshipCount = db.fetchOne(Int.self, "SELECT COUNT(*) FROM citizenships")!
XCTAssertEqual(citizenshipCount, 1)
}
}
}
func testSelectWithKey() {
assertNoError {
try dbQueue.inDatabase { db in
@@ -25,6 +25,7 @@
import XCTest
import GRDB
// Item has no primary key.
class Item: RowModel {
var name: String?
+14 -19
View File
@@ -25,6 +25,7 @@
import XCTest
import GRDB
// Person has a RowID primary key, and a overriden insert() method.
class Person: RowModel {
var id: Int64!
var name: String!
@@ -159,8 +160,8 @@ class PrimaryKeyRowIDTests: RowModelTestCase {
arthur = db.fetchOne(Person.self, primaryKey: arthur.id)!
XCTAssertEqual(arthur.age, 42)
try arthur.delete(db)
do {
try arthur.delete(db)
try arthur.update(db) // object no longer in database
XCTFail("Expected RowModelError.RowModelNotFound")
} catch RowModelError.RowModelNotFound {
@@ -175,32 +176,26 @@ class PrimaryKeyRowIDTests: RowModelTestCase {
func testSave() {
assertNoError {
let arthur = Person(name: "Arthur", age: 41)
let person = Person(name: "Arthur", age: 41)
XCTAssertTrue(arthur.id == nil)
XCTAssertTrue(person.id == nil)
try dbQueue.inTransaction { db in
try arthur.save(db) // insert
try person.save(db) // insert
return .Commit
}
XCTAssertTrue(arthur.id != nil)
arthur.age = 18
XCTAssertTrue(person.id != nil)
person.age = 18
try dbQueue.inTransaction { db in
try arthur.save(db) // update
try person.save(db) // update
return .Commit
}
try dbQueue.inDatabase{ db in
let arthur2 = db.fetchOne(Person.self, primaryKey: arthur.id!)!
XCTAssertEqual(arthur2.age!, 18)
try arthur2.delete(db)
do {
try arthur.save(db) // object no longer in database
XCTFail("Expected RowModelError.RowModelNotFound")
} catch RowModelError.RowModelNotFound {
} catch {
XCTFail("Expected RowModelError.RowModelNotFound, not \(error)")
}
try dbQueue.inDatabase { db in
try person.delete(db)
try person.save(db) // inserts
let persons = db.fetchAll(Person.self, "SELECT * FROM persons")
XCTAssertEqual(persons.count, 1)
}
}
}
@@ -25,6 +25,7 @@
import XCTest
import GRDB
// Pet has a non-RowID primary key, and a reference to Person.
class Pet: RowModel {
var UUID: String?
var masterID: Int64?
@@ -183,8 +184,8 @@ class PrimaryKeySingleTests: RowModelTestCase {
pet = db.fetchOne(Pet.self, primaryKey: pet.UUID!)!
XCTAssertEqual(pet.name!, "Karl")
try pet.delete(db)
do {
try pet.delete(db)
try pet.update(db) // object no longer in database
XCTFail("Expected RowModelError.RowModelNotFound")
} catch RowModelError.RowModelNotFound {
@@ -197,6 +198,39 @@ class PrimaryKeySingleTests: RowModelTestCase {
}
}
func testSave() {
assertNoError {
let person = Person(name: "Arthur", age: 41)
try dbQueue.inTransaction { db in
try person.insert(db)
return .Commit
}
let pet = Pet(UUID: "BobbyID", name: "Bobby", masterID: person.id)
try dbQueue.inTransaction { db in
try pet.save(db) // insert
let petCount = db.fetchOne(Int.self, "SELECT COUNT(*) FROM pets")!
XCTAssertEqual(petCount, 1)
return .Commit
}
try dbQueue.inTransaction { db in
try pet.save(db) // update
let petCount = db.fetchOne(Int.self, "SELECT COUNT(*) FROM pets")!
XCTAssertEqual(petCount, 1)
return .Commit
}
try dbQueue.inDatabase { db in
try pet.delete(db)
try pet.save(db) // inserts
let petCount = db.fetchOne(Int.self, "SELECT COUNT(*) FROM pets")!
XCTAssertEqual(petCount, 1)
}
}
}
func testSelectWithPrimaryKey() {
assertNoError {
let petUUID = "BobbyID"
@@ -35,6 +35,8 @@ class RowModelTestCase : GRDBTestCase {
migrator.registerMigration("createPets", Pet.setupInDatabase)
migrator.registerMigration("createItems", Item.setupInDatabase)
migrator.registerMigration("createCitizenships", Citizenship.setupInDatabase)
migrator.registerMigration("createMinimalRowIDs", MinimalRowID.setupInDatabase)
migrator.registerMigration("createMinimalSingles", MinimalSingle.setupInDatabase)
assertNoError {
try migrator.migrate(dbQueue)
+12
View File
@@ -17,6 +17,10 @@
5683C2691B4D445E00296494 /* libsqlite3.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 5683C2681B4D445E00296494 /* libsqlite3.dylib */; };
569978CB1B5243BB005EBEED /* DictionaryRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569978CA1B5243BB005EBEED /* DictionaryRowTests.swift */; };
569978CC1B5243BB005EBEED /* DictionaryRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569978CA1B5243BB005EBEED /* DictionaryRowTests.swift */; };
569978CF1B525CA9005EBEED /* MinimalPrimaryKeyRowIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569978CD1B525CA9005EBEED /* MinimalPrimaryKeyRowIDTests.swift */; };
569978D01B525CA9005EBEED /* MinimalPrimaryKeyRowIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569978CD1B525CA9005EBEED /* MinimalPrimaryKeyRowIDTests.swift */; };
569978D11B525CA9005EBEED /* MinimalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569978CE1B525CA9005EBEED /* MinimalPrimaryKeySingleTests.swift */; };
569978D21B525CA9005EBEED /* MinimalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569978CE1B525CA9005EBEED /* MinimalPrimaryKeySingleTests.swift */; };
5699AE571B42C34A00C35172 /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5699AE561B42C34A00C35172 /* Statement.swift */; };
5699AE591B42CD7800C35172 /* Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5699AE581B42CD7800C35172 /* Row.swift */; };
5699AE5B1B42D3DC00C35172 /* SelectStatement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5699AE5A1B42D3DC00C35172 /* SelectStatement.swift */; };
@@ -121,6 +125,8 @@
565E191D1B42B2B600D32814 /* Database.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Database.swift; sourceTree = "<group>"; };
5683C2681B4D445E00296494 /* libsqlite3.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libsqlite3.dylib; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.4.sdk/usr/lib/libsqlite3.dylib; sourceTree = DEVELOPER_DIR; };
569978CA1B5243BB005EBEED /* DictionaryRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DictionaryRowTests.swift; sourceTree = "<group>"; };
569978CD1B525CA9005EBEED /* MinimalPrimaryKeyRowIDTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MinimalPrimaryKeyRowIDTests.swift; sourceTree = "<group>"; };
569978CE1B525CA9005EBEED /* MinimalPrimaryKeySingleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MinimalPrimaryKeySingleTests.swift; sourceTree = "<group>"; };
5699AE561B42C34A00C35172 /* Statement.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Statement.swift; sourceTree = "<group>"; };
5699AE581B42CD7800C35172 /* Row.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Row.swift; sourceTree = "<group>"; };
5699AE5A1B42D3DC00C35172 /* SelectStatement.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SelectStatement.swift; sourceTree = "<group>"; };
@@ -242,6 +248,8 @@
56C9E6521B468EB200DDC541 /* RowModel */ = {
isa = PBXGroup;
children = (
569978CD1B525CA9005EBEED /* MinimalPrimaryKeyRowIDTests.swift */,
569978CE1B525CA9005EBEED /* MinimalPrimaryKeySingleTests.swift */,
56C9E6531B468EB200DDC541 /* PrimaryKeyMultipleTests.swift */,
56C9E6541B468EB200DDC541 /* PrimaryKeyNoneTests.swift */,
56C9E6561B468EB200DDC541 /* PrimaryKeyRowIDTests.swift */,
@@ -575,6 +583,7 @@
56E5D8261B4D435D00430942 /* CustomDatabaseValueConvertibleTests.swift in Sources */,
56E5D8231B4D435D00430942 /* RowModelInitializersTests.swift in Sources */,
56105B131B4F18CC002CD224 /* RowModelIsEditedTests.swift in Sources */,
569978D01B525CA9005EBEED /* MinimalPrimaryKeyRowIDTests.swift in Sources */,
56E5D8211B4D435D00430942 /* RowModelDescriptionTests.swift in Sources */,
56E5D8251B4D435D00430942 /* RowModelTestCase.swift in Sources */,
56E5D8201B4D435D00430942 /* PrimaryKeySingleTests.swift in Sources */,
@@ -586,6 +595,7 @@
56E5D82B1B4D435D00430942 /* SelectStatementTests.swift in Sources */,
56E5D8291B4D435D00430942 /* DatabaseErrorTests.swift in Sources */,
56E5D8271B4D435D00430942 /* RawRepresentableTests.swift in Sources */,
569978D21B525CA9005EBEED /* MinimalPrimaryKeySingleTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -605,6 +615,7 @@
56E5D8061B4D424400430942 /* InMemoryDatabaseTests.swift in Sources */,
56E5D80F1B4D424400430942 /* RowModelInitializersTests.swift in Sources */,
56105B121B4F18CC002CD224 /* RowModelIsEditedTests.swift in Sources */,
569978CF1B525CA9005EBEED /* MinimalPrimaryKeyRowIDTests.swift in Sources */,
56E5D80C1B4D424400430942 /* PrimaryKeySingleTests.swift in Sources */,
56E5D8151B4D424400430942 /* DatabaseErrorTests.swift in Sources */,
56E5D8161B4D424400430942 /* UpdateStatementTests.swift in Sources */,
@@ -616,6 +627,7 @@
56E5D80D1B4D424400430942 /* RowModelDescriptionTests.swift in Sources */,
56E5D80B1B4D424400430942 /* PrimaryKeyRowIDTests.swift in Sources */,
56E5D8111B4D424400430942 /* RowModelTestCase.swift in Sources */,
569978D11B525CA9005EBEED /* MinimalPrimaryKeySingleTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
+27 -6
View File
@@ -248,7 +248,12 @@ public class RowModel {
}
/**
Updates if row model has a non-nil primary key, and inserts otherwise.
Stores the row model in the database.
If the row model has a non-nil primary key and a matching row in the
database, this method performs an update.
Otherwise, performs an insert.
- parameter db: A Database.
*/
@@ -438,7 +443,7 @@ public class RowModel {
// recoverable.
// 2. fatalError, assuming it is a programmer error to "forget"
// keys from storedDatabaseDictionary.
// 3. do nothing and return.
// 3. do nothing.
//
// Option 1 is not OK, because this error couldn't be recovered
// at runtime: the implementation of storedDatabaseDictionary
@@ -447,7 +452,19 @@ public class RowModel {
// I remember opening rdar://problem/10236982, based on a Core
// Data entity without any attribute. It was for testing
// purpose, and the test did not require any attribute, so the
// Core Data entity had no attribute. So let's choose option 3:
// Core Data entity had no attribute. So let's choose option 3,
// and do nothing.
//
// But that's not quite ended: update() is supposed to throw
// RowModelNotFound when there is no matching row in the
// database. I mean, consistency is important. So:
let whereSQL = " AND ".join(primaryKeyDictionary.keys.map { column in "\(column.quotedDatabaseIdentifier)=?" })
let sql = "SELECT 1 FROM \(table.name.quotedDatabaseIdentifier) WHERE \(whereSQL)"
let row = db.fetchOneRow(sql, bindings: Bindings(primaryKeyDictionary.values))
guard row != nil else {
throw RowModelError.RowModelNotFound(rowModel)
}
return
}
@@ -466,8 +483,12 @@ public class RowModel {
func save(db: Database) throws -> (String, Int64)? {
if let _ = strongPrimaryKeyDictionary {
try update(db)
return nil
do {
try update(db)
return nil
} catch RowModelError.RowModelNotFound {
return try insert(db)
}
} else {
return try insert(db)
}
@@ -495,7 +516,7 @@ public class RowModel {
let sql = "DELETE FROM \(table.name.quotedDatabaseIdentifier) WHERE \(whereSQL)"
try db.execute(sql, bindings: bindings)
}
func fetchOneRow(db: Database) throws -> Row? {
// Fail early if databaseTable is nil (not overriden)
guard databaseTable != nil else {