From f8ad2f2f6a2358637cbadfd5752367720f80cfa6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 17 Dec 2015 10:23:19 +0100 Subject: [PATCH] Use precondition() when validating user input --- GRDB/Core/Database.swift | 14 ++++++------- GRDB/Core/DatabaseQueue.swift | 4 +--- GRDB/Core/Protocols/DatabasePersistable.swift | 4 +--- .../Core/Protocols/DatabaseTableMapping.swift | 9 ++------- GRDB/Core/Row.swift | 20 +++++-------------- GRDB/Core/SelectStatement.swift | 6 +++--- GRDB/Core/Statement.swift | 6 ++---- GRDB/Migrations/DatabaseMigrator.swift | 4 +--- 8 files changed, 21 insertions(+), 46 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index fe68da4ee..e5c5fc51c 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -78,7 +78,7 @@ public final class Database { /// - returns: A DatabaseChanges. Note that insertedRowID will always be nil. /// - throws: A DatabaseError whenever a SQLite error occurs. public func executeMultiStatement(sql: String) throws -> DatabaseChanges { - assertValidQueue() + preconditionValidQueue() let changedRowsBefore = sqlite3_total_changes(sqliteConnection) @@ -117,7 +117,7 @@ public final class Database { /// either .Commit or .Rollback. /// - throws: The error thrown by the block. public func inTransaction(kind: TransactionKind? = nil, block: () throws -> TransactionCompletion) throws { - assertValidQueue() + preconditionValidQueue() var completion: TransactionCompletion = .Rollback var blockError: ErrorType? = nil @@ -458,7 +458,7 @@ public final class Database { /// You may need to clear the cache if you modify the database schema /// outside of a migration (see DatabaseMigrator). public func clearSchemaCache() { - assertValidQueue() + preconditionValidQueue() columnInfosCache = [:] } @@ -614,7 +614,7 @@ public final class Database { // ========================================================================= // MARK: - Initialization - /// The queue from which the database can be used. See assertValidQueue(). + /// 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 @@ -649,10 +649,8 @@ public final class Database { // ========================================================================= // MARK: - Misc - func assertValidQueue() { - guard databaseQueueID == nil || databaseQueueID == dispatch_get_specific(DatabaseQueue.databaseQueueIDKey) else { - fatalError("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, use fetchAll() instead: it returns an Array that can be iterated on any thread.") - } + 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, use fetchAll() instead: it returns an Array that can be iterated on any thread.") } func setupForeignKeys() throws { diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 4613a49f9..aeae61c0d 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -197,9 +197,7 @@ public final class DatabaseQueue { // // I try not to ship half-baked solutions, so until a complete solution // is found to this problem, I prefer totally disabling reentrancy. - guard databaseQueueID != dispatch_get_specific(DatabaseQueue.databaseQueueIDKey) else { - fatalError("DatabaseQueue.inDatabase(_:) or DatabaseQueue.inTransaction(_:) was called reentrantly, which would lead to a deadlock.") - } + precondition(databaseQueueID != dispatch_get_specific(DatabaseQueue.databaseQueueIDKey), "DatabaseQueue.inDatabase(_:) or DatabaseQueue.inTransaction(_:) was called reentrantly, which would lead to a deadlock.") return try DatabaseQueue.dispatchSync(queue, block: block) } diff --git a/GRDB/Core/Protocols/DatabasePersistable.swift b/GRDB/Core/Protocols/DatabasePersistable.swift index a8ac8c68b..fa32cc071 100644 --- a/GRDB/Core/Protocols/DatabasePersistable.swift +++ b/GRDB/Core/Protocols/DatabasePersistable.swift @@ -515,9 +515,7 @@ final class DataMapper { // Fail early if persistentDictionary is empty let persistentDictionary = persistable.persistentDictionary - guard persistentDictionary.count > 0 else { - fatalError("Invalid empty dictionary returned from \(persistable.dynamicType).persistentDictionary") - } + precondition(persistentDictionary.count > 0, "Invalid empty dictionary returned from \(persistable.dynamicType).persistentDictionary") self.db = db self.persistable = persistable diff --git a/GRDB/Core/Protocols/DatabaseTableMapping.swift b/GRDB/Core/Protocols/DatabaseTableMapping.swift index e0f46a96e..f0739b51c 100644 --- a/GRDB/Core/Protocols/DatabaseTableMapping.swift +++ b/GRDB/Core/Protocols/DatabaseTableMapping.swift @@ -76,9 +76,7 @@ extension RowConvertible where Self: DatabaseTableMapping { // Fail early if database table has not one column in its primary key let columns = primaryKey.columns - guard columns.count == 1 else { - fatalError("Primary key of table \(databaseTableName.quotedDatabaseIdentifier) is not made of a single column. See \(self).databaseTableName()") - } + precondition(columns.count == 1, "Primary key of table \(databaseTableName.quotedDatabaseIdentifier) is not made of a single column. See \(self).databaseTableName()") let keys = keys.map { $0 as DatabaseValueConvertible? } @@ -160,10 +158,7 @@ extension RowConvertible where Self: DatabaseTableMapping { var arguments: [DatabaseValueConvertible?] = [] var whereClauses: [String] = [] for dictionary in keys { - guard dictionary.count > 0 else { - fatalError("Invalid empty key") - } - + precondition(dictionary.count > 0, "Invalid empty key dictionary") arguments.appendContentsOf(dictionary.values) whereClauses.append("(" + dictionary.keys.map { "\($0.quotedDatabaseIdentifier) = ?" }.joinWithSeparator(" AND ") + ")") } diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index a5db0a01f..0729f668a 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -65,9 +65,7 @@ public final class Row: CollectionType { /// - parameter index: A column index. /// - returns: An Int64, Double, String, NSData or nil. public func value(atIndex index: Int) -> DatabaseValueConvertible? { - guard index >= 0 && index < count else { - fatalError("Row index out of range") - } + precondition(index >= 0 && index < count, "Row index out of range") return impl .databaseValue(atIndex: index) .value() @@ -93,9 +91,7 @@ public final class Row: CollectionType { /// - parameter index: A column index. /// - returns: An optional *Value*. public func value(atIndex index: Int) -> Value? { - guard index >= 0 && index < count else { - fatalError("Row index out of range") - } + precondition(index >= 0 && index < count, "Row index out of range") return impl .databaseValue(atIndex: index) .value() @@ -126,9 +122,7 @@ public final class Row: CollectionType { /// - parameter index: A column index. /// - returns: An optional *Value*. public func value>(atIndex index: Int) -> Value? { - guard index >= 0 && index < count else { - fatalError("Row index out of range") - } + precondition(index >= 0 && index < count, "Row index out of range") let sqliteStatement = self.sqliteStatement if sqliteStatement != nil { // Metal row @@ -163,9 +157,7 @@ public final class Row: CollectionType { /// - parameter index: A column index. /// - returns: A *Value*. public func value(atIndex index: Int) -> Value { - guard index >= 0 && index < count else { - fatalError("Row index out of range") - } + precondition(index >= 0 && index < count, "Row index out of range") return impl .databaseValue(atIndex: index) .value() @@ -196,9 +188,7 @@ public final class Row: CollectionType { /// - parameter index: A column index. /// - returns: A *Value*. public func value>(atIndex index: Int) -> Value { - guard index >= 0 && index < count else { - fatalError("Row index out of range") - } + precondition(index >= 0 && index < count, "Row index out of range") let sqliteStatement = self.sqliteStatement if sqliteStatement != nil { // Metal row diff --git a/GRDB/Core/SelectStatement.swift b/GRDB/Core/SelectStatement.swift index 9c38bec96..19a47e3db 100644 --- a/GRDB/Core/SelectStatement.swift +++ b/GRDB/Core/SelectStatement.swift @@ -57,18 +57,18 @@ public struct DatabaseSequence: SequenceType { private init(statement: SelectStatement, yield: () -> T) { generateImpl = { - let assertValidQueue = statement.database.assertValidQueue + let preconditionValidQueue = statement.database.preconditionValidQueue let sqliteStatement = statement.sqliteStatement // Check that sequence is built on a valid queue. - assertValidQueue() + preconditionValidQueue() // DatabaseSequence can be restarted: statement.reset() return DatabaseGenerator { // Check that generator is used on a valid queue. - assertValidQueue() + preconditionValidQueue() let code = sqlite3_step(sqliteStatement) switch code { diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index e9cd9cffb..fe86f63e5 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -31,7 +31,7 @@ public class Statement { let database: Database init(database: Database, sql: String) throws { - database.assertValidQueue() + database.preconditionValidQueue() // See https://www.sqlite.org/c3ref/prepare.html @@ -149,9 +149,7 @@ public class Statement { final func setArgument(value: DatabaseValueConvertible?, forKey key: String) { let argumentName = ":\(key)" let index = Int(sqlite3_bind_parameter_index(sqliteStatement, argumentName)) - guard index > 0 else { - fatalError("Argument not found in SQLite statement: `\(argumentName)`") - } + precondition(index > 0, "Argument not found in SQLite statement: `\(argumentName)`") setArgument(value, atIndex: index) } diff --git a/GRDB/Migrations/DatabaseMigrator.swift b/GRDB/Migrations/DatabaseMigrator.swift index d354a4b90..6bc397ce6 100644 --- a/GRDB/Migrations/DatabaseMigrator.swift +++ b/GRDB/Migrations/DatabaseMigrator.swift @@ -92,9 +92,7 @@ public struct DatabaseMigrator { private var migrations: [Migration] = [] private mutating func registerMigration(migration: Migration) { - guard migrations.map({ $0.identifier }).indexOf(migration.identifier) == nil else { - fatalError("Already registered migration: \"\(migration.identifier)\"") - } + precondition(migrations.map({ $0.identifier }).indexOf(migration.identifier) == nil, "Already registered migration: \"\(migration.identifier)\"") migrations.append(migration) }