Refactor the RowModel.databaseTableName and RowModel.databasePrimaryKey methods in a single RowModel.databaseTable method. Rename RowModel.databaseDictionary into RowModel.storedDatabaseDictionary.

This commit is contained in:
Gwendal Roué committed 2015-07-08 08:52:49 +02:00
1 parent 761d35610b
commit 39bb46aa65
7 files changed
+172 -146

No files matched your search

@@ -31,16 +31,16 @@ class Citizenship: RowModel {
var grantedDate: NSDate?
var native: Bool?
override class var databaseTableName: String? {
return "citizenships"
override class var databaseTable: Table? {
return Table(named: "citizenships", primaryKey: .Columns(["personID", "countryName"]))
}
override class var databasePrimaryKey: PrimaryKey {
return .Columns(["personID", "countryName"])
}
override var databaseDictionary: [String: SQLiteValueConvertible?] {
return ["personID": personID, "countryName": countryName, "grantedTimestamp": DBDate(grantedDate), "native": native]
override var storedDatabaseDictionary: [String: SQLiteValueConvertible?] {
return [
"personID": personID,
"countryName": countryName,
"grantedTimestamp": DBDate(grantedDate),
"native": native]
}
override func setSQLiteValue(sqliteValue: SQLiteValue, forColumn column: String) {
@@ -28,11 +28,11 @@ import GRDB
class Item: RowModel {
var name: String?
override class var databaseTableName: String? {
return "items"
override class var databaseTable: Table? {
return Table(named: "items", primaryKey: .None)
}
override var databaseDictionary: [String: SQLiteValueConvertible?] {
override var storedDatabaseDictionary: [String: SQLiteValueConvertible?] {
return ["name": name]
}
@@ -31,15 +31,11 @@ class Person: RowModel {
var age: Int!
var creationDate: NSDate!
override class var databaseTableName: String? {
return "persons"
override class var databaseTable: Table? {
return Table(named: "persons", primaryKey: .RowID("id"))
}
override class var databasePrimaryKey: PrimaryKey {
return .RowID("id")
}
override var databaseDictionary: [String: SQLiteValueConvertible?] {
override var storedDatabaseDictionary: [String: SQLiteValueConvertible?] {
return [
"id": id,
"name": name,
@@ -30,16 +30,15 @@ class Pet: RowModel {
var masterID: Int64?
var name: String?
override class var databaseTableName: String? {
return "pets"
override class var databaseTable: Table? {
return Table(named: "pets", primaryKey: .Column("UUID"))
}
override class var databasePrimaryKey: PrimaryKey {
return .Column("UUID")
}
override var databaseDictionary: [String: SQLiteValueConvertible?] {
return ["UUID": UUID, "name": name, "masterID": masterID]
override var storedDatabaseDictionary: [String: SQLiteValueConvertible?] {
return [
"UUID": UUID,
"name": name,
"masterID": masterID]
}
override func setSQLiteValue(sqliteValue: SQLiteValue, forColumn column: String) {
@@ -15,7 +15,7 @@ class EmptyRowModel : RowModel {
class SingleColumnRowModel : RowModel {
var name: String?
override var databaseDictionary: [String: SQLiteValueConvertible?] {
override var storedDatabaseDictionary: [String: SQLiteValueConvertible?] {
return ["name": name]
}
}
@@ -24,7 +24,7 @@ class DoubleColumnRowModel : RowModel {
var name: String?
var age: Int?
override var databaseDictionary: [String: SQLiteValueConvertible?] {
override var storedDatabaseDictionary: [String: SQLiteValueConvertible?] {
return ["name": name, "age": age]
}
}
+59 -97
View File
@@ -26,9 +26,7 @@
public class RowModel {
// MARK: - Core methods
/// The type of the primary key
/// A primary key
public enum PrimaryKey {
/// No primary key.
case None
@@ -43,21 +41,34 @@ public class RowModel {
case Columns([String])
}
/// The table name used by insert, update, save, delete and reload methods.
/// The base class RowModel returns nil.
public class var databaseTableName : String? {
return nil
/// A table used by the insert, update, save, delete and reload methods.
public struct Table {
/// The table name
public let name: String
/// The primary key
public let primaryKey: PrimaryKey
/// Creates a Table given its name and primary key (default .None)
public init(named name: String, primaryKey: PrimaryKey = .None) {
self.name = name
self.primaryKey = primaryKey
}
}
/// The primary key used by insert, update, save, delete and reload methods.
/// The base class RowModel returns PrimaryKey.None (no primary key).
public class var databasePrimaryKey: PrimaryKey {
return .None
// MARK: - Core methods
/// The table used by the insert, update, save, delete and reload methods.
/// The base class RowModel returns nil, which means that those methods
/// are not available.
public class var databaseTable: Table? {
return nil
}
/// The values stored by insert, update, and save methods.
/// The base class RowModel returns an empty dictionary.
public var databaseDictionary: [String: SQLiteValueConvertible?] {
public var storedDatabaseDictionary: [String: SQLiteValueConvertible?] {
return [:]
}
@@ -138,13 +149,13 @@ public class RowModel {
}
/// Throws an error if the model has no table name, or no primary key
final public func delete(db: Database) throws {
public func delete(db: Database) throws {
try Version(self).delete(db)
}
/// Throws an error if the model has no table name, or no primary key.
/// Returns true if the model still exists in the database and has been reloaded.
final public func reload(db: Database) throws {
public func reload(db: Database) throws {
let row = try Version(self).fetchRow(db)
updateWithRow(row)
}
@@ -156,37 +167,37 @@ public class RowModel {
/// Version makes the promise that it will NEVER change the rowModel.
let rowModel: RowModel
lazy var databaseTableName: String? = self.rowModel.dynamicType.databaseTableName
lazy var databasePrimaryKey: PrimaryKey = self.rowModel.dynamicType.databasePrimaryKey
lazy var databaseDictionary: [String: SQLiteValueConvertible?] = self.rowModel.databaseDictionary
lazy var databaseTable: Table? = self.rowModel.dynamicType.databaseTable
lazy var storedDatabaseDictionary: [String: SQLiteValueConvertible?] = self.rowModel.storedDatabaseDictionary
// A primary key dictionary. Its values may be nil.
lazy var weakPrimaryKeyDictionary: [String: SQLiteValueConvertible?]? = {
switch self.databasePrimaryKey {
guard let primaryKey = self.databaseTable?.primaryKey else {
return nil
}
switch primaryKey {
case .None:
return nil
case .RowID(let column):
let databaseDictionary = self.databaseDictionary
if let value = databaseDictionary[column] {
if let value = self.storedDatabaseDictionary[column] {
return [column: value]
} else {
return nil
}
case .Column(let column):
let databaseDictionary = self.databaseDictionary
if let value = databaseDictionary[column] {
if let value = self.storedDatabaseDictionary[column] {
return [column: value]
} else {
return nil
}
case .Columns(let columns):
let databaseDictionary = self.databaseDictionary
let storedDatabaseDictionary = self.storedDatabaseDictionary
var primaryKeyDictionary = [String: SQLiteValueConvertible?]()
for column in columns {
if let value = databaseDictionary[column] {
if let value = storedDatabaseDictionary[column] {
primaryKeyDictionary[column] = value
} else {
primaryKeyDictionary[column] = nil
@@ -214,14 +225,13 @@ public class RowModel {
/// Returns an optional (columnName, insertedRowID) if and only if the
/// row model should be updated.
func insert(db: Database, conflictResolution: ConflictResolution?) throws -> (String, Int64)? {
guard let tableName = databaseTableName else {
fatalError("Override databaseTableName and return a table name.")
guard let table = databaseTable else {
fatalError("Missing databaseTable.")
}
// INSERT INTO table (id, name) VALUES (:id, :name)
let insertedDic = databaseDictionary
let insertedDic = storedDatabaseDictionary
let columnNames = insertedDic.keys
let columnSQL = ",".join(columnNames.map { $0.sqliteQuotedIdentifier })
let valuesSQL = ",".join([String](count: columnNames.count, repeatedValue: "?"))
@@ -242,22 +252,22 @@ public class RowModel {
} else {
verb = "INSERT"
}
let sql = "\(verb) INTO \(tableName.sqliteQuotedIdentifier) (\(columnSQL)) VALUES (\(valuesSQL))"
let sql = "\(verb) INTO \(table.name.sqliteQuotedIdentifier) (\(columnSQL)) VALUES (\(valuesSQL))"
let changes = try db.execute(sql, bindings: Bindings(insertedDic.values))
// Update RowID column if needed
switch databasePrimaryKey {
switch table.primaryKey {
case .RowID(let column):
if let optionalValue = databaseDictionary[column] {
if let optionalValue = storedDatabaseDictionary[column] {
if optionalValue == nil { // ID was not set
return (column, changes.insertedRowID!)
} else {
return nil
}
} else {
fatalError("databaseDictionary must return the value for the primary key `(column)`")
fatalError("storedDatabaseDictionary must return the value for the primary key `(column)`")
}
default:
return nil
@@ -265,8 +275,8 @@ public class RowModel {
}
func update(db: Database, conflictResolution: ConflictResolution? = nil) throws {
guard let tableName = databaseTableName else {
fatalError("Override databaseTableName and return a table name.")
guard let table = databaseTable else {
fatalError("Missing databaseTable.")
}
guard let primaryKeyDictionary = strongPrimaryKeyDictionary else {
@@ -276,7 +286,7 @@ public class RowModel {
// Don't update primary key columns
var updatedDictionary = databaseDictionary
var updatedDictionary = storedDatabaseDictionary
for column in primaryKeyDictionary.keys {
updatedDictionary.removeValueForKey(column)
}
@@ -304,7 +314,7 @@ public class RowModel {
} else {
verb = "UPDATE"
}
let sql = "\(verb) \(tableName.sqliteQuotedIdentifier) SET \(updateSQL) WHERE \(whereSQL)"
let sql = "\(verb) \(table.name.sqliteQuotedIdentifier) SET \(updateSQL) WHERE \(whereSQL)"
let changedRowCount = try db.execute(sql, bindings: bindings).changedRowCount
@@ -323,8 +333,8 @@ public class RowModel {
}
func delete(db: Database) throws {
guard let tableName = databaseTableName else {
fatalError("Override databaseTableName and return a table name.")
guard let table = databaseTable else {
fatalError("Missing databaseTable.")
}
guard let primaryKeyDictionary = strongPrimaryKeyDictionary else {
@@ -336,13 +346,13 @@ public class RowModel {
let whereSQL = " AND ".join(primaryKeyDictionary.keys.map { column in "\(column.sqliteQuotedIdentifier)=?" })
let bindings = Bindings(Array(primaryKeyDictionary.values))
let sql = "DELETE FROM \(tableName.sqliteQuotedIdentifier) WHERE \(whereSQL)"
let sql = "DELETE FROM \(table.name.sqliteQuotedIdentifier) WHERE \(whereSQL)"
try db.execute(sql, bindings: bindings)
}
func fetchRow(db: Database) throws -> Row {
guard let tableName = databaseTableName else {
fatalError("Override databaseTableName and return a table name.")
guard let table = databaseTable else {
fatalError("Missing databaseTable.")
}
guard let primaryKeyDictionary = strongPrimaryKeyDictionary else {
@@ -354,7 +364,7 @@ public class RowModel {
let whereSQL = " AND ".join(primaryKeyDictionary.keys.map { column in "\(column.sqliteQuotedIdentifier)=?" })
let bindings = Bindings(Array(primaryKeyDictionary.values))
let sql = "SELECT * FROM \(tableName.sqliteQuotedIdentifier) WHERE \(whereSQL)"
let sql = "SELECT * FROM \(table.name.sqliteQuotedIdentifier) WHERE \(whereSQL)"
if let row = db.fetchOneRow(sql, bindings: bindings) {
return row
} else {
@@ -362,54 +372,6 @@ public class RowModel {
}
}
}
// Attempts to build a primary key dictionary [String: SQLiteValueConvertible?].
//
// Result values come from the *dictionary* argument.
// Result keys come from the *primaryKey* argument.
//
// The result is nil if:
// - *primaryKey* is not .None
// - and *dictionary* contains a non-nil value for at least one primary key.
//
// Otherwise the result is nil.
private class func primaryKeyDictionary(dictionary: [String: SQLiteValueConvertible?]) -> [String: SQLiteValueConvertible?]? {
switch databasePrimaryKey {
case .None:
return nil
case .RowID(let column):
if let optionalValue = dictionary[column], let value = optionalValue {
return [column: value]
} else {
return nil
}
case .Column(let column):
if let optionalValue = dictionary[column], let value = optionalValue {
return [column: value]
} else {
return nil
}
case .Columns(let columns):
var primaryKeyDictionary = [String: SQLiteValueConvertible?]()
var oneValueIsNotNil = false
for column in columns {
if let optionalValue = dictionary[column], let value = optionalValue {
oneValueIsNotNil = true
primaryKeyDictionary[column] = value
} else {
primaryKeyDictionary[column] = nil
}
}
if oneValueIsNotNil {
return primaryKeyDictionary
} else {
return nil
}
}
}
}
@@ -417,7 +379,7 @@ public class RowModel {
extension RowModel : CustomStringConvertible {
public var description: String {
return "<\(reflect(self.dynamicType).summary)" + "".join(databaseDictionary.map { (key, value) in
return "<\(reflect(self.dynamicType).summary)" + "".join(storedDatabaseDictionary.map { (key, value) in
if var string = value as? String {
string = string.stringByReplacingOccurrencesOfString("\\", withString: "\\\\")
string = string.stringByReplacingOccurrencesOfString("\n", withString: "\\n")
@@ -500,21 +462,21 @@ extension Database {
// let person = db.fetchOne(Person.self, primaryKey: ...)
public func fetchOne<RowModel: GRDB.RowModel>(type: RowModel.Type, primaryKey: SQLiteValueConvertible) -> RowModel? {
guard let tableName = RowModel.databaseTableName else {
fatalError("Override databaseTableName and return a table name.")
guard let table = RowModel.databaseTable else {
fatalError("Missing databaseTable.")
}
let sql: String
switch RowModel.databasePrimaryKey {
switch table.primaryKey {
case .None:
fatalError("Missing primary key")
case .RowID(let column):
sql = "SELECT * FROM \(tableName.sqliteQuotedIdentifier) WHERE \(column.sqliteQuotedIdentifier) = ?"
sql = "SELECT * FROM \(table.name.sqliteQuotedIdentifier) WHERE \(column.sqliteQuotedIdentifier) = ?"
case .Column(let column):
sql = "SELECT * FROM \(tableName.sqliteQuotedIdentifier) WHERE \(column.sqliteQuotedIdentifier) = ?"
sql = "SELECT * FROM \(table.name.sqliteQuotedIdentifier) WHERE \(column.sqliteQuotedIdentifier) = ?"
case .Columns(let columns):
if columns.count == 1 {
sql = "SELECT * FROM \(tableName.sqliteQuotedIdentifier) WHERE \(columns.first!.sqliteQuotedIdentifier) = ?"
sql = "SELECT * FROM \(table.name.sqliteQuotedIdentifier) WHERE \(columns.first!.sqliteQuotedIdentifier) = ?"
} else {
fatalError("Primary key columns count mismatch.")
}
+90 -21
View File
@@ -508,7 +508,7 @@ try migrator.migrate(dbQueue)
## Row Models
**RowModel** is a convenience class that wraps a table row, or the result of any query.
**RowModel** is a class that wraps a table row, or the result of any query. It is designed to be subclassed.
Subclasses opt in RowModel features by overriding all or part of the base methods that define their relationship with the SQLite database.
@@ -517,16 +517,15 @@ For example, we see below that **fetching** only requires the `setSQLiteValue(_:
| Methods | fetch | insert | update | delete |
|:------------------------------ |:-----:|:------:|:------:|:------:|
| `setSQLiteValue(_:forColumn:)` | X | | | |
| `databasePrimaryKey` | | ¹ | X | X |
| `databaseTableName` | | X | X | X |
| `databaseDictionary` | | X | X | X |
¹ See [primary keys](#primary-keys) below for more information.
| `databaseTable` | | X | X | X |
| `storedDatabaseDictionary` | | X | X | X |
- [Fetching Row Models](#fetching-row-models)
- [Ad Hoc Subclasses](#ad-hoc-subclasses)
- [Primary Keys](#primary-keys)
- [Insert, Update and Delete](#insert-update-and-delete)
- [RowModel Errors](#rowmodels-errors)
- [Full List of RowModel methods](full-list-of-rowmodel-methods)
### Fetching Row Models
@@ -601,9 +600,13 @@ class PersonsViewController: UITableViewController {
private class PersonViewModel : Person {
var bookCount: Int!
override func updateFromDatabaseRow(row: Row) {
super.updateFromDatabaseRow(row)
if let v = row["bookCount"] { bookCount = v.value() }
override func setSQLiteValue(sqliteValue: SQLiteValue, forColumn column: String) {
switch column {
case "bookCount":
bookCount = sqliteValue.value()
default:
super.setSQLiteValue(sqliteValue, forColumn: column)
}
}
}
@@ -630,12 +633,13 @@ class PersonsViewController: UITableViewController {
### Primary Keys
Declare a **Primary Key** and a **Table name** in order to identify row models by primary key:
Declare a **Table** given its **name** and **primary key** in order to fetch row models by ID:
```swift
class Person : RowModel {
override class var databaseTableName: String? { return "persons" }
override class var databasePrimaryKey: PrimaryKey { return .RowID("id") }
override class var databaseTable: Table? {
return Table(named:"persons", primaryKey: .RowID("id"))
}
}
try dbQueue.inDatabase { db in
@@ -655,17 +659,17 @@ There are four kinds of primary keys:
- **Columns**: for primary keys that span accross several columns.
The kind of primary key impacts the insert/update/delete methods that we will see below.
The kind of primary key has consequences on the insert/update/delete methods that we will see below.
### Storage
### Insert, Update and Delete
With one more method, you get the `insert`, `update`, `delete` methods, plus the convenience `save` and `reload` methods.
```swift
class Person : RowModel {
// The values stored in the database:
override var databaseDictionary: [String: SQLiteValueConvertible?] {
override var storedDatabaseDictionary: [String: SQLiteValueConvertible?] {
return [
"id": id,
"name": name,
@@ -679,11 +683,11 @@ try dbQueue.inTransaction { db in
// Insert
let person = Person(name: "Arthur", age: 41)
try person.insert(db)
try person.insert(db) // save(db) inserts when the primary key is not set.
// Update
person.age = 42
try person.update(db)
try person.update(db) // save(db) updates when the primary key is set.
// Reload
person.age = 666
@@ -696,20 +700,85 @@ try dbQueue.inTransaction { db in
}
```
Models that declare a `RowID` primary key have their id automatically set after successful insertion (with the `updateFromDatabaseRow` method).
Models that declare a `RowID` primary key have their id automatically set after successful insertion (with the `setSQLiteValue(_:forColumn:)` method).
Other primary keys (single or multiple columns) are not managed by GRDB: you have to manage them yourself. You can for example **override** the `insert` primitive method, and make sure your primary key is set before calling `super.insert`.
Other primary keys (single or multiple columns) are not managed by GRDB: you have to manage them yourself. You can for example override the `insert` primitive method, and make sure your primary key is set before calling `super.insert`.
### RowModel Errors
RowModel methods can throw [SQLiteError](#error-handling) and also specific errors of type RowModelError:
RowModel methods can throw [SQLiteError](#error-handling) and also specific errors of type **RowModelError**:
- **RowModelError.InvalidPrimaryKey**: thrown by `update`, `delete` and `reload` when the primary key is invalid (nil).
- **rowModelError.NotFound**: thrown by `update` and `reload` when the primary key does not match any row in the database.
- **RowModelError.NotFound**: thrown by `update` and `reload` when the primary key does not match any row in the database.
### Full List of RowModel methods
**Core methods**
- `class var databaseTable: Table?`
The table, with its name and primary key. Required by `insert`, `update`, `save`, `delete`, `reload`. Tables without primary key are OK only for `insert`.
- `var storedDatabaseDictionary: [String: SQLiteValueConvertible?]`
The values stored in the database.
- `func setSQLiteValue(_:forColumn:)`
Updates the RowModel with a fetched SQLite value.
**Initializers**
- `init()`
Initializes an empty RowModel
- `init(row:)`
Initializes a RowModel from a database Row. Invokes `updateWithRow`
**CRUD**
- `final func updateWithRow(row: Row)`
Repeatedly calls `setSQLiteValue(_:forColumn:)`
- `func insert(db:conflictResolution:) throws`
Inserts the RowModel
- `func update(db:conflictResolution:) throws`
Updates the RowModel. Throws RowModelError.InvalidPrimaryKey if the primary ey is nil, or RowModelError.NotFound if the primary key does not match any row in the database.
- `final func save(db:conflictResolution:) throws`
Inserts if primary key is nil, updates otherwise. Throws RowModelError.NotFound if the primary key does not match any row in the database.
- `public func delete(db: Database) throws`
Deletes the RowModel. Throws RowModelError.InvalidPrimaryKey if the primary ey is nil.
- `public func reload(db: Database) throws`
Reloads the RowModel. Throws RowModelError.InvalidPrimaryKey if the primary ey is nil, or RowModelError.NotFound if the primary key does not match any row in the database.
**Fetching**
- `Database.fetch(type:sql:bindings:) -> AnySequence<Type>`
- `Database.fetchAll(type:sql:bindings:) -> [Type]`
- `Database.fetchOne(type:sql:bindings:) -> Type?`
- `Database.fetchOne(type:primaryKey:) -> Type?`
- `SelectStatement.fetch(type:bindings:) -> AnySequence<Type>`
- `SelectStatement.fetchAll(type:bindings:) -> [Type]`
- `SelectStatement.fetchOne(type:bindings:) -> Type?`-
## Thanks