diff --git a/DatabaseMigratorTests.swift b/DatabaseMigratorTests.swift index 8a848651b..eec68f9a1 100644 --- a/DatabaseMigratorTests.swift +++ b/DatabaseMigratorTests.swift @@ -67,7 +67,7 @@ class DatabaseMigratorTests: GRDBTests { // The first migration should be committed. // The second migration should be rollbacked. let names = dbQueue.inDatabase { db in - db.fetchValues("SELECT * FROM persons", type: String.self).map { $0! } + db.fetch("SELECT * FROM persons", type: String.self).map { $0! } } XCTAssertEqual(names, ["Arthur"]) } diff --git a/GRDB Tests/DatabaseTests.swift b/GRDB Tests/DatabaseTests.swift index cac9208c8..dd991f9a2 100644 --- a/GRDB Tests/DatabaseTests.swift +++ b/GRDB Tests/DatabaseTests.swift @@ -443,7 +443,7 @@ class DatabaseTests: GRDBTests { } // Value sequences require explicit `type` parameter - for name in db.fetchValues("SELECT name FROM persons", type: String.self) { + for name in db.fetch("SELECT name FROM persons", type: String.self) { // name is `String?` because some rows may have a NULL name. print(name) } @@ -453,7 +453,7 @@ class DatabaseTests: GRDBTests { // Extracting values out of a database block: let names = dbQueue.inDatabase { db in - db.fetchValues("SELECT name FROM persons ORDER BY name", type: String.self).map { $0! } + db.fetch("SELECT name FROM persons ORDER BY name", type: String.self).map { $0! } } XCTAssertEqual(names, ["Arthur", "Barbara"]) } diff --git a/GRDB/Database.swift b/GRDB/Database.swift index 6cd59a48e..b5c40b2d5 100644 --- a/GRDB/Database.swift +++ b/GRDB/Database.swift @@ -134,6 +134,7 @@ public class Database { } extension Database { + public func fetchRowGenerator(sql: String, bindings: Bindings? = nil) -> AnyGenerator { let statement = try! selectStatement(sql, bindings: bindings) return statement.fetchRowGenerator() @@ -150,22 +151,25 @@ extension Database { public func fetchOneRow(sql: String, bindings: Bindings? = nil) -> Row? { return fetchRowGenerator(sql, bindings: bindings).next() } +} + +extension Database { - public func fetchValueGenerator(sql: String, bindings: Bindings? = nil, type: T.Type) -> AnyGenerator { + public func fetchGenerator(sql: String, bindings: Bindings? = nil, type: T.Type) -> AnyGenerator { let statement = try! selectStatement(sql, bindings: bindings) - return statement.fetchValueGenerator(type) + return statement.fetchGenerator(type) } - public func fetchValues(sql: String, bindings: Bindings? = nil, type: T.Type) -> AnySequence { - return AnySequence { self.fetchValueGenerator(sql, bindings: bindings, type: type) } + public func fetch(sql: String, bindings: Bindings? = nil, type: T.Type) -> AnySequence { + return AnySequence { self.fetchGenerator(sql, bindings: bindings, type: type) } } - public func fetchAllValues(sql: String, bindings: Bindings? = nil, type: T.Type) -> [T?] { - return Array(fetchValues(sql, bindings: bindings, type: type)) + public func fetchAll(sql: String, bindings: Bindings? = nil, type: T.Type) -> [T?] { + return Array(fetch(sql, bindings: bindings, type: type)) } public func fetchOne(sql: String, bindings: Bindings? = nil, type: T.Type) -> T? { - if let first = fetchValueGenerator(sql, bindings: bindings, type: type).next() { + if let first = fetchGenerator(sql, bindings: bindings, type: type).next() { // one row containing an optional value return first } else { diff --git a/GRDB/DatabaseMigrator.swift b/GRDB/DatabaseMigrator.swift index 3525e3711..140b89cab 100644 --- a/GRDB/DatabaseMigrator.swift +++ b/GRDB/DatabaseMigrator.swift @@ -42,7 +42,7 @@ public struct DatabaseMigrator { private func runMigrations(dbQueue: DatabaseQueue) throws { let appliedMigrationIdentifiers = dbQueue.inDatabase { db in - db.fetchValues("SELECT identifier FROM grdb_migrations", type: String.self).map { $0! } + db.fetch("SELECT identifier FROM grdb_migrations", type: String.self).map { $0! } } for (position, migration) in self.migrations.enumerate() { diff --git a/GRDB/SelectStatement.swift b/GRDB/SelectStatement.swift index dfbd8d1a3..32397aecf 100644 --- a/GRDB/SelectStatement.swift +++ b/GRDB/SelectStatement.swift @@ -85,8 +85,11 @@ extension SelectStatement { public func fetchOneRow() -> Row? { return fetchRowGenerator().next() } +} + +extension SelectStatement { - public func fetchValueGenerator(type: T.Type) -> AnyGenerator { + public func fetchGenerator(type: T.Type) -> AnyGenerator { let rowGenerator = fetchRowGenerator() return anyGenerator { () -> T?? in if let row = rowGenerator.next() { @@ -97,16 +100,16 @@ extension SelectStatement { } } - public func fetchValues(type: T.Type) -> AnySequence { - return AnySequence { self.fetchValueGenerator(type) } + public func fetch(type: T.Type) -> AnySequence { + return AnySequence { self.fetchGenerator(type) } } - public func fetchAllValues(type: T.Type) -> [T?] { - return Array(fetchValues(type)) + public func fetchAll(type: T.Type) -> [T?] { + return Array(fetch(type)) } - public func fetchOneValue(type: T.Type) -> T? { - if let optionalValue = fetchValueGenerator(type).next() { + public func fetchOne(type: T.Type) -> T? { + if let optionalValue = fetchGenerator(type).next() { // one row containing an optional value return optionalValue } else { diff --git a/README.md b/README.md index 3171979a2..dc76a76b1 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,7 @@ dbQueue.inDatabase { db in } // Value sequences require explicit `type` parameter - for name in db.fetchValues("SELECT name FROM persons", type: String.self) { + for name in db.fetch("SELECT name FROM persons", type: String.self) { // name is `String?` because some rows may have a NULL name. print(name) } @@ -91,7 +91,7 @@ dbQueue.inDatabase { db in // Extracting values out of a database block: let names = dbQueue.inDatabase { db in - db.fetchValues("SELECT name FROM persons ORDER BY name", type: String.self).map { $0! } + db.fetch("SELECT name FROM persons ORDER BY name", type: String.self).map { $0! } } // names is [String]: ["Arthur", "Barbara"] ``` diff --git a/RowModel.swift b/RowModel.swift index dc00b1bcc..6803a79d6 100644 --- a/RowModel.swift +++ b/RowModel.swift @@ -32,6 +32,13 @@ public class RowModel { public func updateFromDatabaseRow(row: Row) { } + public init() { + } + + required public init(row: Row) { + updateFromDatabaseRow(row) + } + final public func insert(db: Database) throws { // TODO: validation // TODO: dirty @@ -144,16 +151,51 @@ public class RowModel { try db.execute(sql, bindings: bindings) } - public init () { - } - - required public init (row: Row) { - updateFromDatabaseRow(row) + final public func save(db: Database) throws { + + guard let tableName = self.dynamicType.databaseTableName else { + fatalError("Missing table name") + } + + let needUpdate: Bool + pk: switch self.dynamicType.databasePrimaryKey { + case .None: + needUpdate = false + case .SQLiteRowID(let column): + if let value = databaseDictionary[column]! { // unwrap double optional + needUpdate = db.fetchOne("SELECT 1 FROM \(tableName) WHERE \(column) = ?", bindings: [value], type: Bool.self)! + } else { + needUpdate = false + } + case .Single(let column): + if let value = databaseDictionary[column]! { // unwrap double optional + needUpdate = db.fetchOne("SELECT 1 FROM \(tableName) WHERE \(column) = ?", bindings: [value], type: Bool.self)! + } else { + needUpdate = false + } + case .Multiple(let columns): + let dic = databaseDictionary + for column in columns { + if dic[column]! == nil { // unwrap double optional + needUpdate = false + break pk + } + } + let whereSQL = " AND ".join(columns.map { column in "\(column)=?" }) + let bindings = Bindings(columns.map { column in dic[column]! }) + needUpdate = db.fetchOne("SELECT 1 FROM \(tableName) WHERE \(whereSQL)", bindings: bindings, type: Bool.self)! + } + + if needUpdate { + try update(db) + } else { + try insert(db) + } } } extension Database { - public func fetchModelGenerator(sql: String, bindings: Bindings? = nil, type: T.Type) -> AnyGenerator { + public func fetchGenerator(sql: String, bindings: Bindings? = nil, type: T.Type) -> AnyGenerator { let rowGenerator = fetchRowGenerator(sql, bindings: bindings) return anyGenerator { if let row = rowGenerator.next() { @@ -164,16 +206,16 @@ extension Database { } } - public func fetchModels(sql: String, bindings: Bindings? = nil, type: T.Type) -> AnySequence { - return AnySequence { self.fetchModelGenerator(sql, bindings: bindings, type: type) } + public func fetch(sql: String, bindings: Bindings? = nil, type: T.Type) -> AnySequence { + return AnySequence { self.fetchGenerator(sql, bindings: bindings, type: type) } } - public func fetchAllModels(sql: String, bindings: Bindings? = nil, type: T.Type) -> [T] { - return Array(fetchModels(sql, bindings: bindings, type: type)) + public func fetchAll(sql: String, bindings: Bindings? = nil, type: T.Type) -> [T] { + return Array(fetch(sql, bindings: bindings, type: type)) } - public func fetchOneModel(sql: String, bindings: Bindings? = nil, type: T.Type) -> T? { - if let first = fetchModelGenerator(sql, bindings: bindings, type: type).next() { + public func fetchOne(sql: String, bindings: Bindings? = nil, type: T.Type) -> T? { + if let first = fetchGenerator(sql, bindings: bindings, type: type).next() { // one row containing an optional value return first } else { @@ -182,7 +224,7 @@ extension Database { } } - public func fetchOneModel(primaryKey primaryKey: DatabaseValue, type: T.Type) -> T? { + public func fetchOne(primaryKey primaryKey: DatabaseValue, type: T.Type) -> T? { guard let tableName = T.databaseTableName else { fatalError("Missing table name") } @@ -199,7 +241,7 @@ extension Database { fatalError("Multiple primary key") } - return fetchOneModel(sql, bindings: [primaryKey], type: type) + return fetchOne(sql, bindings: [primaryKey], type: type) } } diff --git a/RowModelTests.swift b/RowModelTests.swift index 74ed40487..c333faf72 100644 --- a/RowModelTests.swift +++ b/RowModelTests.swift @@ -199,7 +199,7 @@ class RowModelTests: GRDBTests { // After insertion, model should be present in the database dbQueue.inDatabase { db in - let persons = db.fetchAllModels("SELECT * FROM persons ORDER BY name", type: Person.self) + let persons = db.fetchAll("SELECT * FROM persons ORDER BY name", type: Person.self) XCTAssertEqual(persons.count, 1) XCTAssertEqual(persons.first!.name!, "Arthur") } @@ -247,7 +247,7 @@ class RowModelTests: GRDBTests { // After insertion, model should be present in the database dbQueue.inDatabase { db in - let stuffs = db.fetchAllModels("SELECT * FROM stuffs ORDER BY name", type: Stuff.self) + let stuffs = db.fetchAll("SELECT * FROM stuffs ORDER BY name", type: Stuff.self) XCTAssertEqual(stuffs.count, 1) XCTAssertEqual(stuffs.first!.name!, "foo") } @@ -273,7 +273,7 @@ class RowModelTests: GRDBTests { // After insertion, model should be present in the database dbQueue.inDatabase { db in - let stuffs = db.fetchAllModels("SELECT * FROM stuffs ORDER BY name", type: Stuff.self) + let stuffs = db.fetchAll("SELECT * FROM stuffs ORDER BY name", type: Stuff.self) XCTAssertEqual(stuffs.count, 2) XCTAssertEqual(stuffs.first!.name!, "foo") XCTAssertEqual(stuffs.last!.name!, "foo") @@ -307,7 +307,7 @@ class RowModelTests: GRDBTests { // After insertion, model should be present in the database dbQueue.inDatabase { db in - let pets = db.fetchAllModels("SELECT * FROM pets ORDER BY name", type: Pet.self) + let pets = db.fetchAll("SELECT * FROM pets ORDER BY name", type: Pet.self) XCTAssertEqual(pets.count, 1) XCTAssertEqual(pets.first!.UUID!, "BobbyID") XCTAssertEqual(pets.first!.name!, "Bobby") @@ -410,7 +410,7 @@ class RowModelTests: GRDBTests { // After insertion, model should be present in the database dbQueue.inDatabase { db in - let citizenships = db.fetchAllModels("SELECT * FROM citizenships", type: Citizenship.self) + let citizenships = db.fetchAll("SELECT * FROM citizenships", type: Citizenship.self) XCTAssertEqual(citizenships.count, 1) XCTAssertEqual(citizenships.first!.personID!, arthur.ID!) XCTAssertEqual(citizenships.first!.countryName!, "France") @@ -460,7 +460,7 @@ class RowModelTests: GRDBTests { } dbQueue.inDatabase { db in - let persons = db.fetchAllModels("SELECT * FROM persons ORDER BY name", type: Person.self) + let persons = db.fetchAll("SELECT * FROM persons ORDER BY name", type: Person.self) XCTAssertEqual(persons.count, 1) XCTAssertEqual(persons.first!.name!, "Arthur") XCTAssertEqual(persons.first!.age!, 42) @@ -483,7 +483,7 @@ class RowModelTests: GRDBTests { // After insertion, model should be present in the database dbQueue.inDatabase { db in - let pets = db.fetchAllModels("SELECT * FROM pets ORDER BY name", type: Pet.self) + let pets = db.fetchAll("SELECT * FROM pets ORDER BY name", type: Pet.self) XCTAssertEqual(pets.count, 1) XCTAssertEqual(pets.first!.UUID!, "BobbyID") XCTAssertEqual(pets.first!.name!, "Karl") @@ -520,7 +520,7 @@ class RowModelTests: GRDBTests { // After insertion, model should be present in the database dbQueue.inDatabase { db in - let citizenships = db.fetchAllModels("SELECT * FROM citizenships", type: Citizenship.self) + let citizenships = db.fetchAll("SELECT * FROM citizenships", type: Citizenship.self) XCTAssertEqual(citizenships.count, 1) XCTAssertEqual(citizenships.first!.countryName!, "France") XCTAssertEqual(calendar.component(NSCalendarUnit.Year, fromDate: citizenships.first!.grantedDate!), 2000) @@ -528,6 +528,31 @@ class RowModelTests: GRDBTests { } } + func testSaveRowModelWithSQLiteRowIDPrimaryKey() { + assertNoError { + let arthur = Person(name: "Arthur", age: 41) + + XCTAssertTrue(arthur.ID == nil) + try dbQueue.inTransaction { db in + // Initial save should insert + try arthur.save(db) + return .Commit + } + XCTAssertTrue(arthur.ID != nil) + arthur.age = 42 + try dbQueue.inTransaction { db in + // Initial save should update + try arthur.save(db) + return .Commit + } + + dbQueue.inDatabase { db in + let arthur2 = db.fetchOne(primaryKey: arthur.ID!, type: Person.self)! + XCTAssertEqual(arthur2.age!, 42) + } + } + } + func testSelect() { assertNoError { try dbQueue.inTransaction { db in @@ -537,8 +562,8 @@ class RowModelTests: GRDBTests { } dbQueue.inDatabase { db in - let persons = db.fetchAllModels("SELECT * FROM persons ORDER BY name", type: Person.self) - let arthur = db.fetchOneModel("SELECT * FROM persons ORDER BY age DESC", type: Person.self)! + let persons = db.fetchAll("SELECT * FROM persons ORDER BY name", type: Person.self) + let arthur = db.fetchOne("SELECT * FROM persons ORDER BY age DESC", type: Person.self)! XCTAssertEqual(persons.map { $0.name! }, ["Arthur", "Barbara"]) XCTAssertEqual(persons.map { $0.age! }, [41, 36]) @@ -559,7 +584,7 @@ class RowModelTests: GRDBTests { } dbQueue.inDatabase { db in - let arthur = db.fetchOneModel(primaryKey: arthurID!, type: Person.self)! + let arthur = db.fetchOne(primaryKey: arthurID!, type: Person.self)! XCTAssertEqual(arthur.ID!, arthurID!) XCTAssertEqual(arthur.name!, "Arthur") @@ -584,7 +609,7 @@ class RowModelTests: GRDBTests { dbQueue.inDatabase { db in - let pet = db.fetchOneModel(primaryKey: petUUID, type: Pet.self)! + let pet = db.fetchOne(primaryKey: petUUID, type: Pet.self)! XCTAssertEqual(pet.UUID!, petUUID) XCTAssertEqual(pet.name!, "Bobby")