diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index 24a0be28e..90d31c490 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -5,7 +5,7 @@ import Foundation import SQLite3 #endif -public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible { +public struct ResultCode : RawRepresentable { public let rawValue: Int32 public init(rawValue: Int32) { @@ -25,24 +25,6 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible return self == primaryResultCode } - public var description: String { - // sqlite3_errstr was added in SQLite 3.7.15 http://www.sqlite.org/changes.html#version_3_7_15 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - #if GRDBCUSTOMSQLITE || GRDBCIPHER - return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))" - #else - if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, iOSApplicationExtension 8.2, *) { - return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))" - } else { - return "\(rawValue)" - } - #endif - } - - public static func == (_ lhs: ResultCode, _ rhs: ResultCode) -> Bool { - return lhs.rawValue == rhs.rawValue - } - /// Returns true if the code on the left matches the code on the right. /// /// Primary result codes match themselves and their extended result codes, @@ -155,7 +137,28 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible public static let SQLITE_WARNING_AUTOINDEX = ResultCode(rawValue: (SQLITE_WARNING.rawValue | (1<<8))) public static let SQLITE_AUTH_USER = ResultCode(rawValue: (SQLITE_AUTH.rawValue | (1<<8))) public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8))) +} +extension ResultCode : Equatable { + public static func == (_ lhs: ResultCode, _ rhs: ResultCode) -> Bool { + return lhs.rawValue == rhs.rawValue + } +} + +extension ResultCode : CustomStringConvertible { + public var description: String { + // sqlite3_errstr was added in SQLite 3.7.15 http://www.sqlite.org/changes.html#version_3_7_15 + // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + #if GRDBCUSTOMSQLITE || GRDBCIPHER + return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))" + #else + if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, iOSApplicationExtension 8.2, *) { + return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))" + } else { + return "\(rawValue)" + } + #endif + } } /// DatabaseError wraps an SQLite error. @@ -221,7 +224,6 @@ public struct DatabaseError : Error { } extension DatabaseError: CustomStringConvertible { - /// A textual representation of `self`. public var description: String { var description = "SQLite error \(resultCode.rawValue)" if let sql = sql { diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 08115b82b..6c93daa75 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -10,8 +10,25 @@ import Foundation /// A DatabasePool grants concurrent accesses to an SQLite database. public final class DatabasePool { + private let writer: SerializedDatabase + private var readerConfig: Configuration + private var readerPool: Pool! - // MARK: - Initializers + private var functions = Set() + private var collations = Set() + + #if os(iOS) + private weak var application: UIApplication? + #endif + + // MARK: - Database Information + + /// The path to the database. + public var path: String { + return writer.path + } + + // MARK: - Initializer /// Opens the SQLite database at path *path*. /// @@ -91,17 +108,11 @@ public final class DatabasePool { NotificationCenter.default.removeObserver(self) } #endif - - - // MARK: - Configuration - - /// The path to the database. - public var path: String { - return writer.path - } - - - // MARK: - WAL Management +} + +// MARK: - WAL Checkpoints + +extension DatabasePool { /// Runs a WAL checkpoint /// @@ -121,9 +132,11 @@ public final class DatabasePool { } } } - - - // MARK: - Memory management +} + +// MARK: - Memory management + +extension DatabasePool { /// Free as much memory as possible. /// @@ -155,8 +168,6 @@ public final class DatabasePool { center.addObserver(self, selector: #selector(DatabasePool.applicationDidEnterBackground(_:)), name: .UIApplicationDidEnterBackground, object: nil) } - private var application: UIApplication! - @objc private func applicationDidEnterBackground(_ notification: NSNotification) { guard let application = application else { return @@ -183,25 +194,12 @@ public final class DatabasePool { } } #endif - - - // MARK: - Not public - - private let writer: SerializedDatabase - private var readerConfig: Configuration - private var readerPool: Pool! = nil // var and nil-initialized so that we can use `self` when creating readerPool in DatabasePool.init() - - private var functions = Set() - private var collations = Set() } - -// ========================================================================= // MARK: - Encryption #if SQLITE_HAS_CODEC extension DatabasePool { - /// Changes the passphrase of an encrypted database public func change(passphrase: String) throws { try readerPool.clear(andThen: { @@ -212,8 +210,6 @@ public final class DatabasePool { } #endif - -// ========================================================================= // MARK: - DatabaseReader extension DatabasePool : DatabaseReader { @@ -417,8 +413,6 @@ extension DatabasePool : DatabaseReader { } } - -// ========================================================================= // MARK: - DatabaseWriter extension DatabasePool : DatabaseWriter { @@ -510,7 +504,6 @@ extension DatabasePool : DatabaseWriter { return try writer.reentrantSync(block) } - // MARK: - Reading from Database /// Asynchronously executes a read-only block in a protected dispatch queue, diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index a9268055d..59c829ea3 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -6,6 +6,22 @@ import UIKit /// A DatabaseQueue serializes access to an SQLite database. public final class DatabaseQueue { + private var serializedDatabase: SerializedDatabase + #if os(iOS) + private weak var application: UIApplication? + #endif + + // MARK: - Configuration + + /// The database configuration + public var configuration: Configuration { + return serializedDatabase.configuration + } + + /// The path to the database file; it is ":memory:" for in-memory databases. + public var path: String { + return serializedDatabase.path + } // MARK: - Initializers @@ -50,22 +66,11 @@ public final class DatabaseQueue { NotificationCenter.default.removeObserver(self) } #endif - - - // MARK: - Configuration - - /// The database configuration - public var configuration: Configuration { - return serializedDatabase.configuration - } - - /// The path to the database file; it is ":memory:" for in-memory databases. - public var path: String { - return serializedDatabase.path - } - - - // MARK: - Database access +} + +// MARK: - Database Access + +extension DatabaseQueue { /// Synchronously executes a block in a protected dispatch queue, and /// returns its result. @@ -111,9 +116,11 @@ public final class DatabaseQueue { } } } - - - // MARK: - Memory management +} + +// MARK: - Memory management + +extension DatabaseQueue { /// Free as much memory as possible. /// @@ -124,7 +131,6 @@ public final class DatabaseQueue { inDatabase { $0.releaseMemory() } } - #if os(iOS) /// Listens to UIApplicationDidEnterBackgroundNotification and /// UIApplicationDidReceiveMemoryWarningNotification in order to release @@ -140,8 +146,6 @@ public final class DatabaseQueue { center.addObserver(self, selector: #selector(DatabaseQueue.applicationDidEnterBackground(_:)), name: .UIApplicationDidEnterBackground, object: nil) } - private var application: UIApplication? - @objc private func applicationDidEnterBackground(_ notification: NSNotification) { guard let application = application else { return @@ -168,37 +172,13 @@ public final class DatabaseQueue { } } #endif - - - // MARK: - Not public - - // https://www.sqlite.org/isolation.html - // - // > Within a single database connection X, a SELECT statement always - // > sees all changes to the database that are completed prior to the - // > start of the SELECT statement, whether committed or uncommitted. - // > And the SELECT statement obviously does not see any changes that - // > occur after the SELECT statement completes. But what about changes - // > that occur while the SELECT statement is running? What if a SELECT - // > statement is started and the sqlite3_step() interface steps through - // > roughly half of its output, then some UPDATE statements are run by - // > the application that modify the table that the SELECT statement is - // > reading, then more calls to sqlite3_step() are made to finish out - // > the SELECT statement? Will the later steps of the SELECT statement - // > see the changes made by the UPDATE or not? The answer is that this - // > behavior is undefined. - // - // This is why we use a serialized database: - private var serializedDatabase: SerializedDatabase } - -// ========================================================================= // MARK: - Encryption #if SQLITE_HAS_CODEC extension DatabaseQueue { - + /// Changes the passphrase of an encrypted database public func change(passphrase: String) throws { try inDatabase { try $0.change(passphrase: passphrase) } @@ -207,7 +187,6 @@ public final class DatabaseQueue { #endif -// ========================================================================= // MARK: - DatabaseReader extension DatabaseQueue : DatabaseReader { @@ -307,8 +286,6 @@ extension DatabaseQueue : DatabaseReader { } } - -// ========================================================================= // MARK: - DatabaseWriter extension DatabaseQueue : DatabaseWriter { @@ -356,19 +333,13 @@ extension DatabaseQueue : DatabaseWriter { } } -// Wraps the block between two `PRAGMA query_only` statements. -// -// This method is unsafe because the two calls to `PRAGMA query_only` are -// not guaranteed to be serialized (some other thread could mess with this). private func readOnly(_ db: Database, _ block: (Database) throws -> T) rethrows -> T { - if db.configuration.readonly { + guard !db.configuration.readonly else { return try block(db) - } else { - try! db.execute("PRAGMA query_only = 1") // Assume can't fail - let result = try block(db) - try! db.execute("PRAGMA query_only = 0") // Assume can't fail - return result } + + // Assume those pragmas never fail + try! db.execute("PRAGMA query_only = 1") + defer { try! db.execute("PRAGMA query_only = 0") } + return try block(db) } - - diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index a57373076..57b7aee3d 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -11,6 +11,11 @@ import Foundation /// /// See https://www.sqlite.org/datatype3.html public struct DatabaseValue { + /// The SQLite storage + public let storage: Storage + + /// The NULL DatabaseValue. + public static let null = DatabaseValue(storage: .null) /// An SQLite storage (NULL, INTEGER, REAL, TEXT, BLOB). public enum Storage : Equatable { @@ -62,12 +67,6 @@ public struct DatabaseValue { } } - /// The SQLite storage - public let storage: Storage - - /// The NULL DatabaseValue. - public static let null = DatabaseValue(storage: .null) - /// Creates a DatabaseValue from Any. /// /// The result is nil unless object adopts DatabaseValueConvertible. @@ -78,7 +77,6 @@ public struct DatabaseValue { self = convertible.databaseValue } - // MARK: - Extracting Value /// Returns true if databaseValue is NULL. @@ -91,7 +89,6 @@ public struct DatabaseValue { } } - // MARK: - Not Public init(storage: Storage) { @@ -147,10 +144,8 @@ public struct DatabaseValue { } } - // MARK: - Hashable & Equatable -/// DatabaseValue adopts Hashable. extension DatabaseValue : Hashable { /// The hash value @@ -207,7 +202,6 @@ extension DatabaseValue : Hashable { } } - // MARK: - Lossless conversions extension DatabaseValue { @@ -286,10 +280,6 @@ extension DatabaseValue { } } - -// MARK: - DatabaseValueConvertible & SQLExpressible & SQLExpression - -/// DatabaseValue adopts DatabaseValueConvertible. extension DatabaseValue : DatabaseValueConvertible { /// Returns self public var databaseValue: DatabaseValue { @@ -303,14 +293,12 @@ extension DatabaseValue : DatabaseValueConvertible { } extension DatabaseValue : SQLExpressible { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) public var sqlExpression: SQLExpression { return self } } -/// DatabaseValue adopts SQLExpression. extension DatabaseValue : SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) public func expressionSQL(_ arguments: inout StatementArguments?) -> String { @@ -355,11 +343,7 @@ extension DatabaseValue : SQLExpression { } } -// MARK: - CustomStringConvertible - -/// DatabaseValue adopts CustomStringConvertible. extension DatabaseValue : CustomStringConvertible { - /// A textual representation of `self`. public var description: String { switch storage { case .null: diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index aa102d37a..eeed050b9 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -30,9 +30,7 @@ public protocol DatabaseValueConvertible : SQLExpressible { static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? } -// SQLExpressible adoption extension DatabaseValueConvertible { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) public var sqlExpression: SQLExpression { return databaseValue @@ -132,7 +130,6 @@ public final class NullableDatabaseValueCursor /// DatabaseValueConvertible is adopted by Bool, Int, String, etc. extension DatabaseValueConvertible { - // MARK: Fetching From SelectStatement /// Returns a cursor over values fetched from a prepared statement. diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 540130e20..2b0e84740 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -7,6 +7,21 @@ import Foundation /// A database row. public final class Row { + let impl: RowImpl + + /// Unless we are producing a row array, we use a single row when iterating + /// a statement: + /// + /// let rows = try Row.fetchCursor(db, "SELECT ...") + /// let players = try Player.fetchAll(db, "SELECT ...") + /// + /// This row keeps an unmanaged reference to the statement, and a handle to + /// the sqlite statement, so that we avoid many retain/release invocations. + /// + /// The statementRef is released in deinit. + let statementRef: Unmanaged? + let sqliteStatement: SQLiteStatement? + /// The number of columns in the row. public let count: Int @@ -51,26 +66,11 @@ public final class Row { // MARK: - Not Public - let impl: RowImpl - /// Returns true if and only if the row was fetched from a database. var isFetched: Bool { return impl.isFetched } - /// Unless we are producing a row array, we use a single row when iterating - /// a statement: - /// - /// let rows = try Row.fetchCursor(db, "SELECT ...") - /// let players = try Player.fetchAll(db, "SELECT ...") - /// - /// This row keeps an unmanaged reference to the statement, and a handle to - /// the sqlite statement, so that we avoid many retain/release invocations. - /// - /// The statementRef is released in deinit. - let statementRef: Unmanaged? - let sqliteStatement: SQLiteStatement? - deinit { statementRef?.release() } @@ -830,7 +830,6 @@ extension Row : Hashable { /// Row adopts CustomStringConvertible. extension Row: CustomStringConvertible { - /// A textual representation of `self`. public var description: String { return " String in String(cString: sqlite3_column_name(sqliteStatement, Int32(index))) } + return (0.. StatementCursor { return StatementCursor(statement: self, arguments: arguments) } - + + /// Utility function for cursors + func cursorReset(arguments: StatementArguments? = nil) { + SchedulingWatchdog.preconditionValidQueue(database) + prepare(withArguments: arguments) + reset() + } + /// Information about the table and columns read by a SelectStatement public struct SelectionInfo : CustomStringConvertible { + /// Selection is unknown when a statement uses the COUNT function, + /// and SQLite version < 3.19: + /// + /// `SELECT COUNT(*) FROM t1` -> unknown selection + private let isUnknown: Bool + + /// `SELECT a, b FROM t1` -> ["t1": ["a", "b"]] + private var columns: [String: Set] = [:] + + /// `SELECT COUNT(*) FROM t1` -> ["t1"] + private var tables: Set = [] + + /// The unknown selection + static let unknown = SelectionInfo(isUnknown: true) + mutating func insert(allColumnsOfTable table: String) { tables.insert(table) } @@ -335,24 +350,10 @@ public final class SelectStatement : Statement, AuthorizedStatement { self.init(isUnknown: false) } - static func unknown() -> SelectionInfo { - return self.init(isUnknown: true) - } - - /// If true, selection is unknown - private let isUnknown: Bool - - // `SELECT a, b FROM t1` -> ["t1": ["a", "b"]] - private var columns: [String: Set] = [:] - - // `SELECT COUNT(*) FROM t1` -> ["t1"] - private var tables: Set = [] - private init(isUnknown: Bool) { self.isUnknown = isUnknown } - /// A textual representation of `self`. public var description: String { if isUnknown { return "unknown" @@ -900,7 +901,6 @@ extension StatementArguments : ExpressibleByDictionaryLiteral { } extension StatementArguments : CustomStringConvertible { - /// A textual representation of `self`. public var description: String { let valuesDescriptions = values.map { $0.description } let namedValuesDescriptions = namedValues.map { (key, value) -> String in diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index 0d55151d1..a6efe2167 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -126,7 +126,7 @@ final class StatementCompilationAuthorizer : StatementAuthorizer { guard sqlite3_libversion_number() < 3019000 else { return SQLITE_OK } guard let cString2 = cString2 else { return SQLITE_OK } if sqlite3_stricmp(cString2, "COUNT") == 0 { - selectionInfo = .unknown() + selectionInfo = .unknown } return SQLITE_OK diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index 8755c6e13..0ddfbbfbf 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -1004,8 +1004,6 @@ public enum FetchedRecordChange { } extension FetchedRecordChange: CustomStringConvertible { - - /// A textual representation of `self`. public var description: String { switch self { case .insertion(let indexPath): diff --git a/GRDB/Record/Persistable.swift b/GRDB/Record/Persistable.swift index 697d78d36..253e11e39 100644 --- a/GRDB/Record/Persistable.swift +++ b/GRDB/Record/Persistable.swift @@ -21,7 +21,6 @@ public enum PersistenceError: Error { } extension PersistenceError : CustomStringConvertible { - /// A textual representation of `self`. public var description: String { switch self { case .recordNotFound(let persistable):