From 98cc352856ca071e4d60cab8e0fba64b233ecbde Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 13 Jan 2016 08:28:44 +0100 Subject: [PATCH 01/25] Improve performance of Row.value(named:) --- GRDB/Core/Row.swift | 32 ++++++++++++++++++++++---------- GRDB/Core/Statement.swift | 26 ++++++++++++-------------- 2 files changed, 34 insertions(+), 24 deletions(-) diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index aa406be36..c93537f94 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -88,9 +88,11 @@ public final class Row: CollectionType { /// - returns: An optional *Value*. public func value(atIndex index: Int) -> Value? { precondition(index >= 0 && index < count, "row index out of range") - return impl - .databaseValue(atIndex: index) - .value() + return unsafeValue(atIndex: index) + } + + private func unsafeValue(atIndex index: Int) -> Value? { + return impl.databaseValue(atIndex: index).value() } /// Returns the value at given index, converted to the requested type. @@ -119,6 +121,10 @@ public final class Row: CollectionType { /// - returns: An optional *Value*. public func value>(atIndex index: Int) -> Value? { precondition(index >= 0 && index < count, "row index out of range") + return unsafeValue(atIndex: index) + } + + private func unsafeValue>(atIndex index: Int) -> Value? { let sqliteStatement = self.sqliteStatement if sqliteStatement != nil { // Metal row @@ -154,9 +160,11 @@ public final class Row: CollectionType { /// - returns: A *Value*. public func value(atIndex index: Int) -> Value { precondition(index >= 0 && index < count, "row index out of range") - return impl - .databaseValue(atIndex: index) - .value() + return unsafeValue(atIndex: index) + } + + private func unsafeValue(atIndex index: Int) -> Value { + return impl.databaseValue(atIndex: index).value() } /// Returns the value at given index, converted to the requested type. @@ -185,6 +193,10 @@ public final class Row: CollectionType { /// - returns: A *Value*. public func value>(atIndex index: Int) -> Value { precondition(index >= 0 && index < count, "row index out of range") + return unsafeValue(atIndex: index) + } + + private func unsafeValue>(atIndex index: Int) -> Value { let sqliteStatement = self.sqliteStatement if sqliteStatement != nil { // Metal row @@ -244,7 +256,7 @@ public final class Row: CollectionType { guard let index = impl.indexForColumn(named: columnName) else { return nil } - return value(atIndex: index) + return unsafeValue(atIndex: index) } /// Returns the value at given column, converted to the requested type. @@ -273,7 +285,7 @@ public final class Row: CollectionType { guard let index = impl.indexForColumn(named: columnName) else { return nil } - return value(atIndex: index) + return unsafeValue(atIndex: index) } /// Returns the value at given column, converted to the requested type. @@ -299,7 +311,7 @@ public final class Row: CollectionType { guard let index = impl.indexForColumn(named: columnName) else { fatalError("no such column: \(columnName)") } - return value(atIndex: index) + return unsafeValue(atIndex: index) } /// Returns the value at given column, converted to the requested type. @@ -330,7 +342,7 @@ public final class Row: CollectionType { guard let index = impl.indexForColumn(named: columnName) else { fatalError("no such column: \(columnName)") } - return value(atIndex: index) + return unsafeValue(atIndex: index) } /// Returns the optional `NSData` at given index. diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 8f0108ecd..94c11ed59 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -292,21 +292,19 @@ public final class SelectStatement : Statement { /// The column index, case insensitive. func indexForColumn(named name: String) -> Int? { - return lowercaseColumnIndexes[name] ?? lowercaseColumnIndexes[name.lowercaseString] - } - - /// Support for indexForColumn(named:) - private lazy var lowercaseColumnIndexes: [String: Int] = { - var indexes = [String: Int]() - let count = self.columnCount - // Reverse so that we return indexes for the leftmost columns. - // SELECT 1 AS a, 2 AS a -> lowercaseColumnIndexes["a”] = 0 - for (index, columnName) in self.columnNames.reverse().enumerate() { - indexes[columnName.lowercaseString] = count - index - 1 + // This is faster than dictionary lookup + for (index, column) in columnNames.enumerate() { + if column == name { + return index + } } - return indexes - }() - + for (index, column) in columnNames.enumerate() { + if column.lowercaseString == name.lowercaseString { + return index + } + } + return nil + } } /// A sequence of elements fetched from the database. From 373f457b2c7e72e39f9bec0fd66e8b8f78290a6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 13 Jan 2016 09:04:17 +0100 Subject: [PATCH 02/25] Improve performance of Record.insert() --- .../Public/Record/RecordEditedTests.swift | 263 ++++++++++++++++++ GRDB/Core/Protocols/DatabasePersistable.swift | 29 +- GRDB/Record/Record.swift | 36 ++- 3 files changed, 318 insertions(+), 10 deletions(-) diff --git a/GRDB Tests/Public/Record/RecordEditedTests.swift b/GRDB Tests/Public/Record/RecordEditedTests.swift index b86e65c22..c2016e831 100644 --- a/GRDB Tests/Public/Record/RecordEditedTests.swift +++ b/GRDB Tests/Public/Record/RecordEditedTests.swift @@ -21,6 +21,57 @@ class IntegerPropertyOnRealAffinityColumn : Record { } } +class PersonWithModifiedCaseColumns: Record { + var id: Int64! + var name: String! + var age: Int? + var creationDate: NSDate! + + init(id: Int64? = nil, name: String? = nil, age: Int? = nil, creationDate: NSDate? = nil) { + self.id = id + self.name = name + self.age = age + self.creationDate = creationDate + super.init() + } + + // Record + + override class func databaseTableName() -> String { + return "persons" + } + + required init(_ row: Row) { + id = row.value(named: "ID") + age = row.value(named: "AGE") + name = row.value(named: "NAME") + creationDate = row.value(named: "CREATIONDATE") + super.init(row) + } + + override var persistentDictionary: [String: DatabaseValueConvertible?] { + return [ + "ID": id, + "NAME": name, + "AGE": age, + "CREATIONDATE": creationDate, + ] + } + + override func insert(db: Database) throws { + // This is implicitely tested with the NOT NULL constraint on creationDate + if creationDate == nil { + creationDate = NSDate() + } + + try super.insert(db) + } + + override func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + self.id = rowID + } +} + class RecordEditedTests: GRDBTestCase { override func setUp() { @@ -60,6 +111,11 @@ class RecordEditedTests: GRDBTestCase { let person = Person.fetchOne(db, "SELECT * FROM persons")! XCTAssertFalse(person.hasPersistentChangedValues) } + try dbQueue.inDatabase { db in + try PersonWithModifiedCaseColumns(name: "Arthur", age: 41).insert(db) + let person = Person.fetchOne(db, "SELECT * FROM persons")! + XCTAssertFalse(person.hasPersistentChangedValues) + } } } @@ -104,6 +160,11 @@ class RecordEditedTests: GRDBTestCase { let person = Person.fetchOne(db, "SELECT *, 1 AS foo FROM persons")! XCTAssertFalse(person.hasPersistentChangedValues) } + try dbQueue.inDatabase { db in + try PersonWithModifiedCaseColumns(name: "Arthur", age: 41).insert(db) + let person = Person.fetchOne(db, "SELECT *, 1 AS foo FROM persons")! + XCTAssertFalse(person.hasPersistentChangedValues) + } } } @@ -118,6 +179,11 @@ class RecordEditedTests: GRDBTestCase { let person = Person.fetchOne(db, "SELECT name FROM persons")! XCTAssertTrue(person.hasPersistentChangedValues) } + try dbQueue.inDatabase { db in + try PersonWithModifiedCaseColumns(name: "Arthur", age: 41).insert(db) + let person = Person.fetchOne(db, "SELECT name FROM persons")! + XCTAssertTrue(person.hasPersistentChangedValues) + } } } @@ -129,6 +195,11 @@ class RecordEditedTests: GRDBTestCase { try person.insert(db) XCTAssertFalse(person.hasPersistentChangedValues) } + try dbQueue.inDatabase { db in + let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41) + try person.insert(db) + XCTAssertFalse(person.hasPersistentChangedValues) + } } } @@ -159,6 +230,29 @@ class RecordEditedTests: GRDBTestCase { XCTAssertTrue(person.hasPersistentChangedValues) } } + try dbQueue.inDatabase { db in + do { + let person = PersonWithModifiedCaseColumns(name: "Arthur") + try person.insert(db) + XCTAssertTrue(person.name != nil) + person.name = "Bobby" // non-nil vs. non-nil + XCTAssertTrue(person.hasPersistentChangedValues) + } + do { + let person = PersonWithModifiedCaseColumns(name: "Arthur") + try person.insert(db) + XCTAssertTrue(person.name != nil) + person.name = nil // non-nil vs. nil + XCTAssertTrue(person.hasPersistentChangedValues) + } + do { + let person = PersonWithModifiedCaseColumns(name: "Arthur") + try person.insert(db) + XCTAssertTrue(person.age == nil) + person.age = 41 // nil vs. non-nil + XCTAssertTrue(person.hasPersistentChangedValues) + } + } } } @@ -180,6 +274,22 @@ class RecordEditedTests: GRDBTestCase { XCTAssertFalse(person.hasPersistentChangedValues) } } + try dbQueue.inDatabase { db in + do { + let person = PersonWithModifiedCaseColumns(name: "Arthur") + try person.insert(db) + XCTAssertTrue(person.name != nil) + person.name = "Arthur" // non-nil vs. non-nil + XCTAssertFalse(person.hasPersistentChangedValues) + } + do { + let person = PersonWithModifiedCaseColumns(name: "Arthur") + try person.insert(db) + XCTAssertTrue(person.age == nil) + person.age = nil // nil vs. nil + XCTAssertFalse(person.hasPersistentChangedValues) + } + } } } @@ -193,6 +303,13 @@ class RecordEditedTests: GRDBTestCase { try person.update(db) XCTAssertFalse(person.hasPersistentChangedValues) } + try dbQueue.inDatabase { db in + let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41) + try person.insert(db) + person.name = "Bobby" + try person.update(db) + XCTAssertFalse(person.hasPersistentChangedValues) + } } } @@ -208,6 +325,15 @@ class RecordEditedTests: GRDBTestCase { try person.save(db) XCTAssertFalse(person.hasPersistentChangedValues) } + try dbQueue.inDatabase { db in + let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41) + try person.save(db) + XCTAssertFalse(person.hasPersistentChangedValues) + person.name = "Bobby" + XCTAssertTrue(person.hasPersistentChangedValues) + try person.save(db) + XCTAssertFalse(person.hasPersistentChangedValues) + } } } @@ -220,6 +346,12 @@ class RecordEditedTests: GRDBTestCase { person.id = person.id + 1 XCTAssertTrue(person.hasPersistentChangedValues) } + try dbQueue.inDatabase { db in + let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41) + try person.insert(db) + person.id = person.id + 1 + XCTAssertTrue(person.hasPersistentChangedValues) + } } } @@ -240,6 +372,25 @@ class RecordEditedTests: GRDBTestCase { XCTAssertFalse(person.hasPersistentChangedValues) XCTAssertFalse(person.copy().hasPersistentChangedValues) + person.hasPersistentChangedValues = true + XCTAssertTrue(person.hasPersistentChangedValues) + XCTAssertTrue(person.copy().hasPersistentChangedValues) + } + try dbQueue.inDatabase { db in + let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41) + + try person.insert(db) + XCTAssertFalse(person.hasPersistentChangedValues) + XCTAssertFalse(person.copy().hasPersistentChangedValues) + + person.name = "Barbara" + XCTAssertTrue(person.hasPersistentChangedValues) + XCTAssertTrue(person.copy().hasPersistentChangedValues) + + person.hasPersistentChangedValues = false + XCTAssertFalse(person.hasPersistentChangedValues) + XCTAssertFalse(person.copy().hasPersistentChangedValues) + person.hasPersistentChangedValues = true XCTAssertTrue(person.hasPersistentChangedValues) XCTAssertTrue(person.copy().hasPersistentChangedValues) @@ -299,6 +450,12 @@ class RecordEditedTests: GRDBTestCase { let changes = person.persistentChangedValues XCTAssertEqual(changes.count, 0) } + try dbQueue.inDatabase { db in + try PersonWithModifiedCaseColumns(name: "Arthur", age: 41).insert(db) + let person = Person.fetchOne(db, "SELECT * FROM persons")! + let changes = person.persistentChangedValues + XCTAssertEqual(changes.count, 0) + } } } @@ -326,6 +483,24 @@ class RecordEditedTests: GRDBTestCase { } } } + try dbQueue.inDatabase { db in + try PersonWithModifiedCaseColumns(name: "Arthur", age: 41).insert(db) + let person = Person.fetchOne(db, "SELECT name FROM persons")! + let changes = person.persistentChangedValues + XCTAssertEqual(changes.count, 3) + for (column, old) in changes { + switch column { + case "ID": + XCTAssertTrue(old == nil) + case "AGE": + XCTAssertTrue(old == nil) + case "CREATIONDATE": + XCTAssertTrue(old == nil) + default: + XCTFail("Unexpected column: \(column)") + } + } + } } } @@ -338,6 +513,12 @@ class RecordEditedTests: GRDBTestCase { let changes = person.persistentChangedValues XCTAssertEqual(changes.count, 0) } + try dbQueue.inDatabase { db in + let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41) + try person.insert(db) + let changes = person.persistentChangedValues + XCTAssertEqual(changes.count, 0) + } } } @@ -367,6 +548,28 @@ class RecordEditedTests: GRDBTestCase { } } } + try dbQueue.inDatabase { db in + let person = PersonWithModifiedCaseColumns(name: "Arthur", age: nil) + try person.insert(db) + + person.name = "Bobby" // non-nil -> non-nil + person.age = 41 // nil -> non-nil + person.creationDate = nil // non-nil -> nil + let changes = person.persistentChangedValues + XCTAssertEqual(changes.count, 3) + for (column, old) in changes { + switch column { + case "NAME": + XCTAssertEqual(old, "Arthur".databaseValue) + case "AGE": + XCTAssertEqual(old, DatabaseValue.Null) + case "CREATIONDATE": + XCTAssertTrue((old?.value() as NSDate?) != nil) + default: + XCTFail("Unexpected column: \(column)") + } + } + } } } @@ -380,6 +583,13 @@ class RecordEditedTests: GRDBTestCase { try person.update(db) XCTAssertEqual(person.persistentChangedValues.count, 0) } + try dbQueue.inDatabase { db in + let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41) + try person.insert(db) + person.name = "Bobby" + try person.update(db) + XCTAssertEqual(person.persistentChangedValues.count, 0) + } } } @@ -405,6 +615,25 @@ class RecordEditedTests: GRDBTestCase { try person.save(db) XCTAssertEqual(person.persistentChangedValues.count, 0) } + try dbQueue.inDatabase { db in + let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41) + try person.save(db) + XCTAssertEqual(person.persistentChangedValues.count, 0) + + person.name = "Bobby" + let changes = person.persistentChangedValues + XCTAssertEqual(changes.count, 1) + for (column, old) in changes { + switch column { + case "NAME": + XCTAssertEqual(old, "Arthur".databaseValue) + default: + XCTFail("Unexpected column: \(column)") + } + } + try person.save(db) + XCTAssertEqual(person.persistentChangedValues.count, 0) + } } } @@ -426,6 +655,21 @@ class RecordEditedTests: GRDBTestCase { } } } + try dbQueue.inDatabase { db in + let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41) + try person.insert(db) + person.id = person.id + 1 + let changes = person.persistentChangedValues + XCTAssertEqual(changes.count, 1) + for (column, old) in changes { + switch column { + case "ID": + XCTAssertEqual(old, (person.id - 1).databaseValue) + default: + XCTFail("Unexpected column: \(column)") + } + } + } } } @@ -446,6 +690,25 @@ class RecordEditedTests: GRDBTestCase { XCTAssertEqual(person.persistentChangedValues.count, 0) XCTAssertEqual(person.copy().persistentChangedValues.count, 0) + person.hasPersistentChangedValues = true + XCTAssertTrue(person.persistentChangedValues.count > 0) // TODO: compare actual changes + XCTAssertEqual(person.persistentChangedValues.count, person.copy().persistentChangedValues.count) + } + try dbQueue.inDatabase { db in + let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41) + + try person.insert(db) + XCTAssertEqual(person.persistentChangedValues.count, 0) + XCTAssertEqual(person.copy().persistentChangedValues.count, 0) + + person.name = "Barbara" + XCTAssertTrue(person.persistentChangedValues.count > 0) // TODO: compare actual changes + XCTAssertEqual(person.persistentChangedValues.count, person.copy().persistentChangedValues.count) + + person.hasPersistentChangedValues = false + XCTAssertEqual(person.persistentChangedValues.count, 0) + XCTAssertEqual(person.copy().persistentChangedValues.count, 0) + person.hasPersistentChangedValues = true XCTAssertTrue(person.persistentChangedValues.count > 0) // TODO: compare actual changes XCTAssertEqual(person.persistentChangedValues.count, person.copy().persistentChangedValues.count) diff --git a/GRDB/Core/Protocols/DatabasePersistable.swift b/GRDB/Core/Protocols/DatabasePersistable.swift index d906d017b..7c99db5cb 100644 --- a/GRDB/Core/Protocols/DatabasePersistable.swift +++ b/GRDB/Core/Protocols/DatabasePersistable.swift @@ -210,8 +210,8 @@ public extension MutableDatabasePersistable { 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) + if case .Managed(let column) = dataMapper.primaryKey { + didInsertWithRowID(rowID, forColumn: column) } else { didInsertWithRowID(rowID, forColumn: nil) } @@ -428,7 +428,7 @@ public extension DatabasePersistable { // MARK: - DataMapper /// DataMapper takes care of DatabasePersistable CRUD -private class DataMapper { +final class DataMapper { /// The database let db: Database @@ -458,7 +458,17 @@ private class DataMapper { let persistentDictionary = self.persistentDictionary var dictionary: [String: DatabaseValueConvertible?] = [:] for column in columns { - dictionary[column] = persistentDictionary[column] + if let value = persistentDictionary[column] { + dictionary[column] = value + } else { + dictionary[column] = nil + let lowercaseColumn = column.lowercaseString + for (persistentColumn, value) in persistentDictionary { + if persistentColumn.lowercaseString == lowercaseColumn { + dictionary[column] = value + } + } + } } return dictionary }() @@ -505,16 +515,19 @@ private class DataMapper { // MARK: - Initializer - init(_ db: Database, _ persistable: MutableDatabasePersistable) { + convenience init(_ db: Database, _ persistable: MutableDatabasePersistable) { + self.init(db, persistable: persistable, persistentDictionary: persistable.persistentDictionary) + } + + init(_ db: Database, persistable: MutableDatabasePersistable, persistentDictionary: [String: DatabaseValueConvertible?]) { let databaseTableName = persistable.dynamicType.databaseTableName() - + // Fail early if database table does not exist. guard let primaryKey = db.primaryKey(databaseTableName) else { fatalError("no such table: \(databaseTableName)") } - + // Fail early if persistentDictionary is empty - let persistentDictionary = persistable.persistentDictionary precondition(persistentDictionary.count > 0, "\(persistable.dynamicType).persistentDictionary: invalid empty dictionary") self.db = db diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index f6b2f55ac..0221336c3 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -205,8 +205,40 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabasePersistable /// - parameter db: A Database. /// - throws: A DatabaseError whenever a SQLite error occurs. public func insert(db: Database) throws { - try performInsert(db) - hasPersistentChangedValues = false + // The simplest code would be: + // + // try performInsert(db) + // hasPersistentChangedValues = false + // + // But this triggers two calls to persistentDictionary, and this is + // costly. + // + // So let's provide our custom implementation of insert: + + var persistentDictionary = self.persistentDictionary + + let dataMapper = DataMapper(db, persistable: self, persistentDictionary: persistentDictionary) + let changes = try dataMapper.insertStatement().execute() + if let rowID = changes.insertedRowID { + if case .Managed(let column) = dataMapper.primaryKey { + if persistentDictionary[column] != nil { + persistentDictionary[column] = rowID + } else { + let lowercaseColumn = column.lowercaseString + for persistentColumn in persistentDictionary.keys { + if lowercaseColumn == persistentColumn.lowercaseString { + persistentDictionary[persistentColumn] = rowID + break + } + } + } + didInsertWithRowID(rowID, forColumn: column) + } else { + didInsertWithRowID(rowID, forColumn: nil) + } + } + + referenceRow = Row(persistentDictionary) } /// Executes an UPDATE statement. From 35183f894ce6043b2ce9cb13fbb2584c24b1d157 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 13 Jan 2016 09:11:03 +0100 Subject: [PATCH 03/25] Fix tests for persistent changed values of Record class that mangles column cases. --- GRDB Tests/Public/Record/RecordEditedTests.swift | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/GRDB Tests/Public/Record/RecordEditedTests.swift b/GRDB Tests/Public/Record/RecordEditedTests.swift index c2016e831..dc12d92dd 100644 --- a/GRDB Tests/Public/Record/RecordEditedTests.swift +++ b/GRDB Tests/Public/Record/RecordEditedTests.swift @@ -113,7 +113,7 @@ class RecordEditedTests: GRDBTestCase { } try dbQueue.inDatabase { db in try PersonWithModifiedCaseColumns(name: "Arthur", age: 41).insert(db) - let person = Person.fetchOne(db, "SELECT * FROM persons")! + let person = PersonWithModifiedCaseColumns.fetchOne(db, "SELECT * FROM persons")! XCTAssertFalse(person.hasPersistentChangedValues) } } @@ -162,7 +162,7 @@ class RecordEditedTests: GRDBTestCase { } try dbQueue.inDatabase { db in try PersonWithModifiedCaseColumns(name: "Arthur", age: 41).insert(db) - let person = Person.fetchOne(db, "SELECT *, 1 AS foo FROM persons")! + let person = PersonWithModifiedCaseColumns.fetchOne(db, "SELECT *, 1 AS foo FROM persons")! XCTAssertFalse(person.hasPersistentChangedValues) } } @@ -181,7 +181,7 @@ class RecordEditedTests: GRDBTestCase { } try dbQueue.inDatabase { db in try PersonWithModifiedCaseColumns(name: "Arthur", age: 41).insert(db) - let person = Person.fetchOne(db, "SELECT name FROM persons")! + let person = PersonWithModifiedCaseColumns.fetchOne(db, "SELECT name FROM persons")! XCTAssertTrue(person.hasPersistentChangedValues) } } @@ -452,7 +452,7 @@ class RecordEditedTests: GRDBTestCase { } try dbQueue.inDatabase { db in try PersonWithModifiedCaseColumns(name: "Arthur", age: 41).insert(db) - let person = Person.fetchOne(db, "SELECT * FROM persons")! + let person = PersonWithModifiedCaseColumns.fetchOne(db, "SELECT * FROM persons")! let changes = person.persistentChangedValues XCTAssertEqual(changes.count, 0) } @@ -485,7 +485,7 @@ class RecordEditedTests: GRDBTestCase { } try dbQueue.inDatabase { db in try PersonWithModifiedCaseColumns(name: "Arthur", age: 41).insert(db) - let person = Person.fetchOne(db, "SELECT name FROM persons")! + let person = PersonWithModifiedCaseColumns.fetchOne(db, "SELECT name FROM persons")! let changes = person.persistentChangedValues XCTAssertEqual(changes.count, 3) for (column, old) in changes { From 07081edafabad268b2cf39e9bc3482d6d6cf7cb2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 13 Jan 2016 09:56:09 +0100 Subject: [PATCH 04/25] v0.39.1 --- CHANGELOG.md | 11 +++++++++++ GRDB.swift.podspec | 2 +- GRDB/Info.plist | 2 +- README.md | 10 +++++----- 4 files changed, 18 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 170c09742..50ddf2231 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,17 @@ Release Notes ============= +## 0.39.1 + +**New** + +- Various [performance improvements](https://github.com/groue/GRDB.swift/wiki/Performance) + +**Fixed** + +- Fixed the change tracking of Record subclasses that mangle the case of column names. + + ## 0.39.0 Released January 11, 2016 diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 51d6e7105..2c94da4d3 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.39.0' + s.version = '0.39.1' 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/Info.plist b/GRDB/Info.plist index da8636834..04cccf7db 100644 --- a/GRDB/Info.plist +++ b/GRDB/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 0.39.0 + 0.39.1 CFBundleSignature ???? CFBundleVersion diff --git a/README.md b/README.md index c9b796d73..e1cffcbb4 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ GRDB.swift is an [SQLite](https://www.sqlite.org) toolkit for Swift 2. It ships with a low-level database API, plus application-level tools. -**January 11, 2016: GRDB.swift 0.39.0 is out** - [Release notes](CHANGELOG.md). Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips. +**January 13, 2016: GRDB.swift 0.39.1 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+ @@ -41,7 +41,7 @@ Features Documentation ============= -- **[GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.39.0/index.html)** (on cocoadocs.org) +- **[GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.39.1/index.html)** (on cocoadocs.org) - **[Installation](#installation)** @@ -97,7 +97,7 @@ To use GRDB.swift with Cocoapods, specify in your Podfile: source 'https://github.com/CocoaPods/Specs.git' use_frameworks! -pod 'GRDB.swift', '~> 0.39.0' +pod 'GRDB.swift', '~> 0.39.1' ``` @@ -108,7 +108,7 @@ pod 'GRDB.swift', '~> 0.39.0' To use GRDB.swift with Carthage, specify in your Cartfile: ``` -github "groue/GRDB.swift" ~> 0.39.0 +github "groue/GRDB.swift" ~> 0.39.1 ``` @@ -210,7 +210,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.39.0/Structs/Configuration.html) and [Concurrency](#concurrency) for more details. +See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.39.1/Structs/Configuration.html) and [Concurrency](#concurrency) for more details. From b85cf92ce7cb7e7c269f7eb292cea81bf0e4acc6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 13 Jan 2016 10:39:11 +0100 Subject: [PATCH 05/25] Update JSONSynchronization.playground --- .../Contents.swift | 39 +++++++++++-------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/Playgrounds/JSONSynchronization.playground/Contents.swift b/Playgrounds/JSONSynchronization.playground/Contents.swift index c30849345..9a93213a7 100644 --- a/Playgrounds/JSONSynchronization.playground/Contents.swift +++ b/Playgrounds/JSONSynchronization.playground/Contents.swift @@ -1,18 +1,25 @@ // To run this playground, select and build the GRDBOSX scheme. // -// This sample code shows how to synchronize a database table with a JSON -// payload with as few SQL queries as possible. In particular, useless UPDATE -// statement are avoided. +// This sample code shows how to use GRDB to synchronize a database table +// with a JSON payload. We use as few SQL queries as possible: +// +// - Only one SELECT query. +// - One query per insert, delete, and update. +// - Useless UPDATE statements are avoided. import Foundation import GRDB -// Create the databsae +// Open an in-memory database that logs all its SQL statements var configuration = Configuration() -configuration.trace = LogSQL -let dbQueue = DatabaseQueue(configuration: configuration) // Memory database +configuration.trace = { print($0) } +let dbQueue = DatabaseQueue(configuration: configuration) + + +// Create a database table + try dbQueue.inDatabase { db in try db.execute( "CREATE TABLE persons (" + @@ -22,9 +29,9 @@ try dbQueue.inDatabase { db in } -// Person is a subclass of Record. +// Define the Person subclass of GRDB's Record. // -// We'll use the change tracking granted by the Record class to avoid useless +// Record provides change tracking that helps avoiding useless // UPDATE statements. class Person : Record { var id: Int64? @@ -62,7 +69,7 @@ func synchronizePersonsWithJSON(jsonString: String, inDatabase db: Database) thr let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)! let json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as! NSDictionary - // A function that extracts an ID from a JSON person. + // A support function that extracts an ID from a JSON person. func jsonPersonId(jsonPerson: NSDictionary) -> Int64 { return (jsonPerson["id"] as! NSNumber).longLongValue } @@ -72,11 +79,11 @@ func synchronizePersonsWithJSON(jsonString: String, inDatabase db: Database) thr return jsonPersonId($0) < jsonPersonId($1) } - // Load database persons, sorted by id. + // Sort database persons by id: let persons = Person.fetchAll(db, "SELECT * FROM persons ORDER BY id") - // Now that both lists are sorted by id, we can compare them with - // the sortedMerge() function. + // Now that both lists are sorted by id, we can compare them with + // the sortedMerge() function (see https://gist.github.com/groue/7e8510849ded36f7d770). // // We'll delete, insert or update persons, depending on their presence // in either lists. @@ -88,15 +95,15 @@ func synchronizePersonsWithJSON(jsonString: String, inDatabase db: Database) thr { switch mergeStep { case .Left(let person): - // Database person without matching JSON person: + // Delete database person without matching JSON person: try person.delete(db) case .Right(let jsonPerson): - // JSON person without matching database person: - let row = Row(dictionary: jsonPerson)! + // Insert JSON person without matching database person: + let row = Row(jsonPerson)! // Granted JSON keys are database columns let person = Person(row) try person.insert(db) case .Common(let person, let jsonPerson): - // Matching database and JSON persons: + // Update database person with its JSON counterpart: person.updateFromJSON(jsonPerson) if person.hasPersistentChangedValues { try person.update(db) From 7053632a72ef0e9bff1aef1eefa95b7262405246 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 13 Jan 2016 21:26:26 +0100 Subject: [PATCH 06/25] Improve performance of binding named values --- GRDB/Core/Database.swift | 4 +-- GRDB/Core/Statement.swift | 69 +++++++++++++++++++++++---------------- 2 files changed, 42 insertions(+), 31 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 162d82ce9..6b0c95476 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -106,7 +106,7 @@ public final class Database { // Statement.validateArguments() let (consumeArguments, validateRemainingArguments) = { () -> (UpdateStatement -> StatementArguments, () throws -> ()) in switch usedArguments.kind { - case .Array(let values): + case .Values(let values): // Extract as many values as needed, statement after statement: var remainingValues = values let consumeArguments = { (statement: UpdateStatement) -> StatementArguments in @@ -127,7 +127,7 @@ public final class Database { } } return (consumeArguments, validateRemainingArguments) - case .Dictionary: + case .NamedValues: // Reuse the dictionary argument for all statements: let consumeArguments = { (_: UpdateStatement) -> StatementArguments in return usedArguments } let validateRemainingArguments = { () in } diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 94c11ed59..9bb5322a9 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -107,16 +107,21 @@ public class Statement { clearBindings() switch arguments.kind { - case .Array(let array): - for (index, value) in array.enumerate() { + case .Values(let values): + for (index, value) in values.enumerate() { try! bindDatabaseValue(value?.databaseValue ?? .Null, atIndex: Int32(index + 1)) } break - case .Dictionary(let dictionary): + case .NamedValues(let namedValues): // TODO: test for (index, argumentName) in sqliteArgumentNames.enumerate() { - if let argumentName = argumentName, let value = dictionary[argumentName] { - try! bindDatabaseValue(value?.databaseValue ?? .Null, atIndex: Int32(index + 1)) + if let argumentName = argumentName { + for (key, value) in namedValues { + if key == argumentName { + try! bindDatabaseValue(value?.databaseValue ?? .Null, atIndex: Int32(index + 1)) + break + } + } } } } @@ -179,10 +184,10 @@ public class Statement { // If one of the values is nil, then we have a missing argument. let keyValueBindings: [(String?, DatabaseValue?)] = { switch arguments.kind { - case .Array(let array): + case .Values(let values): var keyValueBindings: [(String?, DatabaseValue?)] = [] var argumentNameGen = sqliteArgumentNames.generate() - var valuesGen = array.map { $0?.databaseValue ?? .Null }.generate() + var valuesGen = values.map { $0?.databaseValue ?? .Null }.generate() var argumentNameOpt = argumentNameGen.next() var valueOpt = valuesGen.next() outer: while true { @@ -203,14 +208,15 @@ public class Statement { } return keyValueBindings - case .Dictionary(let dictionary): + case .NamedValues(let namedValues): return sqliteArgumentNames.map { argumentName in if let argumentName = argumentName { - if let value = dictionary[argumentName] { - return (argumentName, value?.databaseValue ?? .Null) - } else { - return (argumentName, nil) + for (key, value) in namedValues { + if key == argumentName { + return (argumentName, value?.databaseValue ?? .Null) + } } + return (argumentName, nil) } return (nil, nil) } @@ -485,7 +491,7 @@ public struct StatementArguments { /// DatabaseValueConvertible protocol. /// - returns: A StatementArguments. public init>(_ sequence: Sequence) { - kind = .Array(Array(sequence)) + kind = .Values(Array(sequence)) } @@ -499,16 +505,20 @@ public struct StatementArguments { /// - parameter dictionary: A dictionary of optional values that adopt the /// DatabaseValueConvertible protocol. /// - returns: A StatementArguments. - public init(_ dictionary: [String: DatabaseValueConvertible?]) { - kind = .Dictionary(dictionary) +// public init(_ dictionary: [String: DatabaseValueConvertible?]) { +// kind = .Pairs(dictionary.map({ ($0, $1) })) +// } + + public init(_ sequence: KeyValueSequence) { + kind = .NamedValues(Array(sequence)) } public var isEmpty: Bool { switch kind { - case .Array(let array): - return array.isEmpty - case .Dictionary(let dictionary): - return dictionary.isEmpty + case .Values(let values): + return values.isEmpty + case .NamedValues(let namedValues): + return namedValues.isEmpty } } @@ -516,8 +526,8 @@ public struct StatementArguments { // MARK: Not Public enum Kind { - case Array([DatabaseValueConvertible?]) - case Dictionary([String: DatabaseValueConvertible?]) + case Values([DatabaseValueConvertible?]) + case NamedValues([(String, DatabaseValueConvertible?)]) } let kind: Kind @@ -541,11 +551,12 @@ extension StatementArguments : DictionaryLiteralConvertible { /// /// db.selectRows("SELECT ...", arguments: ["name": "Arthur", "age": 41]) public init(dictionaryLiteral elements: (String, DatabaseValueConvertible?)...) { - var dictionary = [String: DatabaseValueConvertible?]() - for (key, value) in elements { - dictionary[key] = value - } - self.init(dictionary) + self.init(elements) +// var dictionary = [String: DatabaseValueConvertible?]() +// for (key, value) in elements { +// dictionary[key] = value +// } +// self.init(dictionary) } } @@ -553,7 +564,7 @@ extension StatementArguments : CustomStringConvertible { /// A textual representation of `self`. public var description: String { switch kind { - case .Array(let values): + case .Values(let values): return "[" + values .map { value in @@ -566,9 +577,9 @@ extension StatementArguments : CustomStringConvertible { .joinWithSeparator(", ") + "]" - case .Dictionary(let dictionary): + case .NamedValues(let namedValues): return "[" - + dictionary.map { (key, value) in + + namedValues.map { (key, value) in if let value = value { return "\(key):\(String(reflecting: value))" } else { From b2eec3cba7fe4e76dcf8611018fea3aafdeb84e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 13 Jan 2016 21:40:46 +0100 Subject: [PATCH 07/25] Minor --- GRDB/Core/Statement.swift | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 9bb5322a9..aaad6fbd5 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -116,11 +116,9 @@ public class Statement { // TODO: test for (index, argumentName) in sqliteArgumentNames.enumerate() { if let argumentName = argumentName { - for (key, value) in namedValues { - if key == argumentName { - try! bindDatabaseValue(value?.databaseValue ?? .Null, atIndex: Int32(index + 1)) - break - } + for (name, value) in namedValues where name == argumentName { + try! bindDatabaseValue(value?.databaseValue ?? .Null, atIndex: Int32(index + 1)) + break } } } @@ -211,10 +209,8 @@ public class Statement { case .NamedValues(let namedValues): return sqliteArgumentNames.map { argumentName in if let argumentName = argumentName { - for (key, value) in namedValues { - if key == argumentName { - return (argumentName, value?.databaseValue ?? .Null) - } + for (name, value) in namedValues where name == argumentName { + return (argumentName, value?.databaseValue ?? .Null) } return (argumentName, nil) } From 20b68c76fd7cad0c38d20cf764692e8a56cd2028 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 13 Jan 2016 22:11:57 +0100 Subject: [PATCH 08/25] Document StatementArguments initializer from any sequence of (key, value) pairs --- GRDB/Core/Statement.swift | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index aaad6fbd5..d1a989df3 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -493,18 +493,14 @@ public struct StatementArguments { // MARK: Named Arguments - /// Initializes arguments from a dictionary of optional values. + /// Initializes arguments from a sequence of (key, value) pairs, such as + /// a dictionary. /// - /// let values: [String: String?] = ["firstName": nil, "lastName": "Miller"] + /// let values: [String: DatabaseValueConvertible?] = ["firstName": nil, "lastName": "Miller"] /// db.execute("INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values)) /// - /// - parameter dictionary: A dictionary of optional values that adopt the - /// DatabaseValueConvertible protocol. + /// - parameter sequence: A sequence of (key, value) pairs /// - returns: A StatementArguments. -// public init(_ dictionary: [String: DatabaseValueConvertible?]) { -// kind = .Pairs(dictionary.map({ ($0, $1) })) -// } - public init(_ sequence: KeyValueSequence) { kind = .NamedValues(Array(sequence)) } From 38cc0b14ce619bdb33ce24d432dd692f40743abf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 14 Jan 2016 06:20:45 +0100 Subject: [PATCH 09/25] StatementArguments Documentation --- .../Core/Statement/SelectStatementTests.swift | 6 +++++- GRDB/Core/Statement.swift | 18 ++++-------------- 2 files changed, 9 insertions(+), 15 deletions(-) diff --git a/GRDB Tests/Public/Core/Statement/SelectStatementTests.swift b/GRDB Tests/Public/Core/Statement/SelectStatementTests.swift index 67900c987..5fe043fa7 100644 --- a/GRDB Tests/Public/Core/Statement/SelectStatementTests.swift +++ b/GRDB Tests/Public/Core/Statement/SelectStatementTests.swift @@ -58,7 +58,11 @@ class SelectStatementTests : GRDBTestCase { let statement = try db.selectStatement("SELECT COUNT(*) FROM persons WHERE age < :age") // TODO: Remove this explicit type declaration required by rdar://22357375 let ageDicts: [[String: DatabaseValueConvertible?]] = [["age": 20], ["age": 30], ["age": 40], ["age": 50]] - let counts = ageDicts.map { Int.fetchOne(statement, arguments: StatementArguments($0))! } + let counts = ageDicts.map { dic -> Int in + // Make sure we don't trigger a failible initializer + let arguments: StatementArguments = StatementArguments(dic) + return Int.fetchOne(statement, arguments: arguments)! + } XCTAssertEqual(counts, [1,2,2,3]) } } diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index d1a989df3..093b5b2ff 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -480,13 +480,12 @@ public struct StatementArguments { /// Initializes arguments from a sequence of optional values. /// - /// let values: [String?] = ["foo", "bar", nil] + /// let values: [DatabaseValueConvertible?] = ["foo", 1, nil] /// db.execute("INSERT ... (?,?,?)", arguments: StatementArguments(values)) /// - /// - parameter sequence: A sequence of optional values that adopt the - /// DatabaseValueConvertible protocol. + /// - parameter sequence: A sequence of DatabaseValueConvertible values. /// - returns: A StatementArguments. - public init>(_ sequence: Sequence) { + public init(_ sequence: Sequence) { kind = .Values(Array(sequence)) } @@ -501,7 +500,7 @@ public struct StatementArguments { /// /// - parameter sequence: A sequence of (key, value) pairs /// - returns: A StatementArguments. - public init(_ sequence: KeyValueSequence) { + public init(_ sequence: Sequence) { kind = .NamedValues(Array(sequence)) } @@ -523,10 +522,6 @@ public struct StatementArguments { } let kind: Kind - - private init(kind: Kind) { - self.kind = kind - } } extension StatementArguments : ArrayLiteralConvertible { @@ -544,11 +539,6 @@ extension StatementArguments : DictionaryLiteralConvertible { /// db.selectRows("SELECT ...", arguments: ["name": "Arthur", "age": 41]) public init(dictionaryLiteral elements: (String, DatabaseValueConvertible?)...) { self.init(elements) -// var dictionary = [String: DatabaseValueConvertible?]() -// for (key, value) in elements { -// dictionary[key] = value -// } -// self.init(dictionary) } } From 5632e150062a1d13d15138357c57063c39bf60fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 14 Jan 2016 08:53:48 +0100 Subject: [PATCH 10/25] Expose Statement.unsafeSetArguments() --- CHANGELOG.md | 7 + .../Statement/StatementArgumentsTests.swift | 128 ++++++++++++++++++ GRDB/Core/Statement.swift | 14 +- TODO.md | 1 - 4 files changed, 142 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 50ddf2231..48dcdf1d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,13 @@ Release Notes ============= +## Next Release + +**New** + +- `Statement.unsafeSetArguments(_)` binds prepared statement arguments without checking if arguments fit the statement. + + ## 0.39.1 **New** diff --git a/GRDB Tests/Public/Core/Statement/StatementArgumentsTests.swift b/GRDB Tests/Public/Core/Statement/StatementArgumentsTests.swift index 544105f93..5f3fcb427 100644 --- a/GRDB Tests/Public/Core/Statement/StatementArgumentsTests.swift +++ b/GRDB Tests/Public/Core/Statement/StatementArgumentsTests.swift @@ -96,6 +96,48 @@ class StatementArgumentsTests: GRDBTestCase { } } + func testPositionalStatementArguments() { + assertNoError { + try dbQueue.inDatabase { db in + let name = "Arthur" + let age = 42 + let arguments = StatementArguments([name, age] as [DatabaseValueConvertible?]) + + let updateStatement = try db.updateStatement("INSERT INTO persons (firstName, age) VALUES (?, ?)") + updateStatement.arguments = arguments + try updateStatement.execute() + + let selectStatement = try db.selectStatement("SELECT * FROM persons WHERE firstName = ? AND age = ?") + selectStatement.arguments = arguments + let row = Row.fetchOne(selectStatement)! + + XCTAssertEqual(row.value(named: "firstName") as String, name) + XCTAssertEqual(row.value(named: "age") as Int, age) + } + } + } + + func testUnsafePositionalStatementArguments() { + assertNoError { + try dbQueue.inDatabase { db in + let name = "Arthur" + let age = 42 + let arguments = StatementArguments([name, age] as [DatabaseValueConvertible?]) + + let updateStatement = try db.updateStatement("INSERT INTO persons (firstName, age) VALUES (?, ?)") + updateStatement.unsafeSetArguments(arguments) + try updateStatement.execute() + + let selectStatement = try db.selectStatement("SELECT * FROM persons WHERE firstName = ? AND age = ?") + selectStatement.unsafeSetArguments(arguments) + let row = Row.fetchOne(selectStatement)! + + XCTAssertEqual(row.value(named: "firstName") as String, name) + XCTAssertEqual(row.value(named: "age") as Int, age) + } + } + } + func testNamedStatementArgumentsValidation() { assertNoError { try dbQueue.inDatabase { db in @@ -175,6 +217,48 @@ class StatementArgumentsTests: GRDBTestCase { } } + func testNamedStatementArguments() { + assertNoError { + try dbQueue.inDatabase { db in + let name = "Arthur" + let age = 42 + let arguments = StatementArguments(["name": name, "age": age] as [String: DatabaseValueConvertible?]) + + let updateStatement = try db.updateStatement("INSERT INTO persons (firstName, age) VALUES (:name, :age)") + updateStatement.arguments = arguments + try updateStatement.execute() + + let selectStatement = try db.selectStatement("SELECT * FROM persons WHERE firstName = :name AND age = :age") + selectStatement.arguments = arguments + let row = Row.fetchOne(selectStatement)! + + XCTAssertEqual(row.value(named: "firstName") as String, name) + XCTAssertEqual(row.value(named: "age") as Int, age) + } + } + } + + func testUnsafeNamedStatementArguments() { + assertNoError { + try dbQueue.inDatabase { db in + let name = "Arthur" + let age = 42 + let arguments = StatementArguments(["name": name, "age": age] as [String: DatabaseValueConvertible?]) + + let updateStatement = try db.updateStatement("INSERT INTO persons (firstName, age) VALUES (:name, :age)") + updateStatement.unsafeSetArguments(arguments) + try updateStatement.execute() + + let selectStatement = try db.selectStatement("SELECT * FROM persons WHERE firstName = :name AND age = :age") + selectStatement.unsafeSetArguments(arguments) + let row = Row.fetchOne(selectStatement)! + + XCTAssertEqual(row.value(named: "firstName") as String, name) + XCTAssertEqual(row.value(named: "age") as Int, age) + } + } + } + func testReusedNamedStatementArgumentsValidation() { assertNoError { try dbQueue.inDatabase { db in @@ -261,4 +345,48 @@ class StatementArgumentsTests: GRDBTestCase { } } } + + + func testReusedNamedStatementArguments() { + assertNoError { + try dbQueue.inDatabase { db in + let name = "Arthur" + let age = 42 + let arguments = StatementArguments(["name": name, "age": age] as [String: DatabaseValueConvertible?]) + + let updateStatement = try db.updateStatement("INSERT INTO persons (firstName, lastName, age) VALUES (:name, :name, :age)") + updateStatement.arguments = arguments + try updateStatement.execute() + + let selectStatement = try db.selectStatement("SELECT * FROM persons WHERE firstName = :name AND lastName = :name AND age = :age") + selectStatement.arguments = arguments + let row = Row.fetchOne(selectStatement)! + + XCTAssertEqual(row.value(named: "firstName") as String, name) + XCTAssertEqual(row.value(named: "age") as Int, age) + } + } + } + + func testUnsafeReusedNamedStatementArguments() { + assertNoError { + try dbQueue.inDatabase { db in + let name = "Arthur" + let age = 42 + let arguments = StatementArguments(["name": name, "age": age] as [String: DatabaseValueConvertible?]) + + let updateStatement = try db.updateStatement("INSERT INTO persons (firstName, lastName, age) VALUES (:name, :name, :age)") + updateStatement.unsafeSetArguments(arguments) + try updateStatement.execute() + + let selectStatement = try db.selectStatement("SELECT * FROM persons WHERE firstName = :name AND lastName = :name AND age = :age") + selectStatement.unsafeSetArguments(arguments) + let row = Row.fetchOne(selectStatement)! + + XCTAssertEqual(row.value(named: "firstName") as String, name) + XCTAssertEqual(row.value(named: "age") as Int, age) + } + } + } + } diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 093b5b2ff..d35853f67 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -13,12 +13,6 @@ public class Statement { /// The SQL query public let sql: String - /// The statement arguments - public var arguments: StatementArguments { - get { return _arguments } - set { try! setArgumentsWithValidation(newValue) } - } - // MARK: Not public @@ -97,8 +91,14 @@ public class Statement { } }() + /// The statement arguments. + public var arguments: StatementArguments { + get { return _arguments } + set { try! setArgumentsWithValidation(newValue) } + } + /// Set arguments without any validation. Trades safety for performance. - func unsafeSetArguments(arguments: StatementArguments) { + public func unsafeSetArguments(arguments: StatementArguments) { _arguments = arguments argumentsNeedValidation = false diff --git a/TODO.md b/TODO.md index 8e3408663..254b772ac 100644 --- a/TODO.md +++ b/TODO.md @@ -1,4 +1,3 @@ -- [ ] Expose Statement.unsafeSetArguments() - [ ] How to have robust single writer/several readers? Not sure: From cb89cde5f4bae77493283f90069379559507f67c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 14 Jan 2016 10:02:50 +0100 Subject: [PATCH 11/25] ShortDictionary behaves as a dictionary, but compares keys one by one --- GRDB/Core/Statement.swift | 47 ++++++++++++++++++++++++++++++--------- 1 file changed, 37 insertions(+), 10 deletions(-) diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index d35853f67..4da838f77 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -113,13 +113,9 @@ public class Statement { } break case .NamedValues(let namedValues): - // TODO: test for (index, argumentName) in sqliteArgumentNames.enumerate() { - if let argumentName = argumentName { - for (name, value) in namedValues where name == argumentName { - try! bindDatabaseValue(value?.databaseValue ?? .Null, atIndex: Int32(index + 1)) - break - } + if let argumentName = argumentName, let value = namedValues[argumentName] { + try! bindDatabaseValue(value?.databaseValue ?? .Null, atIndex: Int32(index + 1)) } } } @@ -209,10 +205,11 @@ public class Statement { case .NamedValues(let namedValues): return sqliteArgumentNames.map { argumentName in if let argumentName = argumentName { - for (name, value) in namedValues where name == argumentName { + if let value = namedValues[argumentName] { return (argumentName, value?.databaseValue ?? .Null) + } else { + return (argumentName, nil) } - return (argumentName, nil) } return (nil, nil) } @@ -501,7 +498,7 @@ public struct StatementArguments { /// - parameter sequence: A sequence of (key, value) pairs /// - returns: A StatementArguments. public init(_ sequence: Sequence) { - kind = .NamedValues(Array(sequence)) + kind = .NamedValues(ShortDictionary(sequence)) } public var isEmpty: Bool { @@ -518,7 +515,7 @@ public struct StatementArguments { enum Kind { case Values([DatabaseValueConvertible?]) - case NamedValues([(String, DatabaseValueConvertible?)]) + case NamedValues(ShortDictionary) } let kind: Kind @@ -575,6 +572,36 @@ extension StatementArguments : CustomStringConvertible { } +/// MARK: - ShortDictionary + +struct ShortDictionary: SequenceType { + let pairs: [(Key, Value)] + + init(_ sequence: Sequence) { + pairs = Array(sequence) + } + + var isEmpty: Bool { + return pairs.isEmpty + } + + func generate() -> IndexingGenerator<[(Key, Value)]> { + return pairs.generate() + } +} + +extension ShortDictionary where Key: Hashable /* Require Hashable to that ShortDictionary can be replaced with Dictionary */ { + subscript(key: Key) -> Value? { + for (k, value) in pairs { + if key == k { + return value + } + } + return nil + } +} + + // MARK: - SQLite identifier quoting extension String { From 6655b28810445d2590c3891b28703ca3101b82b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 14 Jan 2016 10:12:42 +0100 Subject: [PATCH 12/25] Minor --- GRDB/Core/Statement.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 4da838f77..522c236e1 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -572,7 +572,7 @@ extension StatementArguments : CustomStringConvertible { } -/// MARK: - ShortDictionary +// MARK: - ShortDictionary struct ShortDictionary: SequenceType { let pairs: [(Key, Value)] From 4860ae698049b62f0cdabe920a80bd12d1dd878f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 14 Jan 2016 10:34:03 +0100 Subject: [PATCH 13/25] Performance tests --- GRDB Tests/Performance/PerformanceTests.swift | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/GRDB Tests/Performance/PerformanceTests.swift b/GRDB Tests/Performance/PerformanceTests.swift index 4fcb38ae5..908838542 100644 --- a/GRDB Tests/Performance/PerformanceTests.swift +++ b/GRDB Tests/Performance/PerformanceTests.swift @@ -19,18 +19,18 @@ let i9Column = Expression("i9") // MARK:- GRDB class Item : Record { - var i0: Int? - var i1: Int? - var i2: Int? - var i3: Int? - var i4: Int? - var i5: Int? - var i6: Int? - var i7: Int? - var i8: Int? - var i9: Int? + var i0: Int + var i1: Int + var i2: Int + var i3: Int + var i4: Int + var i5: Int + var i6: Int + var i7: Int + var i8: Int + var i9: Int - init(i0: Int?, i1: Int?, i2: Int?, i3: Int?, i4: Int?, i5: Int?, i6: Int?, i7: Int?, i8: Int?, i9: Int?) { + init(i0: Int, i1: Int, i2: Int, i3: Int, i4: Int, i5: Int, i6: Int, i7: Int, i8: Int, i9: Int) { self.i0 = i0 self.i1 = i1 self.i2 = i2 From 42178355cbadedfd7e6d0e6ed49c4ccd3935fb59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 14 Jan 2016 10:38:17 +0100 Subject: [PATCH 14/25] Performance tests: avoid Core Data warning --- .../PerformanceModel.xcdatamodel/contents | 2 +- GRDB.xcodeproj/project.pbxproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/GRDB Tests/Performance/PerformanceModel.xcdatamodeld/PerformanceModel.xcdatamodel/contents b/GRDB Tests/Performance/PerformanceModel.xcdatamodeld/PerformanceModel.xcdatamodel/contents index af393ef83..6061d0978 100644 --- a/GRDB Tests/Performance/PerformanceModel.xcdatamodeld/PerformanceModel.xcdatamodel/contents +++ b/GRDB Tests/Performance/PerformanceModel.xcdatamodeld/PerformanceModel.xcdatamodel/contents @@ -1,6 +1,6 @@ - + diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index b21c73425..e7b0bd449 100644 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -769,6 +769,7 @@ children = ( 56BB86111BA9886D001F9168 /* PerformanceTests.sqlite */, 56DE7B361C42BBBB00861EB8 /* PerformanceCoreDataTests.sqlite */, + 56DE7B2D1C42B23B00861EB8 /* PerformanceModel.xcdatamodeld */, 56DE7B271C41302500861EB8 /* FetchNamedValuesTests.swift */, 56DE7B291C4130AF00861EB8 /* FetchPositionalValuesTests.swift */, 56DE7B2B1C41311900861EB8 /* FetchRecordTests.swift */, @@ -778,7 +779,6 @@ 56CA22211BB41565009A04C5 /* PerformanceTests.swift */, 56CA21FE1BB414FE009A04C5 /* SQLite.xcodeproj */, 56BB86171BA988F2001F9168 /* fmdb */, - 56DE7B2D1C42B23B00861EB8 /* PerformanceModel.xcdatamodeld */, ); path = Performance; sourceTree = ""; From a6a23615b3802fe6b37c1af6fbec910c07c0e05c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 14 Jan 2016 10:38:31 +0100 Subject: [PATCH 15/25] v0.40.0 --- CHANGELOG.md | 5 +++-- GRDB.swift.podspec | 2 +- GRDB/Info.plist | 2 +- README.md | 10 +++++----- 4 files changed, 10 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 48dcdf1d6..eb18a1c07 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,11 +1,12 @@ Release Notes ============= -## Next Release +## 0.40.0 **New** -- `Statement.unsafeSetArguments(_)` binds prepared statement arguments without checking if arguments fit the statement. +- Various [performance improvements](https://github.com/groue/GRDB.swift/wiki/Performance) +- `Statement.unsafeSetArguments(_)` binds arguments in a prepared statement without checking if arguments fit. ## 0.39.1 diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 2c94da4d3..f49eb7f90 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.39.1' + s.version = '0.40.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/Info.plist b/GRDB/Info.plist index 04cccf7db..9d0de9891 100644 --- a/GRDB/Info.plist +++ b/GRDB/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 0.39.1 + 0.40.0 CFBundleSignature ???? CFBundleVersion diff --git a/README.md b/README.md index e1cffcbb4..2917c3f4d 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ GRDB.swift is an [SQLite](https://www.sqlite.org) toolkit for Swift 2. It ships with a low-level database API, plus application-level tools. -**January 13, 2016: GRDB.swift 0.39.1 is out** - [Release notes](CHANGELOG.md). Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips. +**January 14, 2016: GRDB.swift 0.40.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+ @@ -41,7 +41,7 @@ Features Documentation ============= -- **[GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.39.1/index.html)** (on cocoadocs.org) +- **[GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.40.0/index.html)** (on cocoadocs.org) - **[Installation](#installation)** @@ -97,7 +97,7 @@ To use GRDB.swift with Cocoapods, specify in your Podfile: source 'https://github.com/CocoaPods/Specs.git' use_frameworks! -pod 'GRDB.swift', '~> 0.39.1' +pod 'GRDB.swift', '~> 0.40.0' ``` @@ -108,7 +108,7 @@ pod 'GRDB.swift', '~> 0.39.1' To use GRDB.swift with Carthage, specify in your Cartfile: ``` -github "groue/GRDB.swift" ~> 0.39.1 +github "groue/GRDB.swift" ~> 0.40.0 ``` @@ -210,7 +210,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.39.1/Structs/Configuration.html) and [Concurrency](#concurrency) for more details. +See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.40.0/Structs/Configuration.html) and [Concurrency](#concurrency) for more details. From 2ec05fea85906e919f6d6de58b40a3cf62215c41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 14 Jan 2016 13:46:23 +0100 Subject: [PATCH 16/25] Minor --- GRDB/Core/Statement.swift | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 522c236e1..a560d1558 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -498,7 +498,7 @@ public struct StatementArguments { /// - parameter sequence: A sequence of (key, value) pairs /// - returns: A StatementArguments. public init(_ sequence: Sequence) { - kind = .NamedValues(ShortDictionary(sequence)) + kind = .NamedValues(OptimisticDictionary(sequence)) } public var isEmpty: Bool { @@ -515,7 +515,7 @@ public struct StatementArguments { enum Kind { case Values([DatabaseValueConvertible?]) - case NamedValues(ShortDictionary) + case NamedValues(OptimisticDictionary) } let kind: Kind @@ -572,9 +572,17 @@ extension StatementArguments : CustomStringConvertible { } -// MARK: - ShortDictionary +// MARK: - OptimisticDictionary -struct ShortDictionary: SequenceType { +/// OptimisticDictionary is faster than Dictionary at optimistic key lookup when +/// there are few keys. +/// +/// TODO: we need evidence to support that. +/// +/// Assuming this is true, this makes OptimisticDictionary a suitable storage +/// for named statement arguments, since there are usually not numberous, and +/// they usually match the names of arguments in the SQL query. +struct OptimisticDictionary: SequenceType /* Require Hashable key like Dictionary */ { let pairs: [(Key, Value)] init(_ sequence: Sequence) { @@ -588,9 +596,7 @@ struct ShortDictionary: SequenceType { func generate() -> IndexingGenerator<[(Key, Value)]> { return pairs.generate() } -} - -extension ShortDictionary where Key: Hashable /* Require Hashable to that ShortDictionary can be replaced with Dictionary */ { + subscript(key: Key) -> Value? { for (k, value) in pairs { if key == k { From 693add8df97fb1ab986ec0f25f964568f2305d13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 14 Jan 2016 18:14:45 +0100 Subject: [PATCH 17/25] Drop too optimistic OptimisticDictionary --- GRDB/Core/Statement.swift | 38 ++++++-------------------------------- 1 file changed, 6 insertions(+), 32 deletions(-) diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index a560d1558..b7eea1e71 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -498,7 +498,7 @@ public struct StatementArguments { /// - parameter sequence: A sequence of (key, value) pairs /// - returns: A StatementArguments. public init(_ sequence: Sequence) { - kind = .NamedValues(OptimisticDictionary(sequence)) + kind = .NamedValues(Dictionary(sequence)) } public var isEmpty: Bool { @@ -515,7 +515,7 @@ public struct StatementArguments { enum Kind { case Values([DatabaseValueConvertible?]) - case NamedValues(OptimisticDictionary) + case NamedValues(Dictionary) } let kind: Kind @@ -572,38 +572,12 @@ extension StatementArguments : CustomStringConvertible { } -// MARK: - OptimisticDictionary - -/// OptimisticDictionary is faster than Dictionary at optimistic key lookup when -/// there are few keys. -/// -/// TODO: we need evidence to support that. -/// -/// Assuming this is true, this makes OptimisticDictionary a suitable storage -/// for named statement arguments, since there are usually not numberous, and -/// they usually match the names of arguments in the SQL query. -struct OptimisticDictionary: SequenceType /* Require Hashable key like Dictionary */ { - let pairs: [(Key, Value)] - +extension Dictionary { init(_ sequence: Sequence) { - pairs = Array(sequence) - } - - var isEmpty: Bool { - return pairs.isEmpty - } - - func generate() -> IndexingGenerator<[(Key, Value)]> { - return pairs.generate() - } - - subscript(key: Key) -> Value? { - for (k, value) in pairs { - if key == k { - return value - } + self.init(minimumCapacity: sequence.underestimateCount()) + for (key, value) in sequence { + self[key] = value } - return nil } } From a384051942c12fd6aa9b19fb64f7486fb8bdce26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 14 Jan 2016 19:58:19 +0100 Subject: [PATCH 18/25] Remove all DatabaseValue initializers, but the low-level ones --- GRDB/Core/DatabaseValue.swift | 41 ++----------------- GRDB/CoreGraphics/CGFloat.swift | 2 +- GRDB/Foundation/DatabaseCoder.swift | 2 +- GRDB/Foundation/DatabaseDateComponents.swift | 2 +- .../Foundation/DatabaseValue+Foundation.swift | 2 +- GRDB/Foundation/NSData.swift | 7 +++- GRDB/Foundation/NSDate.swift | 2 +- GRDB/Foundation/NSString.swift | 2 +- GRDB/Foundation/NSURL.swift | 2 +- GRDB/Swift/RawRepresentable.swift | 8 ++-- GRDB/Swift/StandardLibraryTypes.swift | 14 +++---- 11 files changed, 27 insertions(+), 57 deletions(-) diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index d13925e2f..2d10e01ce 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -47,46 +47,9 @@ public struct DatabaseValue : Hashable { } } - - // MARK: - Creating DatabaseValue - /// The NULL DatabaseValue. public static let Null = DatabaseValue(storage: .Null) - /// Returns a DatabaseValue storing an Int64. - init(_ int64: Swift.Int64) { - storage = .Int64(int64) - } - - /// Returns a DatabaseValue storing a Double. - init(_ double: Swift.Double) { - storage = .Double(double) - } - - /// Returns a DatabaseValue storing a String. - init(_ string: Swift.String) { - storage = .String(string) - } - - /// Returns a DatabaseValue storing NSData. - /// - /// SQLite cant' store zero-length blobs: if data has zero length, the - /// result is NULL. - init(_ data: NSData) { - if data.length == 0 { - // SQLite cant' store zero-length blobs. - storage = .Null - } else { - storage = .Blob(data) - } - } - - /// Copy initializer - init(_ databaseValue: DatabaseValue) { - // This initializer is used by DatabaseValue.init?(object: AnyObject) - self = databaseValue - } - // MARK: - Extracting Value @@ -167,6 +130,7 @@ public struct DatabaseValue : Hashable { self.storage = storage } + // SQLite column value init(sqliteStatement: SQLiteStatement, index: Int) { switch sqlite3_column_type(sqliteStatement, Int32(index)) { case SQLITE_NULL: @@ -177,7 +141,7 @@ public struct DatabaseValue : Hashable { storage = .Double(sqlite3_column_double(sqliteStatement, Int32(index))) case SQLITE_TEXT: let cString = UnsafePointer(sqlite3_column_text(sqliteStatement, Int32(index))) - storage = .String(Swift.String.fromCString(cString)!) + storage = .String(String.fromCString(cString)!) case SQLITE_BLOB: let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) let length = sqlite3_column_bytes(sqliteStatement, Int32(index)) @@ -187,6 +151,7 @@ public struct DatabaseValue : Hashable { } } + // SQLite function argument init(sqliteValue: SQLiteValue) { switch sqlite3_value_type(sqliteValue) { case SQLITE_NULL: diff --git a/GRDB/CoreGraphics/CGFloat.swift b/GRDB/CoreGraphics/CGFloat.swift index 0bf8dc0a0..766dabe61 100644 --- a/GRDB/CoreGraphics/CGFloat.swift +++ b/GRDB/CoreGraphics/CGFloat.swift @@ -5,7 +5,7 @@ extension CGFloat : DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return DatabaseValue(Double(self)) + return Double(self).databaseValue } /// Returns a value initialized from *databaseValue*, if possible. diff --git a/GRDB/Foundation/DatabaseCoder.swift b/GRDB/Foundation/DatabaseCoder.swift index 8302ed1a1..6d8f8cfc9 100644 --- a/GRDB/Foundation/DatabaseCoder.swift +++ b/GRDB/Foundation/DatabaseCoder.swift @@ -22,7 +22,7 @@ public struct DatabaseCoder: DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return DatabaseValue(NSKeyedArchiver.archivedDataWithRootObject(object)) + return NSKeyedArchiver.archivedDataWithRootObject(object).databaseValue } /// Returns a DatabaseCoder if *databaseValue* contains an archived object. diff --git a/GRDB/Foundation/DatabaseDateComponents.swift b/GRDB/Foundation/DatabaseDateComponents.swift index f9856608e..e73dbf184 100644 --- a/GRDB/Foundation/DatabaseDateComponents.swift +++ b/GRDB/Foundation/DatabaseDateComponents.swift @@ -95,7 +95,7 @@ public struct DatabaseDateComponents : DatabaseValueConvertible { timeString = nil } - return DatabaseValue([dateString, timeString].flatMap { $0 }.joinWithSeparator(" ")) + return [dateString, timeString].flatMap { $0 }.joinWithSeparator(" ").databaseValue } /// Returns a DatabaseDateComponents if *databaseValue* contains a diff --git a/GRDB/Foundation/DatabaseValue+Foundation.swift b/GRDB/Foundation/DatabaseValue+Foundation.swift index b02b02956..8033d86a9 100644 --- a/GRDB/Foundation/DatabaseValue+Foundation.swift +++ b/GRDB/Foundation/DatabaseValue+Foundation.swift @@ -13,7 +13,7 @@ extension DatabaseValue { guard let convertible = object as? DatabaseValueConvertible else { return nil } - self.init(convertible.databaseValue) + self.init(storage: convertible.databaseValue.storage) } /// Converts a DatabaseValue to AnyObject. diff --git a/GRDB/Foundation/NSData.swift b/GRDB/Foundation/NSData.swift index 77b2825d3..35e4f44be 100644 --- a/GRDB/Foundation/NSData.swift +++ b/GRDB/Foundation/NSData.swift @@ -4,7 +4,12 @@ import Foundation extension NSData : DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return DatabaseValue(self) + if length == 0 { + // SQLite cant' store zero-length blobs. + return .Null + } else { + return DatabaseValue(storage: .Blob(self)) + } } /// Returns an NSData initialized from *databaseValue*, if it contains diff --git a/GRDB/Foundation/NSDate.swift b/GRDB/Foundation/NSDate.swift index 55147867a..f1a951365 100644 --- a/GRDB/Foundation/NSDate.swift +++ b/GRDB/Foundation/NSDate.swift @@ -6,7 +6,7 @@ extension NSDate : DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return DatabaseValue(storageDateFormatter.stringFromDate(self)) + return storageDateFormatter.stringFromDate(self).databaseValue } /// Returns an NSDate initialized from *databaseValue*, if possible. diff --git a/GRDB/Foundation/NSString.swift b/GRDB/Foundation/NSString.swift index e90473136..452529187 100644 --- a/GRDB/Foundation/NSString.swift +++ b/GRDB/Foundation/NSString.swift @@ -5,7 +5,7 @@ extension NSString: DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return DatabaseValue(self as String) + return (self as String).databaseValue } /// Returns an NSString initialized from *databaseValue*, if possible. diff --git a/GRDB/Foundation/NSURL.swift b/GRDB/Foundation/NSURL.swift index f79970d64..bd23eaa32 100644 --- a/GRDB/Foundation/NSURL.swift +++ b/GRDB/Foundation/NSURL.swift @@ -6,7 +6,7 @@ extension NSURL : DatabaseValueConvertible { /// Returns a value that can be stored in the database. /// (the URL's absoluteString). public var databaseValue: DatabaseValue { - return DatabaseValue(absoluteString) + return absoluteString.databaseValue } /// Returns an NSURL initialized from *databaseValue*, if possible. diff --git a/GRDB/Swift/RawRepresentable.swift b/GRDB/Swift/RawRepresentable.swift index 3d75e3e1a..a6cd61e1e 100644 --- a/GRDB/Swift/RawRepresentable.swift +++ b/GRDB/Swift/RawRepresentable.swift @@ -25,7 +25,7 @@ extension DatabaseIntRepresentable { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return DatabaseValue(Int64(rawValue)) + return rawValue.databaseValue } /// Returns a value initialized from *databaseValue*, if possible. @@ -68,7 +68,7 @@ extension DatabaseInt32Representable { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return DatabaseValue(Int64(rawValue)) + return rawValue.databaseValue } /// Returns a value initialized from *databaseValue*, if possible. @@ -111,7 +111,7 @@ extension DatabaseInt64Representable { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return DatabaseValue(rawValue) + return rawValue.databaseValue } /// Returns a value initialized from *databaseValue*, if possible. @@ -154,7 +154,7 @@ extension DatabaseStringRepresentable { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return DatabaseValue(rawValue) + return rawValue.databaseValue } /// Returns a value initialized from *databaseValue*, if possible. diff --git a/GRDB/Swift/StandardLibraryTypes.swift b/GRDB/Swift/StandardLibraryTypes.swift index 3a7d3f76d..40f0f676b 100644 --- a/GRDB/Swift/StandardLibraryTypes.swift +++ b/GRDB/Swift/StandardLibraryTypes.swift @@ -11,7 +11,7 @@ extension Bool: DatabaseValueConvertible, SQLiteStatementConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return DatabaseValue(Int64(self ? 1 : 0)) + return (self ? 1 : 0).databaseValue } /// Returns a Bool initialized from *databaseValue*, if possible. @@ -99,7 +99,7 @@ extension Int: DatabaseValueConvertible, SQLiteStatementConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return DatabaseValue(Int64(self)) + return Int64(self).databaseValue } /// Returns an Int initialized from *databaseValue*, if possible. @@ -131,7 +131,7 @@ extension Int32: DatabaseValueConvertible, SQLiteStatementConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return DatabaseValue(Int64(self)) + return Int64(self).databaseValue } /// Returns an Int32 initialized from *databaseValue*, if possible. @@ -163,7 +163,7 @@ extension Int64: DatabaseValueConvertible, SQLiteStatementConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return DatabaseValue(self) + return DatabaseValue(storage: .Int64(self)) } /// Returns an Int64 initialized from *databaseValue*, if possible. @@ -195,7 +195,7 @@ extension Double: DatabaseValueConvertible, SQLiteStatementConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return DatabaseValue(self) + return DatabaseValue(storage: .Double(self)) } /// Returns a Double initialized from *databaseValue*, if possible. @@ -227,7 +227,7 @@ extension Float: DatabaseValueConvertible, SQLiteStatementConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return DatabaseValue(Double(self)) + return Double(self).databaseValue } /// Returns a Float initialized from *databaseValue*, if possible. @@ -260,7 +260,7 @@ extension String: DatabaseValueConvertible, SQLiteStatementConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return DatabaseValue(self) + return DatabaseValue(storage: .String(self)) } /// Returns a String initialized from *databaseValue*, if possible. From 0a8111a34d81cf692e96d9e2baf2c99df18f57ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 15 Jan 2016 08:22:55 +0100 Subject: [PATCH 19/25] Dictionary(sequence) documentation --- GRDB/Core/Statement.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index b7eea1e71..e99566cfe 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -573,7 +573,9 @@ extension StatementArguments : CustomStringConvertible { extension Dictionary { - init(_ sequence: Sequence) { + + /// Creates a dictionary with the keys and values in the given sequence. + init(_ sequence: Sequence) { self.init(minimumCapacity: sequence.underestimateCount()) for (key, value) in sequence { self[key] = value From f7d4376147981592d23104a40b8f8157489b4445 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 15 Jan 2016 08:23:35 +0100 Subject: [PATCH 20/25] Minor --- GRDB/Core/Protocols/DatabasePersistable.swift | 11 ++-- GRDB/Record/Record.swift | 55 +++++++++++-------- 2 files changed, 36 insertions(+), 30 deletions(-) diff --git a/GRDB/Core/Protocols/DatabasePersistable.swift b/GRDB/Core/Protocols/DatabasePersistable.swift index 7c99db5cb..1fc919dcd 100644 --- a/GRDB/Core/Protocols/DatabasePersistable.swift +++ b/GRDB/Core/Protocols/DatabasePersistable.swift @@ -425,6 +425,7 @@ public extension DatabasePersistable { } + // MARK: - DataMapper /// DataMapper takes care of DatabasePersistable CRUD @@ -515,19 +516,15 @@ final class DataMapper { // MARK: - Initializer - convenience init(_ db: Database, _ persistable: MutableDatabasePersistable) { - self.init(db, persistable: persistable, persistentDictionary: persistable.persistentDictionary) - } - - init(_ db: Database, persistable: MutableDatabasePersistable, persistentDictionary: [String: DatabaseValueConvertible?]) { - let databaseTableName = persistable.dynamicType.databaseTableName() - + init(_ db: Database, _ persistable: MutableDatabasePersistable) { // Fail early if database table does not exist. + let databaseTableName = persistable.dynamicType.databaseTableName() guard let primaryKey = db.primaryKey(databaseTableName) else { fatalError("no such table: \(databaseTableName)") } // Fail early if persistentDictionary is empty + let persistentDictionary = persistable.persistentDictionary precondition(persistentDictionary.count > 0, "\(persistable.dynamicType).persistentDictionary: invalid empty dictionary") self.db = db diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 0221336c3..c411e6c95 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -134,16 +134,8 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabasePersistable /// false does not prevent it from turning true on subsequent modifications /// of the record. public var hasPersistentChangedValues: Bool { - get { - return generatePersistentChangedValues().next() != nil - } - set { - if newValue { - referenceRow = nil - } else { - referenceRow = Row(persistentDictionary) - } - } + get { return generatePersistentChangedValues().next() != nil } + set { referenceRow = newValue ? nil : Row(persistentDictionary) } } /// A dictionary of changes that have not been saved. @@ -156,11 +148,7 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabasePersistable /// /// See `hasPersistentChangedValues` for more information. public var persistentChangedValues: [String: DatabaseValue?] { - var changes: [String: DatabaseValue?] = [:] - for (column: column, old: old) in generatePersistentChangedValues() { - changes[column] = old - } - return changes + return Dictionary(generatePersistentChangedValues()) } // A change generator that is used by both hasPersistentChangedValues and @@ -210,17 +198,19 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabasePersistable // try performInsert(db) // hasPersistentChangedValues = false // - // But this triggers two calls to persistentDictionary, and this is - // costly. + // But this triggers two calls to persistentDictionary, and this is both + // costly, and ambiguous. Costly because persistentDictionary is slow. + // Ambiguous because persistentDictionary may return a different value. // - // So let's provide our custom implementation of insert: + // So let's provide our custom implementation of insert, which uses the + // same persistentDictionary for both insertion, and change tracking. - var persistentDictionary = self.persistentDictionary - - let dataMapper = DataMapper(db, persistable: self, persistentDictionary: persistentDictionary) + let dataMapper = DataMapper(db, self) + var persistentDictionary = dataMapper.persistentDictionary let changes = try dataMapper.insertStatement().execute() if let rowID = changes.insertedRowID { if case .Managed(let column) = dataMapper.primaryKey { + // Update persistentDictionary with inserted id if persistentDictionary[column] != nil { persistentDictionary[column] = rowID } else { @@ -238,6 +228,7 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabasePersistable } } + // Set hasPersistentChangedValues to false referenceRow = Row(persistentDictionary) } @@ -254,8 +245,26 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabasePersistable /// 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 { - try performUpdate(db) - hasPersistentChangedValues = false + // The simplest code would be: + // + // try performUpdate(db) + // hasPersistentChangedValues = false + // + // But this triggers two calls to persistentDictionary, and this is both + // costly, and ambiguous. Costly because persistentDictionary is slow. + // Ambiguous because persistentDictionary may return a different value. + // + // So let's provide our custom implementation of insert, which uses the + // same persistentDictionary for both update, and change tracking. + + let dataMapper = DataMapper(db, self) + let changes = try dataMapper.updateStatement().execute() + if changes.changedRowCount == 0 { + throw PersistenceError.NotFound(self) + } + + // Set hasPersistentChangedValues to false + referenceRow = Row(dataMapper.persistentDictionary) } /// Executes an INSERT or an UPDATE statement so that `self` is saved in From 474b28366baa7e5d379c9b9f69a0448df9061a68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 15 Jan 2016 08:35:08 +0100 Subject: [PATCH 21/25] Improve names of PrimaryKey enum cases --- GRDB/Core/Database.swift | 21 ++++++++++--------- GRDB/Core/Protocols/DatabasePersistable.swift | 6 +++--- GRDB/Record/Record.swift | 2 +- 3 files changed, 15 insertions(+), 14 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 6b0c95476..aee97976e 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -646,13 +646,13 @@ public final class Database { // We ignore the exception, and consider all INTEGER primary keys as // aliases for the rowid: if pkColumnInfo.type.uppercaseString == "INTEGER" { - primaryKey = .Managed(pkColumnInfo.name) + primaryKey = .RowID(pkColumnInfo.name) } else { - primaryKey = .Unmanaged([pkColumnInfo.name]) + primaryKey = .Regular([pkColumnInfo.name]) } default: // Multi-columns primary key - primaryKey = .Unmanaged(pkColumnInfos.map { $0.name }) + primaryKey = .Regular(pkColumnInfos.map { $0.name }) } primaryKeyCache[tableName] = primaryKey @@ -778,21 +778,22 @@ enum PrimaryKey { /// No primary key case None - /// A primary key managed by SQLite. Associated string is a column name. - case Managed(String) + /// An INTEGER PRIMARY KEY column that aliases the Row ID. + /// Associated string is the column name. + case RowID(String) - /// A primary key not managed by SQLite. It can span accross several - /// columns. Associated strings are column names. - case Unmanaged([String]) + /// Any primary key, but INTEGER PRIMARY KEY. + /// Associated strings are column names. + case Regular([String]) /// The columns in the primary key. May be empty. var columns: [String] { switch self { case .None: return [] - case .Managed(let column): + case .RowID(let column): return [column] - case .Unmanaged(let columns): + case .Regular(let columns): return columns } } diff --git a/GRDB/Core/Protocols/DatabasePersistable.swift b/GRDB/Core/Protocols/DatabasePersistable.swift index 1fc919dcd..ce85ae70c 100644 --- a/GRDB/Core/Protocols/DatabasePersistable.swift +++ b/GRDB/Core/Protocols/DatabasePersistable.swift @@ -210,7 +210,7 @@ public extension MutableDatabasePersistable { let dataMapper = DataMapper(db, self) let changes = try dataMapper.insertStatement().execute() if let rowID = changes.insertedRowID { - if case .Managed(let column) = dataMapper.primaryKey { + if case .RowID(let column) = dataMapper.primaryKey { didInsertWithRowID(rowID, forColumn: column) } else { didInsertWithRowID(rowID, forColumn: nil) @@ -386,8 +386,8 @@ public extension DatabasePersistable { 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) + if case .RowID(let column) = dataMapper.primaryKey { + didInsertWithRowID(rowID, forColumn: column) } else { didInsertWithRowID(rowID, forColumn: nil) } diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index c411e6c95..abc2ca9c1 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -209,7 +209,7 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabasePersistable var persistentDictionary = dataMapper.persistentDictionary let changes = try dataMapper.insertStatement().execute() if let rowID = changes.insertedRowID { - if case .Managed(let column) = dataMapper.primaryKey { + if case .RowID(let column) = dataMapper.primaryKey { // Update persistentDictionary with inserted id if persistentDictionary[column] != nil { persistentDictionary[column] = rowID From 5d9363a61d2aa3412d88e5d7a5270dd7aef40d50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 15 Jan 2016 09:14:41 +0100 Subject: [PATCH 22/25] Database.swift organization --- GRDB/Core/Database.swift | 983 +++++++++++++++++++-------------------- 1 file changed, 473 insertions(+), 510 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index aee97976e..ff0e1e788 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -15,8 +15,177 @@ public typealias SQLiteConnection = COpaquePointer /// } public final class Database { - // ========================================================================= - // MARK: - Select Statements + /// The database configuration + public let configuration: Configuration + + /// The raw SQLite connection, suitable for the SQLite C API. + public let sqliteConnection: SQLiteConnection + + /// The last error message + var lastErrorMessage: String? { return String.fromCString(sqlite3_errmsg(sqliteConnection)) } + + private var functions = Set() + private var collations = Set() + + // Cache + private var columnInfosCache: [String: [ColumnInfo]] = [:] + private var primaryKeyCache: [String: PrimaryKey] = [:] + private var updateStatementCache: [String: UpdateStatement] = [:] + private var selectStatementCache: [String: SelectStatement] = [:] + + /// Updated in SQLite callbacks (see setupTransactionHooks()) + /// Consumed in updateStatementDidFail() and updateStatementDidExecute(). + private var statementCompletion: StatementCompletion = .Regular + + /// The busy handler callback, if any. See Configuration.busyMode. + private var busyCallback: BusyCallback? + + /// The queue from which the database can be used. See preconditionValidQueue(). + /// Design note: this is not very clean. A delegation pattern may be a + /// better fit. + var databaseQueueID: DatabaseQueueID = nil + + init(path: String, configuration: Configuration) throws { + self.configuration = configuration + + // See https://www.sqlite.org/c3ref/open.html + var sqliteConnection = SQLiteConnection() + let code = sqlite3_open_v2(path, &sqliteConnection, configuration.sqliteOpenFlags, nil) + self.sqliteConnection = sqliteConnection + if code != SQLITE_OK { + throw DatabaseError(code: code, message: String.fromCString(sqlite3_errmsg(sqliteConnection))) + } + + // Setup trace first, so that all queries, including initialization queries, are traced. + setupTrace() + + try setupForeignKeys() + setupBusyMode() + setupTransactionHooks() + } + + // Initializes an in-memory database + convenience init(configuration: Configuration) { + try! self.init(path: ":memory:", configuration: configuration) + } + + deinit { + sqlite3_close(sqliteConnection) + } + + func preconditionValidQueue() { + precondition(databaseQueueID == nil || databaseQueueID == dispatch_get_specific(DatabaseQueue.databaseQueueIDKey), "Database was not used on the correct thread: execute your statements inside DatabaseQueue.inDatabase() or DatabaseQueue.inTransaction(). If you get this error while iterating the result of a fetch() method, consider using the array returned by fetchAll() instead.") + } + + func setupForeignKeys() throws { + if configuration.foreignKeysEnabled { + try execute("PRAGMA foreign_keys = ON") + } + } + + func setupTrace() { + guard configuration.trace != nil else { + return + } + let dbPointer = unsafeBitCast(self, UnsafeMutablePointer.self) + sqlite3_trace(sqliteConnection, { (dbPointer, sql) in + let database = unsafeBitCast(dbPointer, Database.self) + database.configuration.trace!(String.fromCString(sql)!) + }, dbPointer) + } + + func setupBusyMode() { + switch configuration.busyMode { + case .ImmediateError: + break + + case .Timeout(let duration): + let milliseconds = Int32(duration * 1000) + sqlite3_busy_timeout(sqliteConnection, milliseconds) + + case .Callback(let callback): + let dbPointer = unsafeBitCast(self, UnsafeMutablePointer.self) + busyCallback = callback + + sqlite3_busy_handler( + sqliteConnection, + { (dbPointer: UnsafeMutablePointer, numberOfTries: Int32) in + let database = unsafeBitCast(dbPointer, Database.self) + let callback = database.busyCallback! + return callback(numberOfTries: Int(numberOfTries)) ? 1 : 0 + }, + dbPointer) + } + } +} + + +/// A SQLite threading mode. See https://www.sqlite.org/threadsafe.html. +enum ThreadingMode { + case Default + case MultiThread + case Serialized + + var sqliteOpenFlags: Int32 { + switch self { + case .Default: + return 0 + case .MultiThread: + return SQLITE_OPEN_NOMUTEX + case .Serialized: + return SQLITE_OPEN_FULLMUTEX + } + } +} + + +/// See BusyMode and https://www.sqlite.org/c3ref/busy_handler.html +public typealias BusyCallback = (numberOfTries: Int) -> Bool + +/// When there are several connections to a database, a connection may try to +/// access the database while it is locked by another connection. +/// +/// The BusyMode enum describes the behavior of GRDB when such a situation +/// occurs: +/// +/// - .ImmediateError: The SQLITE_BUSY error is immediately returned to the +/// connection that tries to access the locked database. +/// +/// - .Timeout: The SQLITE_BUSY error will be returned only if the database +/// remains locked for more than the specified duration. +/// +/// - .Callback: Perform your custom lock handling. +/// +/// To set the busy mode of a database, use Configuration: +/// +/// let configuration = Configuration(busyMode: .Timeout(1)) +/// let dbQueue = DatabaseQueue(path: "...", configuration: configuration) +/// +/// Relevant SQLite documentation: +/// +/// - https://www.sqlite.org/c3ref/busy_timeout.html +/// - https://www.sqlite.org/c3ref/busy_handler.html +/// - https://www.sqlite.org/lang_transaction.html +/// - https://www.sqlite.org/wal.html +public enum BusyMode { + /// The SQLITE_BUSY error is immediately returned to the connection that + /// tries to access the locked database. + case ImmediateError + + /// The SQLITE_BUSY error will be returned only if the database remains + /// locked for more than the specified duration. + case Timeout(NSTimeInterval) + + /// A custom callback that is called when a database is locked. + /// See https://www.sqlite.org/c3ref/busy_handler.html + case Callback(BusyCallback) +} + + +// ========================================================================= +// MARK: - Statements + +extension Database { /// Returns a prepared statement that can be reused. /// @@ -41,11 +210,7 @@ public final class Database { return statement } - - // ========================================================================= - // MARK: - Update Statements - - /// Returns an prepared statement that can be reused. + /// Returns a prepared statement that can be reused. /// /// let statement = try db.updateStatement("INSERT INTO persons (name) VALUES (?)") /// try statement.execute(arguments: ["Arthur"]) @@ -134,7 +299,7 @@ public final class Database { return (consumeArguments, validateRemainingArguments) } }() - + // Execute statements @@ -178,244 +343,13 @@ public final class Database { } - // ========================================================================= - // MARK: - Transactions - - /// Executes a block inside a database transaction. - /// - /// try dbQueue.inDatabase do { - /// try db.inTransaction { - /// try db.execute("INSERT ...") - /// return .Commit - /// } - /// } - /// - /// If the block throws an error, the transaction is rollbacked and the - /// error is rethrown. - /// - /// This method is not reentrant: you can't nest transactions. - /// - /// - parameter kind: The transaction type (default nil). If nil, the - /// transaction type is configuration.defaultTransactionKind, which itself - /// defaults to .Immediate. See https://www.sqlite.org/lang_transaction.html - /// for more information. - /// - parameter block: A block that executes SQL statements and return - /// either .Commit or .Rollback. - /// - throws: The error thrown by the block. - public func inTransaction(kind: TransactionKind? = nil, block: () throws -> TransactionCompletion) throws { - preconditionValidQueue() - - var completion: TransactionCompletion = .Rollback - var blockError: ErrorType? = nil - - try beginTransaction(kind) - - do { - completion = try block() - } catch { - completion = .Rollback - blockError = error - } - - switch completion { - case .Commit: - try commit() - case .Rollback: - // https://www.sqlite.org/lang_transaction.html#immediate - // - // > Response To Errors Within A Transaction - // > - // > If certain kinds of errors occur within a transaction, the - // > transaction may or may not be rolled back automatically. The - // > errors that can cause an automatic rollback include: - // > - // > - SQLITE_FULL: database or disk full - // > - SQLITE_IOERR: disk I/O error - // > - SQLITE_BUSY: database in use by another process - // > - SQLITE_NOMEM: out or memory - // > - // > [...] It is recommended that applications respond to the errors - // > listed above by explicitly issuing a ROLLBACK command. If the - // > transaction has already been rolled back automatically by the - // > error response, then the ROLLBACK command will fail with an - // > error, but no harm is caused by this. - if let blockError = blockError as? DatabaseError { - switch Int32(blockError.code) { - case SQLITE_FULL, SQLITE_IOERR, SQLITE_BUSY, SQLITE_NOMEM: - do { try rollback() } catch { } - default: - try rollback() - } - } else { - try rollback() - } - } - - if let blockError = blockError { - throw blockError - } - } - - private func beginTransaction(kind: TransactionKind? = nil) throws { - switch kind ?? configuration.defaultTransactionKind { - case .Deferred: - try execute("BEGIN DEFERRED TRANSACTION") - case .Immediate: - try execute("BEGIN IMMEDIATE TRANSACTION") - case .Exclusive: - try execute("BEGIN EXCLUSIVE TRANSACTION") - } - } - - private func rollback() throws { - try execute("ROLLBACK TRANSACTION") - } - - private func commit() throws { - try execute("COMMIT TRANSACTION") - } - - - // ========================================================================= - // MARK: - Transaction Observation - - private enum StatementCompletion { - // Statement has ended with a commit (implicit or explicit). - case TransactionCommit - - // Statement has ended with a rollback. - case TransactionRollback - - // Statement has been rollbacked by transactionObserver. - case TransactionErrorRollback(ErrorType) - - // All other cases (CREATE TABLE, etc.) - case Regular - } - - /// Updated in SQLite callbacks (see setupTransactionHooks()) - /// Consumed in updateStatementDidFail() and updateStatementDidExecute(). - private var statementCompletion: StatementCompletion = .Regular - - func updateStatementDidFail() throws { - let statementCompletion = self.statementCompletion - self.statementCompletion = .Regular - - switch statementCompletion { - case .TransactionErrorRollback(let error): - // The transaction has been rollbacked from - // TransactionObserverType.transactionWillCommit(). - configuration.transactionObserver!.databaseDidRollback(self) - throw error - default: - break - } - } - - func updateStatementDidExecute() { - let statementCompletion = self.statementCompletion - self.statementCompletion = .Regular - - switch statementCompletion { - case .TransactionCommit: - configuration.transactionObserver!.databaseDidCommit(self) - case .TransactionRollback: - configuration.transactionObserver!.databaseDidRollback(self) - default: - break - } - } - - private func setupTransactionHooks() { - // No need to setup any hook when there is no transactionObserver: - guard configuration.transactionObserver != nil else { - return - } - - let dbPointer = unsafeBitCast(self, UnsafeMutablePointer.self) - - - sqlite3_update_hook(sqliteConnection, { (dbPointer, updateKind, databaseName, tableName, rowID) in - let db = unsafeBitCast(dbPointer, Database.self) - - // Notify change event - let event = DatabaseEvent( - kind: DatabaseEvent.Kind(rawValue: updateKind)!, - databaseName: String.fromCString(databaseName)!, - tableName: String.fromCString(tableName)!, - rowID: rowID) - db.configuration.transactionObserver!.databaseDidChangeWithEvent(event) - }, dbPointer) - - - sqlite3_commit_hook(sqliteConnection, { dbPointer in - let db = unsafeBitCast(dbPointer, Database.self) - - do { - try db.configuration.transactionObserver!.databaseWillCommit() - // Next step: updateStatementDidExecute() - db.statementCompletion = .TransactionCommit - return 0 - } catch { - // Next step: sqlite3_rollback_hook callback - db.statementCompletion = .TransactionErrorRollback(error) - return 1 - } - }, dbPointer) - - - sqlite3_rollback_hook(sqliteConnection, { dbPointer in - let db = unsafeBitCast(dbPointer, Database.self) - - switch db.statementCompletion { - case .TransactionErrorRollback: - // The transactionObserver has rollbacked the transaction. - // Don't lose this information. - // Next step: updateStatementDidFail() - break - default: - // Next step: updateStatementDidExecute() - db.statementCompletion = .TransactionRollback - } - }, dbPointer) - } - - - // ========================================================================= - // MARK: - Concurrency - - /// The busy handler callback, if any. See Configuration.busyMode. - private var busyCallback: BusyCallback? - - func setupBusyMode() { - switch configuration.busyMode { - case .ImmediateError: - break - - case .Timeout(let duration): - let milliseconds = Int32(duration * 1000) - sqlite3_busy_timeout(sqliteConnection, milliseconds) - - case .Callback(let callback): - let dbPointer = unsafeBitCast(self, UnsafeMutablePointer.self) - busyCallback = callback - - sqlite3_busy_handler( - sqliteConnection, - { (dbPointer: UnsafeMutablePointer, numberOfTries: Int32) in - let database = unsafeBitCast(dbPointer, Database.self) - let callback = database.busyCallback! - return callback(numberOfTries: Int(numberOfTries)) ? 1 : 0 - }, - dbPointer) - } - } - - - // ========================================================================= - // MARK: - Functions - - private var functions = Set() +} + + +// ========================================================================= +// MARK: - Functions + +extension Database { /// Add or redefine an SQL function. /// @@ -486,12 +420,66 @@ public final class Database { fatalError(DatabaseError(code: code, message: lastErrorMessage, sql: nil, arguments: nil).description) } } +} + + +/// An SQL function. +public class DatabaseFunction : Hashable { + let name: String + let argumentCount: Int32 + let pure: Bool + let function: (COpaquePointer, Int32, UnsafeMutablePointer) throws -> DatabaseValue + var eTextRep: Int32 { return pure ? SQLITE_DETERMINISTIC : 0 } + /// The hash value. + public var hashValue: Int { + return name.hashValue ^ argumentCount.hashValue + } - // ========================================================================= - // MARK: - Collations - - private var collations = Set() + /// Returns an SQL function. + /// + /// let fn = DatabaseFunction("succ", argumentCount: 1) { databaseValues in + /// let dbv = databaseValues.first! + /// guard let int = dbv.value() as Int? else { + /// return nil + /// } + /// return int + 1 + /// } + /// db.addFunction(fn) + /// Int.fetchOne(db, "SELECT succ(1)")! // 2 + /// + /// - parameter name: The function name. + /// - parameter argumentCount: The number of arguments of the function. If + /// omitted, or nil, the function accepts any number of arguments. + /// - parameter pure: Whether the function is "pure", which means that its + /// results only depends on its inputs. When a function is pure, SQLite + /// has the opportunity to perform additional optimizations. Default value + /// is false. + /// - parameter function: A function that takes an array of DatabaseValue + /// arguments, and returns an optional DatabaseValueConvertible such as + /// Int, String, NSDate, etc. The array is guaranteed to have exactly + /// *argumentCount* elements, provided *argumentCount* is not nil. + public init(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, function: [DatabaseValue] throws -> DatabaseValueConvertible?) { + self.name = name + self.argumentCount = argumentCount ?? -1 + self.pure = pure + self.function = { (context, argc, argv) in + let arguments = (0.. Bool { + return lhs.name == rhs.name && lhs.argumentCount == rhs.argumentCount +} + + +// ========================================================================= +// MARK: - Collations + +extension Database { /// Add or redefine a collation. /// @@ -534,21 +522,47 @@ public final class Database { SQLITE_UTF8, nil, nil, nil) } +} + +/// A Collation. +public class DatabaseCollation : Hashable { + let name: String + let function: (String, String) -> NSComparisonResult + /// The hash value. + public var hashValue: Int { + // We can't compute a hash since the equality is based on the opaque + // sqlite3_strnicmp SQLite function. + return 0 + } - // ========================================================================= - // MARK: - Database Informations - - /// The database configuration - public let configuration: Configuration - - /// The last error message - var lastErrorMessage: String? { return String.fromCString(sqlite3_errmsg(sqliteConnection)) } - - private var columnInfosCache: [String: [ColumnInfo]] = [:] - private var primaryKeyCache: [String: PrimaryKey] = [:] - private var updateStatementCache: [String: UpdateStatement] = [:] - private var selectStatementCache: [String: SelectStatement] = [:] + /// Returns a collation. + /// + /// let collation = DatabaseCollation("localized_standard") { (string1, string2) in + /// return (string1 as NSString).localizedStandardCompare(string2) + /// } + /// db.addCollation(collation) + /// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD") + /// + /// - parameter name: The function name. + /// - parameter function: A function that compares two strings. + public init(_ name: String, function: (String, String) -> NSComparisonResult) { + self.name = name + self.function = function + } +} + +/// Two collations are equal if they share the same name (case insensitive) +public func ==(lhs: DatabaseCollation, rhs: DatabaseCollation) -> Bool { + // See https://www.sqlite.org/c3ref/create_collation.html + return sqlite3_stricmp(lhs.name, lhs.name) == 0 +} + + +// ========================================================================= +// MARK: - Database Schema + +extension Database { /// Clears the database schema cache. /// @@ -687,7 +701,6 @@ public final class Database { } } - // Cache for columnInfos() private func columnInfos(tableName: String) -> [ColumnInfo] { if let columnInfos = columnInfosCache[tableName] { return columnInfos @@ -697,81 +710,8 @@ public final class Database { columnInfosCache[tableName] = columnInfos return columnInfos } - - - // ========================================================================= - // MARK: - Raw SQLite connetion - - /// The raw SQLite connection, suitable for the SQLite C API. - public let sqliteConnection: SQLiteConnection - - - // ========================================================================= - // MARK: - Initialization - - /// The queue from which the database can be used. See preconditionValidQueue(). - /// Design note: this is not very clean. A delegation pattern may be a - /// better fit. - var databaseQueueID: DatabaseQueueID = nil - - init(path: String, configuration: Configuration) throws { - self.configuration = configuration - - // See https://www.sqlite.org/c3ref/open.html - var sqliteConnection = SQLiteConnection() - let code = sqlite3_open_v2(path, &sqliteConnection, configuration.sqliteOpenFlags, nil) - self.sqliteConnection = sqliteConnection - if code != SQLITE_OK { - throw DatabaseError(code: code, message: String.fromCString(sqlite3_errmsg(sqliteConnection))) - } - - // Setup trace first, so that all queries, including initialization queries, are traced. - setupTrace() - - try setupForeignKeys() - setupBusyMode() - setupTransactionHooks() - } - - // Initializes an in-memory database - convenience init(configuration: Configuration) { - try! self.init(path: ":memory:", configuration: configuration) - } - - deinit { - sqlite3_close(sqliteConnection) - } - - - // ========================================================================= - // MARK: - Misc - - func preconditionValidQueue() { - precondition(databaseQueueID == nil || databaseQueueID == dispatch_get_specific(DatabaseQueue.databaseQueueIDKey), "Database was not used on the correct thread: execute your statements inside DatabaseQueue.inDatabase() or DatabaseQueue.inTransaction(). If you get this error while iterating the result of a fetch() method, consider using the array returned by fetchAll() instead.") - } - - func setupForeignKeys() throws { - if configuration.foreignKeysEnabled { - try execute("PRAGMA foreign_keys = ON") - } - } - - func setupTrace() { - guard configuration.trace != nil else { - return - } - let dbPointer = unsafeBitCast(self, UnsafeMutablePointer.self) - sqlite3_trace(sqliteConnection, { (dbPointer, sql) in - let database = unsafeBitCast(dbPointer, Database.self) - database.configuration.trace!(String.fromCString(sql)!) - }, dbPointer) - } } - -// ============================================================================= -// MARK: - PrimaryKey - /// A primary key enum PrimaryKey { @@ -800,8 +740,202 @@ enum PrimaryKey { } -// ============================================================================= -// MARK: - TransactionKind +// ========================================================================= +// MARK: - Transactions + +extension Database { + /// Executes a block inside a database transaction. + /// + /// try dbQueue.inDatabase do { + /// try db.inTransaction { + /// try db.execute("INSERT ...") + /// return .Commit + /// } + /// } + /// + /// If the block throws an error, the transaction is rollbacked and the + /// error is rethrown. + /// + /// This method is not reentrant: you can't nest transactions. + /// + /// - parameter kind: The transaction type (default nil). If nil, the + /// transaction type is configuration.defaultTransactionKind, which itself + /// defaults to .Immediate. See https://www.sqlite.org/lang_transaction.html + /// for more information. + /// - parameter block: A block that executes SQL statements and return + /// either .Commit or .Rollback. + /// - throws: The error thrown by the block. + public func inTransaction(kind: TransactionKind? = nil, block: () throws -> TransactionCompletion) throws { + preconditionValidQueue() + + var completion: TransactionCompletion = .Rollback + var blockError: ErrorType? = nil + + try beginTransaction(kind) + + do { + completion = try block() + } catch { + completion = .Rollback + blockError = error + } + + switch completion { + case .Commit: + try commit() + case .Rollback: + // https://www.sqlite.org/lang_transaction.html#immediate + // + // > Response To Errors Within A Transaction + // > + // > If certain kinds of errors occur within a transaction, the + // > transaction may or may not be rolled back automatically. The + // > errors that can cause an automatic rollback include: + // > + // > - SQLITE_FULL: database or disk full + // > - SQLITE_IOERR: disk I/O error + // > - SQLITE_BUSY: database in use by another process + // > - SQLITE_NOMEM: out or memory + // > + // > [...] It is recommended that applications respond to the errors + // > listed above by explicitly issuing a ROLLBACK command. If the + // > transaction has already been rolled back automatically by the + // > error response, then the ROLLBACK command will fail with an + // > error, but no harm is caused by this. + if let blockError = blockError as? DatabaseError { + switch Int32(blockError.code) { + case SQLITE_FULL, SQLITE_IOERR, SQLITE_BUSY, SQLITE_NOMEM: + do { try rollback() } catch { } + default: + try rollback() + } + } else { + try rollback() + } + } + + if let blockError = blockError { + throw blockError + } + } + + private func beginTransaction(kind: TransactionKind? = nil) throws { + switch kind ?? configuration.defaultTransactionKind { + case .Deferred: + try execute("BEGIN DEFERRED TRANSACTION") + case .Immediate: + try execute("BEGIN IMMEDIATE TRANSACTION") + case .Exclusive: + try execute("BEGIN EXCLUSIVE TRANSACTION") + } + } + + private func rollback() throws { + try execute("ROLLBACK TRANSACTION") + } + + private func commit() throws { + try execute("COMMIT TRANSACTION") + } + + func updateStatementDidFail() throws { + let statementCompletion = self.statementCompletion + self.statementCompletion = .Regular + + switch statementCompletion { + case .TransactionErrorRollback(let error): + // The transaction has been rollbacked from + // TransactionObserverType.transactionWillCommit(). + configuration.transactionObserver!.databaseDidRollback(self) + throw error + default: + break + } + } + + func updateStatementDidExecute() { + let statementCompletion = self.statementCompletion + self.statementCompletion = .Regular + + switch statementCompletion { + case .TransactionCommit: + configuration.transactionObserver!.databaseDidCommit(self) + case .TransactionRollback: + configuration.transactionObserver!.databaseDidRollback(self) + default: + break + } + } + + private func setupTransactionHooks() { + // No need to setup any hook when there is no transactionObserver: + guard configuration.transactionObserver != nil else { + return + } + + let dbPointer = unsafeBitCast(self, UnsafeMutablePointer.self) + + + sqlite3_update_hook(sqliteConnection, { (dbPointer, updateKind, databaseName, tableName, rowID) in + let db = unsafeBitCast(dbPointer, Database.self) + + // Notify change event + let event = DatabaseEvent( + kind: DatabaseEvent.Kind(rawValue: updateKind)!, + databaseName: String.fromCString(databaseName)!, + tableName: String.fromCString(tableName)!, + rowID: rowID) + db.configuration.transactionObserver!.databaseDidChangeWithEvent(event) + }, dbPointer) + + + sqlite3_commit_hook(sqliteConnection, { dbPointer in + let db = unsafeBitCast(dbPointer, Database.self) + + do { + try db.configuration.transactionObserver!.databaseWillCommit() + // Next step: updateStatementDidExecute() + db.statementCompletion = .TransactionCommit + return 0 + } catch { + // Next step: sqlite3_rollback_hook callback + db.statementCompletion = .TransactionErrorRollback(error) + return 1 + } + }, dbPointer) + + + sqlite3_rollback_hook(sqliteConnection, { dbPointer in + let db = unsafeBitCast(dbPointer, Database.self) + + switch db.statementCompletion { + case .TransactionErrorRollback: + // The transactionObserver has rollbacked the transaction. + // Don't lose this information. + // Next step: updateStatementDidFail() + break + default: + // Next step: updateStatementDidExecute() + db.statementCompletion = .TransactionRollback + } + }, dbPointer) + } + + private enum StatementCompletion { + // Statement has ended with a commit (implicit or explicit). + case TransactionCommit + + // Statement has ended with a rollback. + case TransactionRollback + + // Statement has been rollbacked by transactionObserver. + case TransactionErrorRollback(ErrorType) + + // All other cases (CREATE TABLE, etc.) + case Regular + } +} + /// A SQLite transaction kind. See https://www.sqlite.org/lang_transaction.html public enum TransactionKind { @@ -811,9 +945,6 @@ public enum TransactionKind { } -// ============================================================================= -// MARK: - TransactionCompletion - /// The end of a transaction: Commit, or Rollback public enum TransactionCompletion { case Commit @@ -821,9 +952,6 @@ public enum TransactionCompletion { } -// ============================================================================= -// MARK: - TransactionObserverType - /// A transaction observer is notified of all changes and transactions committed /// or rollbacked on a database. /// @@ -868,9 +996,6 @@ public protocol TransactionObserverType : class { } -// ============================================================================= -// MARK: - DatabaseEvent - /// A database event, notified to TransactionObserverType. /// /// See https://www.sqlite.org/c3ref/update_hook.html for more information. @@ -894,165 +1019,3 @@ public struct DatabaseEvent { /// The rowID of the changed row. public let rowID: Int64 } - - -// ============================================================================= -// MARK: - ThreadingMode - -/// A SQLite threading mode. See https://www.sqlite.org/threadsafe.html. -enum ThreadingMode { - case Default - case MultiThread - case Serialized - - var sqliteOpenFlags: Int32 { - switch self { - case .Default: - return 0 - case .MultiThread: - return SQLITE_OPEN_NOMUTEX - case .Serialized: - return SQLITE_OPEN_FULLMUTEX - } - } -} - - -// ============================================================================= -// MARK: - BusyMode - -/// See BusyMode and https://www.sqlite.org/c3ref/busy_handler.html -public typealias BusyCallback = (numberOfTries: Int) -> Bool - -/// When there are several connections to a database, a connection may try to -/// access the database while it is locked by another connection. -/// -/// The BusyMode enum describes the behavior of GRDB when such a situation -/// occurs: -/// -/// - .ImmediateError: The SQLITE_BUSY error is immediately returned to the -/// connection that tries to access the locked database. -/// -/// - .Timeout: The SQLITE_BUSY error will be returned only if the database -/// remains locked for more than the specified duration. -/// -/// - .Callback: Perform your custom lock handling. -/// -/// To set the busy mode of a database, use Configuration: -/// -/// let configuration = Configuration(busyMode: .Timeout(1)) -/// let dbQueue = DatabaseQueue(path: "...", configuration: configuration) -/// -/// Relevant SQLite documentation: -/// -/// - https://www.sqlite.org/c3ref/busy_timeout.html -/// - https://www.sqlite.org/c3ref/busy_handler.html -/// - https://www.sqlite.org/lang_transaction.html -/// - https://www.sqlite.org/wal.html -public enum BusyMode { - /// The SQLITE_BUSY error is immediately returned to the connection that - /// tries to access the locked database. - case ImmediateError - - /// The SQLITE_BUSY error will be returned only if the database remains - /// locked for more than the specified duration. - case Timeout(NSTimeInterval) - - /// A custom callback that is called when a database is locked. - /// See https://www.sqlite.org/c3ref/busy_handler.html - case Callback(BusyCallback) -} - - -// ========================================================================= -// MARK: - Functions - -/// An SQL function. -public class DatabaseFunction : Hashable { - let name: String - let argumentCount: Int32 - let pure: Bool - let function: (COpaquePointer, Int32, UnsafeMutablePointer) throws -> DatabaseValue - var eTextRep: Int32 { return pure ? SQLITE_DETERMINISTIC : 0 } - - /// The hash value. - public var hashValue: Int { - return name.hashValue ^ argumentCount.hashValue - } - - /// Returns an SQL function. - /// - /// let fn = DatabaseFunction("succ", argumentCount: 1) { databaseValues in - /// let dbv = databaseValues.first! - /// guard let int = dbv.value() as Int? else { - /// return nil - /// } - /// return int + 1 - /// } - /// db.addFunction(fn) - /// Int.fetchOne(db, "SELECT succ(1)")! // 2 - /// - /// - parameter name: The function name. - /// - parameter argumentCount: The number of arguments of the function. If - /// omitted, or nil, the function accepts any number of arguments. - /// - parameter pure: Whether the function is "pure", which means that its - /// results only depends on its inputs. When a function is pure, SQLite - /// has the opportunity to perform additional optimizations. Default value - /// is false. - /// - parameter function: A function that takes an array of DatabaseValue - /// arguments, and returns an optional DatabaseValueConvertible such as - /// Int, String, NSDate, etc. The array is guaranteed to have exactly - /// *argumentCount* elements, provided *argumentCount* is not nil. - public init(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, function: [DatabaseValue] throws -> DatabaseValueConvertible?) { - self.name = name - self.argumentCount = argumentCount ?? -1 - self.pure = pure - self.function = { (context, argc, argv) in - let arguments = (0.. Bool { - return lhs.name == rhs.name && lhs.argumentCount == rhs.argumentCount -} - - -// ========================================================================= -// MARK: - Collations - -/// A Collation. -public class DatabaseCollation : Hashable { - let name: String - let function: (String, String) -> NSComparisonResult - - /// The hash value. - public var hashValue: Int { - // We can't compute a hash since the equality is based on the opaque - // sqlite3_strnicmp SQLite function. - return 0 - } - - /// Returns a collation. - /// - /// let collation = DatabaseCollation("localized_standard") { (string1, string2) in - /// return (string1 as NSString).localizedStandardCompare(string2) - /// } - /// db.addCollation(collation) - /// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD") - /// - /// - parameter name: The function name. - /// - parameter function: A function that compares two strings. - public init(_ name: String, function: (String, String) -> NSComparisonResult) { - self.name = name - self.function = function - } -} - -/// Two collations are equal if they share the same name (case insensitive) -public func ==(lhs: DatabaseCollation, rhs: DatabaseCollation) -> Bool { - // See https://www.sqlite.org/c3ref/create_collation.html - return sqlite3_stricmp(lhs.name, lhs.name) == 0 -} From 706f936831b0fca8703ced00f7d0636e7d968537 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 15 Jan 2016 09:17:27 +0100 Subject: [PATCH 23/25] Database.swift organization --- GRDB/Core/Database.swift | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index ff0e1e788..25bde7317 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -21,28 +21,24 @@ public final class Database { /// The raw SQLite connection, suitable for the SQLite C API. public let sqliteConnection: SQLiteConnection - /// The last error message var lastErrorMessage: String? { return String.fromCString(sqlite3_errmsg(sqliteConnection)) } private var functions = Set() private var collations = Set() - // Cache private var columnInfosCache: [String: [ColumnInfo]] = [:] private var primaryKeyCache: [String: PrimaryKey] = [:] private var updateStatementCache: [String: UpdateStatement] = [:] private var selectStatementCache: [String: SelectStatement] = [:] - /// Updated in SQLite callbacks (see setupTransactionHooks()) - /// Consumed in updateStatementDidFail() and updateStatementDidExecute(). + /// See setupTransactionHooks(), updateStatementDidFail(), updateStatementDidExecute() private var statementCompletion: StatementCompletion = .Regular - /// The busy handler callback, if any. See Configuration.busyMode. + /// See setupBusyMode() private var busyCallback: BusyCallback? - /// The queue from which the database can be used. See preconditionValidQueue(). - /// Design note: this is not very clean. A delegation pattern may be a - /// better fit. + /// The queue from which the database can be used. + /// See preconditionValidQueue(). var databaseQueueID: DatabaseQueueID = nil init(path: String, configuration: Configuration) throws { From 56406d6ca586f441f62acb3903c17feda3db8879 Mon Sep 17 00:00:00 2001 From: Pascal Edmond Date: Wed, 9 Dec 2015 18:15:45 +0100 Subject: [PATCH 24/25] WIP : Welcome FetchedRecordsController --- GRDB/Core/Configuration.swift | 1 - GRDB/Core/Database.swift | 50 ++++++++++++++++++++++++++--------- 2 files changed, 37 insertions(+), 14 deletions(-) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 9f4f71e0e..549676591 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -16,7 +16,6 @@ public struct Configuration { /// The default kind of transaction. public var defaultTransactionKind: TransactionKind = .Immediate - public var transactionObserver: TransactionObserverType? // MARK: - Concurrency diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 25bde7317..23968604c 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -34,6 +34,9 @@ public final class Database { /// See setupTransactionHooks(), updateStatementDidFail(), updateStatementDidExecute() private var statementCompletion: StatementCompletion = .Regular + /// The transaction observers + private var transactionObservers = [TransactionObserverType]() + /// See setupBusyMode() private var busyCallback: BusyCallback? @@ -68,7 +71,7 @@ public final class Database { deinit { sqlite3_close(sqliteConnection) } - + func preconditionValidQueue() { precondition(databaseQueueID == nil || databaseQueueID == dispatch_get_specific(DatabaseQueue.databaseQueueIDKey), "Database was not used on the correct thread: execute your statements inside DatabaseQueue.inDatabase() or DatabaseQueue.inTransaction(). If you get this error while iterating the result of a fetch() method, consider using the array returned by fetchAll() instead.") } @@ -815,6 +818,10 @@ extension Database { } } + public func addTransactionObserver(transactionObserver: TransactionObserverType) { + transactionObservers.append(transactionObserver) + } + private func beginTransaction(kind: TransactionKind? = nil) throws { switch kind ?? configuration.defaultTransactionKind { case .Deferred: @@ -842,7 +849,7 @@ extension Database { case .TransactionErrorRollback(let error): // The transaction has been rollbacked from // TransactionObserverType.transactionWillCommit(). - configuration.transactionObserver!.databaseDidRollback(self) + propagateDatabaseDidRollback() throw error default: break @@ -855,23 +862,41 @@ extension Database { switch statementCompletion { case .TransactionCommit: - configuration.transactionObserver!.databaseDidCommit(self) + propagateDatabaseDidCommit() case .TransactionRollback: - configuration.transactionObserver!.databaseDidRollback(self) + propagateDatabaseDidRollback() default: break } } - private func setupTransactionHooks() { - // No need to setup any hook when there is no transactionObserver: - guard configuration.transactionObserver != nil else { - return + private func propagateDatabaseWillCommit() throws { + for observer: TransactionObserverType in transactionObservers { + try observer.databaseWillCommit() } - + } + + private func propagateDatabaseDidChangeWithEvent(event: DatabaseEvent) { + for observer: TransactionObserverType in transactionObservers { + observer.databaseDidChangeWithEvent(event) + } + } + + private func propagateDatabaseDidCommit() { + for observer: TransactionObserverType in transactionObservers { + observer.databaseDidCommit(self) + } + } + + private func propagateDatabaseDidRollback() { + for observer: TransactionObserverType in transactionObservers { + observer.databaseDidRollback(self) + } + } + + private func setupTransactionHooks() { let dbPointer = unsafeBitCast(self, UnsafeMutablePointer.self) - sqlite3_update_hook(sqliteConnection, { (dbPointer, updateKind, databaseName, tableName, rowID) in let db = unsafeBitCast(dbPointer, Database.self) @@ -881,15 +906,14 @@ extension Database { databaseName: String.fromCString(databaseName)!, tableName: String.fromCString(tableName)!, rowID: rowID) - db.configuration.transactionObserver!.databaseDidChangeWithEvent(event) + db.propagateDatabaseDidChangeWithEvent(event) }, dbPointer) sqlite3_commit_hook(sqliteConnection, { dbPointer in let db = unsafeBitCast(dbPointer, Database.self) - do { - try db.configuration.transactionObserver!.databaseWillCommit() + try db.propagateDatabaseWillCommit() // Next step: updateStatementDidExecute() db.statementCompletion = .TransactionCommit return 0 From b29869e0cd9b7eba15c88c396a909c0af4ac62f9 Mon Sep 17 00:00:00 2001 From: Pascal Edmond Date: Wed, 23 Dec 2015 15:03:06 +0100 Subject: [PATCH 25/25] Database Transaction Observation : allow multiple observers --- GRDB/Core/Database.swift | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 23968604c..5c30bf639 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -819,9 +819,17 @@ extension Database { } public func addTransactionObserver(transactionObserver: TransactionObserverType) { + preconditionValidQueue() transactionObservers.append(transactionObserver) } + public func removeTransactionObserver(transactionObserver: TransactionObserverType) { + preconditionValidQueue() + if let index = transactionObservers.indexOf({ observer in observer === transactionObserver}) { + transactionObservers.removeAtIndex(index) + } + } + private func beginTransaction(kind: TransactionKind? = nil) throws { switch kind ?? configuration.defaultTransactionKind { case .Deferred: