From 61ae4605251dd7519a3fcd45bd9a511ca38592b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 23 Feb 2019 20:33:10 +0100 Subject: [PATCH] Persistence methods specialization, PersistenceContainer optimizations --- GRDB/QueryInterface/SQLRelation.swift | 10 +-- GRDB/Record/PersistableRecord+Encodable.swift | 3 +- GRDB/Record/PersistableRecord.swift | 72 ++++++++++++------- GRDB/Record/Record.swift | 2 +- GRDB/Utils/OrderedDictionary.swift | 62 +++++++++++++--- GRDB/Utils/Utils.swift | 6 +- ...MutablePersistableRecordChangesTests.swift | 6 +- Tests/Performance/DateParsingTests.swift | 4 +- 8 files changed, 116 insertions(+), 49 deletions(-) diff --git a/GRDB/QueryInterface/SQLRelation.swift b/GRDB/QueryInterface/SQLRelation.swift index 7187abdb1..144d91185 100644 --- a/GRDB/QueryInterface/SQLRelation.swift +++ b/GRDB/QueryInterface/SQLRelation.swift @@ -81,9 +81,9 @@ extension SQLRelation { // can't merge fatalError("The association key \"\(key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") } - relation.joins.append(value: mergedJoin, forKey: key) + relation.joins.appendValue(mergedJoin, forKey: key) } else { - relation.joins.append(value: join, forKey: key) + relation.joins.appendValue(join, forKey: key) } return relation } @@ -390,13 +390,13 @@ extension SQLRelation { // can't merge return nil } - mergedJoins.append(value: mergedJoin, forKey: key) + mergedJoins.appendValue(mergedJoin, forKey: key) } else { - mergedJoins.append(value: join, forKey: key) + mergedJoins.appendValue(join, forKey: key) } } for (key, join) in other.joins where mergedJoins[key] == nil { - mergedJoins.append(value: join, forKey: key) + mergedJoins.appendValue(join, forKey: key) } // replace selection unless empty diff --git a/GRDB/Record/PersistableRecord+Encodable.swift b/GRDB/Record/PersistableRecord+Encodable.swift index fb923f226..176d7ff60 100644 --- a/GRDB/Record/PersistableRecord+Encodable.swift +++ b/GRDB/Record/PersistableRecord+Encodable.swift @@ -2,8 +2,7 @@ import Foundation extension MutablePersistableRecord where Self: Encodable { public func encode(to container: inout PersistenceContainer) { - let persistenceContainer = PersistenceContainer() - let encoder = RecordEncoder(persistenceContainer: persistenceContainer) + let encoder = RecordEncoder(persistenceContainer: container) try! encode(to: encoder) container = encoder.persistenceContainer } diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index 013bffa54..df8f78fe8 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -1,6 +1,7 @@ import Foundation extension Database.ConflictResolution { + @usableFromInline var invalidatesLastInsertedRowID: Bool { switch self { case .abort, .fail, .rollback, .replace: @@ -49,7 +50,9 @@ extension PersistenceError { /// } public struct PersistenceContainer { // fileprivate for Row(_:PersistenceContainer) - fileprivate var storage: [String: DatabaseValueConvertible?] + // The ordering of the OrderedDictionary helps generating always the same + // SQL queries, and hit the statement cache. + fileprivate var storage: OrderedDictionary /// Accesses the value associated with the given column. /// @@ -72,22 +75,27 @@ public struct PersistenceContainer { } init() { - storage = [:] + storage = OrderedDictionary() + } + + init(minimumCapacity: Int) { + storage = OrderedDictionary(minimumCapacity: minimumCapacity) } /// Convenience initializer from a record - /// - /// // Sweet - /// let container = PersistenceContainer(record) - /// - /// // Meh - /// var container = PersistenceContainer() - /// record.encode(to: container) init(_ record: MutablePersistableRecord) { - storage = [:] + self.init() record.encode(to: &self) } + /// Convenience initializer from a database connection and a record + init(_ db: Database,_ record: MutablePersistableRecord) throws { + let databaseTableName = type(of: record).databaseTableName + let columnCount = try db.columns(in: databaseTableName).count + self.init(minimumCapacity: columnCount) + record.encode(to: &self) + } + /// Columns stored in the container, ordered like values. var columns: [String] { return Array(storage.keys) @@ -142,7 +150,7 @@ public struct PersistenceContainer { } /// An iterator over the (column, value) pairs - func makeIterator() -> DictionaryIterator { + func makeIterator() -> IndexingIterator> { return storage.makeIterator() } } @@ -153,7 +161,7 @@ extension Row { } convenience init(_ container: PersistenceContainer) { - self.init(container.storage) + self.init(Dictionary(container.storage)) } } @@ -448,7 +456,7 @@ extension MutablePersistableRecord { extension MutablePersistableRecord { /// A dictionary whose keys are the columns encoded in the `encode(to:)` method. public var databaseDictionary: [String: DatabaseValue] { - return PersistenceContainer(self).storage.mapValues { $0?.databaseValue ?? .null } + return Dictionary(PersistenceContainer(self).storage).mapValues { $0?.databaseValue ?? .null } } } @@ -546,7 +554,7 @@ extension MutablePersistableRecord { /// - SeeAlso: updateChanges(_:with:) @discardableResult public func updateChanges(_ db: Database, from record: MutablePersistableRecord) throws -> Bool { - return try updateChanges(db, from: PersistenceContainer(record)) + return try updateChanges(db, from: PersistenceContainer(db, record)) } /// Mutates the record according to the provided closure, and then, if the @@ -574,7 +582,7 @@ extension MutablePersistableRecord { /// match any row in the database and record could not be updated. @discardableResult public mutating func updateChanges(_ db: Database, with change: (inout Self) throws -> Void) throws -> Bool { - let container = PersistenceContainer(self) + let container = try PersistenceContainer(db, self) try change(&self) return try updateChanges(db, from: container) } @@ -653,10 +661,11 @@ extension MutablePersistableRecord { // MARK: - CRUD Internals /// Return true if record has a non-null primary key - fileprivate func canUpdate(_ db: Database) throws -> Bool { + @usableFromInline + func canUpdate(_ db: Database) throws -> Bool { let databaseTableName = type(of: self).databaseTableName let primaryKey = try db.primaryKey(databaseTableName) - let container = PersistenceContainer(self) + let container = try PersistenceContainer(db, self) for column in primaryKey.columns { if let value = container[caseInsensitive: column], !value.databaseValue.isNull { return true @@ -672,6 +681,7 @@ extension MutablePersistableRecord { /// that adopt MutablePersistableRecord can invoke performInsert() in their /// implementation of insert(). They should not provide their own /// implementation of performInsert(). + @inlinable public mutating func performInsert(_ db: Database) throws { let conflictResolutionForInsert = type(of: self).persistenceConflictPolicy.conflictResolutionForInsert let dao = try DAO(db, self) @@ -695,8 +705,9 @@ extension MutablePersistableRecord { /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database. + @inlinable public func performUpdate(_ db: Database, columns: Set) throws { - guard let statement = try DAO(db, self).updateStatement(db, columns: columns, onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) else { + guard let statement = try DAO(db, self).updateStatement(columns: columns, onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) else { // Nil primary key throw PersistenceError.recordNotFound(self) } @@ -715,6 +726,7 @@ extension MutablePersistableRecord { /// implementation of performSave(). /// /// This default implementation forwards the job to `update` or `insert`. + @inlinable public 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 @@ -742,6 +754,7 @@ extension MutablePersistableRecord { /// that adopt MutablePersistableRecord can invoke performDelete() in /// their implementation of delete(). They should not provide their own /// implementation of performDelete(). + @inlinable public func performDelete(_ db: Database) throws -> Bool { guard let statement = try DAO(db, self).deleteStatement() else { // Nil primary key @@ -758,6 +771,7 @@ extension MutablePersistableRecord { /// that adopt MutablePersistableRecord can invoke performExists() in /// their implementation of exists(). They should not provide their own /// implementation of performExists(). + @inlinable public func performExists(_ db: Database) throws -> Bool { guard let statement = try DAO(db, self).existsStatement() else { // Nil primary key @@ -796,7 +810,7 @@ extension MutablePersistableRecord where Self: AnyObject { /// match any row in the database and record could not be updated. @discardableResult public func updateChanges(_ db: Database, with change: (Self) throws -> Void) throws -> Bool { - let container = PersistenceContainer(self) + let container = try PersistenceContainer(db, self) try change(self) return try updateChanges(db, from: container) } @@ -1017,6 +1031,7 @@ extension PersistableRecord { /// that adopt PersistableRecord can invoke performInsert() in their /// implementation of insert(). They should not provide their own /// implementation of performInsert(). + @inlinable public func performInsert(_ db: Database) throws { let conflictResolutionForInsert = type(of: self).persistenceConflictPolicy.conflictResolutionForInsert let dao = try DAO(db, self) @@ -1036,6 +1051,7 @@ extension PersistableRecord { /// implementation of performSave(). /// /// This default implementation forwards the job to `update` or `insert`. + @inlinable public 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. @@ -1130,13 +1146,14 @@ public enum DatabaseUUIDEncodingStrategy { // MARK: - DAO /// DAO takes care of PersistableRecord CRUD -final class DAO { +@usableFromInline +final class DAO { /// The database let db: Database /// The record - let record: MutablePersistableRecord + let record: Record /// DAO keeps a copy the record's persistenceContainer, so that this /// dictionary is built once whatever the database operation. It is @@ -1147,12 +1164,13 @@ final class DAO { let databaseTableName: String /// The table primary key - let primaryKey: PrimaryKeyInfo + @usableFromInline let primaryKey: PrimaryKeyInfo - init(_ db: Database, _ record: MutablePersistableRecord) throws { + @usableFromInline + init(_ db: Database, _ record: Record) throws { let databaseTableName = type(of: record).databaseTableName let primaryKey = try db.primaryKey(databaseTableName) - let persistenceContainer = PersistenceContainer(record) + let persistenceContainer = try PersistenceContainer(db, record) GRDBPrecondition(!persistenceContainer.isEmpty, "\(type(of: record)): invalid empty persistence container") @@ -1163,6 +1181,7 @@ final class DAO { self.primaryKey = primaryKey } + @usableFromInline func insertStatement(onConflict: Database.ConflictResolution) throws -> UpdateStatement { let query = InsertQuery( onConflict: onConflict, @@ -1174,7 +1193,8 @@ final class DAO { } /// Returns nil if and only if primary key is nil - func updateStatement(_ db: Database, columns: Set, onConflict: Database.ConflictResolution) throws -> UpdateStatement? { + @usableFromInline + func updateStatement(columns: Set, onConflict: Database.ConflictResolution) throws -> UpdateStatement? { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey.columns let primaryKeyValues = primaryKeyColumns.map { @@ -1223,6 +1243,7 @@ final class DAO { } /// Returns nil if and only if primary key is nil + @usableFromInline func deleteStatement() throws -> UpdateStatement? { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey.columns @@ -1242,6 +1263,7 @@ final class DAO { } /// Returns nil if and only if primary key is nil + @usableFromInline func existsStatement() throws -> SelectStatement? { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey.columns diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 30b0f7894..f13962220 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -274,7 +274,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { // // But this would trigger two calls to `encode(to:)`. let dao = try DAO(db, self) - guard let statement = try dao.updateStatement(db, columns: columns, onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) else { + guard let statement = try dao.updateStatement(columns: columns, onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) else { // Nil primary key throw PersistenceError.recordNotFound(self) } diff --git a/GRDB/Utils/OrderedDictionary.swift b/GRDB/Utils/OrderedDictionary.swift index 0b19d050d..6f60af283 100644 --- a/GRDB/Utils/OrderedDictionary.swift +++ b/GRDB/Utils/OrderedDictionary.swift @@ -9,34 +9,68 @@ /// dict["qux"] // nil /// dict.map { $0.key } // ["foo", "bar"], in this order. struct OrderedDictionary { - private var keys: [Key] - private var values: [Key: Value] + private(set) var keys: [Key] + fileprivate private(set) var dictionary: [Key: Value] + + var values: [Value] { + return keys.map { dictionary[$0]! } + } /// Creates an empty ordered dictionary. init() { - self.keys = [] - self.values = [:] + keys = [] + dictionary = [:] } + /// Creates an empty ordered dictionary. + init(minimumCapacity: Int) { + keys = [] + keys.reserveCapacity(minimumCapacity) + dictionary = Dictionary(minimumCapacity: minimumCapacity) + } + /// Returns the value associated with key, or nil. subscript(_ key: Key) -> Value? { - return values[key] + get { return dictionary[key] } + set { + if let value = newValue { + updateValue(value, forKey: key) + } else { + removeValue(forKey: key) + } + } } /// Appends the given value for the given key. /// /// - precondition: There is no value associated with key yet. - mutating func append(value: Value, forKey key: Key) { - guard values.updateValue(value, forKey: key) == nil else { + mutating func appendValue(_ value: Value, forKey key: Key) { + guard updateValue(value, forKey: key) == nil else { fatalError("key is already defined") } + } + + /// Updates the value stored in the dictionary for the given key, or + /// appnds a new key-value pair if the key does not exist. + /// + /// Use this method instead of key-based subscripting when you need to know + /// whether the new value supplants the value of an existing key. If the + /// value of an existing key is updated, updateValue(_:forKey:) returns the + /// original value. If the given key is not present in the dictionary, this + /// method appends the key-value pair and returns nil. + @discardableResult + mutating func updateValue(_ value: Value, forKey key: Key) -> Value? { + if let oldValue = dictionary.updateValue(value, forKey: key) { + return oldValue + } keys.append(key) + return nil } /// Removes the value associated with key. @discardableResult mutating func removeValue(forKey key: Key) -> Value? { - guard let value = values.removeValue(forKey: key) else { + guard let value = dictionary.removeValue(forKey: key) else { return nil } let index = keys.firstIndex { $0 == key }! @@ -48,7 +82,7 @@ struct OrderedDictionary { /// with the values transformed by the given closure. func mapValues(_ transform: (Value) throws -> T) rethrows -> OrderedDictionary { return try reduce(into: OrderedDictionary()) { dict, pair in - dict.append(value: try transform(pair.value), forKey: pair.key) + dict.appendValue(try transform(pair.value), forKey: pair.key) } } } @@ -70,13 +104,19 @@ extension OrderedDictionary: Collection { subscript(position: Int) -> (key: Key, value: Value) { let key = keys[position] - return (key: key, value: values[key]!) + return (key: key, value: dictionary[key]!) } } extension OrderedDictionary: ExpressibleByDictionaryLiteral { init(dictionaryLiteral elements: (Key, Value)...) { self.keys = elements.map { $0.0 } - self.values = Dictionary(uniqueKeysWithValues: elements) + self.dictionary = Dictionary(uniqueKeysWithValues: elements) + } +} + +extension Dictionary { + init(_ orderedDictionary: OrderedDictionary) { + self = orderedDictionary.dictionary } } diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index 330ac5c37..5ab669a98 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -7,17 +7,19 @@ extension String { /// SQL query. /// /// db.execute(sql: "SELECT * FROM \(tableName.quotedDatabaseIdentifier)") + @inlinable public var quotedDatabaseIdentifier: String { // See https://www.sqlite.org/lang_keywords.html - return "\"" + self + "\"" + return "\"\(self)\"" } } /// Return as many question marks separated with commas as the *count* argument. /// /// databaseQuestionMarks(count: 3) // "?,?,?" +@inlinable public func databaseQuestionMarks(count: Int) -> String { - return Array(repeating: "?", count: count).joined(separator: ",") + return repeatElement("?", count: count).joined(separator: ",") } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) diff --git a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift index 0ab1ccccb..2e70ba086 100644 --- a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift @@ -48,7 +48,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { func testDegenerateDatabaseEqualsWithSelf() throws { struct DegenerateRecord: MutablePersistableRecord { - static let databaseTableName = "ignored" + static let databaseTableName = "degenerated" func encode(to container: inout PersistenceContainer) { } } @@ -58,6 +58,10 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in + // table must exist + try db.create(table: DegenerateRecord.databaseTableName) { t in + t.autoIncrementedPrimaryKey("id") + } let totalChangesCount = db.totalChangesCount try XCTAssertFalse(record.updateChanges(db, from: record)) XCTAssertEqual(db.totalChangesCount, totalChangesCount) diff --git a/Tests/Performance/DateParsingTests.swift b/Tests/Performance/DateParsingTests.swift index 35d74cf09..f6e0d15fa 100644 --- a/Tests/Performance/DateParsingTests.swift +++ b/Tests/Performance/DateParsingTests.swift @@ -18,7 +18,7 @@ class DateParsingTests: XCTestCase { func testParseDateComponents() { measure { try! DatabaseQueue().inDatabase { db in - let cursor = try DatabaseDateComponents.fetchCursor(db, request) + let cursor = try DatabaseDateComponents.fetchCursor(db, sql: request) while try cursor.next() != nil { } } } @@ -27,7 +27,7 @@ class DateParsingTests: XCTestCase { func testParseDate() { measure { try! DatabaseQueue().inDatabase { db in - let cursor = try Date.fetchCursor(db, request) + let cursor = try Date.fetchCursor(db, sql: request) while try cursor.next() != nil { } } }