diff --git a/.swiftlint.yml b/.swiftlint.yml new file mode 100644 index 000000000..9b7be2474 --- /dev/null +++ b/.swiftlint.yml @@ -0,0 +1,57 @@ +included: + - GRDB + +disabled_rules: + - cyclomatic_complexity + - file_length + - force_cast + - force_try + - function_body_length + - function_parameter_count + - identifier_name + - is_disjoint + - nesting + - opening_brace + - redundant_optional_initialization + - syntactic_sugar + - todo + - trailing_comma + - trailing_whitespace + - type_body_length + - type_name + - unused_setter_value + +opt_in_rules: + - anyobject_protocol + - array_init + - attributes + - closure_spacing + - collection_alignment + - contains_over_first_not_nil + - convenience_type + - empty_count + - empty_string + - explicit_init + - fatal_error_message + - first_where + - joined_default_parameter + - last_where + - legacy_multiple + - legacy_random + - modifier_order + - no_extension_access_modifier + - overridden_super_call + - pattern_matching_keywords + - prohibited_super_call + - reduce_into + - redundant_type_annotation + - sorted_first_last + - toggle_bool + - unused_declaration + - unused_import + - unused_private_declaration + - yoda_condition + +vertical_whitespace: + max_empty_lines: 2 + diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e6b4e37d..05c33ffcb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,6 +55,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: ## Next Release - [#562](https://github.com/groue/GRDB.swift/pull/562): Fix crash when using more than one DatabaseCollation +- [#574](https://github.com/groue/GRDB.swift/pull/574): SwiftLint ## 4.1.1 diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme index e7450b0c6..7c6bbd3a9 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme @@ -1,6 +1,6 @@ ())? - var SQLiteConnectionWillClose: ((SQLiteConnection) -> ())? - var SQLiteConnectionDidClose: (() -> ())? + var SQLiteConnectionDidOpen: (() -> Void)? + var SQLiteConnectionWillClose: ((SQLiteConnection) -> Void)? + var SQLiteConnectionDidClose: (() -> Void)? var SQLiteOpenFlags: Int32 { let readWriteFlags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE) return threadingMode.SQLiteOpenFlags | readWriteFlags diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index 51ef3b303..95705d5a2 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -29,7 +29,10 @@ extension Sequence { /// Returns a cursor over the concatenated results of mapping transform /// over self. - public func flatMap(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor, SegmentOfResult>> { + public func flatMap( + _ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) + -> FlattenCursor, SegmentOfResult>> + { return AnyCursor(self).flatMap(transform) } } @@ -76,7 +79,7 @@ extension Set { /// `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, /// `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, /// `suffix`. -public protocol Cursor : class { +public protocol Cursor: AnyObject { /// The type of element traversed by the cursor. associatedtype Element @@ -141,7 +144,9 @@ extension Cursor { /// Returns a cursor over the concatenated non-nil results of mapping /// transform over this cursor. - public func compactMap(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor>, ElementOfResult> { + public func compactMap(_ transform: @escaping (Element) throws -> ElementOfResult?) + -> MapCursor>, ElementOfResult> + { return map(transform).filter { $0 != nil }.map { $0! } } @@ -190,7 +195,7 @@ extension Cursor { public func dropFirst() -> DropFirstCursor { return dropFirst(1) } - + /// Returns an array containing all but the given number of final /// elements. /// @@ -243,13 +248,19 @@ extension Cursor { /// Returns a cursor over the concatenated results of mapping transform /// over self. - public func flatMap(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor>> { + public func flatMap(_ transform: @escaping (Element) throws -> SegmentOfResult) + -> FlattenCursor>> + where SegmentOfResult: Sequence + { return flatMap { try AnyCursor(transform($0)) } } /// Returns a cursor over the concatenated results of mapping transform /// over self. - public func flatMap(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor> { + public func flatMap(_ transform: @escaping (Element) throws -> SegmentOfResult) + -> FlattenCursor> + where SegmentOfResult: Cursor + { return map(transform).joined() } @@ -503,7 +514,7 @@ extension Cursor where Element: StringProtocol { /// This cursor forwards its next() method to an arbitrary underlying cursor /// having the same Element type, hiding the specifics of the underlying /// cursor. -public final class AnyCursor : Cursor { +public final class AnyCursor: Cursor { private let element: () throws -> Element? /// Creates a cursor that wraps a base cursor but whose type depends only on @@ -539,11 +550,11 @@ public final class AnyCursor : Cursor { } /// :nodoc: -public final class DropFirstCursor : Cursor { +public final class DropFirstCursor: Cursor { private let base: Base private let limit: Int private var dropped: Int = 0 - + init(_ base: Base, limit: Int) { GRDBPrecondition(limit >= 0, "Can't drop a negative number of elements from a cursor") self.base = base @@ -566,7 +577,7 @@ public final class DropFirstCursor : Cursor { /// consecutive elements of some base cursor that satisfy a given predicate. /// /// :nodoc: -public final class DropWhileCursor : Cursor { +public final class DropWhileCursor: Cursor { private let base: Base private let predicate: (Base.Element) throws -> Bool private var predicateHasFailed = false @@ -605,7 +616,7 @@ public final class DropWhileCursor : Cursor { /// // Prints: "1: bar" /// /// :nodoc: -public final class EnumeratedCursor : Cursor { +public final class EnumeratedCursor: Cursor { private let base: Base private var index: Int @@ -628,7 +639,7 @@ public final class EnumeratedCursor : Cursor { /// also satisfy a given predicate. /// /// :nodoc: -public final class FilterCursor : Cursor { +public final class FilterCursor: Cursor { private let base: Base private let isIncluded: (Base.Element) throws -> Bool @@ -656,7 +667,7 @@ public final class FilterCursor : Cursor { /// See Cursor.joined(), Cursor.flatMap(_:), Sequence.flatMap(_:) /// /// :nodoc: -public final class FlattenCursor : Cursor where Base.Element: Cursor { +public final class FlattenCursor: Cursor where Base.Element: Cursor { private let base: Base private var inner: Base.Element? @@ -686,7 +697,7 @@ public final class FlattenCursor : Cursor where Base.Element: Curs /// See Cursor.map(_:) /// /// :nodoc: -public final class MapCursor : Cursor { +public final class MapCursor: Cursor { private let base: Base private let transform: (Base.Element) throws -> Element @@ -708,7 +719,7 @@ public final class MapCursor : Cursor { /// `Base` cursor. /// /// :nodoc: -public final class PrefixCursor : Cursor { +public final class PrefixCursor: Cursor { private let base: Base private let maxLength: Int private var taken = 0 @@ -735,7 +746,7 @@ public final class PrefixCursor : Cursor { /// some base cursor that satisfy a given predicate. /// /// :nodoc: -public final class PrefixWhileCursor : Cursor { +public final class PrefixWhileCursor: Cursor { private let base: Base private let predicate: (Base.Element) throws -> Bool private var predicateHasFailed = false diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 0155a214e..71e0b773a 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -1,15 +1,15 @@ #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif extension Database { - + // MARK: - Database Schema - + /// Clears the database schema cache. /// /// You may need to clear the cache manually if the database schema is @@ -71,7 +71,7 @@ extension Database { .names(ofType: type) .contains { $0.lowercased() == name } } - + /// The primary key for table named `tableName`. /// /// All tables have a primary key, even when it is not explicit. When a @@ -203,7 +203,12 @@ extension Database { /// True if a sequence of columns uniquely identifies a row, that is to say /// if the columns are the primary key, or if there is a unique index on them. - public func table(_ tableName: String, hasUniqueKey columns: T) throws -> Bool where T.Iterator.Element == String { + public func table( + _ tableName: String, + hasUniqueKey columns: T) + throws -> Bool + where T.Iterator.Element == String + { return try columnsForUniqueKey(Array(columns), in: tableName) != nil } @@ -213,7 +218,9 @@ extension Database { return foreignKeys } - var rawForeignKeys: [(destinationTable: String, mapping: [(origin: String, destination: String?, seq: Int)])] = [] + var rawForeignKeys: [( + destinationTable: String, + mapping: [(origin: String, destination: String?, seq: Int)])] = [] var previousId: Int? = nil for row in try Row.fetchAll(self, sql: "PRAGMA foreign_key_list(\(tableName.quotedDatabaseIdentifier))") { // row = [id:0 seq:0 table:"parents" from:"parentId" to:"id" on_update:"..." on_delete:"..." match:"..."] @@ -224,9 +231,13 @@ extension Database { let destination: String? = row[4] if previousId == id { - rawForeignKeys[rawForeignKeys.count - 1].mapping.append((origin: origin, destination: destination, seq: seq)) + rawForeignKeys[rawForeignKeys.count - 1] + .mapping + .append((origin: origin, destination: destination, seq: seq)) } else { - rawForeignKeys.append((destinationTable: table, mapping: [(origin: origin, destination: destination, seq: seq)])) + rawForeignKeys.append(( + destinationTable: table, + mapping: [(origin: origin, destination: destination, seq: seq)])) previousId = id } } @@ -281,7 +292,7 @@ extension Database { } extension Database { - + /// The columns in the table named `tableName` /// /// - throws: A DatabaseError if table does not exist. @@ -313,7 +324,7 @@ extension Database { // 0 | id | INTEGER | 0 | NULL | 1 | // 1 | name | TEXT | 0 | NULL | 0 | // 2 | score | INTEGER | 0 | NULL | 0 | - + if sqlite3_libversion_number() < 3008005 { // Work around a bug in SQLite where PRAGMA table_info would // return a result even after the table was deleted. @@ -324,7 +335,7 @@ extension Database { let columns = try ColumnInfo .fetchAll(self, sql: "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))") .sorted(by: { $0.cid < $1.cid }) - guard columns.count > 0 else { + if columns.isEmpty { throw DatabaseError(message: "no such table: \(tableName)") } @@ -335,14 +346,25 @@ extension Database { /// If there exists a unique key on columns, return the columns /// ordered as the matching index (or primay key). Case of returned columns /// is not guaranteed. - func columnsForUniqueKey(_ columns: T, in tableName: String) throws -> [String]? where T.Iterator.Element == String { - let primaryKey = try self.primaryKey(tableName) // first, so that we fail early and consistently should the table not exist + func columnsForUniqueKey( + _ columns: T, + in tableName: String) + throws -> [String]? + where T.Iterator.Element == String + { + // Check primaryKey first, so that we fail early if the table does not exist + let primaryKey = try self.primaryKey(tableName) let lowercasedColumns = Set(columns.map { $0.lowercased() }) if Set(primaryKey.columns.map { $0.lowercased() }) == lowercasedColumns { return primaryKey.columns } - if let index = try indexes(on: tableName).first(where: { index in index.isUnique && Set(index.columns.map { $0.lowercased() }) == lowercasedColumns }) { - // There is an explicit unique index on the columns + + // Is there is an explicit unique index on the columns? + let indexes = try self.indexes(on: tableName) + let matchingIndex = indexes.first { index in + index.isUnique && Set(index.columns.map { $0.lowercased() }) == lowercasedColumns + } + if let index = matchingIndex { return index.columns } return nil @@ -366,7 +388,7 @@ extension Database { /// 2 score INTEGER 0 NULL 0 /// /// See `Database.columns(in:)` and https://www.sqlite.org/pragma.html#pragma_table_info -public struct ColumnInfo : FetchableRecord { +public struct ColumnInfo: FetchableRecord { let cid: Int /// The column name diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 1553dbf62..8b39b5643 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -1,10 +1,10 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif extension Database { @@ -213,13 +213,15 @@ extension Database { // Check that all arguments were consumed: it is a programmer error to // provide arguments that do not match the statement. if arguments.values.isEmpty == false { - throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)") + throw DatabaseError( + resultCode: .SQLITE_MISUSE, + message: "wrong number of statement arguments: \(initialValuesCount)") } } } extension Database { - + func updateStatementWillExecute(_ statement: UpdateStatement) { observationBroker.updateStatementWillExecute(statement) } @@ -294,7 +296,7 @@ struct StatementCache { selectStatements[sql] = statement return statement } - + mutating func updateStatement(_ sql: String) throws -> UpdateStatement { if let statement = updateStatements[sql] { return statement diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index ee308af24..5d5b9b27b 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1,10 +1,10 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// A raw SQLite connection, suitable for the SQLite C API. @@ -36,7 +36,7 @@ public final class Database { public let sqliteConnection: SQLiteConnection // MARK: - Configuration - + /// The error logging function. /// /// Quoting https://www.sqlite.org/errlog.html: @@ -53,7 +53,7 @@ public final class Database { if logError != nil { registerErrorLogCallback { (_, code, message) in guard let logError = Database.logError else { return } - guard let message = message.map({ String(cString: $0) }) else { return } + guard let message = message.map(String.init) else { return } let resultCode = ResultCode(rawValue: code) logError(resultCode, message) } @@ -137,11 +137,14 @@ public final class Database { sqlite3_set_authorizer(sqliteConnection, nil, nil) case (nil, .some): let dbPointer = Unmanaged.passUnretained(self).toOpaque() - sqlite3_set_authorizer(sqliteConnection, { (dbPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in - guard let dbPointer = dbPointer else { return SQLITE_OK } - let db = Unmanaged.fromOpaque(dbPointer).takeUnretainedValue() - return db.authorizer!.authorize(actionCode, cString1, cString2, cString3, cString4) - }, dbPointer) + sqlite3_set_authorizer( + sqliteConnection, + { (dbPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in + guard let dbPointer = dbPointer else { return SQLITE_OK } + let db = Unmanaged.fromOpaque(dbPointer).takeUnretainedValue() + return db.authorizer!.authorize(actionCode, cString1, cString2, cString3, cString4) + }, + dbPointer) default: break } @@ -164,9 +167,9 @@ public final class Database { private var collations = Set() private var _readOnlyDepth = 0 // Modify with beginReadOnly/endReadOnly private var isClosed: Bool = false - + // MARK: - Initializer - + init(path: String, configuration: Configuration, schemaCache: DatabaseSchemaCache) throws { self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags) self.configuration = configuration @@ -179,7 +182,7 @@ public final class Database { } extension Database { - + // MARK: - Database Opening private static func openConnection(path: String, flags: Int32) throws -> SQLiteConnection { @@ -207,7 +210,7 @@ extension Database { } extension Database { - + // MARK: - Database Setup /// This method must be called after database initialization @@ -220,14 +223,14 @@ extension Database { setupDefaultCollations() observationBroker.installCommitAndRollbackHooks() try activateExtendedCodes() - + #if SQLITE_HAS_CODEC try validateSQLCipher() if let passphrase = configuration.passphrase { try setCipherPassphrase(passphrase) } #endif - + // Last step before we can start accessing the database. // This is the opportunity to run SQLCipher configuration // pragmas such as cipher_page_size, for example. @@ -240,24 +243,34 @@ extension Database { guard configuration.trace != nil else { return } - // sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0 http://www.sqlite.org/changes.html#version_3_14 - // It is available from iOS 10.0 and OS X 10.12 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + // sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0 + // http://www.sqlite.org/changes.html#version_3_14 + // It is available from iOS 10.0 and OS X 10.12 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) #if GRDBCUSTOMSQLITE || GRDBCIPHER - let dbPointer = Unmanaged.passUnretained(self).toOpaque() - sqlite3_trace_v2(sqliteConnection, UInt32(SQLITE_TRACE_STMT), { (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in - return Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql) - }, dbPointer) + let dbPointer = Unmanaged.passUnretained(self).toOpaque() + sqlite3_trace_v2( + sqliteConnection, + UInt32(SQLITE_TRACE_STMT), + { (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in + Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql) + }, + dbPointer) #elseif os(Linux) - setupTrace_v1() + setupTrace_v1() #else - if #available(iOS 10.0, OSX 10.12, watchOS 3.0, *) { - let dbPointer = Unmanaged.passUnretained(self).toOpaque() - sqlite3_trace_v2(sqliteConnection, UInt32(SQLITE_TRACE_STMT), { (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in - return Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql) - }, dbPointer) - } else { - setupTrace_v1() - } + if #available(iOS 10.0, OSX 10.12, watchOS 3.0, *) { + let dbPointer = Unmanaged.passUnretained(self).toOpaque() + sqlite3_trace_v2( + sqliteConnection, + UInt32(SQLITE_TRACE_STMT), + { (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in + Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql) + }, + dbPointer) + } else { + setupTrace_v1() + } #endif } @@ -265,7 +278,7 @@ extension Database { private func setupTrace_v1() { let dbPointer = Unmanaged.passUnretained(self).toOpaque() sqlite3_trace(sqliteConnection, { (dbPointer, sql) in - guard let sql = sql.map({ String(cString: $0) }) else { return } + guard let sql = sql.map(String.init) else { return } let db = Unmanaged.fromOpaque(dbPointer!).takeUnretainedValue() db.configuration.trace!(sql) }, dbPointer) @@ -391,7 +404,7 @@ extension Database { } extension Database { - + // MARK: - Database Closing /// This method must be called before database deallocation @@ -409,18 +422,19 @@ extension Database { private static func closeConnection(_ sqliteConnection: SQLiteConnection) { // sqlite3_close_v2 was added in SQLite 3.7.14 http://www.sqlite.org/changes.html#version_3_7_14 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + // 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 - closeConnection_v2(sqliteConnection, sqlite3_close_v2) + closeConnection_v2(sqliteConnection, sqlite3_close_v2) #else - if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) { - closeConnection_v2(sqliteConnection, sqlite3_close_v2) - } else { - closeConnection_v1(sqliteConnection) - } + if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) { + closeConnection_v2(sqliteConnection, sqlite3_close_v2) + } else { + closeConnection_v1(sqliteConnection) + } #endif } - + private static func closeConnection_v1(_ sqliteConnection: SQLiteConnection) { // https://www.sqlite.org/c3ref/close.html // > If the database connection is associated with unfinalized prepared @@ -466,7 +480,7 @@ extension Database { } extension Database { - + // MARK: - Functions /// Add or redefine an SQL function. @@ -492,7 +506,7 @@ extension Database { } extension Database { - + // MARK: - Collations /// Add or redefine a collation. @@ -539,7 +553,8 @@ extension Database { _readOnlyDepth += 1 if _readOnlyDepth == 1 && configuration.readonly == false { // PRAGMA query_only was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + // It is available from iOS 8.2 and OS X 10.10 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) try internalCachedUpdateStatement(sql: "PRAGMA query_only = 1").execute() } } @@ -548,7 +563,8 @@ extension Database { _readOnlyDepth -= 1 if _readOnlyDepth == 0 && configuration.readonly == false { // PRAGMA query_only was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + // It is available from iOS 8.2 and OS X 10.10 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) try internalCachedUpdateStatement(sql: "PRAGMA query_only = 0").execute() } } @@ -583,7 +599,7 @@ extension Database { } extension Database { - + // MARK: - Transactions & Savepoint /// Executes a block inside a database transaction. @@ -640,7 +656,7 @@ extension Database { } } } - + if let firstError = firstError { throw firstError } @@ -674,7 +690,7 @@ extension Database { if !isInsideTransaction && configuration.defaultTransactionKind != .deferred { return try inTransaction(configuration.defaultTransactionKind, block) } - + // If the savepoint is top-level, we'll use ROLLBACK TRANSACTION in // order to perform the special error handling of rollbacks (see // the rollback method). @@ -849,7 +865,7 @@ extension Database { } extension Database { - + // MARK: - Memory Management func releaseMemory() { @@ -864,12 +880,18 @@ extension Database { // MARK: - Backup - static func backup(from dbFrom: Database, to dbDest: Database, afterBackupInit: (() -> ())? = nil, afterBackupStep: (() -> ())? = nil) throws { + static func backup( + from dbFrom: Database, + to dbDest: Database, + afterBackupInit: (() -> Void)? = nil, + afterBackupStep: (() -> Void)? = nil) + throws + { guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", dbFrom.sqliteConnection, "main") else { throw DatabaseError(resultCode: dbDest.lastErrorCode, message: dbDest.lastErrorMessage) } guard Int(bitPattern: backup) != Int(SQLITE_ERROR) else { - throw DatabaseError(resultCode: .SQLITE_ERROR) + throw DatabaseError() } afterBackupInit?() @@ -904,35 +926,36 @@ extension Database { } #if SQLITE_HAS_CODEC - extension Database { - - // MARK: - Encryption - - func change(passphrase: String) throws { - // FIXME: sqlite3_rekey is discouraged. - // - // https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320 - // - // > We (Zetetic) have been discouraging the use of sqlite3_rekey in - // > favor of attaching a new database with the desired encryption - // > options and using sqlcipher_export() to migrate the contents and - // > schema of the original db into the new one: - // > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/ - let data = passphrase.data(using: .utf8)! - #if swift(>=5.0) - let code = data.withUnsafeBytes { - sqlite3_rekey(sqliteConnection, $0.baseAddress, Int32($0.count)) - } - #else - let code = data.withUnsafeBytes { - sqlite3_rekey(sqliteConnection, $0, Int32(data.count)) - } - #endif - guard code == SQLITE_OK else { - throw DatabaseError(resultCode: code, message: lastErrorMessage) - } +extension Database { + + // MARK: - Encryption + + func change(passphrase: String) throws { + // FIXME: sqlite3_rekey is discouraged. + // + // https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320 + // + // > We (Zetetic) have been discouraging the use of sqlite3_rekey in + // > favor of attaching a new database with the desired encryption + // > options and using sqlcipher_export() to migrate the contents and + // > schema of the original db into the new one: + // > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/ + // swiftlint:disable:previous line_length + let data = passphrase.data(using: .utf8)! + #if swift(>=5.0) + let code = data.withUnsafeBytes { + sqlite3_rekey(sqliteConnection, $0.baseAddress, Int32($0.count)) + } + #else + let code = data.withUnsafeBytes { + sqlite3_rekey(sqliteConnection, $0, Int32(data.count)) + } + #endif + guard code == SQLITE_OK else { + throw DatabaseError(resultCode: code, message: lastErrorMessage) } } +} #endif extension Database { @@ -991,7 +1014,7 @@ extension Database { /// A built-in SQLite collation. /// /// See https://www.sqlite.org/datatype3.html#collation - public struct CollationName : RawRepresentable, Hashable { + public struct CollationName: RawRepresentable, Hashable { /// :nodoc: public let rawValue: String @@ -1022,7 +1045,7 @@ extension Database { /// } /// /// See https://www.sqlite.org/datatype3.html - public struct ColumnType : RawRepresentable, Hashable { + public struct ColumnType: RawRepresentable, Hashable { /// :nodoc: public let rawValue: String @@ -1063,7 +1086,7 @@ extension Database { /// An SQLite conflict resolution. /// /// See https://www.sqlite.org/lang_conflict.html. - public enum ConflictResolution : String { + public enum ConflictResolution: String { case rollback = "ROLLBACK" case abort = "ABORT" case fail = "FAIL" @@ -1074,7 +1097,7 @@ extension Database { /// A foreign key action. /// /// See https://www.sqlite.org/foreignkeys.html - public enum ForeignKeyAction : String { + public enum ForeignKeyAction: String { case cascade = "CASCADE" case restrict = "RESTRICT" case setNull = "SET NULL" @@ -1091,7 +1114,7 @@ extension Database { } /// An SQLite transaction kind. See https://www.sqlite.org/lang_transaction.html - public enum TransactionKind : String { + public enum TransactionKind: String { case deferred = "DEFERRED" case immediate = "IMMEDIATE" case exclusive = "EXCLUSIVE" diff --git a/GRDB/Core/DatabaseCollation.swift b/GRDB/Core/DatabaseCollation.swift index d94780412..0b182fd94 100644 --- a/GRDB/Core/DatabaseCollation.swift +++ b/GRDB/Core/DatabaseCollation.swift @@ -1,10 +1,10 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// A Collation is a string comparison function used by SQLite. @@ -27,8 +27,16 @@ public final class DatabaseCollation { self.name = name self.function = { (length1, buffer1, length2, buffer2) in // Buffers are not C strings: they do not end with \0. - let string1 = String(bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped), length: Int(length1), encoding: .utf8, freeWhenDone: false)! - let string2 = String(bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped), length: Int(length2), encoding: .utf8, freeWhenDone: false)! + let string1 = String( + bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped), + length: Int(length1), + encoding: .utf8, + freeWhenDone: false)! + let string2 = String( + bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped), + length: Int(length2), + encoding: .utf8, + freeWhenDone: false)! return function(string1, string2) } } diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index 2ed6eab62..308f2d28b 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -1,13 +1,13 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif -public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible { +public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible { public let rawValue: Int32 public init(rawValue: Int32) { @@ -48,6 +48,7 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible // Primary Result codes // https://www.sqlite.org/rescode.html#primary_result_code_list + // swiftlint:disable operator_usage_whitespace public static let SQLITE_OK = ResultCode(rawValue: 0) // Successful result public static let SQLITE_ERROR = ResultCode(rawValue: 1) // SQL error or missing database public static let SQLITE_INTERNAL = ResultCode(rawValue: 2) // Internal logic error in SQLite @@ -79,10 +80,12 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible public static let SQLITE_WARNING = ResultCode(rawValue: 28) // Warnings from sqlite3_log() public static let SQLITE_ROW = ResultCode(rawValue: 100) // sqlite3_step() has another row ready public static let SQLITE_DONE = ResultCode(rawValue: 101) // sqlite3_step() has finished executing + // swiftlint:enable operator_usage_whitespace // Extended Result Code // https://www.sqlite.org/rescode.html#extended_result_code_list + // swiftlint:disable operator_usage_whitespace public static let SQLITE_IOERR_READ = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (1<<8))) public static let SQLITE_IOERR_SHORT_READ = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (2<<8))) public static let SQLITE_IOERR_WRITE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (3<<8))) @@ -139,21 +142,23 @@ 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))) + // swiftlint:enable operator_usage_whitespace } // CustomStringConvertible extension ResultCode { var errorString: 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) + // 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 String(cString: sqlite3_errstr(rawValue)) + return String(cString: sqlite3_errstr(rawValue)) #else - if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) { - return String(cString: sqlite3_errstr(rawValue)) - } else { - return nil - } + if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) { + return String(cString: sqlite3_errstr(rawValue)) + } else { + return nil + } #endif } @@ -168,7 +173,7 @@ extension ResultCode { } /// DatabaseError wraps an SQLite error. -public struct DatabaseError : Error, CustomStringConvertible, CustomNSError { +public struct DatabaseError: Error, CustomStringConvertible, CustomNSError { /// The SQLite error code (see /// https://www.sqlite.org/rescode.html#primary_result_code_list). @@ -207,7 +212,12 @@ public struct DatabaseError : Error, CustomStringConvertible, CustomNSError { public let sql: String? /// Creates a Database Error - public init(resultCode: ResultCode = .SQLITE_ERROR, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) { + public init( + resultCode: ResultCode = .SQLITE_ERROR, + message: String? = nil, + sql: String? = nil, + arguments: StatementArguments? = nil) + { self.extendedResultCode = resultCode self.message = message ?? resultCode.errorString self.sql = sql @@ -264,7 +274,7 @@ extension DatabaseError { /// NSError bridging: the user-info dictionary. /// :nodoc: - public var errorUserInfo: [String : Any] { + public var errorUserInfo: [String: Any] { return [NSLocalizedDescriptionKey: description] } } diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index 0a9f4e036..6827ca0ae 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -1,9 +1,9 @@ #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// An SQL function or aggregate. @@ -44,7 +44,12 @@ public final class DatabaseFunction: Hashable { /// 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: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?) { + public init( + _ name: String, + argumentCount: Int32? = nil, + pure: Bool = false, + function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?) + { self.identity = Identity(name: name, nArg: argumentCount ?? -1) self.pure = pure self.kind = .function{ (argc, argv) in @@ -94,10 +99,15 @@ public final class DatabaseFunction: Hashable { /// an array of DatabaseValue arguments. The array is guaranteed to /// have exactly *argumentCount* elements, provided *argumentCount* is /// not nil. - public init(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, aggregate: Aggregate.Type) { + public init( + _ name: String, + argumentCount: Int32? = nil, + pure: Bool = false, + aggregate: Aggregate.Type) + { self.identity = Identity(name: name, nArg: argumentCount ?? -1) self.pure = pure - self.kind = .aggregate { return Aggregate() } + self.kind = .aggregate { Aggregate() } } /// Calls sqlite3_create_function_v2 @@ -197,7 +207,9 @@ public final class DatabaseFunction: Hashable { var xFunc: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer?) -> Void)? { guard case .function = self else { return nil } return { (sqliteContext, argc, argv) in - let definition = Unmanaged.fromOpaque(sqlite3_user_data(sqliteContext)).takeUnretainedValue() + let definition = Unmanaged + .fromOpaque(sqlite3_user_data(sqliteContext)) + .takeUnretainedValue() do { try DatabaseFunction.report( result: definition.compute(argc, argv), @@ -262,11 +274,15 @@ public final class DatabaseFunction: Hashable { private static func unmanagedAggregateContext(_ sqliteContext: OpaquePointer?) -> Unmanaged { // The current aggregate buffer let stride = MemoryLayout>.stride - let aggregateContextBufferP = UnsafeMutableRawBufferPointer(start: sqlite3_aggregate_context(sqliteContext, Int32(stride))!, count: stride) + let aggregateContextBufferP = UnsafeMutableRawBufferPointer( + start: sqlite3_aggregate_context(sqliteContext, Int32(stride))!, + count: stride) if aggregateContextBufferP.contains(where: { $0 != 0 }) { // TODO: This testt looks weird. Review. // Buffer contains non-null pointer: load aggregate context - let aggregateContextP = aggregateContextBufferP.baseAddress!.assumingMemoryBound(to: Unmanaged.self) + let aggregateContextP = aggregateContextBufferP + .baseAddress! + .assumingMemoryBound(to: Unmanaged.self) return aggregateContextP.pointee } else { // Buffer contains null pointer: create aggregate context... diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 5d9eb114d..2cc913f07 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -1,14 +1,14 @@ import Foundation import Dispatch #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif #if os(iOS) - import UIKit +import UIKit #endif /// A DatabasePool grants concurrent accesses to an SQLite database. @@ -79,7 +79,10 @@ public final class DatabasePool: DatabaseWriter { // opens a pool to an existing non-WAL database, and // attempts to read from it. // See https://github.com/groue/GRDB.swift/issues/102 - try db.execute(sql: "CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY); DROP TABLE grdb_issue_102;") + try db.execute(sql: """ + CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY); + DROP TABLE grdb_issue_102; + """) } } } @@ -87,8 +90,13 @@ public final class DatabasePool: DatabaseWriter { // Readers readerConfig = configuration readerConfig.readonly = true - readerConfig.defaultTransactionKind = .deferred // Make it the default for readers. Other transaction kinds are forbidden by SQLite in read-only connections. - readerConfig.allowsUnsafeTransactions = false // Because there's no guarantee that one can get the same reader in order to close its opened transaction. + // Readers use deferred transactions by default. + // Other transaction kinds are forbidden by SQLite in read-only connections. + readerConfig.defaultTransactionKind = .deferred + // Readers can't allow dangling transactions because there's no + // guarantee that one can get the same reader later in order to close + // an opened transaction. + readerConfig.allowsUnsafeTransactions = false var readerCount = 0 readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: { [unowned self] in readerCount += 1 // protected by pool's ReadWriteBox (undocumented behavior and protection) @@ -134,9 +142,9 @@ public final class DatabasePool: DatabaseWriter { } extension DatabasePool { - + // MARK: - WAL Checkpoints - + /// Runs a WAL checkpoint /// /// See https://www.sqlite.org/wal.html and @@ -151,16 +159,16 @@ extension DatabasePool { // when kind is not .Passive. let code = sqlite3_wal_checkpoint_v2(db.sqliteConnection, nil, kind.rawValue, nil, nil) guard code == SQLITE_OK else { - throw DatabaseError(resultCode: code, message: db.lastErrorMessage, sql: nil) + throw DatabaseError(resultCode: code, message: db.lastErrorMessage) } } } } extension DatabasePool { - + // MARK: - Memory management - + /// Free as much memory as possible. /// /// This method blocks the current thread until all database accesses are completed. @@ -195,7 +203,8 @@ extension DatabasePool { object: nil) } - @objc private func applicationDidEnterBackground(_ notification: NSNotification) { + @objc + private func applicationDidEnterBackground(_ notification: NSNotification) { guard let application = application else { return } @@ -213,7 +222,8 @@ extension DatabasePool { } } - @objc private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) { + @objc + private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) { DispatchQueue.global().async { self.releaseMemory() } @@ -222,24 +232,24 @@ extension DatabasePool { } #if SQLITE_HAS_CODEC - extension DatabasePool { - - // MARK: - Encryption - - /// Changes the passphrase of an encrypted database - public func change(passphrase: String) throws { - try readerPool.clear(andThen: { - try writer.sync { try $0.change(passphrase: passphrase) } - readerConfig.passphrase = passphrase - }) - } +extension DatabasePool { + + // MARK: - Encryption + + /// Changes the passphrase of an encrypted database + public func change(passphrase: String) throws { + try readerPool.clear(andThen: { + try writer.sync { try $0.change(passphrase: passphrase) } + readerConfig.passphrase = passphrase + }) } +} #endif -extension DatabasePool : DatabaseReader { +extension DatabasePool: DatabaseReader { // MARK: - Reading from Database - + /// Synchronously executes a read-only block in a protected dispatch queue, /// and returns its result. The block is wrapped in a deferred transaction. /// @@ -493,7 +503,7 @@ extension DatabasePool : DatabaseReader { asyncConcurrentRead(block) } #endif - + #if compiler(>=5.0) /// Asynchronously executes a read-only block in a protected dispatch queue. /// @@ -649,7 +659,11 @@ extension DatabasePool : DatabaseReader { /// - updates: The updates to the database. /// - throws: The error thrown by the updates, or by the /// wrapping transaction. - public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ updates: (Database) throws -> Database.TransactionCompletion) throws { + public func writeInTransaction( + _ kind: Database.TransactionKind? = nil, + _ updates: (Database) throws -> Database.TransactionCompletion) + throws + { try writer.sync { db in try db.inTransaction(kind) { try updates(db) @@ -811,7 +825,9 @@ extension DatabasePool { // Sanity check if writer.onValidQueue { writer.execute { db in - GRDBPrecondition(!db.isInsideTransaction, "makeSnapshot() must not be called from inside a transaction.") + GRDBPrecondition( + !db.isInsideTransaction, + "makeSnapshot() must not be called from inside a transaction.") } } diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index a4286bc20..791a2f132 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -71,9 +71,9 @@ public final class DatabaseQueue: DatabaseWriter { } extension DatabaseQueue { - + // MARK: - Memory management - + /// Free as much memory as possible. /// /// This method blocks the current thread until all database accesses are completed. @@ -106,7 +106,8 @@ extension DatabaseQueue { object: nil) } - @objc private func applicationDidEnterBackground(_ notification: NSNotification) { + @objc + private func applicationDidEnterBackground(_ notification: NSNotification) { guard let application = application else { return } @@ -124,7 +125,8 @@ extension DatabaseQueue { } } - @objc private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) { + @objc + private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) { DispatchQueue.global().async { self.releaseMemory() } @@ -133,15 +135,15 @@ extension DatabaseQueue { } #if SQLITE_HAS_CODEC - extension DatabaseQueue { - - // MARK: - Encryption - - /// Changes the passphrase of an encrypted database - public func change(passphrase: String) throws { - try writer.sync { try $0.change(passphrase: passphrase) } - } +extension DatabaseQueue { + + // MARK: - Encryption + + /// Changes the passphrase of an encrypted database + public func change(passphrase: String) throws { + try writer.sync { try $0.change(passphrase: passphrase) } } +} #endif extension DatabaseQueue { @@ -202,7 +204,7 @@ extension DatabaseQueue { } } #endif - + /// Synchronously executes a block in a protected dispatch queue, and /// returns its result. /// @@ -302,7 +304,11 @@ extension DatabaseQueue { /// - updates: The updates to the database. /// - throws: The error thrown by the updates, or by the /// wrapping transaction. - public func inTransaction(_ kind: Database.TransactionKind? = nil, _ updates: (Database) throws -> Database.TransactionCompletion) throws { + public func inTransaction( + _ kind: Database.TransactionKind? = nil, + _ updates: (Database) throws -> Database.TransactionCompletion) + throws + { try writer.sync { db in try db.inTransaction(kind) { try updates(db) @@ -323,7 +329,7 @@ extension DatabaseQueue { public func writeWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { return try writer.sync(updates) } - + /// Synchronously executes database updates in a protected dispatch queue, /// outside of any transaction, and returns the result. /// diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index f9a9fd664..ffad142a8 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -1,9 +1,9 @@ #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// The protocol for all types that can fetch values from a database. @@ -21,7 +21,7 @@ /// connection to the database. Should you have to cope with external /// connections, protect yourself with transactions, and be ready to setup a /// [busy handler](https://www.sqlite.org/c3ref/busy_handler.html). -public protocol DatabaseReader : class { +public protocol DatabaseReader: AnyObject { /// The database configuration var configuration: Configuration { get } @@ -220,10 +220,14 @@ extension DatabaseReader { try backup(to: writer, afterBackupInit: nil, afterBackupStep: nil) } - func backup(to writer: DatabaseWriter, afterBackupInit: (() -> ())?, afterBackupStep: (() -> ())?) throws { + func backup(to writer: DatabaseWriter, afterBackupInit: (() -> Void)?, afterBackupStep: (() -> Void)?) throws { try read { dbFrom in try writer.writeWithoutTransaction { dbDest in - try Database.backup(from: dbFrom, to: dbDest, afterBackupInit: afterBackupInit, afterBackupStep: afterBackupStep) + try Database.backup( + from: dbFrom, + to: dbDest, + afterBackupInit: afterBackupInit, + afterBackupStep: afterBackupStep) } } } @@ -233,7 +237,7 @@ extension DatabaseReader { /// /// Instances of AnyDatabaseReader forward their methods to an arbitrary /// underlying database reader. -public final class AnyDatabaseReader : DatabaseReader { +public final class AnyDatabaseReader: DatabaseReader { private let base: DatabaseReader /// Creates a database reader that wraps a base database reader. diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 7df10aa59..c754ca697 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -31,6 +31,7 @@ /// let region = try request.databaseRegion(db) public struct DatabaseRegion: CustomStringConvertible, Equatable { private let tableRegions: [String: TableRegion]? + private init(tableRegions: [String: TableRegion]?) { self.tableRegions = tableRegions } @@ -125,9 +126,9 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable { switch (tableRegion, otherTableRegion) { case (nil, nil): preconditionFailure() - case (nil, let tableRegion?), (let tableRegion?, nil): + case let (nil, tableRegion?), let (tableRegion?, nil): tableRegionUnion = tableRegion - case (let tableRegion?, let otherTableRegion?): + case let (tableRegion?, otherTableRegion?): tableRegionUnion = tableRegion.union(otherTableRegion) } tableRegionsUnion[table] = tableRegionUnion @@ -184,7 +185,10 @@ extension DatabaseRegion { // Slow path when several tables are observed. guard let tableRegion = tableRegions[event.tableName] else { // Shouldn't happen if the precondition is met. - fatalError("precondition failure: event was not filtered out in observes(eventsOfKind:) by region.isModified(byEventsOfKind:)") + fatalError(""" + precondition failure: event was not filtered out in observes(eventsOfKind:) \ + by region.isModified(byEventsOfKind:) + """) } return tableRegion.contains(rowID: event.rowID) } @@ -198,16 +202,14 @@ extension DatabaseRegion { switch (lhs.tableRegions, rhs.tableRegions) { case (nil, nil): return true - case (let ltableRegions?, let rtableRegions?): + case let (ltableRegions?, rtableRegions?): let ltableNames = Set(ltableRegions.keys) let rtableNames = Set(rtableRegions.keys) guard ltableNames == rtableNames else { return false } - for tableName in ltableNames { - if ltableRegions[tableName]! != rtableRegions[tableName]! { - return false - } + for tableName in ltableNames where ltableRegions[tableName]! != rtableRegions[tableName]! { + return false } return true default: @@ -257,17 +259,17 @@ private struct TableRegion: Equatable { func intersection(_ other: TableRegion) -> TableRegion { let columnsIntersection: Set? switch (self.columns, other.columns) { - case (nil, let columns), (let columns, nil): + case let (nil, columns), let (columns, nil): columnsIntersection = columns - case (let columns?, let other?): + case let (columns?, other?): columnsIntersection = columns.intersection(other) } let rowIdsIntersection: Set? switch (self.rowIds, other.rowIds) { - case (nil, let rowIds), (let rowIds, nil): + case let (nil, rowIds), let (rowIds, nil): rowIdsIntersection = rowIds - case (let rowIds?, let other?): + case let (rowIds?, other?): rowIdsIntersection = rowIds.intersection(other) } @@ -279,7 +281,7 @@ private struct TableRegion: Equatable { switch (self.columns, other.columns) { case (nil, _), (_, nil): columnsUnion = nil - case (let columns?, let other?): + case let (columns?, other?): columnsUnion = columns.union(other) } @@ -287,7 +289,7 @@ private struct TableRegion: Equatable { switch (self.rowIds, other.rowIds) { case (nil, _), (_, nil): rowIdsUnion = nil - case (let rowIds?, let other?): + case let (rowIds?, other?): rowIdsUnion = rowIds.union(other) } diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index a55fd2b3f..847525b53 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -18,7 +18,7 @@ public struct DatabaseRegionObservation { /// A closure that is evaluated when the observation starts, and returns /// the observed database region. var observedRegion: (Database) throws -> DatabaseRegion - + // Not public because we foster DatabaseRegionConvertible. init(tracking region: @escaping (Database) throws -> DatabaseRegion) { self.observedRegion = { db in @@ -87,7 +87,11 @@ extension DatabaseRegionObservation { /// - parameter onChange: A closure that is provided a database connection /// with write access each time the observed region has been modified. /// - returns: a TransactionObserver - public func start(in dbWriter: DatabaseWriter, onChange: @escaping (Database) -> Void) throws -> TransactionObserver { + public func start( + in dbWriter: DatabaseWriter, + onChange: @escaping (Database) -> Void) + throws -> TransactionObserver + { // Use unsafeReentrantWrite so that observation can start from any // dispatch queue. return try dbWriter.unsafeReentrantWrite { db -> TransactionObserver in @@ -123,7 +127,7 @@ private class DatabaseRegionObserver: TransactionObserver { func databaseDidCommit(_ db: Database) { guard isChanged else { return } isChanged = false - + onChange(db) } diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 6cef0ca48..094423cf2 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -6,7 +6,7 @@ import Dispatch /// See DatabasePool.makeSnapshot() /// /// For more information, read about "snapshot isolation" at https://sqlite.org/isolation.html -public class DatabaseSnapshot : DatabaseReader { +public class DatabaseSnapshot: DatabaseReader { private var serializedDatabase: SerializedDatabase /// The database configuration diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index b4b84dfc2..aee43d0f6 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -1,10 +1,10 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif // MARK: - DatabaseValue @@ -20,7 +20,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon public static let null = DatabaseValue(storage: .null) /// An SQLite storage (NULL, INTEGER, REAL, TEXT, BLOB). - public enum Storage : Equatable { + public enum Storage: Equatable { /// The NULL storage class. case null @@ -60,10 +60,10 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon public static func == (_ lhs: Storage, _ rhs: Storage) -> Bool { switch (lhs, rhs) { case (.null, .null): return true - case (.int64(let lhs), .int64(let rhs)): return lhs == rhs - case (.double(let lhs), .double(let rhs)): return lhs == rhs - case (.string(let lhs), .string(let rhs)): return lhs == rhs - case (.blob(let lhs), .blob(let rhs)): return lhs == rhs + case let (.int64(lhs), .int64(rhs)): return lhs == rhs + case let (.double(lhs), .double(rhs)): return lhs == rhs + case let (.string(lhs), .string(rhs)): return lhs == rhs + case let (.blob(lhs), .blob(rhs)): return lhs == rhs default: return false } } @@ -120,7 +120,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon fatalError("Unexpected SQLite value type: \(type)") } } - + /// Returns a DatabaseValue initialized from a raw SQLite statement pointer. init(sqliteStatement: SQLiteStatement, index: Int32) { switch sqlite3_column_type(sqliteStatement, index) { @@ -187,17 +187,17 @@ extension DatabaseValue { switch (lhs.storage, rhs.storage) { case (.null, .null): return true - case (.int64(let lhs), .int64(let rhs)): + case let (.int64(lhs), .int64(rhs)): return lhs == rhs - case (.double(let lhs), .double(let rhs)): + case let (.double(lhs), .double(rhs)): return lhs == rhs - case (.int64(let lhs), .double(let rhs)): + case let (.int64(lhs), .double(rhs)): return Int64(exactly: rhs) == lhs - case (.double(let lhs), .int64(let rhs)): + case let (.double(lhs), .int64(rhs)): return rhs == Int64(exactly: lhs) - case (.string(let lhs), .string(let rhs)): + case let (.string(lhs), .string(rhs)): return lhs == rhs - case (.blob(let lhs), .blob(let rhs)): + case let (.blob(lhs), .blob(rhs)): return lhs == rhs default: return false @@ -266,8 +266,10 @@ extension DatabaseValue { case .blob: // We can't assume all blobs are true, and return false: // - // SELECT NOT X'31' -- 0 (because X'31' is turned into the string '1', then into integer 1, which is negated into 0) - // SELECT NOT X'30' -- 1 (because X'30' is turned into the string '0', then into integer 0, which is negated into 1) + // SELECT NOT X'31' -- 0 (because X'31' is turned into the string '1', + // then into integer 1, which is negated into 0) + // SELECT NOT X'30' -- 1 (because X'30' is turned into the string '0', + // then into integer 0, which is negated into 1) return SQLExpressionNot(self) } } @@ -309,17 +311,17 @@ extension DatabaseValue { /// easier testing. func < (lhs: DatabaseValue, rhs: DatabaseValue) -> Bool { switch (lhs.storage, rhs.storage) { - case (.int64(let lhs), .int64(let rhs)): + case let (.int64(lhs), .int64(rhs)): return lhs < rhs - case (.double(let lhs), .double(let rhs)): + case let (.double(lhs), .double(rhs)): return lhs < rhs - case (.int64(let lhs), .double(let rhs)): + case let (.int64(lhs), .double(rhs)): return Double(lhs) < rhs - case (.double(let lhs), .int64(let rhs)): + case let (.double(lhs), .int64(rhs)): return lhs < Double(rhs) - case (.string(let lhs), .string(let rhs)): + case let (.string(lhs), .string(rhs)): return lhs.utf8.lexicographicallyPrecedes(rhs.utf8) - case (.blob(let lhs), .blob(let rhs)): + case let (.blob(lhs), .blob(rhs)): return lhs.lexicographicallyPrecedes(rhs, by: <) case (.blob, _): return false diff --git a/GRDB/Core/DatabaseValueConversion.swift b/GRDB/Core/DatabaseValueConversion.swift index a752e34e5..ca59df531 100644 --- a/GRDB/Core/DatabaseValueConversion.swift +++ b/GRDB/Core/DatabaseValueConversion.swift @@ -1,9 +1,9 @@ #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif // MARK: - Conversion Context and Errors @@ -14,6 +14,7 @@ struct ValueConversionContext { case columnIndex(Int) case columnName(String) } + var row: Row? var sql: String? var arguments: StatementArguments? @@ -89,7 +90,12 @@ extension ValueConversionContext { /// The canonical conversion error message /// /// - parameter dbValue: nil means "missing column" -func conversionErrorMessage(to: T.Type, from dbValue: DatabaseValue?, conversionContext: ValueConversionContext?) -> String { +func conversionErrorMessage( + to: T.Type, + from dbValue: DatabaseValue?, + conversionContext: ValueConversionContext?) + -> String +{ var message: String var extras: [String] = [] @@ -128,12 +134,33 @@ func conversionErrorMessage(to: T.Type, from dbValue: DatabaseValue?, convers /// The canonical conversion fatal error /// /// - parameter dbValue: nil means "missing column", for consistency with (row["missing"] as DatabaseValue? == nil) -func fatalConversionError(to: T.Type, from dbValue: DatabaseValue?, conversionContext: ValueConversionContext?, file: StaticString = #file, line: UInt = #line) -> Never { - fatalError(conversionErrorMessage(to: T.self, from: dbValue, conversionContext: conversionContext), file: file, line: line) +func fatalConversionError( + to: T.Type, + from dbValue: DatabaseValue?, + conversionContext: ValueConversionContext?, + file: StaticString = #file, + line: UInt = #line) + -> Never +{ + fatalError( + conversionErrorMessage( + to: T.self, + from: dbValue, + conversionContext: conversionContext), + file: file, + line: line) } @usableFromInline -func fatalConversionError(to: T.Type, from dbValue: DatabaseValue?, in row: Row, atColumn columnName: String, file: StaticString = #file, line: UInt = #line) -> Never { +func fatalConversionError( + to: T.Type, + from dbValue: DatabaseValue?, + in row: Row, + atColumn columnName: String, + file: StaticString = #file, + line: UInt = #line) + -> Never +{ fatalConversionError( to: T.self, from: dbValue, @@ -141,7 +168,14 @@ func fatalConversionError(to: T.Type, from dbValue: DatabaseValue?, in row: R } @usableFromInline -func fatalConversionError(to: T.Type, sqliteStatement: SQLiteStatement, index: Int32, file: StaticString = #file, line: UInt = #line) -> Never { +func fatalConversionError( + to: T.Type, + sqliteStatement: SQLiteStatement, + index: Int32, + file: StaticString = #file, + line: UInt = #line) + -> Never +{ let row = Row(sqliteStatement: sqliteStatement) fatalConversionError( to: T.self, @@ -150,7 +184,15 @@ func fatalConversionError(to: T.Type, sqliteStatement: SQLiteStatement, index } @usableFromInline -func fatalConversionError(to: T.Type, from dbValue: DatabaseValue?, sqliteStatement: SQLiteStatement, index: Int32, file: StaticString = #file, line: UInt = #line) -> Never { +func fatalConversionError( + to: T.Type, + from dbValue: DatabaseValue?, + sqliteStatement: SQLiteStatement, + index: Int32, + file: StaticString = #file, + line: UInt = #line) + -> Never +{ let row = Row(sqliteStatement: sqliteStatement) fatalConversionError( to: T.self, @@ -172,7 +214,11 @@ extension DatabaseValueConvertible { } } - static func decode(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Self { + static func decode( + from dbValue: DatabaseValue, + conversionContext: @autoclosure () -> ValueConversionContext?) + -> Self + { if let value = fromDatabaseValue(dbValue) { return value } else { @@ -198,8 +244,12 @@ extension DatabaseValueConvertible { fatalConversionError(to: Self.self, from: dbValue, sqliteStatement: sqliteStatement, index: index) } } - - static func decodeIfPresent(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Self? { + + static func decodeIfPresent( + from dbValue: DatabaseValue, + conversionContext: @autoclosure () -> ValueConversionContext?) + -> Self? + { // Use fromDatabaseValue before checking for null: this allows DatabaseValue to convert NULL to .null. if let value = fromDatabaseValue(dbValue) { return value @@ -258,12 +308,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { // Support for @inlinable decoding extension Row { @usableFromInline - func fastDecode(_ type: Value.Type, atUncheckedIndex index: Int) -> Value { + func fastDecode( + _ type: Value.Type, + atUncheckedIndex index: Int) + -> Value + { return impl.fastDecode(type, atUncheckedIndex: index) } @usableFromInline - func fastDecodeIfPresent(_ type: Value.Type, atUncheckedIndex index: Int) -> Value? { + func fastDecodeIfPresent( + _ type: Value.Type, + atUncheckedIndex index: Int) + -> Value? + { return impl.fastDecodeIfPresent(type, atUncheckedIndex: index) } } diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 30cc1753f..936b1da73 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -1,9 +1,9 @@ #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif // MARK: - DatabaseValueConvertible @@ -24,7 +24,7 @@ /// try String.fetchOne(statement, arguments:...) // String? /// /// DatabaseValueConvertible is adopted by Bool, Int, String, etc. -public protocol DatabaseValueConvertible : SQLExpressible { +public protocol DatabaseValueConvertible: SQLExpressible { /// Returns a value that can be stored in the database. var databaseValue: DatabaseValue { get } @@ -49,7 +49,7 @@ extension DatabaseValueConvertible { /// print(url) /// } /// } -public final class DatabaseValueCursor : Cursor { +public final class DatabaseValueCursor: Cursor { @usableFromInline let _statement: SelectStatement @usableFromInline let _sqliteStatement: SQLiteStatement @usableFromInline let _columnIndex: Int32 @@ -102,12 +102,12 @@ public final class DatabaseValueCursor : Cursor /// print(url) /// } /// } -public final class NullableDatabaseValueCursor : Cursor { +public final class NullableDatabaseValueCursor: Cursor { @usableFromInline let _statement: SelectStatement @usableFromInline let _sqliteStatement: SQLiteStatement @usableFromInline let _columnIndex: Int32 @usableFromInline var _done = false - + init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { _statement = statement _sqliteStatement = statement.sqliteStatement @@ -182,7 +182,12 @@ extension DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor { + public static func fetchCursor( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> DatabaseValueCursor + { return try DatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) } @@ -197,7 +202,12 @@ extension DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: An array. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { + public static func fetchAll( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Self] + { return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } @@ -215,7 +225,12 @@ extension DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { + public static func fetchOne( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> Self? + { // fetchOne returns nil if there is no row, or if there is a row with a null value let cursor = try NullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) return try cursor.next() ?? nil @@ -223,7 +238,7 @@ extension DatabaseValueConvertible { } extension DatabaseValueConvertible { - + // MARK: Fetching From SQL /// Returns a cursor over values fetched from an SQL query. @@ -245,7 +260,13 @@ extension DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DatabaseValueCursor { + public static func fetchCursor( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> DatabaseValueCursor + { return try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -260,7 +281,13 @@ extension DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: An array. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self] { + public static func fetchAll( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> [Self] + { return try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -278,7 +305,13 @@ extension DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self? { + public static func fetchOne( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> Self? + { return try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } } @@ -430,7 +463,12 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor { + public static func fetchCursor( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> NullableDatabaseValueCursor + { return try NullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) } @@ -445,7 +483,12 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: An array of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] { + public static func fetchAll( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Wrapped?] + { return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } } @@ -473,7 +516,13 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor { + public static func fetchCursor( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> NullableDatabaseValueCursor + { return try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -488,7 +537,13 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: An array of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Wrapped?] { + public static func fetchAll( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> [Wrapped?] + { return try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } } @@ -515,7 +570,9 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// - request: A FetchRequest. /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: R) throws -> NullableDatabaseValueCursor { + public static func fetchCursor(_ db: Database, _ request: R) + throws -> NullableDatabaseValueCursor + { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchCursor(request.statement, adapter: request.adapter) } @@ -572,4 +629,3 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: return try Optional.fetchAll(db, self) } } - diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 1dbc6c740..20da6b446 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -15,10 +15,10 @@ import Dispatch /// connection to the database. Should you have to cope with external /// connections, protect yourself with transactions, and be ready to setup a /// [busy handler](https://www.sqlite.org/c3ref/busy_handler.html). -public protocol DatabaseWriter : DatabaseReader { +public protocol DatabaseWriter: DatabaseReader { // MARK: - Writing in Database - + /// Synchronously executes database updates in a protected dispatch queue, /// wrapped inside a transaction, and returns the result. /// @@ -76,16 +76,18 @@ public protocol DatabaseWriter : DatabaseReader { /// - parameter completion: A closure that is called with the eventual /// transaction error. /// - throws: The error thrown by the updates, or by the wrapping transaction. - func asyncWrite(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result) -> Void) + func asyncWrite( + _ updates: @escaping (Database) throws -> T, + completion: @escaping (Database, Result) -> Void) #endif - + /// Asynchronously executes database updates in a protected dispatch queue, /// outside of any transaction. /// /// Eventual concurrent reads may see partial updates unless you wrap them /// in a transaction. func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) - + /// Synchronously executes database updates in a protected dispatch queue, /// outside of any transaction, and returns the result. /// @@ -98,7 +100,7 @@ public protocol DatabaseWriter : DatabaseReader { /// This method is reentrant. It should be avoided because it fosters /// dangerous concurrency practices. func unsafeReentrantWrite(_ updates: (Database) throws -> T) rethrows -> T - + // MARK: - Reading from Database /// Concurrently executes a read-only block in a protected dispatch queue. @@ -175,7 +177,7 @@ public protocol DatabaseWriter : DatabaseReader { } extension DatabaseWriter { - + /// Synchronously executes database updates in a protected dispatch queue, /// wrapped inside a transaction, and returns the result. /// @@ -228,7 +230,10 @@ extension DatabaseWriter { /// - parameter completion: A closure that is called with the eventual /// transaction error. /// - throws: The error thrown by the updates, or by the wrapping transaction. - public func asyncWrite(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result) -> Void) { + public func asyncWrite( + _ updates: @escaping (Database) throws -> T, + completion: @escaping (Database, Result) -> Void) + { asyncWriteWithoutTransaction { db in do { var result: T? @@ -255,7 +260,10 @@ extension DatabaseWriter { /// - parameter extent: The duration of the observation. The default is /// the observer lifetime (observation lasts until observer /// is deallocated). - public func add(transactionObserver: TransactionObserver, extent: Database.TransactionObservationExtent = .observerLifetime) { + public func add( + transactionObserver: TransactionObserver, + extent: Database.TransactionObservationExtent = .observerLifetime) + { writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) } } @@ -273,7 +281,8 @@ extension DatabaseWriter { /// execution of this method. public func erase() throws { #if SQLITE_HAS_CODEC - // SQLCipher does not support the backup API: https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631 + // SQLCipher does not support the backup API: + // https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631 // So we'll drop all database objects one after the other. try writeWithoutTransaction { db in // Prevent foreign keys from messing with drop table statements @@ -285,7 +294,8 @@ extension DatabaseWriter { // Remove all database objects, one after the other do { try db.inTransaction { - while let row = try Row.fetchOne(db, sql: "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'") { + let sql = "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'" + while let row = try Row.fetchOne(db, sql: sql) { let type: String = row["type"] let name: String = row["name"] try db.execute(sql: "DROP \(type) \(name.quotedDatabaseIdentifier)") @@ -545,7 +555,7 @@ public class DatabaseFuture { /// /// Instances of AnyDatabaseWriter forward their methods to an arbitrary /// underlying database writer. -public final class AnyDatabaseWriter : DatabaseWriter { +public final class AnyDatabaseWriter: DatabaseWriter { private let base: DatabaseWriter /// Creates a database writer that wraps a base database writer. @@ -608,7 +618,10 @@ public final class AnyDatabaseWriter : DatabaseWriter { #if compiler(>=5.0) /// :nodoc: - public func asyncWrite(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result) -> Void) { + public func asyncWrite( + _ updates: @escaping (Database) throws -> T, + completion: @escaping (Database, Result) -> Void) + { base.asyncWrite(updates, completion: completion) } #endif @@ -617,12 +630,12 @@ public final class AnyDatabaseWriter : DatabaseWriter { public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { base.asyncWriteWithoutTransaction(updates) } - + /// :nodoc: public func unsafeReentrantWrite(_ updates: (Database) throws -> T) rethrows -> T { return try base.unsafeReentrantWrite(updates) } - + // MARK: - Functions /// :nodoc: diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index d0abb0e6a..02a7925d2 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -23,7 +23,7 @@ public struct PreparedRequest { { self.init(statement: statement, adapter: adapter, supplementaryFetch: nil) } - + init( statement: SelectStatement, adapter: RowAdapter?, @@ -62,7 +62,7 @@ public protocol FetchRequest: DatabaseRegionConvertible { /// prepared statement. /// - returns: A prepared statement and an eventual row adapter. func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) - + /// Returns a PreparedRequest that is ready to be executed. /// /// - parameter db: A database connection. @@ -86,7 +86,7 @@ public protocol FetchRequest: DatabaseRegionConvertible { } extension FetchRequest { - + /// Returns an adapted request. public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest { return AdaptedFetchRequest(self, adapter) @@ -134,7 +134,7 @@ extension FetchRequest { // MARK: - AdaptedFetchRequest /// An adapted request. -public struct AdaptedFetchRequest : FetchRequest { +public struct AdaptedFetchRequest: FetchRequest { public typealias RowDecoder = Base.RowDecoder private let base: Base @@ -175,7 +175,7 @@ public struct AdaptedFetchRequest : FetchRequest { /// /// An AnyFetchRequest forwards its operations to an underlying request, /// hiding its specifics. -public struct AnyFetchRequest : FetchRequest { +public struct AnyFetchRequest: FetchRequest { public typealias RowDecoder = T private let _preparedRequest: (Database, _ singleResult: Bool) throws -> PreparedRequest diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 28734b9e9..7f8c0d4ff 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -1,14 +1,17 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// A database row. -public final class Row : Equatable, Hashable, RandomAccessCollection, ExpressibleByDictionaryLiteral, CustomStringConvertible, CustomDebugStringConvertible { +public final class Row: Equatable, Hashable, RandomAccessCollection, + ExpressibleByDictionaryLiteral, CustomStringConvertible, + CustomDebugStringConvertible +{ // It is not a violation of the Demeter law when another type uses this // property, which is exposed for optimizations. let impl: RowImpl @@ -45,7 +48,7 @@ public final class Row : Equatable, Hashable, RandomAccessCollection, Expressibl /// let bookRows = row.prefetchedRows["books"] /// print(bookRows[0]) /// // Prints [id:42 title:"Moby-Dick"] - public internal(set) var prefetchedRows: PrefetchedRowsView = PrefetchedRowsView() + public internal(set) var prefetchedRows = PrefetchedRowsView() // MARK: - Building rows @@ -126,8 +129,13 @@ public final class Row : Equatable, Hashable, RandomAccessCollection, Expressibl /// The row is implemented on top of StatementCopyRowImpl, which *copies* /// the values from the SQLite statement so that further iteration of the /// statement does not modify the row. - convenience init(copiedFromSQLiteStatement sqliteStatement: SQLiteStatement, statementRef: Unmanaged) { - self.init(impl: StatementCopyRowImpl(sqliteStatement: sqliteStatement, columnNames: statementRef.takeUnretainedValue().columnNames)) + convenience init( + copiedFromSQLiteStatement sqliteStatement: SQLiteStatement, + statementRef: Unmanaged) + { + self.init(impl: StatementCopyRowImpl( + sqliteStatement: sqliteStatement, + columnNames: statementRef.takeUnretainedValue().columnNames)) } init(impl: RowImpl) { @@ -139,7 +147,7 @@ public final class Row : Equatable, Hashable, RandomAccessCollection, Expressibl } extension Row { - + // MARK: - Columns /// The names of columns in the row. @@ -416,7 +424,12 @@ extension Row { /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions /// (see https://www.sqlite.org/datatype3.html). @inlinable - public subscript(_ column: Column) -> Value? { + public subscript(_ column: Column) + -> Value? + where + Value: DatabaseValueConvertible & StatementColumnConvertible, + Column: ColumnExpression + { return self[column.name] } @@ -448,7 +461,12 @@ extension Row { /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions /// (see https://www.sqlite.org/datatype3.html). @inlinable - public subscript(_ column: Column) -> Value { + public subscript(_ column: Column) + -> Value + where + Value: DatabaseValueConvertible & StatementColumnConvertible, + Column: ColumnExpression + { return self[column.name] } @@ -565,7 +583,7 @@ extension Row { } return Record(row: scopedRow) } - + /// Returns the eventual record associated with the given scope. /// /// For example: @@ -761,7 +779,7 @@ extension Row { /// try dbQueue.read { db in /// let rows: RowCursor = try Row.fetchCursor(db, sql: "SELECT * FROM player") /// } -public final class RowCursor : Cursor { +public final class RowCursor: Cursor { public let statement: SelectStatement @usableFromInline let _sqliteStatement: SQLiteStatement @usableFromInline let _row: Row // Reused for performance @@ -833,7 +851,12 @@ extension Row { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor { + public static func fetchCursor( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> RowCursor + { return try RowCursor(statement: statement, arguments: arguments, adapter: adapter) } @@ -848,7 +871,12 @@ extension Row { /// - adapter: Optional RowAdapter /// - returns: An array of rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row] { + public static func fetchAll( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Row] + { // The cursor reuses a single mutable row. Return immutable copies. return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter).map { $0.copy() }) } @@ -864,7 +892,12 @@ extension Row { /// - adapter: Optional RowAdapter /// - returns: An optional row. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? { + public static func fetchOne( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> Row? + { let cursor = try fetchCursor(statement, arguments: arguments, adapter: adapter) // Keep cursor alive until we can copy the fetched row return try withExtendedLifetime(cursor) { @@ -905,7 +938,13 @@ extension Row { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RowCursor { + public static func fetchCursor( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> RowCursor + { return try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -924,7 +963,13 @@ extension Row { /// - adapter: Optional RowAdapter /// - returns: An array of rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Row] { + public static func fetchAll( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> [Row] + { return try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -943,7 +988,13 @@ extension Row { /// - adapter: Optional RowAdapter /// - returns: An optional row. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Row? { + public static func fetchOne( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> Row? + { return try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } } @@ -1079,7 +1130,7 @@ extension FetchRequest where RowDecoder == Row { return try Row.fetchOne(db, self) } } - + // ExpressibleByDictionaryLiteral extension Row { @@ -1198,7 +1249,7 @@ extension Row { if level == 0 && self == self.unadapted && prefetchedRows.prefetches.isEmpty { return description } - let prefix = repeatElement(" ", count: level + 1).joined(separator: "") + let prefix = repeatElement(" ", count: level + 1).joined() var str = "" if level == 0 { str = "▿ " + description @@ -1234,7 +1285,7 @@ extension Row { // MARK: - RowIndex /// Indexes to (ColumnName, DatabaseValue) pairs in a database row. -public struct RowIndex : Comparable, Strideable { +public struct RowIndex: Comparable, Strideable { let index: Int init(_ index: Int) { self.index = index } } @@ -1386,7 +1437,7 @@ extension Row { } return names } - + /// Returns the row associated with the given scope. /// /// For example: @@ -1461,7 +1512,7 @@ extension Row { public var isEmpty: Bool { return prefetches.isEmpty } - + /// The keys for available prefetched rows /// /// For example: @@ -1483,7 +1534,7 @@ extension Row { } return result } - + /// Returns the prefetched rows associated with the given key. /// /// For example: @@ -1538,13 +1589,20 @@ extension OrderedDictionary where Key == String, Value == Row.Prefetch { protocol RowImpl { var count: Int { get } var isFetched: Bool { get } + func scopes(prefetchedRows: Row.PrefetchedRowsView) -> Row.ScopesView func columnName(atUncheckedIndex index: Int) -> String - func hasNull(atUncheckedIndex index:Int) -> Bool + func hasNull(atUncheckedIndex index: Int) -> Bool func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue - func fastDecode(_ type: Value.Type, atUncheckedIndex index: Int) -> Value - func fastDecodeIfPresent(_ type: Value.Type, atUncheckedIndex index: Int) -> Value? - func dataNoCopy(atUncheckedIndex index:Int) -> Data? + func fastDecode( + _ type: Value.Type, + atUncheckedIndex index: Int) + -> Value + func fastDecodeIfPresent( + _ type: Value.Type, + atUncheckedIndex index: Int) + -> Value? + func dataNoCopy(atUncheckedIndex index: Int) -> Data? /// Returns the index of the leftmost column that matches *name* (case-insensitive) func index(ofColumn name: String) -> Int? @@ -1558,7 +1616,7 @@ protocol RowImpl { extension RowImpl { func copiedRow(_ row: Row) -> Row { // unless customized, assume unsafe and unadapted row - return Row(impl: ArrayRowImpl(columns: row.map { $0 })) + return Row(impl: ArrayRowImpl(columns: Array(row))) } func unscopedRow(_ row: Row) -> Row { @@ -1576,7 +1634,7 @@ extension RowImpl { return Row.ScopesView() } - func hasNull(atUncheckedIndex index:Int) -> Bool { + func hasNull(atUncheckedIndex index: Int) -> Bool { // unless customized, use slow check (see StatementRowImpl and AdaptedRowImpl for customization) return databaseValue(atUncheckedIndex: index).isNull } @@ -1601,7 +1659,7 @@ extension RowImpl { conversionContext: ValueConversionContext(Row(impl: self)).atColumn(index)) } - func dataNoCopy(atUncheckedIndex index:Int) -> Data? { + func dataNoCopy(atUncheckedIndex index: Int) -> Data? { // unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization) return Data.decodeIfPresent( from: databaseValue(atUncheckedIndex: index), @@ -1611,7 +1669,7 @@ extension RowImpl { // TODO: merge with StatementCopyRowImpl eventually? /// See Row.init(dictionary:) -private struct ArrayRowImpl : RowImpl { +private struct ArrayRowImpl: RowImpl { let columns: [(String, DatabaseValue)] init(columns: [(String, DatabaseValue)]) { @@ -1647,13 +1705,16 @@ private struct ArrayRowImpl : RowImpl { // TODO: merge with ArrayRowImpl eventually? /// See Row.init(copiedFromStatementRef:sqliteStatement:) -private struct StatementCopyRowImpl : RowImpl { +private struct StatementCopyRowImpl: RowImpl { let dbValues: ContiguousArray let columnNames: [String] init(sqliteStatement: SQLiteStatement, columnNames: [String]) { let sqliteStatement = sqliteStatement - self.dbValues = ContiguousArray((0.. let sqliteStatement: SQLiteStatement let lowercaseColumnIndexes: [String: Int] @@ -1694,7 +1755,8 @@ private struct StatementRowImpl : RowImpl { self.statementRef = statementRef self.sqliteStatement = sqliteStatement // Optimize row[columnName] - let lowercaseColumnNames = (0.. Bool { + func hasNull(atUncheckedIndex index: Int) -> Bool { // Avoid extracting values, because this modifies the SQLite statement. return sqlite3_column_type(sqliteStatement, Int32(index)) == SQLITE_NULL } - func dataNoCopy(atUncheckedIndex index:Int) -> Data? { + func dataNoCopy(atUncheckedIndex index: Int) -> Data? { guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else { return nil } @@ -1761,7 +1823,7 @@ private struct StatementRowImpl : RowImpl { } // This one is not optimized at all, since it is only used in fatal conversion errors, so far -private struct SQLiteStatementRowImpl : RowImpl { +private struct SQLiteStatementRowImpl: RowImpl { let sqliteStatement: SQLiteStatement var count: Int { return Int(sqlite3_column_count(sqliteStatement)) } var isFetched: Bool { return true } @@ -1784,7 +1846,7 @@ private struct SQLiteStatementRowImpl : RowImpl { } /// See Row.init() -private struct EmptyRowImpl : RowImpl { +private struct EmptyRowImpl: RowImpl { var count: Int { return 0 } diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index b9ab95c8c..87662cd31 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -100,7 +100,7 @@ public struct LayoutedColumnMapping { /// LayoutedColumnMapping adopts LayoutedRowAdapter /// /// :nodoc: -extension LayoutedColumnMapping : LayoutedRowAdapter { +extension LayoutedColumnMapping: LayoutedRowAdapter { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Returns self. @@ -117,7 +117,7 @@ extension LayoutedColumnMapping : LayoutedRowAdapter { } /// :nodoc: -extension LayoutedColumnMapping : RowLayout { +extension LayoutedColumnMapping: RowLayout { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Returns the index of the leftmost column named `name`, in a @@ -171,7 +171,7 @@ public protocol RowLayout { func layoutIndex(ofColumn name: String) -> Int? } -extension SelectStatement : RowLayout { +extension SelectStatement: RowLayout { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public var layoutColumns: [(Int, String)] { @@ -270,7 +270,7 @@ public struct EmptyRowAdapter: RowAdapter { /// /// // [foo:"bar"] /// try Row.fetchOne(db, sql: sql, adapter: adapter) -public struct ColumnMapping : RowAdapter { +public struct ColumnMapping: RowAdapter { /// A dictionary from mapped column names to column names in a base row. let mapping: [String: String] @@ -287,7 +287,12 @@ public struct ColumnMapping : RowAdapter { .map { (mappedColumn, baseColumn) -> (Int, String) in guard let index = layout.layoutIndex(ofColumn: baseColumn) else { let columnNames = layout.layoutColumns.map { $0.1 } - throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Mapping references missing column \(baseColumn). Valid column names are: \(columnNames.joined(separator: ", ")).") + throw DatabaseError( + resultCode: .SQLITE_MISUSE, + message: """ + Mapping references missing column \(baseColumn). \ + Valid column names are: \(columnNames.joined(separator: ", ")). + """) } let baseIndex = layout.layoutColumns[index].0 return (baseIndex, mappedColumn) @@ -304,7 +309,7 @@ public struct ColumnMapping : RowAdapter { /// /// // [baz:3] /// try Row.fetchOne(db, sql: sql, adapter: adapter) -public struct SuffixRowAdapter : RowAdapter { +public struct SuffixRowAdapter: RowAdapter { /// The suffix index let index: Int @@ -331,7 +336,7 @@ public struct SuffixRowAdapter : RowAdapter { /// /// // [bar:2 baz:3] /// try Row.fetchOne(db, sql: sql, adapter: adapter) -public struct RangeRowAdapter : RowAdapter { +public struct RangeRowAdapter: RowAdapter { /// The range let range: CountableRange @@ -376,7 +381,7 @@ public struct RangeRowAdapter : RowAdapter { /// if let barRow = row.scopes["bar"] { /// barRow["value"] // "bar" /// } -public struct ScopeAdapter : RowAdapter { +public struct ScopeAdapter: RowAdapter { /// The base adapter let base: RowAdapter @@ -439,15 +444,15 @@ public struct ScopeAdapter : RowAdapter { } /// The LayoutedRowAdapter for ScopeAdapter -struct LayoutedScopeAdapter : LayoutedRowAdapter { +struct LayoutedScopeAdapter: LayoutedRowAdapter { let mapping: LayoutedColumnMapping let scopes: [String: LayoutedRowAdapter] } -struct ChainedAdapter : RowAdapter { +struct ChainedAdapter: RowAdapter { let first: RowAdapter let second: RowAdapter - + func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { return try second.layoutedAdapter(from: first.layoutedAdapter(from: layout).mapping) } @@ -458,7 +463,7 @@ extension Row { convenience init(base: Row, adapter: LayoutedRowAdapter) { self.init(impl: AdaptedRowImpl(base: base, adapter: adapter)) } - + /// Returns self if adapter is nil func adapted(with adapter: RowAdapter?, layout: RowLayout) throws -> Row { guard let adapter = adapter else { @@ -468,7 +473,7 @@ extension Row { } } -struct AdaptedRowImpl : RowImpl { +struct AdaptedRowImpl: RowImpl { let base: Row let adapter: LayoutedRowAdapter let mapping: LayoutedColumnMapping @@ -517,7 +522,7 @@ struct AdaptedRowImpl : RowImpl { return Value.fastDecodeIfPresent(from: base, atUncheckedIndex: mappedIndex) } - func dataNoCopy(atUncheckedIndex index:Int) -> Data? { + func dataNoCopy(atUncheckedIndex index: Int) -> Data? { let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index) return base.impl.dataNoCopy(atUncheckedIndex: mappedIndex) } @@ -533,7 +538,7 @@ struct AdaptedRowImpl : RowImpl { func copiedRow(_ row: Row) -> Row { return Row(base: base.copy(), adapter: adapter) } - + func unscopedRow(_ row: Row) -> Row { assert(adapter.mapping.scopes.isEmpty) return Row(base: base, adapter: adapter.mapping) diff --git a/GRDB/Core/SQLInterpolation.swift b/GRDB/Core/SQLInterpolation.swift index 49bc2b3b0..9253c01d8 100644 --- a/GRDB/Core/SQLInterpolation.swift +++ b/GRDB/Core/SQLInterpolation.swift @@ -7,23 +7,23 @@ public struct SQLInterpolation: StringInterpolationProtocol { get { return context.arguments! } set { context.arguments = newValue } } - + public init(literalCapacity: Int, interpolationCount: Int) { sql = "" sql.reserveCapacity(literalCapacity + interpolationCount) } - + /// "SELECT * FROM player" public mutating func appendLiteral(_ sql: String) { self.sql += sql } - + /// "SELECT * FROM \(sql: "player")" public mutating func appendInterpolation(sql: String, arguments: StatementArguments = StatementArguments()) { self.sql += sql self.arguments += arguments } - + /// "SELECT * FROM player WHERE \(literal: condition)" public mutating func appendInterpolation(literal sqlLiteral: SQLLiteral) { sql += sqlLiteral.sql diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index e95e58b88..161cc24f3 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -1,4 +1,5 @@ -/// SQLLiteral is a type which support [SQL Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md). +/// SQLLiteral is a type which support [SQL +/// Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md). /// /// For example: /// @@ -9,8 +10,8 @@ /// try db.execute(literal: query) /// } public struct SQLLiteral { - private(set) public var sql: String - private(set) public var arguments: StatementArguments + public private(set) var sql: String + public private(set) var arguments: StatementArguments /// Creates an SQLLiteral from a plain SQL string, and eventual arguments. /// @@ -63,7 +64,7 @@ extension SQLLiteral { public mutating func append(literal sqlLiteral: SQLLiteral) { self += sqlLiteral } - + /// Appends a plain SQL string to the receiver, and eventual arguments. /// /// let name = "O'Brien" diff --git a/GRDB/Core/SQLRequest.swift b/GRDB/Core/SQLRequest.swift index 60ccd4360..5dd439fb0 100644 --- a/GRDB/Core/SQLRequest.swift +++ b/GRDB/Core/SQLRequest.swift @@ -1,5 +1,5 @@ /// A FetchRequest built from raw SQL. -public struct SQLRequest : FetchRequest { +public struct SQLRequest: FetchRequest { /// There are two statement caches: one "public" for statements generated by /// the user, and one "internal" for the statements generated by GRDB. Those /// are separated so that GRDB has no opportunity to inadvertently modify @@ -30,10 +30,10 @@ public struct SQLRequest : FetchRequest { /// The request adapter public var adapter: RowAdapter? - + private var sqlLiteral: SQLLiteral private let cache: Cache? - + /// Creates a request from an SQL string, optional arguments, and /// optional row adapter. /// @@ -51,8 +51,16 @@ public struct SQLRequest : FetchRequest { /// - cached: Defaults to false. If true, the request reuses a cached /// prepared statement. /// - returns: A SQLRequest - public init(sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil, cached: Bool = false) { - self.init(literal: SQLLiteral(sql: sql, arguments: arguments), adapter: adapter, fromCache: cached ? .public : nil) + public init( + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil, + cached: Bool = false) + { + self.init( + literal: SQLLiteral(sql: sql, arguments: arguments), + adapter: adapter, + fromCache: cached ? .public : nil) } /// Creates a request from an SQLLiteral, and optional row adapter. @@ -80,7 +88,7 @@ public struct SQLRequest : FetchRequest { public init(literal sqlLiteral: SQLLiteral, adapter: RowAdapter? = nil, cached: Bool = false) { self.init(literal: sqlLiteral, adapter: adapter, fromCache: cached ? .public : nil) } - + /// Creates an SQL request from any other fetch request. /// /// - parameters: @@ -89,7 +97,13 @@ public struct SQLRequest : FetchRequest { /// - cached: Defaults to false. If true, the request reuses a cached /// prepared statement. /// - returns: An SQLRequest - public init(_ db: Database, request: Request, cached: Bool = false) throws where Request.RowDecoder == RowDecoder { + public init( + _ db: Database, + request: Request, + cached: Bool = false) + throws + where Request: FetchRequest, Request.RowDecoder == RowDecoder + { let request = try request.makePreparedRequest(db, forSingleResult: false) self.init( literal: SQLLiteral(sql: request.statement.sql, arguments: request.statement.arguments), diff --git a/GRDB/Core/SchedulingWatchdog.swift b/GRDB/Core/SchedulingWatchdog.swift index 93318631b..087926c45 100644 --- a/GRDB/Core/SchedulingWatchdog.swift +++ b/GRDB/Core/SchedulingWatchdog.swift @@ -43,7 +43,12 @@ final class SchedulingWatchdog { return try body() } - static func preconditionValidQueue(_ db: Database, _ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) { + static func preconditionValidQueue( + _ db: Database, + _ message: @autoclosure() -> String = "Database was not used on the correct thread.", + file: StaticString = #file, + line: UInt = #line) + { GRDBPrecondition(current?.allows(db) ?? false, message(), file: file, line: line) } diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index 7fabe2ee2..c08b1445a 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -16,7 +16,14 @@ final class SerializedDatabase { /// The dispatch queue private let queue: DispatchQueue - init(path: String, configuration: Configuration = Configuration(), schemaCache: DatabaseSchemaCache, defaultLabel: String, purpose: String? = nil) throws { + init( + path: String, + configuration: Configuration = Configuration(), + schemaCache: DatabaseSchemaCache, + defaultLabel: String, + purpose: String? = nil) + throws + { // According to https://www.sqlite.org/threadsafe.html // // > SQLite support three different threading modes: @@ -193,12 +200,25 @@ final class SerializedDatabase { } /// Fatal error if current dispatch queue is not valid. - func preconditionValidQueue(_ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) { + func preconditionValidQueue( + _ message: @autoclosure() -> String = "Database was not used on the correct thread.", + file: StaticString = #file, + line: UInt = #line) + { SchedulingWatchdog.preconditionValidQueue(db, message(), file: file, line: line) } /// Fatal error if a transaction has been left opened. - private func preconditionNoUnsafeTransactionLeft(_ db: Database, _ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access", file: StaticString = #file, line: UInt = #line) { - GRDBPrecondition(configuration.allowsUnsafeTransactions || !db.isInsideTransaction, message(), file: file, line: line) + private func preconditionNoUnsafeTransactionLeft( + _ db: Database, + _ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access", + file: StaticString = #file, + line: UInt = #line) + { + GRDBPrecondition( + configuration.allowsUnsafeTransactions || !db.isInsideTransaction, + message(), + file: file, + line: line) } } diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 73a76d472..33c64c9a8 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -1,10 +1,10 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// A raw SQLite statement, suitable for the SQLite C API. @@ -56,18 +56,25 @@ public class Statement { var sqliteStatement: SQLiteStatement? = nil // sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20 #if GRDBCUSTOMSQLITE || GRDBCIPHER - let code = sqlite3_prepare_v3(database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), &sqliteStatement, statementEnd) + let code = sqlite3_prepare_v3( + database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), + &sqliteStatement, statementEnd) #else let code: Int32 if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) { - code = sqlite3_prepare_v3(database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), &sqliteStatement, statementEnd) + code = sqlite3_prepare_v3( + database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), + &sqliteStatement, statementEnd) } else { code = sqlite3_prepare_v2(database.sqliteConnection, statementStart, -1, &sqliteStatement, statementEnd) } #endif guard code == SQLITE_OK else { - throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: String(cString: statementStart)) + throw DatabaseError( + resultCode: code, + message: database.lastErrorMessage, + sql: String(cString: statementStart)) } guard let statement = sqliteStatement else { @@ -102,7 +109,7 @@ public class Statement { // Returns ["id", nil", "name"] for "INSERT INTO table VALUES (:id, ?, :name)" fileprivate lazy var sqliteArgumentNames: [String?] = { - return (0.. ?", arguments: [1000]) /// .fetchAll(db) -public struct StatementArguments: CustomStringConvertible, Equatable, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral { +public struct StatementArguments: CustomStringConvertible, Equatable, + ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral +{ private(set) var values: [DatabaseValue] = [] private(set) var namedValues: [String: DatabaseValue] = [:] @@ -667,7 +684,9 @@ public struct StatementArguments: CustomStringConvertible, Equatable, Expressibl /// /// - parameter sequence: A sequence of (key, value) pairs /// - returns: A StatementArguments. - public init(_ sequence: Sequence) where Sequence.Element == (String, DatabaseValueConvertible?) { + public init(_ sequence: Sequence) + where Sequence: Swift.Sequence, Sequence.Element == (String, DatabaseValueConvertible?) + { namedValues = Dictionary(uniqueKeysWithValues: sequence.map { ($0.0, $0.1?.databaseValue ?? .null) }) } @@ -843,33 +862,48 @@ public struct StatementArguments: CustomStringConvertible, Equatable, Expressibl /// append(contentsOf:) method. public static func += (lhs: inout StatementArguments, rhs: StatementArguments) { let replacedValues = lhs.append(contentsOf: rhs) - GRDBPrecondition(replacedValues.isEmpty, "already defined statement argument: \(replacedValues.keys.joined(separator: ", "))") + GRDBPrecondition( + replacedValues.isEmpty, + "already defined statement argument: \(replacedValues.keys.joined(separator: ", "))") } // MARK: Not Public - mutating func extractBindings(forStatement statement: Statement, allowingRemainingValues: Bool) throws -> [DatabaseValue] { + mutating func extractBindings( + forStatement statement: Statement, + allowingRemainingValues: Bool) + throws -> [DatabaseValue] + { let initialValuesCount = values.count let bindings = try statement.sqliteArgumentNames.map { argumentName -> DatabaseValue in if let argumentName = argumentName { if let dbValue = namedValues[argumentName] { return dbValue } else if values.isEmpty { - throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "missing statement argument: \(argumentName)", sql: statement.sql, arguments: nil) + throw DatabaseError( + resultCode: .SQLITE_MISUSE, + message: "missing statement argument: \(argumentName)", + sql: statement.sql) } else { return values.removeFirst() } } else { if values.isEmpty { - throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)", sql: statement.sql, arguments: nil) + throw DatabaseError( + resultCode: .SQLITE_MISUSE, + message: "wrong number of statement arguments: \(initialValuesCount)", + sql: statement.sql) } else { return values.removeFirst() } } } if !allowingRemainingValues && !values.isEmpty { - throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)", sql: statement.sql, arguments: nil) + throw DatabaseError( + resultCode: .SQLITE_MISUSE, + message: "wrong number of statement arguments: \(initialValuesCount)", + sql: statement.sql) } return bindings } @@ -907,7 +941,7 @@ extension StatementArguments { public var description: String { let valuesDescriptions = values.map { $0.description } let namedValuesDescriptions = namedValues.map { (key, value) -> String in - return "\(String(reflecting: key)): \(value)" + "\(String(reflecting: key)): \(value)" } return "[" + (namedValuesDescriptions + valuesDescriptions).joined(separator: ", ") + "]" } diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index e94bfa4a5..ec72fb117 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -1,16 +1,16 @@ #if os(Linux) - import Glibc +import Glibc #endif #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// A protocol around sqlite3_set_authorizer -protocol StatementAuthorizer : class { +protocol StatementAuthorizer: AnyObject { func authorize( _ actionCode: Int32, _ cString1: UnsafePointer?, @@ -21,7 +21,7 @@ protocol StatementAuthorizer : class { } /// A class that gathers information about one statement during its compilation. -final class StatementCompilationAuthorizer : StatementAuthorizer { +final class StatementCompilationAuthorizer: StatementAuthorizer { /// What this statements reads var databaseRegion = DatabaseRegion() @@ -47,7 +47,11 @@ final class StatementCompilationAuthorizer : StatementAuthorizer { _ cString4: UnsafePointer?) -> Int32 { - // print("StatementCompilationAuthorizer: \(actionCode) \([cString1, cString2, cString3, cString4].flatMap { $0.map({ String(cString: $0) }) })") + // print(""" + // StatementCompilationAuthorizer: \ + // \(actionCode) \ + // \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) }) + // """) switch actionCode { case SQLITE_DROP_TABLE, SQLITE_DROP_VTABLE, SQLITE_DROP_TEMP_TABLE, @@ -67,8 +71,8 @@ final class StatementCompilationAuthorizer : StatementAuthorizer { return SQLITE_OK case SQLITE_READ: - guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK } - guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK } + guard let tableName = cString1.map(String.init) else { return SQLITE_OK } + guard let columnName = cString2.map(String.init) else { return SQLITE_OK } if columnName.isEmpty { // SELECT COUNT(*) FROM table databaseRegion.formUnion(DatabaseRegion(table: tableName)) @@ -79,7 +83,7 @@ final class StatementCompilationAuthorizer : StatementAuthorizer { return SQLITE_OK case SQLITE_INSERT: - guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK } + guard let tableName = cString1.map(String.init) else { return SQLITE_OK } databaseEventKinds.append(.insert(tableName: tableName)) return SQLITE_OK @@ -100,8 +104,8 @@ final class StatementCompilationAuthorizer : StatementAuthorizer { return SQLITE_IGNORE case SQLITE_UPDATE: - guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK } - guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK } + guard let tableName = cString1.map(String.init) else { return SQLITE_OK } + guard let columnName = cString2.map(String.init) else { return SQLITE_OK } insertUpdateEventKind(tableName: tableName, columnName: columnName) return SQLITE_OK @@ -118,7 +122,7 @@ final class StatementCompilationAuthorizer : StatementAuthorizer { case SQLITE_SAVEPOINT: guard let cString1 = cString1 else { return SQLITE_OK } - guard let name = cString2.map({ String(cString: $0) }) else { return SQLITE_OK } + guard let name = cString2.map(String.init) else { return SQLITE_OK } if strcmp(cString1, "BEGIN") == 0 { transactionEffect = .beginSavepoint(name) } else if strcmp(cString1, "RELEASE") == 0 { @@ -168,7 +172,7 @@ final class StatementCompilationAuthorizer : StatementAuthorizer { // /// Warning: to perform well, this authorizer must be used during statement /// execution, not during statement compilation. -final class TruncateOptimizationBlocker : StatementAuthorizer { +final class TruncateOptimizationBlocker: StatementAuthorizer { func authorize( _ actionCode: Int32, _ cString1: UnsafePointer?, @@ -177,8 +181,11 @@ final class TruncateOptimizationBlocker : StatementAuthorizer { _ cString4: UnsafePointer?) -> Int32 { - // print("TruncateOptimizationBlocker: \(actionCode) \([cString1, cString2, cString3, cString4].flatMap { $0.map({ String(cString: $0) }) })") + // print(""" + // TruncateOptimizationBlocker: \ + // \(actionCode) \ + // \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) }) + // """) return (actionCode == SQLITE_DELETE) ? SQLITE_IGNORE : SQLITE_OK } } - diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 2ae6f87ba..734acdb3f 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -1,9 +1,9 @@ #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// The StatementColumnConvertible protocol grants access to the low-level C @@ -109,17 +109,20 @@ public final class FastDatabaseValueCursor = try Optional.fetchCursor(db, sql: "SELECT email FROM player") +/// let emails: FastNullableDatabaseValueCursor = +/// try Optional.fetchCursor(db, sql: "SELECT email FROM player") /// while let email = emails.next() { // String? /// print(email ?? "") /// } /// } -public final class FastNullableDatabaseValueCursor : Cursor { +public final class FastNullableDatabaseValueCursor: Cursor + where Value: DatabaseValueConvertible & StatementColumnConvertible +{ @usableFromInline let _statement: SelectStatement @usableFromInline let _columnIndex: Int32 @usableFromInline let _sqliteStatement: SQLiteStatement @usableFromInline var _done = false - + init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { _statement = statement _sqliteStatement = statement.sqliteStatement @@ -187,7 +190,12 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor { + public static func fetchCursor( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> FastDatabaseValueCursor + { return try FastDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) } @@ -202,7 +210,12 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - adapter: Optional RowAdapter /// - returns: An array of values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { + public static func fetchAll( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Self] + { return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } @@ -217,15 +230,23 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - adapter: Optional RowAdapter /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { + public static func fetchOne( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> Self? + { // fetchOne returns nil if there is no row, or if there is a row with a null value - let cursor = try FastNullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) + let cursor = try FastNullableDatabaseValueCursor( + statement: statement, + arguments: arguments, + adapter: adapter) return try cursor.next() ?? nil } } extension DatabaseValueConvertible where Self: StatementColumnConvertible { - + // MARK: Fetching From SQL /// Returns a cursor over values fetched from an SQL query. @@ -247,7 +268,13 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor { + public static func fetchCursor( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> FastDatabaseValueCursor + { return try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -262,7 +289,13 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - adapter: Optional RowAdapter /// - returns: An array of values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self] { + public static func fetchAll( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> [Self] + { return try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -277,7 +310,13 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - adapter: Optional RowAdapter /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self? { + public static func fetchOne( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> Self? + { return try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } } @@ -304,7 +343,9 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - request: A FetchRequest. /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: R) throws -> FastDatabaseValueCursor { + public static func fetchCursor(_ db: Database, _ request: R) + throws -> FastDatabaseValueCursor + { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchCursor(request.statement, adapter: request.adapter) } @@ -426,7 +467,12 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor { + public static func fetchCursor( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> FastNullableDatabaseValueCursor + { return try FastNullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) } @@ -441,7 +487,12 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// - adapter: Optional RowAdapter /// - returns: An array of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] { + public static func fetchAll( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Wrapped?] + { return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } } @@ -469,7 +520,13 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor { + public static func fetchCursor( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> FastNullableDatabaseValueCursor + { return try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -484,7 +541,13 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// - adapter: Optional RowAdapter /// - returns: An array of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Wrapped?] { + public static func fetchAll( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> [Wrapped?] + { return try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } } @@ -511,7 +574,9 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// - request: A FetchRequest. /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: R) throws -> FastNullableDatabaseValueCursor { + public static func fetchCursor(_ db: Database, _ request: R) + throws -> FastNullableDatabaseValueCursor + { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchCursor(request.statement, adapter: request.adapter) } @@ -532,7 +597,11 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv } } -extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible { +extension FetchRequest + where + RowDecoder: _OptionalProtocol, + RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible +{ // MARK: Fetching Optional values diff --git a/GRDB/Core/Support/CoreGraphics/CGFloat.swift b/GRDB/Core/Support/CoreGraphics/CGFloat.swift index 444dc0c40..a7f7c6bc4 100644 --- a/GRDB/Core/Support/CoreGraphics/CGFloat.swift +++ b/GRDB/Core/Support/CoreGraphics/CGFloat.swift @@ -2,8 +2,8 @@ import CoreGraphics /// CGFloat adopts DatabaseValueConvertible -extension CGFloat : DatabaseValueConvertible { - +extension CGFloat: DatabaseValueConvertible { + /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { return Double(self).databaseValue diff --git a/GRDB/Core/Support/Foundation/Data.swift b/GRDB/Core/Support/Foundation/Data.swift index 8c4202bdc..281fdd920 100644 --- a/GRDB/Core/Support/Foundation/Data.swift +++ b/GRDB/Core/Support/Foundation/Data.swift @@ -1,14 +1,14 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// Data is convertible to and from DatabaseValue. -extension Data : DatabaseValueConvertible, StatementColumnConvertible { +extension Data: DatabaseValueConvertible, StatementColumnConvertible { @inlinable public init(sqliteStatement: SQLiteStatement, index: Int32) { if let bytes = sqlite3_column_blob(sqliteStatement, index) { diff --git a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift index f84be4909..0057f4a6f 100644 --- a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift +++ b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift @@ -1,17 +1,17 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// DatabaseDateComponents reads and stores DateComponents in the database. -public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumnConvertible { - +public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnConvertible { + /// The available formats for reading and storing date components. - public enum Format : String { + public enum Format: String { /// The format "yyyy-MM-dd". case YMD = "yyyy-MM-dd" @@ -81,8 +81,10 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn fatalConversionError(to: DatabaseDateComponents.self, sqliteStatement: sqliteStatement, index: index) } let length = Int(sqlite3_column_bytes(sqliteStatement, index)) // avoid an strlen - let optionalComponents = cString.withMemoryRebound(to: Int8.self, capacity: length + 1 /* trailing \0 */) { cString in - SQLiteDateParser().components(cString: cString, length: length) + let optionalComponents = cString.withMemoryRebound( + to: Int8.self, + capacity: length + 1 /* trailing \0 */) { cString in + SQLiteDateParser().components(cString: cString, length: length) } guard let components = optionalComponents else { fatalConversionError(to: DatabaseDateComponents.self, sqliteStatement: sqliteStatement, index: index) @@ -122,7 +124,9 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn let minute = dateComponents.minute ?? 0 let second = dateComponents.second ?? 0 let nanosecond = dateComponents.nanosecond ?? 0 - timeString = String(format: "%02d:%02d:%02d.%03d", hour, minute, second, Int(round(Double(nanosecond) / 1_000_000.0))) + timeString = String( + format: "%02d:%02d:%02d.%03d", + hour, minute, second, Int(round(Double(nanosecond) / 1_000_000.0))) default: timeString = nil } diff --git a/GRDB/Core/Support/Foundation/DatabaseValueConvertible+ReferenceConvertible.swift b/GRDB/Core/Support/Foundation/DatabaseValueConvertible+ReferenceConvertible.swift index d5fedd5ad..4a3e3c53b 100644 --- a/GRDB/Core/Support/Foundation/DatabaseValueConvertible+ReferenceConvertible.swift +++ b/GRDB/Core/Support/Foundation/DatabaseValueConvertible+ReferenceConvertible.swift @@ -26,14 +26,22 @@ extension DatabaseValueConvertible where Self: ReferenceConvertible, Self.Refere } } -extension DatabaseValueConvertible where Self: Decodable & ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible { +extension DatabaseValueConvertible + where + Self: Decodable & ReferenceConvertible, + Self.ReferenceType: DatabaseValueConvertible +{ public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? { // Preserve custom database decoding return ReferenceType.fromDatabaseValue(databaseValue).flatMap { cast($0) } } } -extension DatabaseValueConvertible where Self: Encodable & ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible { +extension DatabaseValueConvertible + where + Self: Encodable & ReferenceConvertible, + Self.ReferenceType: DatabaseValueConvertible +{ public var databaseValue: DatabaseValue { // Preserve custom database encoding return (self as! ReferenceType).databaseValue diff --git a/GRDB/Core/Support/Foundation/Date.swift b/GRDB/Core/Support/Foundation/Date.swift index 4742c84ed..c51b103fd 100644 --- a/GRDB/Core/Support/Foundation/Date.swift +++ b/GRDB/Core/Support/Foundation/Date.swift @@ -1,16 +1,16 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif #if !os(Linux) /// NSDate is stored in the database using the format /// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone. -extension NSDate : DatabaseValueConvertible { +extension NSDate: DatabaseValueConvertible { /// Returns a database value that contains the date encoded as /// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone. public var databaseValue: DatabaseValue { @@ -38,7 +38,7 @@ extension NSDate : DatabaseValueConvertible { /// Date is stored in the database using the format /// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone. -extension Date : DatabaseValueConvertible { +extension Date: DatabaseValueConvertible { /// Returns a database value that contains the date encoded as /// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone. public var databaseValue: DatabaseValue { @@ -149,7 +149,7 @@ private let storageDateFormatter: DateFormatter = { formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0) return formatter - }() +}() // The NSCalendar for stored dates. private let UTCCalendar: Calendar = { @@ -157,4 +157,4 @@ private let UTCCalendar: Calendar = { calendar.locale = Locale(identifier: "en_US_POSIX") calendar.timeZone = TimeZone(secondsFromGMT: 0)! return calendar - }() +}() diff --git a/GRDB/Core/Support/Foundation/NSData.swift b/GRDB/Core/Support/Foundation/NSData.swift index 8bd9d2ecf..5a29bc4a4 100644 --- a/GRDB/Core/Support/Foundation/NSData.swift +++ b/GRDB/Core/Support/Foundation/NSData.swift @@ -2,7 +2,7 @@ import Foundation /// NSData is convertible to and from DatabaseValue. -extension NSData : DatabaseValueConvertible { +extension NSData: DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { diff --git a/GRDB/Core/Support/Foundation/NSNull.swift b/GRDB/Core/Support/Foundation/NSNull.swift index e954befe4..af531bab5 100644 --- a/GRDB/Core/Support/Foundation/NSNull.swift +++ b/GRDB/Core/Support/Foundation/NSNull.swift @@ -1,7 +1,7 @@ import Foundation /// NSNull adopts DatabaseValueConvertible -extension NSNull : DatabaseValueConvertible { +extension NSNull: DatabaseValueConvertible { /// Returns DatabaseValue.null. public var databaseValue: DatabaseValue { diff --git a/GRDB/Core/Support/Foundation/NSNumber.swift b/GRDB/Core/Support/Foundation/NSNumber.swift index 2caf60868..7c33a68fb 100644 --- a/GRDB/Core/Support/Foundation/NSNumber.swift +++ b/GRDB/Core/Support/Foundation/NSNumber.swift @@ -1,10 +1,16 @@ #if !os(Linux) import Foundation -private let integerRoundingBehavior = NSDecimalNumberHandler(roundingMode: .plain, scale: 0, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false) +private let integerRoundingBehavior = NSDecimalNumberHandler( + roundingMode: .plain, + scale: 0, + raiseOnExactness: false, + raiseOnOverflow: false, + raiseOnUnderflow: false, + raiseOnDivideByZero: false) /// NSNumber adopts DatabaseValueConvertible -extension NSNumber : DatabaseValueConvertible { +extension NSNumber: DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { @@ -34,13 +40,17 @@ extension NSNumber : DatabaseValueConvertible { return Int64(intValue).databaseValue case "L": let uint = uintValue - GRDBPrecondition(UInt64(uint) <= UInt64(Int64.max), "could not convert \(uint) to an Int64 that can be stored in the database") + GRDBPrecondition( + UInt64(uint) <= UInt64(Int64.max), + "could not convert \(uint) to an Int64 that can be stored in the database") return Int64(uint).databaseValue case "q": return Int64(int64Value).databaseValue case "Q": let uint64 = uint64Value - GRDBPrecondition(uint64 <= UInt64(Int64.max), "could not convert \(uint64) to an Int64 that can be stored in the database") + GRDBPrecondition( + uint64 <= UInt64(Int64.max), + "could not convert \(uint64) to an Int64 that can be stored in the database") return Int64(uint64).databaseValue case "f": return Double(floatValue).databaseValue diff --git a/GRDB/Core/Support/Foundation/NSString.swift b/GRDB/Core/Support/Foundation/NSString.swift index d5455bed4..ba9941012 100644 --- a/GRDB/Core/Support/Foundation/NSString.swift +++ b/GRDB/Core/Support/Foundation/NSString.swift @@ -2,7 +2,7 @@ import Foundation /// NSString adopts DatabaseValueConvertible -extension NSString : DatabaseValueConvertible { +extension NSString: DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index cd42663c0..b6630fe39 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -58,6 +58,7 @@ class SQLiteDateParser { withUnsafeMutablePointer(to: &parserComponents.minute) { minuteP in withUnsafeMutablePointer(to: &parserComponents.second) { secondP in parserComponents.nanosecond.withUnsafeMutableBufferPointer { nanosecondBuffer in + // swiftlint:disable:next line_length withVaList([yearP, monthP, dayP, hourP, minuteP, secondP, nanosecondBuffer.baseAddress!]) { pointer in vsscanf(cString, "%4d-%2d-%2d%*1[ T]%2d:%2d:%2d.%9s", pointer) } diff --git a/GRDB/Core/Support/Foundation/URL.swift b/GRDB/Core/Support/Foundation/URL.swift index 4cc95b1b4..6990562e1 100644 --- a/GRDB/Core/Support/Foundation/URL.swift +++ b/GRDB/Core/Support/Foundation/URL.swift @@ -2,7 +2,7 @@ import Foundation #if !os(Linux) /// NSURL stores its absoluteString in the database. -extension NSURL : DatabaseValueConvertible { +extension NSURL: DatabaseValueConvertible { /// Returns a value that can be stored in the database. /// (the URL's absoluteString). @@ -21,4 +21,4 @@ extension NSURL : DatabaseValueConvertible { #endif /// URL stores its absoluteString in the database. -extension URL : DatabaseValueConvertible { } +extension URL: DatabaseValueConvertible { } diff --git a/GRDB/Core/Support/Foundation/UUID.swift b/GRDB/Core/Support/Foundation/UUID.swift index 8ed8d68b0..92447987c 100644 --- a/GRDB/Core/Support/Foundation/UUID.swift +++ b/GRDB/Core/Support/Foundation/UUID.swift @@ -1,10 +1,10 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif #if !os(Linux) diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift index f04cfd071..b37fb8d80 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift @@ -13,7 +13,8 @@ private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer { /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. - /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. + /// - throws: `DecodingError.typeMismatch` if the encountered encoded value + /// cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: Bool.Type) throws -> Bool { if let result = Bool.fromDatabaseValue(dbValue) { @@ -131,9 +132,10 @@ private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer { /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. - /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. + /// - throws: `DecodingError.typeMismatch` if the encountered encoded value + /// cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. - func decode(_ type: T.Type) throws -> T where T : Decodable { + func decode(_ type: T.Type) throws -> T where T: Decodable { if let type = T.self as? DatabaseValueConvertible.Type { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows custom database decoding, such as decoding Date from @@ -159,7 +161,7 @@ private struct DatabaseValueDecoder: Decoder { // Decoder let codingPath: [CodingKey] - var userInfo: [CodingUserInfoKey : Any] { return [:] } + var userInfo: [CodingUserInfoKey: Any] { return [:] } func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer { throw DecodingError.typeMismatch( diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift index 8aa705b32..bd37c0bde 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift @@ -1,4 +1,4 @@ -private struct DatabaseValueEncodingContainer : SingleValueEncodingContainer { +private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer { let encode: (DatabaseValue) -> Void var codingPath: [CodingKey] { return [] } @@ -34,7 +34,7 @@ private struct DatabaseValueEncodingContainer : SingleValueEncodingContainer { /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. /// - precondition: May not be called after a previous `self.encode(_:)` call. - mutating func encode(_ value: T) throws where T : Encodable { + mutating func encode(_ value: T) throws where T: Encodable { if let dbValueConvertible = value as? DatabaseValueConvertible { // Prefer DatabaseValueConvertible encoding over Decodable. // This allows us to encode Date as String, for example. @@ -45,7 +45,7 @@ private struct DatabaseValueEncodingContainer : SingleValueEncodingContainer { } } -private struct DatabaseValueEncoder : Encoder { +private struct DatabaseValueEncoder: Encoder { let encode: (DatabaseValue) -> Void /// The path of coding keys taken to get to this point in encoding. @@ -53,7 +53,7 @@ private struct DatabaseValueEncoder : Encoder { var codingPath: [CodingKey] { return [] } /// Any contextual information set by the user for encoding. - var userInfo: [CodingUserInfoKey : Any] = [:] + var userInfo: [CodingUserInfoKey: Any] = [:] init(encode: @escaping (DatabaseValue) -> Void) { self.encode = encode @@ -64,7 +64,8 @@ private struct DatabaseValueEncoder : Encoder { /// - parameter type: The key type to use for the container. /// - returns: A new keyed encoding container. /// - precondition: May not be called after a prior `self.unkeyedContainer()` call. - /// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call. + /// - precondition: May not be called after a value has been encoded through + /// a previous `self.singleValueContainer()` call. func container(keyedBy type: Key.Type) -> KeyedEncodingContainer { fatalError("keyed encoding is not supported") } @@ -73,7 +74,8 @@ private struct DatabaseValueEncoder : Encoder { /// /// - returns: A new empty unkeyed container. /// - precondition: May not be called after a prior `self.container(keyedBy:)` call. - /// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call. + /// - precondition: May not be called after a value has been encoded through + /// a previous `self.singleValueContainer()` call. func unkeyedContainer() -> UnkeyedEncodingContainer { fatalError("unkeyed encoding is not supported") } @@ -83,7 +85,8 @@ private struct DatabaseValueEncoder : Encoder { /// - returns: A new empty single value container. /// - precondition: May not be called after a prior `self.container(keyedBy:)` call. /// - precondition: May not be called after a prior `self.unkeyedContainer()` call. - /// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call. + /// - precondition: May not be called after a value has been encoded through + /// a previous `self.singleValueContainer()` call. func singleValueContainer() -> SingleValueEncodingContainer { return DatabaseValueEncodingContainer(encode: encode) } diff --git a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift index 099b742fe..0914b0dcf 100644 --- a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift +++ b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift @@ -1,9 +1,9 @@ #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif // MARK: - Value Types @@ -500,11 +500,12 @@ extension DatabaseFunction { /// let nameColumn = Column("name") /// let request = Player.select(nameColumn.capitalized) /// let names = try String.fetchAll(dbQueue, request) // [String] - public static let capitalize = DatabaseFunction("swiftCapitalizedString", argumentCount: 1, pure: true) { dbValues in - guard let string = String.fromDatabaseValue(dbValues[0]) else { - return nil - } - return string.capitalized + public static let capitalize = + DatabaseFunction("swiftCapitalizedString", argumentCount: 1, pure: true) { dbValues in + guard let string = String.fromDatabaseValue(dbValues[0]) else { + return nil + } + return string.capitalized } /// An SQL function that returns the Swift built-in lowercased @@ -519,11 +520,12 @@ extension DatabaseFunction { /// let nameColumn = Column("name") /// let request = Player.select(nameColumn.lowercased()) /// let names = try String.fetchAll(dbQueue, request) // [String] - public static let lowercase = DatabaseFunction("swiftLowercaseString", argumentCount: 1, pure: true) { dbValues in - guard let string = String.fromDatabaseValue(dbValues[0]) else { - return nil - } - return string.lowercased() + public static let lowercase = + DatabaseFunction("swiftLowercaseString", argumentCount: 1, pure: true) { dbValues in + guard let string = String.fromDatabaseValue(dbValues[0]) else { + return nil + } + return string.lowercased() } /// An SQL function that returns the Swift built-in uppercased @@ -538,11 +540,12 @@ extension DatabaseFunction { /// let nameColumn = Column("name") /// let request = Player.select(nameColumn.uppercased()) /// let names = try String.fetchAll(dbQueue, request) // [String] - public static let uppercase = DatabaseFunction("swiftUppercaseString", argumentCount: 1, pure: true) { dbValues in - guard let string = String.fromDatabaseValue(dbValues[0]) else { - return nil - } - return string.uppercased() + public static let uppercase = + DatabaseFunction("swiftUppercaseString", argumentCount: 1, pure: true) { dbValues in + guard let string = String.fromDatabaseValue(dbValues[0]) else { + return nil + } + return string.uppercased() } } @@ -560,11 +563,12 @@ extension DatabaseFunction { /// let request = Player.select(nameColumn.localizedCapitalized) /// let names = try String.fetchAll(dbQueue, request) // [String] @available(iOS 9.0, OSX 10.11, watchOS 3.0, *) - public static let localizedCapitalize = DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { dbValues in - guard let string = String.fromDatabaseValue(dbValues[0]) else { - return nil - } - return string.localizedCapitalized + public static let localizedCapitalize = + DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { dbValues in + guard let string = String.fromDatabaseValue(dbValues[0]) else { + return nil + } + return string.localizedCapitalized } /// An SQL function that returns the Swift built-in @@ -580,11 +584,12 @@ extension DatabaseFunction { /// let request = Player.select(nameColumn.localizedLowercased) /// let names = try String.fetchAll(dbQueue, request) // [String] @available(iOS 9.0, OSX 10.11, watchOS 3.0, *) - public static let localizedLowercase = DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { dbValues in - guard let string = String.fromDatabaseValue(dbValues[0]) else { - return nil - } - return string.localizedLowercase + public static let localizedLowercase = + DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { dbValues in + guard let string = String.fromDatabaseValue(dbValues[0]) else { + return nil + } + return string.localizedLowercase } /// An SQL function that returns the Swift built-in @@ -600,11 +605,12 @@ extension DatabaseFunction { /// let request = Player.select(nameColumn.localizedUppercased) /// let names = try String.fetchAll(dbQueue, request) // [String] @available(iOS 9.0, OSX 10.11, watchOS 3.0, *) - public static let localizedUppercase = DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { dbValues in - guard let string = String.fromDatabaseValue(dbValues[0]) else { - return nil - } - return string.localizedUppercase + public static let localizedUppercase = + DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { dbValues in + guard let string = String.fromDatabaseValue(dbValues[0]) else { + return nil + } + return string.localizedUppercase } } @@ -637,8 +643,9 @@ extension DatabaseCollation { /// name TEXT COLLATE \(collationName) /// ) /// """) - public static let unicodeCompare = DatabaseCollation("swiftCompare") { (lhs, rhs) in - return (lhs < rhs) ? .orderedAscending : ((lhs == rhs) ? .orderedSame : .orderedDescending) + public static let unicodeCompare = + DatabaseCollation("swiftCompare") { (lhs, rhs) in + (lhs < rhs) ? .orderedAscending : ((lhs == rhs) ? .orderedSame : .orderedDescending) } /// A collation, or SQL string comparison function, that compares strings @@ -655,8 +662,9 @@ extension DatabaseCollation { /// name TEXT COLLATE \(collationName) /// ) /// """) - public static let caseInsensitiveCompare = DatabaseCollation("swiftCaseInsensitiveCompare") { (lhs, rhs) in - return lhs.caseInsensitiveCompare(rhs) + public static let caseInsensitiveCompare = + DatabaseCollation("swiftCaseInsensitiveCompare") { (lhs, rhs) in + lhs.caseInsensitiveCompare(rhs) } /// A collation, or SQL string comparison function, that compares strings @@ -673,8 +681,9 @@ extension DatabaseCollation { /// name TEXT COLLATE \(collationName) /// ) /// """) - public static let localizedCaseInsensitiveCompare = DatabaseCollation("swiftLocalizedCaseInsensitiveCompare") { (lhs, rhs) in - return lhs.localizedCaseInsensitiveCompare(rhs) + public static let localizedCaseInsensitiveCompare = + DatabaseCollation("swiftLocalizedCaseInsensitiveCompare") { (lhs, rhs) in + return lhs.localizedCaseInsensitiveCompare(rhs) } /// A collation, or SQL string comparison function, that compares strings @@ -691,8 +700,9 @@ extension DatabaseCollation { /// name TEXT COLLATE \(collationName) /// ) /// """) - public static let localizedCompare = DatabaseCollation("swiftLocalizedCompare") { (lhs, rhs) in - return lhs.localizedCompare(rhs) + public static let localizedCompare = + DatabaseCollation("swiftLocalizedCompare") { (lhs, rhs) in + lhs.localizedCompare(rhs) } /// A collation, or SQL string comparison function, that compares strings @@ -709,7 +719,8 @@ extension DatabaseCollation { /// name TEXT COLLATE \(collationName) /// ) /// """) - public static let localizedStandardCompare = DatabaseCollation("swiftLocalizedStandardCompare") { (lhs, rhs) in - return lhs.localizedStandardCompare(rhs) + public static let localizedStandardCompare = + DatabaseCollation("swiftLocalizedStandardCompare") { (lhs, rhs) in + lhs.localizedStandardCompare(rhs) } } diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 096a246e8..c86139207 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -1,13 +1,13 @@ #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif extension Database { - + // MARK: - Database Observation /// Add a transaction observer, so that it gets notified of @@ -17,7 +17,10 @@ extension Database { /// - parameter extent: The duration of the observation. The default is /// the observer lifetime (observation lasts until observer /// is deallocated). - public func add(transactionObserver: TransactionObserver, extent: TransactionObservationExtent = .observerLifetime) { + public func add( + transactionObserver: TransactionObserver, + extent: TransactionObservationExtent = .observerLifetime) + { SchedulingWatchdog.preconditionValidQueue(self) observationBroker.add(transactionObserver: transactionObserver, extent: extent) } @@ -42,11 +45,11 @@ extension Database { /// /// If the transaction is committed, the closure is executed in a protected /// dispatch queue, serialized will all database updates. - public func afterNextTransactionCommit(_ closure: @escaping (Database) -> ()) { - class CommitHandler : TransactionObserver { - let closure: (Database) -> () + public func afterNextTransactionCommit(_ closure: @escaping (Database) -> Void) { + class CommitHandler: TransactionObserver { + let closure: (Database) -> Void - init(_ closure: @escaping (Database) -> ()) { + init(_ closure: @escaping (Database) -> Void) { self.closure = closure } @@ -195,7 +198,7 @@ class DatabaseObservationBroker { } func disableUntilNextTransaction(transactionObserver: TransactionObserver) { - if let observation = transactionObservations.first(where: { $0.isWrapping(transactionObserver)}) { + if let observation = transactionObservations.first(where: { $0.isWrapping(transactionObserver) }) { observation.isDisabled = true statementObservations.removeFirst { $0.0 === observation } } @@ -293,7 +296,7 @@ class DatabaseObservationBroker { statementObservations = [] database.authorizer = nil SchedulingWatchdog.current!.databaseObservationBroker = nil - + // Reset transactionState before databaseDidRollback eventually // executes other statements. let transactionState = self.transactionState @@ -318,7 +321,7 @@ class DatabaseObservationBroker { statementObservations = [] database.authorizer = nil SchedulingWatchdog.current!.databaseObservationBroker = nil - + // Has statement any effect on transaction/savepoints? if let transactionEffect = statement.transactionEffect { switch transactionEffect { @@ -379,7 +382,7 @@ class DatabaseObservationBroker { } } -#if SQLITE_ENABLE_PREUPDATE_HOOK + #if SQLITE_ENABLE_PREUPDATE_HOOK // Called from sqlite3_preupdate_hook private func databaseWillChange(with event: DatabasePreUpdateEvent) { if savepointStack.isEmpty { @@ -392,7 +395,7 @@ class DatabaseObservationBroker { savepointStack.eventsBuffer.append((event: event.copy(), statementObservations: statementObservations)) } } -#endif + #endif // Called from sqlite3_update_hook private func databaseDidChange(with event: DatabaseEvent) { @@ -597,17 +600,23 @@ class DatabaseObservationBroker { private func installUpdateHook() { let brokerPointer = Unmanaged.passUnretained(self).toOpaque() - sqlite3_update_hook(database.sqliteConnection, { (brokerPointer, updateKind, databaseNameCString, tableNameCString, rowID) in - let broker = Unmanaged.fromOpaque(brokerPointer!).takeUnretainedValue() - broker.databaseDidChange(with: DatabaseEvent( - kind: DatabaseEvent.Kind(rawValue: updateKind)!, - rowID: rowID, - databaseNameCString: databaseNameCString, - tableNameCString: tableNameCString)) - }, brokerPointer) + sqlite3_update_hook( + database.sqliteConnection, + { (brokerPointer, updateKind, databaseNameCString, tableNameCString, rowID) in + let broker = Unmanaged.fromOpaque(brokerPointer!).takeUnretainedValue() + broker.databaseDidChange(with: DatabaseEvent( + kind: DatabaseEvent.Kind(rawValue: updateKind)!, + rowID: rowID, + databaseNameCString: databaseNameCString, + tableNameCString: tableNameCString)) + }, + brokerPointer) #if SQLITE_ENABLE_PREUPDATE_HOOK - sqlite3_preupdate_hook(database.sqliteConnection, { (brokerPointer, databaseConnection, updateKind, databaseNameCString, tableNameCString, initialRowID, finalRowID) in + sqlite3_preupdate_hook( + database.sqliteConnection, + // swiftlint:disable:next line_length + { (brokerPointer, databaseConnection, updateKind, databaseNameCString, tableNameCString, initialRowID, finalRowID) in let broker = Unmanaged.fromOpaque(brokerPointer!).takeUnretainedValue() broker.databaseWillChange(with: DatabasePreUpdateEvent( connection: databaseConnection!, @@ -616,14 +625,15 @@ class DatabaseObservationBroker { finalRowID: finalRowID, databaseNameCString: databaseNameCString, tableNameCString: tableNameCString)) - }, brokerPointer) + }, + brokerPointer) #endif } private func uninstallUpdateHook() { sqlite3_update_hook(database.sqliteConnection, nil, nil) #if SQLITE_ENABLE_PREUPDATE_HOOK - sqlite3_preupdate_hook(database.sqliteConnection, nil, nil) + sqlite3_preupdate_hook(database.sqliteConnection, nil, nil) #endif } @@ -642,7 +652,7 @@ class DatabaseObservationBroker { /// or rollbacked on a database. /// /// Adopting types must be a class. -public protocol TransactionObserver : class { +public protocol TransactionObserver: AnyObject { /// Filters database changes that should be notified the the /// databaseDidChange(with:) method. @@ -713,7 +723,8 @@ public protocol TransactionObserver : class { /// /// As of OSX 10.11.5, and iOS 9.3.2, the built-in SQLite library /// does not have this enabled, so you'll need to compile your own - /// copy using GRDBCustomSQLite. See https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md + /// copy using GRDBCustomSQLite. + /// See https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md /// /// The databaseDidChangeWithEvent callback is always available, /// and may provide most/all of what you need. @@ -726,13 +737,13 @@ extension TransactionObserver { /// Default implementation does nothing public func databaseWillCommit() throws { } - + #if SQLITE_ENABLE_PREUPDATE_HOOK /// Default implementation does nothing public func databaseWillChange(with event: DatabasePreUpdateEvent) { } #endif - + /// After this method has been called, the `databaseDidChange(with:)` /// method won't be called until the next transaction. /// @@ -756,7 +767,10 @@ extension TransactionObserver { /// - precondition: This method must be called from `databaseDidChange(with:)`. public func stopObservingDatabaseChangesUntilNextTransaction() { guard let broker = SchedulingWatchdog.current?.databaseObservationBroker else { - fatalError("stopObservingDatabaseChangesUntilNextTransaction must be called from the databaseDidChange method") + fatalError(""" + stopObservingDatabaseChangesUntilNextTransaction must be called \ + from the databaseDidChange method + """) } broker.disableUntilNextTransaction(transactionObserver: self) } @@ -801,23 +815,23 @@ final class TransactionObservation { if isDisabled { return false } return observer?.observes(eventsOfKind: eventKind) ?? false } - + #if SQLITE_ENABLE_PREUPDATE_HOOK func databaseWillChange(with event: DatabasePreUpdateEvent) { if isDisabled { return } observer?.databaseWillChange(with: event) } #endif - + func databaseDidChange(with event: DatabaseEvent) { if isDisabled { return } observer?.databaseDidChange(with: event) } - + func databaseWillCommit() throws { try observer?.databaseWillCommit() } - + func databaseDidCommit(_ db: Database) { switch extent { case .observerLifetime, .databaseLifetime: @@ -867,11 +881,11 @@ public enum DatabaseEventKind { var modifiedRegion: DatabaseRegion { switch self { - case .delete(let tableName): + case let .delete(tableName): return DatabaseRegion(table: tableName) - case .insert(let tableName): + case let .insert(tableName): return DatabaseRegion(table: tableName) - case .update(let tableName, let updatedColumnNames): + case let .update(tableName, updatedColumnNames): return DatabaseRegion(table: tableName, columns: updatedColumnNames) } } @@ -881,9 +895,9 @@ extension DatabaseEventKind { /// The impacted database table public var tableName: String { switch self { - case .insert(tableName: let tableName): return tableName - case .delete(tableName: let tableName): return tableName - case .update(tableName: let tableName, columnNames: _): return tableName + case let .insert(tableName: tableName): return tableName + case let .delete(tableName: tableName): return tableName + case let .update(tableName: tableName, columnNames: _): return tableName } } } @@ -915,7 +929,7 @@ public struct DatabaseEvent { /// The database name public var databaseName: String { return impl.databaseName } - + /// The table name public var tableName: String { return impl.tableName } @@ -941,11 +955,16 @@ public struct DatabaseEvent { } init(kind: Kind, rowID: Int64, databaseNameCString: UnsafePointer?, tableNameCString: UnsafePointer?) { - self.init(kind: kind, rowID: rowID, impl: MetalDatabaseEventImpl(databaseNameCString: databaseNameCString, tableNameCString: tableNameCString)) + self.init( + kind: kind, + rowID: rowID, + impl: MetalDatabaseEventImpl( + databaseNameCString: databaseNameCString, + tableNameCString: tableNameCString)) } } -extension DatabaseEvent : DatabaseEventProtocol { +extension DatabaseEvent: DatabaseEventProtocol { func send(to observer: TransactionObservation) { observer.databaseDidChange(with: self) } @@ -970,19 +989,25 @@ private protocol DatabaseEventImpl { /// Optimization: MetalDatabaseEventImpl does not create Swift strings from raw /// SQLite char* until actually asked for databaseName or tableName. -private struct MetalDatabaseEventImpl : DatabaseEventImpl { +private struct MetalDatabaseEventImpl: DatabaseEventImpl { let databaseNameCString: UnsafePointer? let tableNameCString: UnsafePointer? - + var databaseName: String { return String(cString: databaseNameCString!) } var tableName: String { return String(cString: tableNameCString!) } + func copy(_ event: DatabaseEvent) -> DatabaseEvent { - return DatabaseEvent(kind: event.kind, rowID: event.rowID, impl: CopiedDatabaseEventImpl(databaseName: databaseName, tableName: tableName)) + return DatabaseEvent( + kind: event.kind, + rowID: event.rowID, + impl: CopiedDatabaseEventImpl( + databaseName: databaseName, + tableName: tableName)) } } /// Impl for DatabaseEvent that contains copies of event strings. -private struct CopiedDatabaseEventImpl : DatabaseEventImpl { +private struct CopiedDatabaseEventImpl: DatabaseEventImpl { let databaseName: String let tableName: String func copy(_ event: DatabaseEvent) -> DatabaseEvent { @@ -992,258 +1017,293 @@ private struct CopiedDatabaseEventImpl : DatabaseEventImpl { #if SQLITE_ENABLE_PREUPDATE_HOOK - public struct DatabasePreUpdateEvent { +public struct DatabasePreUpdateEvent { + + /// An event kind + public enum Kind: Int32 { + /// SQLITE_INSERT + case insert = 18 - /// An event kind - public enum Kind: Int32 { - /// SQLITE_INSERT - case insert = 18 - - /// SQLITE_DELETE - case delete = 9 - - /// SQLITE_UPDATE - case update = 23 - } + /// SQLITE_DELETE + case delete = 9 - /// The event kind - public let kind: Kind - - /// The database name - public var databaseName: String { return impl.databaseName } - - /// The table name - public var tableName: String { return impl.tableName } - - /// The number of columns in the row that is being inserted, updated, or deleted. - public var count: Int { return Int(impl.columnsCount) } - - /// The triggering depth of the row update - /// Returns: - /// 0 if the preupdate callback was invoked as a result of a direct insert, - // update, or delete operation; - /// 1 for inserts, updates, or deletes invoked by top-level triggers; - /// 2 for changes resulting from triggers called by top-level triggers; - /// ... and so forth - public var depth: CInt { return impl.depth } - - /// The initial rowID of the row being changed for .Update and .Delete changes, - /// and nil for .Insert changes. - public let initialRowID: Int64? - - /// The final rowID of the row being changed for .Update and .Insert changes, - /// and nil for .Delete changes. - public let finalRowID: Int64? - - /// The initial database values in the row. - /// - /// Values appear in the same order as the columns in the table. - /// - /// The result is nil if the event is an .Insert event. - public var initialDatabaseValues: [DatabaseValue]? { - guard (kind == .update || kind == .delete) else { return nil } - return impl.initialDatabaseValues - } - - /// Returns the initial `DatabaseValue` at given index. - /// - /// Indexes span from 0 for the leftmost column to (row.count - 1) for the - /// righmost column. - /// - /// The result is nil if the event is an .Insert event. - public func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { - GRDBPrecondition(index >= 0 && index < count, "row index out of range") - guard (kind == .update || kind == .delete) else { return nil } - return impl.initialDatabaseValue(atIndex: index) - } - - /// The final database values in the row. - /// - /// Values appear in the same order as the columns in the table. - /// - /// The result is nil if the event is a .Delete event. - public var finalDatabaseValues: [DatabaseValue]? { - guard (kind == .update || kind == .insert) else { return nil } - return impl.finalDatabaseValues - } - - /// Returns the final `DatabaseValue` at given index. - /// - /// Indexes span from 0 for the leftmost column to (row.count - 1) for the - /// righmost column. - /// - /// The result is nil if the event is a .Delete event. - public func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { - GRDBPrecondition(index >= 0 && index < count, "row index out of range") - guard (kind == .update || kind == .insert) else { return nil } - return impl.finalDatabaseValue(atIndex: index) - } - - /// Returns an event that can be stored: - /// - /// class MyObserver: TransactionObserver { - /// var events: [DatabasePreUpdateEvent] - /// func databaseWillChange(with event: DatabasePreUpdateEvent) { - /// events.append(event.copy()) - /// } - /// } - public func copy() -> DatabasePreUpdateEvent { - return impl.copy(self) - } - - fileprivate init(kind: Kind, initialRowID: Int64?, finalRowID: Int64?, impl: DatabasePreUpdateEventImpl) { - self.kind = kind - self.initialRowID = (kind == .update || kind == .delete ) ? initialRowID : nil - self.finalRowID = (kind == .update || kind == .insert ) ? finalRowID : nil - self.impl = impl - } - - init(connection: SQLiteConnection, kind: Kind, initialRowID: Int64, finalRowID: Int64, databaseNameCString: UnsafePointer?, tableNameCString: UnsafePointer?) { - self.init(kind: kind, - initialRowID: (kind == .update || kind == .delete ) ? finalRowID : nil, - finalRowID: (kind == .update || kind == .insert ) ? finalRowID : nil, - impl: MetalDatabasePreUpdateEventImpl(connection: connection, kind: kind, databaseNameCString: databaseNameCString, tableNameCString: tableNameCString)) - } - - private let impl: DatabasePreUpdateEventImpl + /// SQLITE_UPDATE + case update = 23 } - extension DatabasePreUpdateEvent : DatabaseEventProtocol { - func send(to observer: TransactionObservation) { - observer.databaseWillChange(with: self) - } - - func matchesKind(_ databaseEventKind: DatabaseEventKind) -> Bool { - switch (kind, databaseEventKind) { - case (.insert, .insert(let tableName)): return self.tableName == tableName - case (.delete, .delete(let tableName)): return self.tableName == tableName - case (.update, .update(let tableName, _)): return self.tableName == tableName - default: - return false - } - } + /// The event kind + public let kind: Kind + + /// The database name + public var databaseName: String { return impl.databaseName } + + /// The table name + public var tableName: String { return impl.tableName } + + /// The number of columns in the row that is being inserted, updated, or deleted. + public var count: Int { return Int(impl.columnsCount) } + + /// The triggering depth of the row update + /// Returns: + /// 0 if the preupdate callback was invoked as a result of a direct insert, + // update, or delete operation; + /// 1 for inserts, updates, or deletes invoked by top-level triggers; + /// 2 for changes resulting from triggers called by top-level triggers; + /// ... and so forth + public var depth: CInt { return impl.depth } + + /// The initial rowID of the row being changed for .Update and .Delete changes, + /// and nil for .Insert changes. + public let initialRowID: Int64? + + /// The final rowID of the row being changed for .Update and .Insert changes, + /// and nil for .Delete changes. + public let finalRowID: Int64? + + /// The initial database values in the row. + /// + /// Values appear in the same order as the columns in the table. + /// + /// The result is nil if the event is an .Insert event. + public var initialDatabaseValues: [DatabaseValue]? { + guard kind == .update || kind == .delete else { return nil } + return impl.initialDatabaseValues } - /// Protocol for internal implementation of DatabaseEvent - private protocol DatabasePreUpdateEventImpl { - var databaseName: String { get } - var tableName: String { get } - - var columnsCount: CInt { get } - var depth: CInt { get } - var initialDatabaseValues: [DatabaseValue]? { get } - var finalDatabaseValues: [DatabaseValue]? { get } - - func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? - func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? - - func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent + /// Returns the initial `DatabaseValue` at given index. + /// + /// Indexes span from 0 for the leftmost column to (row.count - 1) for the + /// righmost column. + /// + /// The result is nil if the event is an .Insert event. + public func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { + GRDBPrecondition(index >= 0 && index < count, "row index out of range") + guard kind == .update || kind == .delete else { return nil } + return impl.initialDatabaseValue(atIndex: index) } - /// Optimization: MetalDatabasePreUpdateEventImpl does not create Swift strings from raw - /// SQLite char* until actually asked for databaseName or tableName, - /// nor does it request other data via the sqlite3_preupdate_* APIs - /// until asked. - private struct MetalDatabasePreUpdateEventImpl : DatabasePreUpdateEventImpl { - let connection: SQLiteConnection - let kind: DatabasePreUpdateEvent.Kind - - let databaseNameCString: UnsafePointer? - let tableNameCString: UnsafePointer? - - var databaseName: String { return String(cString: databaseNameCString!) } - var tableName: String { return String(cString: tableNameCString!) } - - var columnsCount: CInt { return sqlite3_preupdate_count(connection) } - var depth: CInt { return sqlite3_preupdate_depth(connection) } - var initialDatabaseValues: [DatabaseValue]? { - guard (kind == .update || kind == .delete) else { return nil } - return preupdate_getValues_old(connection) - } - - var finalDatabaseValues: [DatabaseValue]? { - guard (kind == .update || kind == .insert) else { return nil } - return preupdate_getValues_new(connection) - } - - func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { - let columnCount = columnsCount - precondition(index >= 0 && index < Int(columnCount), "row index out of range") - return getValue(connection, column: CInt(index), sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in - return sqlite3_preupdate_old(connection, column, &value) - }) - } - - func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { - let columnCount = columnsCount - precondition(index >= 0 && index < Int(columnCount), "row index out of range") - return getValue(connection, column: CInt(index), sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in - return sqlite3_preupdate_new(connection, column, &value) - }) - } - - func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent { - return DatabasePreUpdateEvent(kind: event.kind, initialRowID: event.initialRowID, finalRowID: event.finalRowID, impl: CopiedDatabasePreUpdateEventImpl( - databaseName: databaseName, - tableName: tableName, - columnsCount: columnsCount, - depth: depth, - initialDatabaseValues: initialDatabaseValues, - finalDatabaseValues: finalDatabaseValues)) - } - - private func preupdate_getValues(_ connection: SQLiteConnection, sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt ) -> [DatabaseValue]? { - let columnCount = sqlite3_preupdate_count(connection) - guard columnCount > 0 else { return nil } - - var columnValues = [DatabaseValue]() - - for i in 0.. CInt ) -> DatabaseValue? { - var value : SQLiteValue? = nil - guard sqlite_func(connection, column, &value) == SQLITE_OK else { return nil } - if let value = value { - return DatabaseValue(sqliteValue: value) - } - return nil - } - - private func preupdate_getValues_old(_ connection: SQLiteConnection) -> [DatabaseValue]? { - return preupdate_getValues(connection, sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in - return sqlite3_preupdate_old(connection, column, &value) - }) - } - - private func preupdate_getValues_new(_ connection: SQLiteConnection) -> [DatabaseValue]? { - return preupdate_getValues(connection, sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in - return sqlite3_preupdate_new(connection, column, &value) - }) - } + /// The final database values in the row. + /// + /// Values appear in the same order as the columns in the table. + /// + /// The result is nil if the event is a .Delete event. + public var finalDatabaseValues: [DatabaseValue]? { + guard kind == .update || kind == .insert else { return nil } + return impl.finalDatabaseValues } - /// Impl for DatabasePreUpdateEvent that contains copies of all event data. - private struct CopiedDatabasePreUpdateEventImpl : DatabasePreUpdateEventImpl { - let databaseName: String - let tableName: String - let columnsCount: CInt - let depth: CInt - let initialDatabaseValues: [DatabaseValue]? - let finalDatabaseValues: [DatabaseValue]? - - func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { return initialDatabaseValues?[index] } - func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { return finalDatabaseValues?[index] } - - func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent { - return event + /// Returns the final `DatabaseValue` at given index. + /// + /// Indexes span from 0 for the leftmost column to (row.count - 1) for the + /// righmost column. + /// + /// The result is nil if the event is a .Delete event. + public func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { + GRDBPrecondition(index >= 0 && index < count, "row index out of range") + guard kind == .update || kind == .insert else { return nil } + return impl.finalDatabaseValue(atIndex: index) + } + + /// Returns an event that can be stored: + /// + /// class MyObserver: TransactionObserver { + /// var events: [DatabasePreUpdateEvent] + /// func databaseWillChange(with event: DatabasePreUpdateEvent) { + /// events.append(event.copy()) + /// } + /// } + public func copy() -> DatabasePreUpdateEvent { + return impl.copy(self) + } + + fileprivate init(kind: Kind, initialRowID: Int64?, finalRowID: Int64?, impl: DatabasePreUpdateEventImpl) { + self.kind = kind + self.initialRowID = (kind == .update || kind == .delete ) ? initialRowID : nil + self.finalRowID = (kind == .update || kind == .insert ) ? finalRowID : nil + self.impl = impl + } + + init( + connection: SQLiteConnection, + kind: Kind, + initialRowID: Int64, + finalRowID: Int64, + databaseNameCString: UnsafePointer?, + tableNameCString: UnsafePointer?) + { + self.init( + kind: kind, + initialRowID: (kind == .update || kind == .delete ) ? finalRowID : nil, + finalRowID: (kind == .update || kind == .insert ) ? finalRowID : nil, + impl: MetalDatabasePreUpdateEventImpl( + connection: connection, + kind: kind, + databaseNameCString: databaseNameCString, + tableNameCString: tableNameCString)) + } + + private let impl: DatabasePreUpdateEventImpl +} + +extension DatabasePreUpdateEvent: DatabaseEventProtocol { + func send(to observer: TransactionObservation) { + observer.databaseWillChange(with: self) + } + + func matchesKind(_ databaseEventKind: DatabaseEventKind) -> Bool { + switch (kind, databaseEventKind) { + case (.insert, .insert(let tableName)): return self.tableName == tableName + case (.delete, .delete(let tableName)): return self.tableName == tableName + case (.update, .update(let tableName, _)): return self.tableName == tableName + default: + return false } } +} + +/// Protocol for internal implementation of DatabaseEvent +private protocol DatabasePreUpdateEventImpl { + var databaseName: String { get } + var tableName: String { get } + + var columnsCount: CInt { get } + var depth: CInt { get } + var initialDatabaseValues: [DatabaseValue]? { get } + var finalDatabaseValues: [DatabaseValue]? { get } + + func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? + func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? + + func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent +} + +/// Optimization: MetalDatabasePreUpdateEventImpl does not create Swift strings from raw +/// SQLite char* until actually asked for databaseName or tableName, +/// nor does it request other data via the sqlite3_preupdate_* APIs +/// until asked. +private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { + let connection: SQLiteConnection + let kind: DatabasePreUpdateEvent.Kind + + let databaseNameCString: UnsafePointer? + let tableNameCString: UnsafePointer? + + var databaseName: String { return String(cString: databaseNameCString!) } + var tableName: String { return String(cString: tableNameCString!) } + + var columnsCount: CInt { return sqlite3_preupdate_count(connection) } + var depth: CInt { return sqlite3_preupdate_depth(connection) } + var initialDatabaseValues: [DatabaseValue]? { + guard kind == .update || kind == .delete else { return nil } + return preupdate_getValues_old(connection) + } + + var finalDatabaseValues: [DatabaseValue]? { + guard kind == .update || kind == .insert else { return nil } + return preupdate_getValues_new(connection) + } + + func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { + let columnCount = columnsCount + precondition(index >= 0 && index < Int(columnCount), "row index out of range") + return getValue( + connection, + column: CInt(index), + sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in + sqlite3_preupdate_old(connection, column, &value) + }) + } + + func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { + let columnCount = columnsCount + precondition(index >= 0 && index < Int(columnCount), "row index out of range") + return getValue( + connection, + column: CInt(index), + sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in + sqlite3_preupdate_new(connection, column, &value) + }) + } + + func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent { + return DatabasePreUpdateEvent( + kind: event.kind, + initialRowID: event.initialRowID, + finalRowID: event.finalRowID, + impl: CopiedDatabasePreUpdateEventImpl( + databaseName: databaseName, + tableName: tableName, + columnsCount: columnsCount, + depth: depth, + initialDatabaseValues: initialDatabaseValues, + finalDatabaseValues: finalDatabaseValues)) + } + + private func preupdate_getValues( + _ connection: SQLiteConnection, + sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt) + -> [DatabaseValue]? + { + let columnCount = sqlite3_preupdate_count(connection) + guard columnCount > 0 else { return nil } + + var columnValues = [DatabaseValue]() + + for i in 0.. CInt) + -> DatabaseValue? + { + var value: SQLiteValue? = nil + guard sqlite_func(connection, column, &value) == SQLITE_OK else { return nil } + if let value = value { + return DatabaseValue(sqliteValue: value) + } + return nil + } + + private func preupdate_getValues_old(_ connection: SQLiteConnection) -> [DatabaseValue]? { + return preupdate_getValues( + connection, + sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in + sqlite3_preupdate_old(connection, column, &value) + }) + } + + private func preupdate_getValues_new(_ connection: SQLiteConnection) -> [DatabaseValue]? { + return preupdate_getValues( + connection, + sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in + sqlite3_preupdate_new(connection, column, &value) + }) + } +} + +/// Impl for DatabasePreUpdateEvent that contains copies of all event data. +private struct CopiedDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { + let databaseName: String + let tableName: String + let columnsCount: CInt + let depth: CInt + let initialDatabaseValues: [DatabaseValue]? + let finalDatabaseValues: [DatabaseValue]? + + func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { return initialDatabaseValues?[index] } + func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { return finalDatabaseValues?[index] } + + func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent { + return event + } +} #endif @@ -1330,4 +1390,3 @@ class SavepointStack { } } } - diff --git a/GRDB/FTS/FTS3.swift b/GRDB/FTS/FTS3.swift index 4bf3abfca..edc39bac3 100644 --- a/GRDB/FTS/FTS3.swift +++ b/GRDB/FTS/FTS3.swift @@ -4,7 +4,7 @@ /// try db.create(virtualTable: "document", using: FTS3()) { t in /// t.column("content") /// } -public struct FTS3 : VirtualTableModule { +public struct FTS3: VirtualTableModule { /// Options for Latin script characters. Matches the raw "remove_diacritics" /// tokenizer argument. /// @@ -55,7 +55,10 @@ public struct FTS3 : VirtualTableModule { if tokenizer.arguments.isEmpty { arguments.append("tokenize=\(tokenizer.name)") } else { - arguments.append("tokenize=\(tokenizer.name) " + tokenizer.arguments.map { "\"\($0)\"" as String }.joined(separator: " ")) + arguments.append( + "tokenize=\(tokenizer.name) " + tokenizer.arguments + .map { "\"\($0)\"" as String } + .joined(separator: " ")) } } return arguments diff --git a/GRDB/FTS/FTS3Pattern.swift b/GRDB/FTS/FTS3Pattern.swift index 69c43d0e1..4859285ee 100644 --- a/GRDB/FTS/FTS3Pattern.swift +++ b/GRDB/FTS/FTS3Pattern.swift @@ -24,7 +24,7 @@ public struct FTS3Pattern { } } catch let error as DatabaseError { // Remove private SQL & arguments from the thrown error - throw DatabaseError(resultCode: error.extendedResultCode, message: error.message, sql: nil, arguments: nil) + throw DatabaseError(resultCode: error.extendedResultCode, message: error.message) } // Pattern is valid @@ -115,7 +115,7 @@ public struct FTS3Pattern { #endif } -extension FTS3Pattern : DatabaseValueConvertible { +extension FTS3Pattern: DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { return rawPattern.databaseValue diff --git a/GRDB/FTS/FTS3TokenizerDescriptor.swift b/GRDB/FTS/FTS3TokenizerDescriptor.swift index 44f667d0f..8f4f6a401 100644 --- a/GRDB/FTS/FTS3TokenizerDescriptor.swift +++ b/GRDB/FTS/FTS3TokenizerDescriptor.swift @@ -48,7 +48,12 @@ public struct FTS3TokenizerDescriptor { /// these characters as token characters. /// /// See https://www.sqlite.org/fts3.html#tokenizer - public static func unicode61(diacritics: FTS3.Diacritics = .removeLegacy, separators: Set = [], tokenCharacters: Set = []) -> FTS3TokenizerDescriptor { + public static func unicode61( + diacritics: FTS3.Diacritics = .removeLegacy, + separators: Set = [], + tokenCharacters: Set = []) + -> FTS3TokenizerDescriptor + { return _unicode61(diacritics: diacritics, separators: separators, tokenCharacters: tokenCharacters) } #else @@ -68,14 +73,25 @@ public struct FTS3TokenizerDescriptor { /// /// See https://www.sqlite.org/fts3.html#tokenizer @available(OSX 10.10, *) - public static func unicode61(diacritics: FTS3.Diacritics = .removeLegacy, separators: Set = [], tokenCharacters: Set = []) -> FTS3TokenizerDescriptor { + public static func unicode61( + diacritics: FTS3.Diacritics = .removeLegacy, + separators: Set = [], + tokenCharacters: Set = []) + -> FTS3TokenizerDescriptor + { // query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + // It is available from iOS 8.2 and OS X 10.10 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) return _unicode61(diacritics: diacritics, separators: separators, tokenCharacters: tokenCharacters) } #endif - private static func _unicode61(diacritics: FTS3.Diacritics, separators: Set = [], tokenCharacters: Set = []) -> FTS3TokenizerDescriptor { + private static func _unicode61( + diacritics: FTS3.Diacritics, + separators: Set = [], + tokenCharacters: Set = []) + -> FTS3TokenizerDescriptor + { var arguments: [String] = [] switch diacritics { case .removeLegacy: @@ -88,12 +104,16 @@ public struct FTS3TokenizerDescriptor { #endif } if !separators.isEmpty { - // TODO: test "=" and "\"", "(" and ")" as separators, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:) - arguments.append("separators=" + separators.sorted().map { String($0) }.joined(separator: "")) + // TODO: test "=" and "\"", "(" and ")" as separators, with + // both FTS3Pattern(matchingAnyTokenIn:tokenizer:) + // and Database.create(virtualTable:using:) + arguments.append("separators=" + separators.sorted().map { String($0) }.joined()) } if !tokenCharacters.isEmpty { - // TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:) - arguments.append("tokenchars=" + tokenCharacters.sorted().map { String($0) }.joined(separator: "")) + // TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with + // both FTS3Pattern(matchingAnyTokenIn:tokenizer:) + // and Database.create(virtualTable:using:) + arguments.append("tokenchars=" + tokenCharacters.sorted().map { String($0) }.joined()) } return FTS3TokenizerDescriptor("unicode61", arguments: arguments) } @@ -108,13 +128,14 @@ public struct FTS3TokenizerDescriptor { return _tokenize(string) } #endif - + /// Returns an array of tokens found in the string argument. /// /// FTS3TokenizerDescriptor.simple.tokenize("foo bar") // ["foo", "bar"] private func _tokenize(_ string: String) -> [String] { // fts3tokenize was introduced in SQLite 3.7.17 https://www.sqlite.org/changes.html#version_3_7_17 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + // It is available from iOS 8.2 and OS X 10.10 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) return DatabaseQueue().inDatabase { db in var tokenizerChunks: [String] = [] tokenizerChunks.append(name) @@ -124,7 +145,9 @@ public struct FTS3TokenizerDescriptor { let tokenizerSQL = tokenizerChunks.joined(separator: ", ") // Assume fts3tokenize virtual table in an in-memory database always succeeds try! db.execute(sql: "CREATE VIRTUAL TABLE tokens USING fts3tokenize(\(tokenizerSQL))") - return try! String.fetchAll(db, sql: "SELECT token FROM tokens WHERE input = ? ORDER BY position", arguments: [string]) + return try! String.fetchAll(db, sql: """ + SELECT token FROM tokens WHERE input = ? ORDER BY position + """, arguments: [string]) } } } diff --git a/GRDB/FTS/FTS4.swift b/GRDB/FTS/FTS4.swift index 56dc6e0f8..29cfc4b85 100644 --- a/GRDB/FTS/FTS4.swift +++ b/GRDB/FTS/FTS4.swift @@ -6,7 +6,7 @@ /// } /// /// See https://www.sqlite.org/fts3.html -public struct FTS4 : VirtualTableModule { +public struct FTS4: VirtualTableModule { /// Creates a FTS4 module suitable for the Database /// `create(virtualTable:using:)` method. @@ -53,7 +53,10 @@ public struct FTS4 : VirtualTableModule { if tokenizer.arguments.isEmpty { arguments.append("tokenize=\(tokenizer.name)") } else { - arguments.append("tokenize=\(tokenizer.name) " + tokenizer.arguments.map { "\"\($0)\"" as String }.joined(separator: " ")) + arguments.append( + "tokenize=\(tokenizer.name) " + tokenizer.arguments + .map { "\"\($0)\"" as String } + .joined(separator: " ")) } } @@ -273,7 +276,8 @@ public final class FTS4ColumnDefinition { @discardableResult public func notIndexed() -> Self { // notindexed FTS4 option was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + // It is available from iOS 8.2 and OS X 10.10 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) self.isIndexed = false return self } @@ -292,7 +296,8 @@ public final class FTS4ColumnDefinition { @discardableResult public func notIndexed() -> Self { // notindexed FTS4 option was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + // It is available from iOS 8.2 and OS X 10.10 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) self.isIndexed = false return self } diff --git a/GRDB/FTS/FTS5.swift b/GRDB/FTS/FTS5.swift index d7346948f..83c4c83e2 100644 --- a/GRDB/FTS/FTS5.swift +++ b/GRDB/FTS/FTS5.swift @@ -1,10 +1,10 @@ #if SQLITE_ENABLE_FTS5 #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// FTS5 lets you define "fts5" virtual tables. @@ -15,7 +15,7 @@ /// } /// /// See https://www.sqlite.org/fts5.html -public struct FTS5 : VirtualTableModule { +public struct FTS5: VirtualTableModule { /// Options for Latin script characters. Matches the raw "remove_diacritics" /// tokenizer argument. /// @@ -34,7 +34,7 @@ public struct FTS5 : VirtualTableModule { case remove #endif } - + /// Creates a FTS5 module suitable for the Database /// `create(virtualTable:using:)` method. /// @@ -75,30 +75,41 @@ public struct FTS5 : VirtualTableModule { } if let tokenizer = definition.tokenizer { - arguments.append("tokenize=\(tokenizer.components.joined(separator: " ").sqlExpression.quotedSQL(wrappedInParenthesis: false))") + let tokenizerSQL = tokenizer + .components + .joined(separator: " ") + .sqlExpression + .quotedSQL() + arguments.append("tokenize=\(tokenizerSQL)") } switch definition.contentMode { - case .raw(let content, let contentRowID): + case let .raw(content, contentRowID): if let content = content { - let quotedContent = content.sqlExpression.quotedSQL(wrappedInParenthesis: false) + let quotedContent = content.sqlExpression.quotedSQL() arguments.append("content=\(quotedContent)") } if let contentRowID = contentRowID { - let quotedContentRowID = contentRowID.sqlExpression.quotedSQL(wrappedInParenthesis: false) + let quotedContentRowID = contentRowID.sqlExpression.quotedSQL() arguments.append("content_rowid=\(quotedContentRowID)") } - case .synchronized(let contentTable): - arguments.append("content=\(contentTable.sqlExpression.quotedSQL(wrappedInParenthesis: false))") + case let .synchronized(contentTable): + arguments.append("content=\(contentTable.sqlExpression.quotedSQL())") if let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn { - let quotedRowID = rowIDColumn.sqlExpression.quotedSQL(wrappedInParenthesis: false) + let quotedRowID = rowIDColumn.sqlExpression.quotedSQL() arguments.append("content_rowid=\(quotedRowID)") } } if let prefixes = definition.prefixes { - arguments.append("prefix=\(prefixes.sorted().map { "\($0)" }.joined(separator: " ").sqlExpression.quotedSQL(wrappedInParenthesis: false))") + let prefix = prefixes + .sorted() + .map { "\($0)" } + .joined(separator: " ") + .sqlExpression + .quotedSQL() + arguments.append("prefix=\(prefix)") } if let columnSize = definition.columnSize { @@ -141,14 +152,14 @@ public struct FTS5 : VirtualTableModule { try db.execute(sql: """ CREATE TRIGGER \("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN - INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); + INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); END; CREATE TRIGGER \("__\(tableName)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN - INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); + INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); END; CREATE TRIGGER \("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN - INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); - INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); + INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); + INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); END; """) @@ -190,7 +201,7 @@ public struct FTS5 : VirtualTableModule { } #if swift(>=5.0) return data.withUnsafeBytes { - $0.bindMemory(to: UnsafePointer.self).first! + $0.bindMemory(to: UnsafePointer.self).first! } #else return data.withUnsafeBytes { @@ -203,7 +214,9 @@ public struct FTS5 : VirtualTableModule { // https://forums.swift.org/t/c-interoperability-combinations-of-library-and-os-versions/14029/4 private static func api_v2( _ db: Database, + // swiftlint:disable:next line_length _ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer?, Int32, UInt32, UnsafeMutablePointer?, UnsafeMutablePointer?>?) -> Int32, + // swiftlint:disable:next line_length _ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, Int32, UnsafeMutableRawPointer?, UnsafePointer?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> Int32) -> UnsafePointer { diff --git a/GRDB/FTS/FTS5CustomTokenizer.swift b/GRDB/FTS/FTS5CustomTokenizer.swift index 9d3a54570..ebfc24d5c 100644 --- a/GRDB/FTS/FTS5CustomTokenizer.swift +++ b/GRDB/FTS/FTS5CustomTokenizer.swift @@ -1,14 +1,14 @@ #if SQLITE_ENABLE_FTS5 #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// The protocol for custom FTS5 tokenizers. -public protocol FTS5CustomTokenizer : FTS5Tokenizer { +public protocol FTS5CustomTokenizer: FTS5Tokenizer { /// The name of the tokenizer; should uniquely identify your custom /// tokenizer. static var name: String { get } @@ -41,7 +41,6 @@ extension FTS5CustomTokenizer { public static func tokenizerDescriptor(arguments: [String] = []) -> FTS5TokenizerDescriptor { return FTS5TokenizerDescriptor(components: [name] + arguments) } - } extension Database { @@ -52,7 +51,10 @@ extension Database { let db: Database let constructor: (Database, [String], UnsafeMutablePointer?) -> Int32 - init(db: Database, constructor: @escaping (Database, [String], UnsafeMutablePointer?) -> Int32) { + init( + db: Database, + constructor: @escaping (Database, [String], UnsafeMutablePointer?) -> Int32) + { self.db = db self.constructor = constructor } @@ -101,7 +103,13 @@ extension Database { Unmanaged.fromOpaque(constructorPointer).release() } - func xCreateTokenizer(constructorPointer: UnsafeMutableRawPointer?, azArg: UnsafeMutablePointer?>?, nArg: Int32, tokenizerHandle: UnsafeMutablePointer?) -> Int32 { + func xCreateTokenizer( + constructorPointer: UnsafeMutableRawPointer?, + azArg: UnsafeMutablePointer?>?, + nArg: Int32, + tokenizerHandle: UnsafeMutablePointer?) + -> Int32 + { guard let constructorPointer = constructorPointer else { return SQLITE_ERROR } @@ -122,20 +130,41 @@ extension Database { Unmanaged.fromOpaque(UnsafeMutableRawPointer(tokenizerPointer)).release() } - func xTokenize(tokenizerPointer: OpaquePointer?, context: UnsafeMutableRawPointer?, flags: Int32, pText: UnsafePointer?, nText: Int32, tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, Int32, UnsafePointer?, Int32, Int32, Int32) -> Int32)?) -> Int32 { + func xTokenize( + tokenizerPointer: OpaquePointer?, + context: UnsafeMutableRawPointer?, + flags: Int32, + pText: UnsafePointer?, + nText: Int32, + // swiftlint:disable:next line_length + tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, Int32, UnsafePointer?, Int32, Int32, Int32) -> Int32)?) + -> Int32 + { guard let tokenizerPointer = tokenizerPointer else { return SQLITE_ERROR } - let object = Unmanaged.fromOpaque(UnsafeMutableRawPointer(tokenizerPointer)).takeUnretainedValue() + let object = Unmanaged + .fromOpaque(UnsafeMutableRawPointer(tokenizerPointer)) + .takeUnretainedValue() guard let tokenizer = object as? FTS5Tokenizer else { return SQLITE_ERROR } - return tokenizer.tokenize(context: context, tokenization: FTS5Tokenization(rawValue: flags), pText: pText, nText: nText, tokenCallback: tokenCallback!) + return tokenizer.tokenize( + context: context, + tokenization: FTS5Tokenization(rawValue: flags), + pText: pText, + nText: nText, + tokenCallback: tokenCallback!) } var xTokenizer = fts5_tokenizer(xCreate: xCreateTokenizer, xDelete: xDeleteTokenizer, xTokenize: xTokenize) let code = withUnsafeMutablePointer(to: &xTokenizer) { xTokenizerPointer in - api.pointee.xCreateTokenizer(UnsafeMutablePointer(mutating: api), Tokenizer.name, constructorPointer, xTokenizerPointer, deleteConstructor) + api.pointee.xCreateTokenizer( + UnsafeMutablePointer(mutating: api), + Tokenizer.name, + constructorPointer, + xTokenizerPointer, + deleteConstructor) } guard code == SQLITE_OK else { // Assume a GRDB bug: there is no point throwing any error. diff --git a/GRDB/FTS/FTS5Pattern.swift b/GRDB/FTS/FTS5Pattern.swift index c67558f10..72632c932 100644 --- a/GRDB/FTS/FTS5Pattern.swift +++ b/GRDB/FTS/FTS5Pattern.swift @@ -13,7 +13,14 @@ public struct FTS5Pattern { /// /// - parameter string: The string to turn into an FTS5 pattern public init?(matchingAnyTokenIn string: String) { - guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil } + guard + let tokens = try? DatabaseQueue().inDatabase({ db in + try db + .makeTokenizer(.ascii()) + .nonSynonymTokens(in: string, for: .query) }) + else { + return nil + } guard !tokens.isEmpty else { return nil } try? self.init(rawPattern: tokens.joined(separator: " OR ")) } @@ -26,7 +33,14 @@ public struct FTS5Pattern { /// /// - parameter string: The string to turn into an FTS5 pattern public init?(matchingAllTokensIn string: String) { - guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil } + guard + let tokens = try? DatabaseQueue().inDatabase({ db in + try db + .makeTokenizer(.ascii()) + .nonSynonymTokens(in: string, for: .query) }) + else { + return nil + } guard !tokens.isEmpty else { return nil } try? self.init(rawPattern: tokens.joined(separator: " ")) } @@ -39,7 +53,14 @@ public struct FTS5Pattern { /// /// - parameter string: The string to turn into an FTS5 pattern public init?(matchingPhrase string: String) { - guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil } + guard + let tokens = try? DatabaseQueue().inDatabase({ db in + try db + .makeTokenizer(.ascii()) + .nonSynonymTokens(in: string, for: .query) }) + else { + return nil + } guard !tokens.isEmpty else { return nil } try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"") } @@ -52,7 +73,14 @@ public struct FTS5Pattern { /// /// - parameter string: The string to turn into an FTS5 pattern public init?(matchingPrefixPhrase string: String) { - guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil } + guard + let tokens = try? DatabaseQueue().inDatabase({ db in + try db + .makeTokenizer(.ascii()) + .nonSynonymTokens(in: string, for: .query) }) + else { + return nil + } guard !tokens.isEmpty else { return nil } try? self.init(rawPattern: "^\"" + tokens.joined(separator: " ") + "\"") } @@ -80,7 +108,7 @@ public struct FTS5Pattern { } } catch let error as DatabaseError { // Remove private SQL & arguments from the thrown error - throw DatabaseError(resultCode: error.extendedResultCode, message: error.message, sql: nil, arguments: nil) + throw DatabaseError(resultCode: error.extendedResultCode, message: error.message) } // Pattern is valid @@ -104,7 +132,7 @@ extension Database { } } -extension FTS5Pattern : DatabaseValueConvertible { +extension FTS5Pattern: DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { return rawPattern.databaseValue diff --git a/GRDB/FTS/FTS5Tokenizer.swift b/GRDB/FTS/FTS5Tokenizer.swift index d5dd44de2..ab659f264 100644 --- a/GRDB/FTS/FTS5Tokenizer.swift +++ b/GRDB/FTS/FTS5Tokenizer.swift @@ -1,21 +1,28 @@ #if SQLITE_ENABLE_FTS5 #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// A low-level SQLite function that lets FTS5Tokenizer notify tokens. /// /// See FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:) -public typealias FTS5TokenCallback = @convention(c) (_ context: UnsafeMutableRawPointer?, _ flags: Int32, _ pToken: UnsafePointer?, _ nToken: Int32, _ iStart: Int32, _ iEnd: Int32) -> Int32 +public typealias FTS5TokenCallback = @convention(c) ( + _ context: UnsafeMutableRawPointer?, + _ flags: Int32, + _ pToken: UnsafePointer?, + _ nToken: Int32, + _ iStart: Int32, + _ iEnd: Int32) + -> Int32 /// The reason why FTS5 is requesting tokenization. /// /// See https://www.sqlite.org/fts5.html#custom_tokenizers -public struct FTS5Tokenization : OptionSet { +public struct FTS5Tokenization: OptionSet { public let rawValue: Int32 public init(rawValue: Int32) { @@ -36,7 +43,7 @@ public struct FTS5Tokenization : OptionSet { } /// The protocol for FTS5 tokenizers -public protocol FTS5Tokenizer : class { +public protocol FTS5Tokenizer: AnyObject { /// Tokenizes the text described by `pText` and `nText`, and /// notifies found tokens to the `tokenCallback` function. /// @@ -51,7 +58,13 @@ public protocol FTS5Tokenizer : class { /// - nText: The number of bytes in the tokenized text. /// - tokenCallback: The function to call for each found token. /// It matches the `xToken` callback at https://www.sqlite.org/fts5.html#custom_tokenizers - func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 + func tokenize( + context: UnsafeMutableRawPointer?, + tokenization: FTS5Tokenization, + pText: UnsafePointer?, + nText: Int32, + tokenCallback: @escaping FTS5TokenCallback) + -> Int32 } private class TokenizeContext { @@ -81,20 +94,34 @@ extension FTS5Tokenizer { var context = TokenizeContext() try withUnsafeMutablePointer(to: &context) { contextPointer in - let code = tokenize(context: UnsafeMutableRawPointer(contextPointer), tokenization: tokenization, pText: pText, nText: nText, tokenCallback: { (contextPointer, flags, pToken, nToken, iStart, iEnd) -> Int32 in - guard let contextPointer = contextPointer else { return SQLITE_ERROR } - - // Extract token - guard let token = pToken.flatMap({ String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0), count: Int(nToken), deallocator: .none), encoding: .utf8) }) else { + let code = tokenize( + context: UnsafeMutableRawPointer(contextPointer), + tokenization: tokenization, + pText: pText, + nText: nText, + tokenCallback: { (contextPointer, flags, pToken, nToken, _ /* iStart */, _ /* iEnd */) -> Int32 in + guard let contextPointer = contextPointer else { + return SQLITE_ERROR + } + + // Extract token + guard + let token = pToken.flatMap({ + String( + data: Data( + bytesNoCopy: UnsafeMutableRawPointer(mutating: $0), + count: Int(nToken), + deallocator: .none), + encoding: .utf8) }) + else { + return SQLITE_OK + } + + let context = contextPointer.assumingMemoryBound(to: TokenizeContext.self).pointee + context.tokens.append((token, FTS5TokenFlags(rawValue: flags))) return SQLITE_OK - } - - let context = contextPointer.assumingMemoryBound(to: TokenizeContext.self).pointee - context.tokens.append((token, FTS5TokenFlags(rawValue: flags))) - - return SQLITE_OK }) - if (code != SQLITE_OK) { + if code != SQLITE_OK { throw DatabaseError(resultCode: code) } } @@ -119,13 +146,13 @@ extension Database { /// Private type that makes a pre-registered FTS5 tokenizer available /// through the FTS5Tokenizer protocol. - private final class FTS5RegisteredTokenizer : FTS5Tokenizer { + private final class FTS5RegisteredTokenizer: FTS5Tokenizer { let xTokenizer: fts5_tokenizer let tokenizerPointer: OpaquePointer init(xTokenizer: fts5_tokenizer, contextPointer: UnsafeMutableRawPointer?, arguments: [String]) throws { guard let xCreate = xTokenizer.xCreate else { - throw DatabaseError(resultCode: .SQLITE_ERROR, message: "nil fts5_tokenizer.xCreate") + throw DatabaseError(message: "nil fts5_tokenizer.xCreate") } self.xTokenizer = xTokenizer @@ -135,7 +162,13 @@ extension Database { if let argument = arguments.first { // Turn [String] into ContiguousArray> // (for an alternative implementation see https://oleb.net/blog/2016/10/swift-array-of-c-strings/) - func convertArguments(_ array: inout ContiguousArray>, _ car: String, _ cdr: [String], _ body: (ContiguousArray>) -> Result) -> Result { + func convertArguments( + _ array: inout ContiguousArray>, + _ car: String, + _ cdr: [String], + _ body: (ContiguousArray>) -> Result) + -> Result + { return car.withCString { cString in if let car = cdr.first { array.append(cString) @@ -148,7 +181,11 @@ extension Database { var cStrings = ContiguousArray>() code = convertArguments(&cStrings, argument, Array(arguments.suffix(from: 1))) { cStrings in cStrings.withUnsafeBufferPointer { azArg in - xCreate(contextPointer, UnsafeMutablePointer(OpaquePointer(azArg.baseAddress!)), Int32(cStrings.count), &tokenizerPointer) + xCreate( + contextPointer, + UnsafeMutablePointer(OpaquePointer(azArg.baseAddress!)), + Int32(cStrings.count), + &tokenizerPointer) } } } else { @@ -172,7 +209,14 @@ extension Database { } } - func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 { + func tokenize( + context: UnsafeMutableRawPointer?, + tokenization: FTS5Tokenization, + pText: UnsafePointer?, + nText: Int32, + tokenCallback: @escaping FTS5TokenCallback) + -> Int32 + { guard let xTokenize = xTokenizer.xTokenize else { return SQLITE_ERROR } @@ -216,7 +260,10 @@ extension Database { } let contextPointer = contextHandle.pointee - return try FTS5RegisteredTokenizer(xTokenizer: xTokenizerPointer.pointee, contextPointer: contextPointer, arguments: descriptor.arguments) + return try FTS5RegisteredTokenizer( + xTokenizer: xTokenizerPointer.pointee, + contextPointer: contextPointer, + arguments: descriptor.arguments) } } #endif diff --git a/GRDB/FTS/FTS5TokenizerDescriptor.swift b/GRDB/FTS/FTS5TokenizerDescriptor.swift index dab8ec8a4..7ef83c9ff 100644 --- a/GRDB/FTS/FTS5TokenizerDescriptor.swift +++ b/GRDB/FTS/FTS5TokenizerDescriptor.swift @@ -57,11 +57,20 @@ public struct FTS5TokenizerDescriptor { /// /// See https://www.sqlite.org/fts5.html#ascii_tokenizer public static func ascii(separators: Set = []) -> FTS5TokenizerDescriptor { + let components: [String] if separators.isEmpty { - return FTS5TokenizerDescriptor(components: ["ascii"]) + components = ["ascii"] } else { - return FTS5TokenizerDescriptor(components: ["ascii", "separators", separators.map { String($0) }.joined(separator: "").sqlExpression.quotedSQL(wrappedInParenthesis: false)]) + components = [ + "ascii", + "separators", + separators + .map { String($0) } + .joined() + .sqlExpression + .quotedSQL()] } + return FTS5TokenizerDescriptor(components: components) } /// The "porter" tokenizer @@ -98,7 +107,12 @@ public struct FTS5TokenizerDescriptor { /// consider these characters as token characters. /// /// See https://www.sqlite.org/fts5.html#unicode61_tokenizer - public static func unicode61(diacritics: FTS5.Diacritics = .removeLegacy, separators: Set = [], tokenCharacters: Set = []) -> FTS5TokenizerDescriptor { + public static func unicode61( + diacritics: FTS5.Diacritics = .removeLegacy, + separators: Set = [], + tokenCharacters: Set = []) + -> FTS5TokenizerDescriptor + { var components: [String] = ["unicode61"] switch diacritics { case .removeLegacy: @@ -111,26 +125,32 @@ public struct FTS5TokenizerDescriptor { #endif } if !separators.isEmpty { - // TODO: test "=" and "\"", "(" and ")" as separators, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:) + // TODO: test "=" and "\"", "(" and ")" as separators, with + // both FTS3Pattern(matchingAnyTokenIn:tokenizer:) + // and Database.create(virtualTable:using:) components.append(contentsOf: [ "separators", separators .sorted() .map { String($0) } - .joined(separator: "") + .joined() .sqlExpression - .quotedSQL(wrappedInParenthesis: false)]) + .quotedSQL() + ]) } if !tokenCharacters.isEmpty { - // TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:) + // TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with + // both FTS3Pattern(matchingAnyTokenIn:tokenizer:) + // and Database.create(virtualTable:using:) components.append(contentsOf: [ "tokenchars", tokenCharacters .sorted() .map { String($0) } - .joined(separator: "") + .joined() .sqlExpression - .quotedSQL(wrappedInParenthesis: false)]) + .quotedSQL() + ]) } return FTS5TokenizerDescriptor(components: components) } diff --git a/GRDB/FTS/FTS5WrapperTokenizer.swift b/GRDB/FTS/FTS5WrapperTokenizer.swift index a217176cb..bfa346335 100644 --- a/GRDB/FTS/FTS5WrapperTokenizer.swift +++ b/GRDB/FTS/FTS5WrapperTokenizer.swift @@ -1,16 +1,16 @@ #if SQLITE_ENABLE_FTS5 #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// Flags that tell SQLite how to register a token. /// /// See https://www.sqlite.org/fts5.html#custom_tokenizers -public struct FTS5TokenFlags : OptionSet { +public struct FTS5TokenFlags: OptionSet { public let rawValue: Int32 public init(rawValue: Int32) { @@ -24,7 +24,7 @@ public struct FTS5TokenFlags : OptionSet { /// A function that lets FTS5WrapperTokenizer notify tokens. /// /// See FTS5WrapperTokenizer.accept(token:flags:tokenCallback:) -public typealias FTS5WrapperTokenCallback = (_ token: String, _ flags: FTS5TokenFlags) throws -> () +public typealias FTS5WrapperTokenCallback = (_ token: String, _ flags: FTS5TokenFlags) throws -> Void /// The protocol for custom FTS5 tokenizers that wrap another tokenizer. /// @@ -44,11 +44,17 @@ public typealias FTS5WrapperTokenCallback = (_ token: String, _ flags: FTS5Token /// wrappedTokenizer = try db.makeTokenizer(.ascii()) /// } /// -/// func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws { +/// func accept( +/// token: String, +/// flags: FTS5TokenFlags, +/// for tokenization: FTS5Tokenization, +/// tokenCallback: FTS5WrapperTokenCallback) +/// throws +/// { /// try tokenCallback(token, flags) /// } /// } -public protocol FTS5WrapperTokenizer : FTS5CustomTokenizer { +public protocol FTS5WrapperTokenizer: FTS5CustomTokenizer { /// The wrapped tokenizer var wrappedTokenizer: FTS5Tokenizer { get } @@ -57,7 +63,13 @@ public protocol FTS5WrapperTokenizer : FTS5CustomTokenizer { /// /// For example: /// - /// func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws { + /// func accept( + /// token: String, + /// flags: FTS5TokenFlags, + /// for tokenization: FTS5Tokenization, + /// tokenCallback: FTS5WrapperTokenCallback) + /// throws + /// { /// // pass through: /// try tokenCallback(token, flags) /// } @@ -77,7 +89,12 @@ public protocol FTS5WrapperTokenizer : FTS5CustomTokenizer { /// - flags: Flags that tell SQLite how to register a token. /// - tokenization: The reason why FTS5 is requesting tokenization. /// - tokenCallback: The function to call for each customized token. - func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws + func accept( + token: String, + flags: FTS5TokenFlags, + for tokenization: FTS5Tokenization, + tokenCallback: FTS5WrapperTokenCallback) + throws } private struct FTS5WrapperContext { @@ -89,7 +106,14 @@ private struct FTS5WrapperContext { extension FTS5WrapperTokenizer { /// Default implementation - public func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 { + public func tokenize( + context: UnsafeMutableRawPointer?, + tokenization: FTS5Tokenization, + pText: UnsafePointer?, + nText: Int32, + tokenCallback: @escaping FTS5TokenCallback) + -> Int32 + { // `tokenCallback` is @convention(c). This requires a little setup // in order to transfer context. var customContext = FTS5WrapperContext( @@ -99,49 +123,62 @@ extension FTS5WrapperTokenizer { tokenCallback: tokenCallback) return withUnsafeMutablePointer(to: &customContext) { customContextPointer in // Invoke wrappedTokenizer - return wrappedTokenizer.tokenize(context: customContextPointer, tokenization: tokenization, pText: pText, nText: nText) { (customContextPointer, tokenFlags, pToken, nToken, iStart, iEnd) in - - // Extract token produced by wrapped tokenizer - guard let token = pToken.flatMap({ String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0), count: Int(nToken), deallocator: .none), encoding: .utf8) }) else { - return 0 // SQLITE_OK - } - - // Extract context - let customContext = customContextPointer!.assumingMemoryBound(to: FTS5WrapperContext.self).pointee - let tokenizer = customContext.tokenizer - let context = customContext.context - let tokenization = customContext.tokenization - let tokenCallback = customContext.tokenCallback - - // Process token produced by wrapped tokenizer - do { - try tokenizer.accept( - token: token, - flags: FTS5TokenFlags(rawValue: tokenFlags), - for: tokenization, - tokenCallback: { (token, flags) in - // Turn token into bytes - return try ContiguousArray(token.utf8).withUnsafeBufferPointer { buffer in - guard let addr = buffer.baseAddress else { - return - } - let pToken = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: Int8.self) - let nToken = Int32(buffer.count) - - // Inject token bytes into SQLite - let code = tokenCallback(context, flags.rawValue, pToken, nToken, iStart, iEnd) - guard code == SQLITE_OK else { - throw DatabaseError(resultCode: code, message: "token callback failed") - } - } - }) + return wrappedTokenizer.tokenize( + context: customContextPointer, + tokenization: tokenization, + pText: pText, + nText: nText) { (customContextPointer, tokenFlags, pToken, nToken, iStart, iEnd) in - return SQLITE_OK - } catch let error as DatabaseError { - return error.extendedResultCode.rawValue - } catch { - return SQLITE_ERROR - } + // Extract token produced by wrapped tokenizer + guard + let token = pToken.flatMap({ + String( + data: Data( + bytesNoCopy: UnsafeMutableRawPointer(mutating: $0), + count: Int(nToken), + deallocator: .none), + encoding: .utf8) }) + else { + return SQLITE_OK // 0 // SQLITE_OK + } + + // Extract context + let customContext = customContextPointer!.assumingMemoryBound(to: FTS5WrapperContext.self).pointee + let tokenizer = customContext.tokenizer + let context = customContext.context + let tokenization = customContext.tokenization + let tokenCallback = customContext.tokenCallback + + // Process token produced by wrapped tokenizer + do { + try tokenizer.accept( + token: token, + flags: FTS5TokenFlags(rawValue: tokenFlags), + for: tokenization, + tokenCallback: { (token, flags) in + // Turn token into bytes + return try ContiguousArray(token.utf8).withUnsafeBufferPointer { buffer in + guard let addr = buffer.baseAddress else { + return + } + let pToken = UnsafeMutableRawPointer(mutating: addr) + .assumingMemoryBound(to: Int8.self) + let nToken = Int32(buffer.count) + + // Inject token bytes into SQLite + let code = tokenCallback(context, flags.rawValue, pToken, nToken, iStart, iEnd) + guard code == SQLITE_OK else { + throw DatabaseError(resultCode: code, message: "token callback failed") + } + } + }) + + return SQLITE_OK + } catch let error as DatabaseError { + return error.extendedResultCode.rawValue + } catch { + return SQLITE_ERROR + } } } } diff --git a/GRDB/Fixit/GRDB-4.0.swift b/GRDB/Fixit/GRDB-4.0.swift index f468c0604..1c6c41220 100644 --- a/GRDB/Fixit/GRDB-4.0.swift +++ b/GRDB/Fixit/GRDB-4.0.swift @@ -4,7 +4,10 @@ import Dispatch extension Cursor { @available(*, unavailable, renamed: "compactMap") - public func flatMap(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor>, ElementOfResult> { preconditionFailure() } + public func flatMap( + _ transform: @escaping (Element) throws -> ElementOfResult?) + -> MapCursor>, ElementOfResult> + { preconditionFailure() } } extension DatabaseWriter { @@ -14,17 +17,26 @@ extension DatabaseWriter { extension ValueObservation { @available(*, unavailable, message: "Provide the reducer in a (Database) -> Reducer closure") - public static func tracking(_ regions: DatabaseRegionConvertible..., reducer: Reducer) -> ValueObservation { preconditionFailure() } + public static func tracking(_ regions: DatabaseRegionConvertible..., reducer: Reducer) + -> ValueObservation + { preconditionFailure() } @available(*, unavailable, message: "Use removeDuplicates() instead") - public static func tracking(_ regions: DatabaseRegionConvertible..., fetchDistinct fetch: @escaping (Database) throws -> Value) -> ValueObservation>> where Value: Equatable { preconditionFailure() } + public static func tracking( + _ regions: DatabaseRegionConvertible..., + fetchDistinct fetch: @escaping (Database) throws -> Value) + -> ValueObservation>> + where Value: Equatable + { preconditionFailure() } } @available(*, unavailable, renamed: "FastDatabaseValueCursor") -public typealias ColumnCursor = FastDatabaseValueCursor +public typealias ColumnCursor = FastDatabaseValueCursor + where Value: DatabaseValueConvertible & StatementColumnConvertible @available(*, unavailable, renamed: "FastNullableDatabaseValueCursor") -public typealias NullableColumnCursor = FastNullableDatabaseValueCursor +public typealias NullableColumnCursor = FastNullableDatabaseValueCursor + where Value: DatabaseValueConvertible & StatementColumnConvertible extension Database { @available(*, unavailable, renamed: "execute(sql:arguments:)") @@ -45,58 +57,141 @@ extension Database { extension DatabaseValueConvertible { @available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)") - public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor { preconditionFailure() } + public static func fetchCursor( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> DatabaseValueCursor + { preconditionFailure() } @available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)") - public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { preconditionFailure() } + public static func fetchAll( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Self] + { preconditionFailure() } @available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)") - public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { preconditionFailure() } + public static func fetchOne( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> Self? + { preconditionFailure() } } extension Optional where Wrapped: DatabaseValueConvertible { @available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)") - public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor { preconditionFailure() } + public static func fetchCursor( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> NullableDatabaseValueCursor + { preconditionFailure() } @available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)") - public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] { preconditionFailure() } + public static func fetchAll( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Wrapped?] + { preconditionFailure() } } extension Row { @available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)") - public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor { preconditionFailure() } + public static func fetchCursor( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> RowCursor + { preconditionFailure() } @available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)") - public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row] { preconditionFailure() } + public static func fetchAll( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Row] + { preconditionFailure() } @available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)") - public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? { preconditionFailure() } + public static func fetchOne( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> Row? + { preconditionFailure() } } extension DatabaseValueConvertible where Self: StatementColumnConvertible { @available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)") - public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor { preconditionFailure() } + public static func fetchCursor( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> FastDatabaseValueCursor + { preconditionFailure() } } extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible { @available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)") - public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor { preconditionFailure() } + public static func fetchCursor( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> FastNullableDatabaseValueCursor + { preconditionFailure() } } extension FetchableRecord { @available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)") - public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor { preconditionFailure() } + public static func fetchCursor( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> RecordCursor + { preconditionFailure() } @available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)") - public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { preconditionFailure() } + public static func fetchAll( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Self] + { preconditionFailure() } @available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)") - public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { preconditionFailure() } + public static func fetchOne( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> Self? + { preconditionFailure() } } extension SQLRequest { @available(*, unavailable, renamed: "init(sql:arguments:adapter:cached:)") - public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false) { preconditionFailure() } + public init( + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil, + cached: Bool = false) + { preconditionFailure() } } extension SQLExpressionLiteral { @@ -111,30 +206,49 @@ extension SQLExpression { extension FTS3TokenizerDescriptor { @available(*, unavailable, renamed: "unicode61(diacritics:separators:tokenCharacters:)") - public static func unicode61(removeDiacritics: Bool, separators: Set = [], tokenCharacters: Set = []) -> FTS3TokenizerDescriptor { preconditionFailure() } + public static func unicode61( + removeDiacritics: Bool, + separators: Set = [], + tokenCharacters: Set = []) + -> FTS3TokenizerDescriptor + { preconditionFailure() } } #if SQLITE_ENABLE_FTS5 extension FTS5TokenizerDescriptor { @available(*, unavailable, renamed: "unicode61(diacritics:separators:tokenCharacters:)") - public static func unicode61(removeDiacritics: Bool = true, separators: Set = [], tokenCharacters: Set = []) -> FTS5TokenizerDescriptor { preconditionFailure() } + public static func unicode61( + removeDiacritics: Bool = true, + separators: Set = [], + tokenCharacters: Set = []) + -> FTS5TokenizerDescriptor + { preconditionFailure() } } #endif extension DatabaseValue { @available(*, unavailable) - public func losslessConvert(sql: String? = nil, arguments: StatementArguments? = nil) -> T where T: DatabaseValueConvertible { preconditionFailure() } + public func losslessConvert(sql: String? = nil, arguments: StatementArguments? = nil) + -> T + where T: DatabaseValueConvertible + { preconditionFailure() } @available(*, unavailable) - public func losslessConvert(sql: String? = nil, arguments: StatementArguments? = nil) -> T? where T: DatabaseValueConvertible { preconditionFailure() } + public func losslessConvert(sql: String? = nil, arguments: StatementArguments? = nil) + -> T? + where T: DatabaseValueConvertible + { preconditionFailure() } } extension ValueScheduling { @available(*, unavailable, renamed: "async(onQueue:startImmediately:)") - public static func onQueue(_ queue: DispatchQueue, startImmediately: Bool) -> ValueScheduling { preconditionFailure() } + public static func onQueue(_ queue: DispatchQueue, startImmediately: Bool) + -> ValueScheduling + { preconditionFailure() } } extension ValueObservation { + // swiftlint:disable:next line_length @available(*, unavailable, message: "Observation extent is controlled by the lifetime of observers returned by the start() method.") public var extent: Database.TransactionObservationExtent { get { preconditionFailure() } diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index b8d18d176..70520ce1b 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -68,7 +68,7 @@ public struct DatabaseMigrator { /// for some downloaded data. public var eraseDatabaseOnSchemaChange = false private var migrations: [Migration] = [] - + /// A new migrator. public init() { } @@ -92,58 +92,64 @@ public struct DatabaseMigrator { } #if GRDBCUSTOMSQLITE || GRDBCIPHER - /// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter - /// - /// // Add a NOT NULL constraint on players.name: - /// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in - /// try db.create(table: "new_player") { t in - /// t.autoIncrementedPrimaryKey("id") - /// t.column("name", .text).notNull() - /// } - /// try db.execute(sql: "INSERT INTO new_player SELECT * FROM player") - /// try db.drop(table: "player") - /// try db.rename(table: "new_player", to: "player") - /// } - /// - /// While your migration code runs with disabled foreign key checks, those - /// are re-enabled and checked at the end of the migration, regardless of - /// eventual errors. - /// - /// - parameters: - /// - identifier: The migration identifier. - /// - block: The migration block that performs SQL statements. - /// - precondition: No migration with the same same as already been registered. - /// - /// :nodoc: - public mutating func registerMigrationWithDeferredForeignKeyCheck(_ identifier: String, migrate: @escaping (Database) throws -> Void) { - registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate)) - } + /// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter + /// + /// // Add a NOT NULL constraint on players.name: + /// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in + /// try db.create(table: "new_player") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("name", .text).notNull() + /// } + /// try db.execute(sql: "INSERT INTO new_player SELECT * FROM player") + /// try db.drop(table: "player") + /// try db.rename(table: "new_player", to: "player") + /// } + /// + /// While your migration code runs with disabled foreign key checks, those + /// are re-enabled and checked at the end of the migration, regardless of + /// eventual errors. + /// + /// - parameters: + /// - identifier: The migration identifier. + /// - block: The migration block that performs SQL statements. + /// - precondition: No migration with the same same as already been registered. + /// + /// :nodoc: + public mutating func registerMigrationWithDeferredForeignKeyCheck( + _ identifier: String, + migrate: @escaping (Database) throws -> Void) + { + registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate)) + } #else - @available(OSX 10.10, *) - /// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter - /// - /// // Add a NOT NULL constraint on players.name: - /// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in - /// try db.create(table: "new_player") { t in - /// t.autoIncrementedPrimaryKey("id") - /// t.column("name", .text).notNull() - /// } - /// try db.execute(sql: "INSERT INTO new_player SELECT * FROM player") - /// try db.drop(table: "player") - /// try db.rename(table: "new_player", to: "player") - /// } - /// - /// While your migration code runs with disabled foreign key checks, those - /// are re-enabled and checked at the end of the migration, regardless of - /// eventual errors. - /// - /// - parameters: - /// - identifier: The migration identifier. - /// - block: The migration block that performs SQL statements. - /// - precondition: No migration with the same same as already been registered. - public mutating func registerMigrationWithDeferredForeignKeyCheck(_ identifier: String, migrate: @escaping (Database) throws -> Void) { - registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate)) - } + @available(OSX 10.10, *) + /// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter + /// + /// // Add a NOT NULL constraint on players.name: + /// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in + /// try db.create(table: "new_player") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("name", .text).notNull() + /// } + /// try db.execute(sql: "INSERT INTO new_player SELECT * FROM player") + /// try db.drop(table: "player") + /// try db.rename(table: "new_player", to: "player") + /// } + /// + /// While your migration code runs with disabled foreign key checks, those + /// are re-enabled and checked at the end of the migration, regardless of + /// eventual errors. + /// + /// - parameters: + /// - identifier: The migration identifier. + /// - block: The migration block that performs SQL statements. + /// - precondition: No migration with the same same as already been registered. + public mutating func registerMigrationWithDeferredForeignKeyCheck( + _ identifier: String, + migrate: @escaping (Database) throws -> Void) + { + registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate)) + } #endif /// Iterate migrations in the same order as they were registered. If a @@ -232,7 +238,9 @@ public struct DatabaseMigrator { // MARK: - Non public private mutating func registerMigration(_ migration: Migration) { - GRDBPrecondition(!migrations.map({ $0.identifier }).contains(migration.identifier), "already registered migration: \(String(reflecting: migration.identifier))") + GRDBPrecondition( + !migrations.map({ $0.identifier }).contains(migration.identifier), + "already registered migration: \(String(reflecting: migration.identifier))") migrations.append(migration) } @@ -254,13 +262,17 @@ public struct DatabaseMigrator { } // targetIdentifier must refer to a registered migration - GRDBPrecondition(prefixMigrations.last?.identifier == targetIdentifier, "undefined migration: \(String(reflecting: targetIdentifier))") + GRDBPrecondition( + prefixMigrations.last?.identifier == targetIdentifier, + "undefined migration: \(String(reflecting: targetIdentifier))") // Subsequent migration must not be applied let appliedIdentifiers = try self.appliedIdentifiers(db) if prefixMigrations.count < migrations.count { let nextIdentifier = migrations[prefixMigrations.count].identifier - GRDBPrecondition(!appliedIdentifiers.contains(nextIdentifier), "database is already migrated beyond migration \(String(reflecting: targetIdentifier))") + GRDBPrecondition( + !appliedIdentifiers.contains(nextIdentifier), + "database is already migrated beyond migration \(String(reflecting: targetIdentifier))") } for migration in prefixMigrations where !appliedIdentifiers.contains(migration.identifier) { diff --git a/GRDB/Migration/Migration.swift b/GRDB/Migration/Migration.swift index 17d60de28..ac17249da 100644 --- a/GRDB/Migration/Migration.swift +++ b/GRDB/Migration/Migration.swift @@ -5,26 +5,27 @@ struct Migration { let migrate: (Database) throws -> Void #if GRDBCUSTOMSQLITE || GRDBCIPHER - init(identifier: String, disabledForeignKeyChecks: Bool = false, migrate: @escaping (Database) throws -> Void) { - self.identifier = identifier - self.disabledForeignKeyChecks = disabledForeignKeyChecks - self.migrate = migrate - } + init(identifier: String, disabledForeignKeyChecks: Bool = false, migrate: @escaping (Database) throws -> Void) { + self.identifier = identifier + self.disabledForeignKeyChecks = disabledForeignKeyChecks + self.migrate = migrate + } #else - init(identifier: String, migrate: @escaping (Database) throws -> Void) { - self.identifier = identifier - self.disabledForeignKeyChecks = false - self.migrate = migrate - } + init(identifier: String, migrate: @escaping (Database) throws -> Void) { + self.identifier = identifier + self.disabledForeignKeyChecks = false + self.migrate = migrate + } - @available(OSX 10.10, *) - // PRAGMA foreign_key_check was introduced in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - init(identifier: String, disabledForeignKeyChecks: Bool, migrate: @escaping (Database) throws -> Void) { - self.identifier = identifier - self.disabledForeignKeyChecks = disabledForeignKeyChecks - self.migrate = migrate - } + @available(OSX 10.10, *) + // PRAGMA foreign_key_check was introduced in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16 + // It is available from iOS 8.2 and OS X 10.10 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + init(identifier: String, disabledForeignKeyChecks: Bool, migrate: @escaping (Database) throws -> Void) { + self.identifier = identifier + self.disabledForeignKeyChecks = disabledForeignKeyChecks + self.migrate = migrate + } #endif func run(_ db: Database) throws { diff --git a/GRDB/QueryInterface/FTS5+QueryInterface.swift b/GRDB/QueryInterface/FTS5+QueryInterface.swift index ab3bb55e0..b39ee6ca3 100644 --- a/GRDB/QueryInterface/FTS5+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS5+QueryInterface.swift @@ -1,44 +1,44 @@ #if SQLITE_ENABLE_FTS5 - extension QueryInterfaceRequest { - - // MARK: Full Text Search - - /// Creates a request with a full-text predicate added to the eventual - /// set of already applied predicates. - /// - /// // SELECT * FROM book WHERE book MATCH '...' - /// var request = Book.all() - /// request = request.matching(pattern) - /// - /// If the search pattern is nil, the request does not match any - /// database row. - /// - /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableRecord.databaseSelection` property, or - /// for individual requests with the `TableRecord.select` method. - public func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest { - guard let pattern = pattern else { - return none() - } - let alias = TableAlias() - let matchExpression = TableMatchExpression(alias: alias, pattern: pattern.databaseValue) - return self.aliased(alias).filter(matchExpression) - } - } +extension QueryInterfaceRequest { - extension TableRecord { - - // MARK: Full Text Search - - /// Returns a QueryInterfaceRequest with a matching predicate. - /// - /// // SELECT * FROM book WHERE book MATCH '...' - /// var request = Book.matching(pattern) - /// - /// If the search pattern is nil, the request does not match any - /// database row. - public static func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest { - return all().matching(pattern) + // MARK: Full Text Search + + /// Creates a request with a full-text predicate added to the eventual + /// set of already applied predicates. + /// + /// // SELECT * FROM book WHERE book MATCH '...' + /// var request = Book.all() + /// request = request.matching(pattern) + /// + /// If the search pattern is nil, the request does not match any + /// database row. + /// + /// The selection defaults to all columns. This default can be changed for + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. + public func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest { + guard let pattern = pattern else { + return none() } + let alias = TableAlias() + let matchExpression = TableMatchExpression(alias: alias, pattern: pattern.databaseValue) + return self.aliased(alias).filter(matchExpression) } +} + +extension TableRecord { + + // MARK: Full Text Search + + /// Returns a QueryInterfaceRequest with a matching predicate. + /// + /// // SELECT * FROM book WHERE book MATCH '...' + /// var request = Book.matching(pattern) + /// + /// If the search pattern is nil, the request does not match any + /// database row. + public static func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest { + return all().matching(pattern) + } +} #endif diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index 27cc272fd..8099053da 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -72,12 +72,12 @@ extension Association { extension Association { private func mapDestinationRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self { - return Self.init(sqlAssociation: sqlAssociation.mapDestinationRelation(transform)) + return .init(sqlAssociation: sqlAssociation.mapDestinationRelation(transform)) } } extension Association { - + /// The association key defines how rows fetched from this association /// should be consumed. /// @@ -306,7 +306,7 @@ public protocol AssociationToOne: Association { } extension AssociationToOne { public func forKey(_ key: String) -> Self { let associationKey = SQLAssociationKey.fixedSingular(key) - return Self.init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey)) + return .init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey)) } } @@ -320,7 +320,7 @@ public protocol AssociationToMany: Association { } extension AssociationToMany { public func forKey(_ key: String) -> Self { let associationKey = SQLAssociationKey.fixedPlural(key) - return Self.init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey)) + return .init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey)) } } diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index cf67dd5bb..58b938f97 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -1,5 +1,9 @@ import Foundation +typealias AssociationAggregatePreparation = + (QueryInterfaceRequest) + -> (request: QueryInterfaceRequest, expression: SQLExpression) + /// An AssociationAggregate is able to compute aggregated values from a /// population of associated records. /// @@ -56,12 +60,12 @@ public struct AssociationAggregate { /// - We don't know yet if the aggregated value will be used in the /// SQL selection, or in the HAVING clause. /// - It helps implementing aggregate operators such as `&&`, `+`, etc. - let prepare: (QueryInterfaceRequest) -> (request: QueryInterfaceRequest, expression: SQLExpression) + let prepare: AssociationAggregatePreparation /// The SQL alias for the value of this aggregate. See aliased(_:). var alias: String? - init(_ prepare: @escaping (QueryInterfaceRequest) -> (request: QueryInterfaceRequest, expression: SQLExpression)) { + init(_ prepare: @escaping AssociationAggregatePreparation) { self.prepare = prepare } } @@ -121,7 +125,11 @@ public prefix func ! (aggregate: AssociationAggregate) - /// For example: /// /// Author.having(Author.books.isEmpty && Author.paintings.isEmpty) -public func && (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func && ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -131,7 +139,11 @@ public func && (lhs: AssociationAggregate, rhs: Associat // TODO: test /// :nodoc: -public func && (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func && ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression && rhs) @@ -140,7 +152,11 @@ public func && (lhs: AssociationAggregate, rhs: SQLExpre // TODO: test /// :nodoc: -public func && (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func && ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs && expression) @@ -153,7 +169,11 @@ public func && (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func || ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -163,7 +183,11 @@ public func || (lhs: AssociationAggregate, rhs: Associat // TODO: test /// :nodoc: -public func || (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func || ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression || rhs) @@ -172,7 +196,11 @@ public func || (lhs: AssociationAggregate, rhs: SQLExpre // TODO: test /// :nodoc: -public func || (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func || ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs || expression) @@ -186,7 +214,11 @@ public func || (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func == ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -199,7 +231,11 @@ public func == (lhs: AssociationAggregate, rhs: Associat /// For example: /// /// Author.having(Author.books.count == 3) -public func == (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func == ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression == rhs) @@ -211,7 +247,11 @@ public func == (lhs: AssociationAggregate, rhs: SQLExpre /// For example: /// /// Author.having(3 == Author.books.count) -public func == (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func == ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs == expression) @@ -247,7 +287,11 @@ public func == (lhs: Bool, rhs: AssociationAggregate) -> /// For example: /// /// Author.having(Author.books.count != Author.paintings.count) -public func != (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func != ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -260,7 +304,11 @@ public func != (lhs: AssociationAggregate, rhs: Associat /// For example: /// /// Author.having(Author.books.count != 3) -public func != (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func != ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression != rhs) @@ -272,7 +320,11 @@ public func != (lhs: AssociationAggregate, rhs: SQLExpre /// For example: /// /// Author.having(3 != Author.books.count) -public func != (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func != ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs != expression) @@ -308,7 +360,11 @@ public func != (lhs: Bool, rhs: AssociationAggregate) -> /// For example: /// /// Author.having(Author.books.count === Author.paintings.count) -public func === (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func === ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -321,7 +377,11 @@ public func === (lhs: AssociationAggregate, rhs: Associa /// For example: /// /// Author.having(Author.books.count === 3) -public func === (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func === ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression === rhs) @@ -333,7 +393,11 @@ public func === (lhs: AssociationAggregate, rhs: SQLExpr /// For example: /// /// Author.having(3 === Author.books.count) -public func === (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func === ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs === expression) @@ -345,7 +409,11 @@ public func === (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func !== ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -358,7 +426,11 @@ public func !== (lhs: AssociationAggregate, rhs: Associa /// For example: /// /// Author.having(Author.books.count !== 3) -public func !== (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func !== ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression !== rhs) @@ -370,7 +442,11 @@ public func !== (lhs: AssociationAggregate, rhs: SQLExpr /// For example: /// /// Author.having(3 !== Author.books.count) -public func !== (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func !== ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs !== expression) @@ -384,7 +460,11 @@ public func !== (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func <= ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -397,7 +477,11 @@ public func <= (lhs: AssociationAggregate, rhs: Associat /// For example: /// /// Author.having(Author.books.count <= 3) -public func <= (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func <= ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression <= rhs) @@ -409,7 +493,11 @@ public func <= (lhs: AssociationAggregate, rhs: SQLExpre /// For example: /// /// Author.having(3 <= Author.books.count) -public func <= (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func <= ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs <= expression) @@ -421,7 +509,11 @@ public func <= (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func < ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -434,7 +526,11 @@ public func < (lhs: AssociationAggregate, rhs: Associati /// For example: /// /// Author.having(Author.books.count < 3) -public func < (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func < ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression < rhs) @@ -446,7 +542,11 @@ public func < (lhs: AssociationAggregate, rhs: SQLExpres /// For example: /// /// Author.having(3 < Author.books.count) -public func < (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func < ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs < expression) @@ -458,7 +558,11 @@ public func < (lhs: SQLExpressible, rhs: AssociationAggregate Author.paintings.count) -public func > (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func > ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -471,7 +575,11 @@ public func > (lhs: AssociationAggregate, rhs: Associati /// For example: /// /// Author.having(Author.books.count > 3) -public func > (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func > ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression > rhs) @@ -483,7 +591,11 @@ public func > (lhs: AssociationAggregate, rhs: SQLExpres /// For example: /// /// Author.having(3 > Author.books.count) -public func > (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func > ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs > expression) @@ -495,7 +607,11 @@ public func > (lhs: SQLExpressible, rhs: AssociationAggregate= Author.paintings.count) -public func >= (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func >= ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -508,7 +624,11 @@ public func >= (lhs: AssociationAggregate, rhs: Associat /// For example: /// /// Author.having(Author.books.count >= 3) -public func >= (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func >= ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression >= rhs) @@ -520,7 +640,11 @@ public func >= (lhs: AssociationAggregate, rhs: SQLExpre /// For example: /// /// Author.having(3 >= Author.books.count) -public func >= (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func >= ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs >= expression) @@ -546,7 +670,11 @@ public prefix func - (aggregate: AssociationAggregate) - /// For example: /// /// Author.annotated(with: Author.books.count + Author.paintings.count) -public func + (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func + ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -559,7 +687,11 @@ public func + (lhs: AssociationAggregate, rhs: Associati /// For example: /// /// Author.annotated(with: Author.books.count + 1) -public func + (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func + ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression + rhs) @@ -571,7 +703,11 @@ public func + (lhs: AssociationAggregate, rhs: SQLExpres /// For example: /// /// Author.annotated(with: 1 + Author.books.count) -public func + (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func + ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs + expression) @@ -583,7 +719,11 @@ public func + (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func - ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -596,7 +736,11 @@ public func - (lhs: AssociationAggregate, rhs: Associati /// For example: /// /// Author.annotated(with: Author.books.count - 1) -public func - (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func - ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression - rhs) @@ -608,7 +752,11 @@ public func - (lhs: AssociationAggregate, rhs: SQLExpres /// For example: /// /// Author.annotated(with: 1 - Author.books.count) -public func - (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func - ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs - expression) @@ -620,7 +768,11 @@ public func - (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func * ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -633,7 +785,11 @@ public func * (lhs: AssociationAggregate, rhs: Associati /// For example: /// /// Author.annotated(with: Author.books.count * 2) -public func * (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func * ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression * rhs) @@ -645,7 +801,11 @@ public func * (lhs: AssociationAggregate, rhs: SQLExpres /// For example: /// /// Author.annotated(with: 2 * Author.books.count) -public func * (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func * ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs * expression) @@ -657,7 +817,11 @@ public func * (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func / ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -670,7 +834,11 @@ public func / (lhs: AssociationAggregate, rhs: Associati /// For example: /// /// Author.annotated(with: Author.books.count / 2) -public func / (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func / ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression / rhs) @@ -682,7 +850,11 @@ public func / (lhs: AssociationAggregate, rhs: SQLExpres /// For example: /// /// Author.annotated(with: 2 / Author.books.count) -public func / (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func / ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs / expression) @@ -694,7 +866,11 @@ public func / (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func ?? ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ var aggregate = AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression ?? rhs) diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift index ccc080857..0d43f4f9e 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift @@ -20,7 +20,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { public func annotated(with aggregates: AssociationAggregate...) -> QueryInterfaceRequest { return annotated(with: aggregates) } - + /// Creates a request which appends *aggregates* to the current selection. /// /// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index fcf8db63d..a6e74d751 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -143,7 +143,9 @@ extension QueryInterfaceRequest: SelectionRequest { /// let request = Player.all().select([max(Column("score"))], as: Int.self) /// let maxScore: Int? = try request.fetchOne(db) /// } - public func select(_ selection: [SQLSelectable], as type: RowDecoder.Type) -> QueryInterfaceRequest { + public func select(_ selection: [SQLSelectable], as type: RowDecoder.Type) + -> QueryInterfaceRequest + { return mapQuery { $0.select(selection) }.asRequest(of: RowDecoder.self) } @@ -155,7 +157,9 @@ extension QueryInterfaceRequest: SelectionRequest { /// let request = Player.all().select(max(Column("score")), as: Int.self) /// let maxScore: Int? = try request.fetchOne(db) /// } - public func select(_ selection: SQLSelectable..., as type: RowDecoder.Type) -> QueryInterfaceRequest { + public func select(_ selection: SQLSelectable..., as type: RowDecoder.Type) + -> QueryInterfaceRequest + { return select(selection, as: type) } @@ -167,7 +171,12 @@ extension QueryInterfaceRequest: SelectionRequest { /// let request = Player.all().select(sql: "max(score)", as: Int.self) /// let maxScore: Int? = try request.fetchOne(db) /// } - public func select(sql: String, arguments: StatementArguments = StatementArguments(), as type: RowDecoder.Type) -> QueryInterfaceRequest { + public func select( + sql: String, + arguments: StatementArguments = StatementArguments(), + as type: RowDecoder.Type) + -> QueryInterfaceRequest + { return select(literal: SQLLiteral(sql: sql, arguments: arguments), as: type) } @@ -198,7 +207,11 @@ extension QueryInterfaceRequest: SelectionRequest { /// as: String.self) /// let name: String? = try request.fetchOne(db) /// } - public func select(literal sqlLiteral: SQLLiteral, as type: RowDecoder.Type) -> QueryInterfaceRequest { + public func select( + literal sqlLiteral: SQLLiteral, + as type: RowDecoder.Type) + -> QueryInterfaceRequest + { return select(SQLSelectionLiteral(literal: sqlLiteral), as: type) } @@ -225,7 +238,7 @@ extension QueryInterfaceRequest: SelectionRequest { extension QueryInterfaceRequest: FilteredRequest { // MARK: Request Derivation - + /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. /// @@ -235,7 +248,6 @@ extension QueryInterfaceRequest: FilteredRequest { public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { return mapQuery { $0.filter(predicate) } } - } extension QueryInterfaceRequest: OrderedRequest { @@ -328,7 +340,7 @@ extension QueryInterfaceRequest: JoinableRequest { extension QueryInterfaceRequest { // MARK: Request Derivation - + /// Creates a request which returns distinct rows. /// /// // SELECT DISTINCT * FROM player @@ -479,7 +491,7 @@ extension QueryInterfaceRequest where T: MutablePersistableRecord { // MARK: - Eager loading of hasMany associations /// Append rows from prefetched associations into the argument rows. -fileprivate func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [Row]) throws { +private func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [Row]) throws { guard let firstRow = rows.first else { // No rows -> no prefetch return diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index c8c467d4f..1a45b4cc1 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -176,7 +176,7 @@ extension FilteredRequest { // NOT TESTED return filter(SQLExpressionLiteral(literal: sqlLiteral)) } - + /// Creates a request that matches nothing. /// /// // SELECT * FROM player WHERE 0 @@ -230,7 +230,10 @@ extension TableRequest where Self: FilteredRequest { } /// Creates a request with the provided primary key *predicate*. - public func filter(keys: Sequence) -> Self where Sequence.Element: DatabaseValueConvertible { + public func filter(keys: Sequence) + -> Self + where Sequence.Element: DatabaseValueConvertible + { var request = self let keys = Array(keys) switch keys.count { @@ -241,7 +244,7 @@ extension TableRequest where Self: FilteredRequest { default: break } - + let databaseTableName = self.databaseTableName return request.filter { db in let primaryKey = try db.primaryKey(databaseTableName) @@ -286,7 +289,10 @@ extension TableRequest where Self: FilteredRequest { // ("foo", "bar") is not a unique key (primary key or columns of a // unique index) guard let columns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else { - fatalError("table \(databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))") + fatalError(""" + table \(databaseTableName) has no unique index on column(s) \ + \(key.keys.sorted().joined(separator: ", ")) + """) } let lowercaseColumns = columns.map { $0.lowercased() } @@ -365,13 +371,13 @@ extension AggregatingRequest { // NOT TESTED return group(SQLExpressionLiteral(literal: sqlLiteral)) } - + /// Creates a request with the provided *sql* added to the /// eventual set of already applied predicates. public func having(sql: String, arguments: StatementArguments = StatementArguments()) -> Self { return having(literal: SQLLiteral(sql: sql, arguments: arguments)) } - + /// Creates a request with the provided *sql* added to the /// eventual set of already applied predicates. public func having(literal sqlLiteral: SQLLiteral) -> Self { diff --git a/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift b/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift index 29582b5f2..f80d4de53 100644 --- a/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift @@ -51,7 +51,7 @@ public struct SQLCollatedExpression { } /// :nodoc: -extension SQLCollatedExpression : SQLOrderingTerm { +extension SQLCollatedExpression: SQLOrderingTerm { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: diff --git a/GRDB/QueryInterface/SQL/SQLCollection.swift b/GRDB/QueryInterface/SQL/SQLCollection.swift index a070b8e9c..2ebcd6045 100644 --- a/GRDB/QueryInterface/SQL/SQLCollection.swift +++ b/GRDB/QueryInterface/SQL/SQLCollection.swift @@ -37,15 +37,17 @@ extension SQLCollection { /// SQLExpressionsArray wraps an array of expressions /// /// SQLExpressionsArray([1, 2, 3]) -struct SQLExpressionsArray : SQLCollection { +struct SQLExpressionsArray: SQLCollection { let expressions: [SQLExpression] - init(_ expressions: S) where S.Iterator.Element : SQLExpressible { + init(_ expressions: S) where S.Iterator.Element: SQLExpressible { self.expressions = expressions.map { $0.sqlExpression } } func collectionSQL(_ context: inout SQLGenerationContext) -> String { - return (expressions.map { $0.expressionSQL(&context, wrappedInParenthesis: false) } as [String]).joined(separator: ", ") + return expressions + .map { $0.expressionSQL(&context, wrappedInParenthesis: false) } + .joined(separator: ", ") } func contains(_ value: SQLExpressible) -> SQLExpression { diff --git a/GRDB/QueryInterface/SQL/SQLExpressible.swift b/GRDB/QueryInterface/SQL/SQLExpressible.swift index 366864aee..a0bb76240 100644 --- a/GRDB/QueryInterface/SQL/SQLExpressible.swift +++ b/GRDB/QueryInterface/SQL/SQLExpressible.swift @@ -31,7 +31,7 @@ public protocol SQLExpressible { /// On the other side, Int adopts SQLExpressible (via DatabaseValueConvertible). /// /// :nodoc: -public protocol SQLSpecificExpressible : SQLExpressible { +public protocol SQLSpecificExpressible: SQLExpressible { // SQLExpressible can be adopted by Swift standard types, and user // types, through the DatabaseValueConvertible protocol which inherits // from SQLExpressible. diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift index b94bd973a..814dabf46 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -14,10 +14,10 @@ extension SQLExpression { /// The expression as a quoted SQL literal (not public in order to avoid abuses) /// - /// "foo'bar".databaseValue.quotedSQL(wrappedInParenthesis: true) // "'foo''bar'"" - func quotedSQL(wrappedInParenthesis: Bool) -> String { + /// "foo'bar".databaseValue.quotedSQL() // "'foo''bar'"" + func quotedSQL() -> String { var context = SQLGenerationContext.literalGenerationContext(withArguments: false) - return expressionSQL(&context, wrappedInParenthesis: wrappedInParenthesis) + return expressionSQL(&context, wrappedInParenthesis: false) } } @@ -33,7 +33,7 @@ extension SQLExpression { /// /// SQLExpressionLiteral(sql: "? + ?", arguments: [1, 2]) /// SQLExpressionLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]) -public struct SQLExpressionLiteral : SQLExpression { +public struct SQLExpressionLiteral: SQLExpression { private let sqlLiteral: SQLLiteral public var sql: String { return sqlLiteral.sql } public var arguments: StatementArguments { return sqlLiteral.arguments } @@ -93,7 +93,7 @@ public struct SQLExpressionLiteral : SQLExpression { /// SQLUnaryOperator is a SQLite unary operator. /// /// :nodoc: -public struct SQLUnaryOperator : Hashable { +public struct SQLUnaryOperator: Hashable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// The SQL operator @@ -121,7 +121,7 @@ public struct SQLUnaryOperator : Hashable { /// an operand expression. /// /// :nodoc: -public struct SQLExpressionUnary : SQLExpression { +public struct SQLExpressionUnary: SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// The unary operator @@ -167,7 +167,7 @@ public struct SQLExpressionUnary : SQLExpression { /// SQLBinaryOperator is a SQLite binary operator. /// /// :nodoc: -public struct SQLBinaryOperator : Hashable { +public struct SQLBinaryOperator: Hashable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// The SQL operator @@ -211,7 +211,7 @@ public struct SQLBinaryOperator : Hashable { /// SQLExpressionBinary(.multiply, Column("length"), Column("width")) /// /// :nodoc: -public struct SQLExpressionBinary : SQLExpression { +public struct SQLExpressionBinary: SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// The left operand @@ -252,17 +252,17 @@ public struct SQLExpressionBinary : SQLExpression { \(rhs.expressionSQL(&context, wrappedInParenthesis: true)) """ } - + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public var negated: SQLExpression { if let negatedOp = op.negated { - return SQLExpressionBinary(negatedOp, lhs, rhs) + return SQLExpressionBinary(negatedOp, lhs, rhs) } else { return SQLExpressionNot(self) } } - + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { @@ -272,7 +272,7 @@ public struct SQLExpressionBinary : SQLExpression { // MARK: - SQLExpressionAnd -struct SQLExpressionAnd : SQLExpression { +struct SQLExpressionAnd: SQLExpression { let expressions: [SQLExpression] init(_ expressions: [SQLExpression]) { @@ -312,7 +312,7 @@ struct SQLExpressionAnd : SQLExpression { // MARK: - SQLExpressionOr -struct SQLExpressionOr : SQLExpression { +struct SQLExpressionOr: SQLExpression { let expressions: [SQLExpression] init(_ expressions: [SQLExpression]) { @@ -422,9 +422,9 @@ struct SQLExpressionEqual: SQLExpression { } } switch (lhs, rhs) { - case (let column as ColumnExpression, let dbValue as DatabaseValue): + case let (column as ColumnExpression, dbValue as DatabaseValue): return matchedRowIds(column: column, dbValue: dbValue) - case (let dbValue as DatabaseValue, let column as ColumnExpression): + case let (dbValue as DatabaseValue, column as ColumnExpression): return matchedRowIds(column: column, dbValue: dbValue) default: return nil @@ -443,7 +443,7 @@ struct SQLExpressionEqual: SQLExpression { /// /// // id IN (1,2,3) /// SQLExpressionContains(Column("id"), SQLExpressionsArray([1,2,3])) -struct SQLExpressionContains : SQLExpression { +struct SQLExpressionContains: SQLExpression { let expression: SQLExpression let collection: SQLCollection let isNegated: Bool @@ -509,7 +509,7 @@ struct SQLExpressionContains : SQLExpression { /// /// // id BETWEEN 1 AND 3 /// SQLExpressionBetween(Column("id"), 1.databaseValue, 3.databaseValue) -struct SQLExpressionBetween : SQLExpression { +struct SQLExpressionBetween: SQLExpression { let expression: SQLExpression let lowerBound: SQLExpression let upperBound: SQLExpression @@ -534,7 +534,7 @@ struct SQLExpressionBetween : SQLExpression { \(upperBound.expressionSQL(&context, wrappedInParenthesis: true)) """ } - + var negated: SQLExpression { return SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated) } @@ -553,7 +553,7 @@ struct SQLExpressionBetween : SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// SQLFunctionName is an SQL function name. -public struct SQLFunctionName : Hashable { +public struct SQLFunctionName: Hashable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// The SQL function name @@ -581,7 +581,7 @@ public struct SQLFunctionName : Hashable { /// SQLExpressionFunction(.abs, [-1.databaseValue]) /// /// :nodoc: -public struct SQLExpressionFunction : SQLExpression { +public struct SQLExpressionFunction: SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// The function name @@ -616,11 +616,13 @@ public struct SQLExpressionFunction : SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String { - return """ - \(functionName.sql)(\ - \((arguments.map { $0.expressionSQL(&context, wrappedInParenthesis: false) } as [String]).joined(separator: ", "))\ - ) - """ + var sql = functionName.sql + sql += "(" + sql += arguments + .map { $0.expressionSQL(&context, wrappedInParenthesis: false) } + .joined(separator: ", ") + sql += ")" + return sql } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) @@ -636,7 +638,7 @@ public struct SQLExpressionFunction : SQLExpression { /// /// // COUNT(name) /// SQLExpressionCount(Column("name")) -struct SQLExpressionCount : SQLExpression { +struct SQLExpressionCount: SQLExpression { /// The counted value let counted: SQLSelectable @@ -659,7 +661,7 @@ struct SQLExpressionCount : SQLExpression { /// /// // COUNT(DISTINCT name) /// SQLExpressionCountDistinct(Column("name")) -struct SQLExpressionCountDistinct : SQLExpression { +struct SQLExpressionCountDistinct: SQLExpression { let counted: SQLExpression init(_ counted: SQLExpression) { @@ -680,7 +682,7 @@ struct SQLExpressionCountDistinct : SQLExpression { /// This one helps generating `COUNT(...) = 0` or `COUNT(...) > 0` while letting /// the user using the not `!` logical operator, or comparisons with booleans /// such as `== true` or `== false`. -struct SQLExpressionIsEmpty : SQLExpression { +struct SQLExpressionIsEmpty: SQLExpression { var countExpression: SQLExpression var isEmpty: Bool @@ -739,7 +741,7 @@ struct TableMatchExpression: SQLExpression { /// /// // email = 'arthur@example.com' COLLATE NOCASE /// SQLExpressionCollate(Column("email") == "arthur@example.com", "NOCASE") -struct SQLExpressionCollate : SQLExpression { +struct SQLExpressionCollate: SQLExpression { let expression: SQLExpression let collationName: Database.CollationName @@ -752,9 +754,8 @@ struct SQLExpressionCollate : SQLExpression { if wrappedInParenthesis { return "(\(expressionSQL(&context, wrappedInParenthesis: false)))" } - let sql = expression.expressionSQL(&context, wrappedInParenthesis: false) return """ - \(sql) \ + \(expression.expressionSQL(&context, wrappedInParenthesis: false)) \ COLLATE \ \(collationName.rawValue) """ diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index b2f5582ec..ac9fed167 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -5,20 +5,8 @@ /// SQLExpression is the protocol for types that represent an SQL expression, as /// described at https://www.sqlite.org/lang_expr.html /// -/// GRDB ships with a variety of types that already adopt this protocol, and -/// allow to represent many SQLite expressions: -/// -/// - Column -/// - DatabaseValue -/// - SQLExpressionLiteral -/// - SQLExpressionUnary -/// - SQLExpressionBinary -/// - SQLExpressionExists -/// - SQLExpressionFunction -/// - SQLExpressionCollate -/// /// :nodoc: -public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderingTerm { +public protocol SQLExpression: SQLSpecificExpressible, SQLSelectable, SQLOrderingTerm { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// @@ -131,7 +119,7 @@ extension SQLExpression { // MARK: - SQLExpressionNot -struct SQLExpressionNot : SQLExpression { +struct SQLExpressionNot: SQLExpression { let expression: SQLExpression init(_ expression: SQLExpression) { diff --git a/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift b/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift index 8514256da..18ffe5187 100644 --- a/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift +++ b/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift @@ -67,7 +67,7 @@ struct SQLForeignKeyRequest: Equatable { // No matching foreign key found: use the destination primary key if let originColumns = originColumns { let destinationColumns = try db.primaryKey(destinationTable).columns - if (originColumns.count == destinationColumns.count) { + if originColumns.count == destinationColumns.count { let mapping = zip(originColumns, destinationColumns).map { (origin: $0, destination: $1) } diff --git a/GRDB/QueryInterface/SQL/SQLFunctions.swift b/GRDB/QueryInterface/SQL/SQLFunctions.swift index 8645fc737..06bd1d4a8 100644 --- a/GRDB/QueryInterface/SQL/SQLFunctions.swift +++ b/GRDB/QueryInterface/SQL/SQLFunctions.swift @@ -158,7 +158,7 @@ extension SQLSpecificExpressible { public var capitalized: SQLExpression { return DatabaseFunction.capitalize.apply(sqlExpression) } - + /// Returns an SQL expression that applies the Swift's built-in /// lowercased String property. It is NULL for non-String arguments. /// @@ -168,7 +168,7 @@ extension SQLSpecificExpressible { public var lowercased: SQLExpression { return DatabaseFunction.lowercase.apply(sqlExpression) } - + /// Returns an SQL expression that applies the Swift's built-in /// uppercased String property. It is NULL for non-String arguments. /// diff --git a/GRDB/QueryInterface/SQL/SQLOperators.swift b/GRDB/QueryInterface/SQL/SQLOperators.swift index 8ff7c996f..ac0ee9c87 100644 --- a/GRDB/QueryInterface/SQL/SQLOperators.swift +++ b/GRDB/QueryInterface/SQL/SQLOperators.swift @@ -3,14 +3,14 @@ // Outputs "x = y" or "x IS NULL" private func isEqual(_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression { switch (lhs, rhs) { - case (let lhs, let rhs as DatabaseValue): + case let (lhs, rhs as DatabaseValue): switch rhs.storage { case .null: return SQLExpressionEqual(.is, lhs, rhs) default: return SQLExpressionEqual(.equal, lhs, rhs) } - case (let lhs as DatabaseValue, let rhs): + case let (lhs as DatabaseValue, rhs): switch lhs.storage { case .null: return SQLExpressionEqual(.is, rhs, lhs) diff --git a/GRDB/QueryInterface/SQL/SQLOrdering.swift b/GRDB/QueryInterface/SQL/SQLOrdering.swift index f0ba0a1bf..25be3e43e 100644 --- a/GRDB/QueryInterface/SQL/SQLOrdering.swift +++ b/GRDB/QueryInterface/SQL/SQLOrdering.swift @@ -23,7 +23,7 @@ public protocol SQLOrderingTerm { // MARK: - SQLOrdering -enum SQLOrdering : SQLOrderingTerm { +enum SQLOrdering: SQLOrderingTerm { case asc(SQLExpression) case desc(SQLExpression) diff --git a/GRDB/QueryInterface/SQL/SQLQuery.swift b/GRDB/QueryInterface/SQL/SQLQuery.swift index ad3e1b2fb..87e3825e5 100644 --- a/GRDB/QueryInterface/SQL/SQLQuery.swift +++ b/GRDB/QueryInterface/SQL/SQLQuery.swift @@ -11,7 +11,7 @@ struct SQLQuery { // `(a AND b AND c)` instead of `((a AND b) AND c)`. var havingExpressions: [SQLExpression] var limit: SQLLimit? - + init( relation: SQLRelation, isDistinct: Bool = false, diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index ec5123fa2..ec7f167eb 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -1,4 +1,5 @@ -/// A "relation", as defined by the [relational terminology](https://en.wikipedia.org/wiki/Relational_database#Terminology), +/// A "relation", as defined by the [relational +/// terminology](https://en.wikipedia.org/wiki/Relational_database#Terminology), /// is "a set of tuples sharing the same attributes; a set of columns and rows." /// /// SQLRelation is defined with a selection, a source table of query, and an @@ -200,7 +201,7 @@ extension SQLRelation { relation.selection.append(contentsOf: selection) return relation } - + func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> SQLRelation { var relation = self relation.filtersPromise = relation.filtersPromise.flatMap { filters in @@ -277,10 +278,10 @@ extension SQLRelation { /// as HasManyThrough, which have any number of pivot relations between the /// origin and the destination. func appendingChild(for association: SQLAssociation, kind: SQLRelation.Child.Kind) -> SQLRelation { + // Preserve association cardinality in intermediate steps of + // including(all:), and force desired cardinality otherwize let childCardinality = (kind == .allNotPrefetched) - // preserve association cardinality in intermediate steps of including(all:) ? association.destination.cardinality - // force desired cardinality otherwize : kind.cardinality let childKey = association.destination.key.name(for: childCardinality) let child = SQLRelation.Child( @@ -347,7 +348,10 @@ extension SQLRelation { if let existingChild = relation.children.removeValue(forKey: key) { guard let mergedChild = existingChild.merged(with: child) else { // can't merge - fatalError("The association key \"\(key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") + fatalError(""" + The association key \"\(key)\" is ambiguous. \ + Use the Association.forKey(_:) method is order to disambiguate. + """) } relation.children.appendValue(mergedChild, forKey: key) } else { @@ -387,7 +391,7 @@ enum SQLSource { func qualified(with alias: TableAlias) -> SQLSource { switch self { - case .table(let tableName, let sourceAlias): + case let .table(tableName, sourceAlias): if let sourceAlias = sourceAlias { alias.becomeProxy(of: sourceAlias) return self @@ -395,7 +399,7 @@ enum SQLSource { alias.setTableName(tableName) return .table(tableName: tableName, alias: alias) } - case .query(let query): + case let .query(query): return .query(query.qualified(with: alias)) } } @@ -774,7 +778,7 @@ extension SQLRelation.Child.Kind { // .including(all: associationToDestinationThroughPivot) // .including(all: associationToPivot) fatalError("Not implemented: merging a direct association and an indirect one with including(all:)") - + case (.allNotPrefetched, .allNotPrefetched): // Equivalent to Record.including(all: association) // diff --git a/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift index 08fbe4c48..311e87d16 100644 --- a/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift @@ -18,7 +18,7 @@ public struct AllColumns { public init() { } } -extension AllColumns : SQLSelectable { +extension AllColumns: SQLSelectable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func resultColumnSQL(_ context: inout SQLGenerationContext) -> String { @@ -69,7 +69,7 @@ struct QualifiedAllColumns { } } -extension QualifiedAllColumns : SQLSelectable { +extension QualifiedAllColumns: SQLSelectable { func resultColumnSQL(_ context: inout SQLGenerationContext) -> String { if let qualifier = context.qualifier(for: alias) { return qualifier.quotedDatabaseIdentifier + ".*" @@ -94,10 +94,10 @@ extension QualifiedAllColumns : SQLSelectable { // // So let's always return `*`, and fix this later. -// if context.qualifier(for: alias) != nil { -// // SELECT COUNT(t.*) is invalid SQL -// fatalError("Not implemented, or invalid query") -// } + // if context.qualifier(for: alias) != nil { + // // SELECT COUNT(t.*) is invalid SQL + // fatalError("Not implemented, or invalid query") + // } return "*" } @@ -118,7 +118,7 @@ extension QualifiedAllColumns : SQLSelectable { // MARK: - SQLAliasedExpression -struct SQLAliasedExpression : SQLSelectable { +struct SQLAliasedExpression: SQLSelectable { let expression: SQLExpression let name: String diff --git a/GRDB/QueryInterface/SQL/SQLSelectable.swift b/GRDB/QueryInterface/SQL/SQLSelectable.swift index cc492f4bb..a0497b7d1 100644 --- a/GRDB/QueryInterface/SQL/SQLSelectable.swift +++ b/GRDB/QueryInterface/SQL/SQLSelectable.swift @@ -25,7 +25,7 @@ public protocol SQLSelectable { // MARK: - SQLSelectionLiteral -struct SQLSelectionLiteral : SQLSelectable { +struct SQLSelectionLiteral: SQLSelectable { private let sqlLiteral: SQLLiteral init(literal sqlLiteral: SQLLiteral) { @@ -42,15 +42,24 @@ struct SQLSelectionLiteral : SQLSelectable { } func countedSQL(_ context: inout SQLGenerationContext) -> String { - fatalError("Selection literals can't be counted. To resolve this error, select one or several SQLExpressionLiteral instead.") + fatalError(""" + Selection literals can't be counted. \ + To resolve this error, select one or several SQLExpressionLiteral instead. + """) } func count(distinct: Bool) -> SQLCount? { - fatalError("Selection literals can't be counted. To resolve this error, select one or several SQLExpressionLiteral instead.") + fatalError(""" + Selection literals can't be counted. \ + To resolve this error, select one or several SQLExpressionLiteral instead. + """) } func columnCount(_ db: Database) throws -> Int { - fatalError("Selection literals don't known how many columns they contain. To resolve this error, select one or several SQLExpressionLiteral instead.") + fatalError(""" + Selection literals don't known how many columns they contain. \ + To resolve this error, select one or several SQLExpressionLiteral instead. + """) } func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { diff --git a/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift index 329f3b39e..3c9c39d56 100644 --- a/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift @@ -63,4 +63,3 @@ extension SQLSpecificExpressible { return SQLCollatedExpression(sqlExpression, collationName: Database.CollationName(collation.name)) } } - diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index 60d5f4a1b..525e32728 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -96,7 +96,6 @@ public struct SQLGenerationContext { /// /// A TableAlias identifies a table in a request. public class TableAlias: Hashable { - private var impl: Impl private enum Impl { /// A TableAlias is undefined when it is created by the GRDB user: /// @@ -144,6 +143,8 @@ public class TableAlias: Hashable { case proxy(TableAlias) } + private var impl: Impl + /// Resolve all proxies private var root: TableAlias { if case .proxy(let base) = impl { @@ -221,7 +222,8 @@ public class TableAlias: Hashable { let root = self.root let otherRoot = other.root switch (root.impl, otherRoot.impl) { - case let (.table(tableName: tableName, userName: userName), .table(tableName: otherTableName, userName: otherUserName)): + case let (.table(tableName: tableName, userName: userName), + .table(tableName: otherTableName, userName: otherUserName)): guard tableName == otherTableName else { // can't merge return nil diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 1ab3bf6c2..2d3c8d7b1 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -54,32 +54,43 @@ struct SQLQueryGenerator { GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") sql += " " + selection.map { $0.resultColumnSQL(&context) }.joined(separator: ", ") - sql += try " FROM " + relation.source.sql(db, &context) + sql += " FROM " + sql += try relation.source.sql(db, &context) for (_, join) in relation.joins { - sql += try " " + join.sql(db, &context, leftAlias: relation.alias) + sql += " " + sql += try join.sql(db, &context, leftAlias: relation.alias) } let filters = try relation.filtersPromise.resolve(db) if filters.isEmpty == false { - sql += " WHERE " + SQLExpressionAnd(filters).expressionSQL(&context, wrappedInParenthesis: false) + sql += " WHERE " + sql += SQLExpressionAnd(filters).expressionSQL(&context, wrappedInParenthesis: false) } if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty { - sql += " GROUP BY " + groupExpressions.map { $0.expressionSQL(&context, wrappedInParenthesis: false) }.joined(separator: ", ") + sql += " GROUP BY " + sql += groupExpressions + .map { $0.expressionSQL(&context, wrappedInParenthesis: false) } + .joined(separator: ", ") } if havingExpressions.isEmpty == false { - sql += " HAVING " + SQLExpressionAnd(havingExpressions).expressionSQL(&context, wrappedInParenthesis: false) + sql += " HAVING " + sql += SQLExpressionAnd(havingExpressions).expressionSQL(&context, wrappedInParenthesis: false) } let orderings = try relation.ordering.resolve(db) if !orderings.isEmpty { - sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") + sql += " ORDER BY " + sql += orderings + .map { $0.orderingTermSQL(&context) } + .joined(separator: ", ") } if let limit = limit { - sql += " LIMIT " + limit.sql + sql += " LIMIT " + sql += limit.sql } return sql @@ -409,23 +420,23 @@ private enum SQLQualifiedSource { init(_ source: SQLSource) { switch source { - case .table(let tableName, let alias): + case let .table(tableName, alias): let alias = alias ?? TableAlias(tableName: tableName) self = .table(tableName: tableName, alias: alias) - case .query(let query): + case let .query(query): self = .query(SQLQueryGenerator(query)) } } func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { switch self { - case .table(let tableName, let alias): + case let .table(tableName, alias): if let aliasName = context.aliasName(for: alias) { return "\(tableName.quotedDatabaseIdentifier) \(aliasName.quotedDatabaseIdentifier)" } else { return "\(tableName.quotedDatabaseIdentifier)" } - case .query(let query): + case let .query(query): return try "(\(query.sql(db, &context)))" } } @@ -437,15 +448,22 @@ private struct SQLQualifiedJoin { case leftJoin = "LEFT JOIN" case innerJoin = "JOIN" } + let kind: Kind let condition: SQLAssociationCondition let relation: SQLQualifiedRelation - func sql(_ db: Database,_ context: inout SQLGenerationContext, leftAlias: TableAlias) throws -> String { + func sql(_ db: Database, _ context: inout SQLGenerationContext, leftAlias: TableAlias) throws -> String { return try sql(db, &context, leftAlias: leftAlias, allowingInnerJoin: true) } - private func sql(_ db: Database,_ context: inout SQLGenerationContext, leftAlias: TableAlias, allowingInnerJoin allowsInnerJoin: Bool) throws -> String { + private func sql( + _ db: Database, + _ context: inout SQLGenerationContext, + leftAlias: TableAlias, + allowingInnerJoin allowsInnerJoin: Bool) + throws -> String + { var allowsInnerJoin = allowsInnerJoin var sql = "" diff --git a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift index 52f16831f..6d7d71382 100644 --- a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift @@ -44,7 +44,9 @@ extension SQLInterpolation { /// let request: SQLRequest = " /// SELECT \(CodingKey.name) FROM player /// """ - public mutating func appendInterpolation(_ codingKey: SQLExpressible & SQLSelectable & SQLOrderingTerm & CodingKey) { + public mutating func appendInterpolation( + _ codingKey: SQLExpressible & SQLSelectable & SQLOrderingTerm & CodingKey) + { sql += codingKey.sqlExpression.expressionSQL(&context, wrappedInParenthesis: false) } @@ -133,7 +135,7 @@ extension SQLInterpolation { public mutating func appendInterpolation(_ ordering: SQLOrderingTerm) { sql += ordering.orderingTermSQL(&context) } - + /// Appends the request SQL, wrapped in parentheses /// /// // SELECT name FROM player WHERE score = (SELECT MAX(score) FROM player) diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index 2c4c35c08..10a18d68b 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -25,8 +25,19 @@ extension Database { /// - withoutRowID: If true, uses WITHOUT ROWID optimization. /// - body: A closure that defines table columns and constraints. /// - throws: A DatabaseError whenever an SQLite error occurs. - public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, withoutRowID: Bool = false, body: (TableDefinition) -> Void) throws { - let definition = TableDefinition(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: withoutRowID) + public func create( + table name: String, + temporary: Bool = false, + ifNotExists: Bool = false, + withoutRowID: Bool = false, + body: (TableDefinition) -> Void) + throws + { + let definition = TableDefinition( + name: name, + temporary: temporary, + ifNotExists: ifNotExists, + withoutRowID: withoutRowID) body(definition) let sql = try definition.sql(self) try execute(sql: sql) @@ -55,10 +66,22 @@ extension Database { /// - body: A closure that defines table columns and constraints. /// - throws: A DatabaseError whenever an SQLite error occurs. @available(OSX 10.10, *) - public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, withoutRowID: Bool, body: (TableDefinition) -> Void) throws { + public func create( + table name: String, + temporary: Bool = false, + ifNotExists: Bool = false, + withoutRowID: Bool, + body: (TableDefinition) -> Void) + throws + { // WITHOUT ROWID was added in SQLite 3.8.2 http://www.sqlite.org/changes.html#version_3_8_2 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - let definition = TableDefinition(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: withoutRowID) + // It is available from iOS 8.2 and OS X 10.10 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + let definition = TableDefinition( + name: name, + temporary: temporary, + ifNotExists: ifNotExists, + withoutRowID: withoutRowID) body(definition) let sql = try definition.sql(self) try execute(sql: sql) @@ -84,14 +107,24 @@ extension Database { /// already exists. /// - body: A closure that defines table columns and constraints. /// - throws: A DatabaseError whenever an SQLite error occurs. - public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, body: (TableDefinition) -> Void) throws { - let definition = TableDefinition(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: false) + public func create( + table name: String, + temporary: Bool = false, + ifNotExists: Bool = false, + body: (TableDefinition) -> Void) + throws + { + let definition = TableDefinition( + name: name, + temporary: temporary, + ifNotExists: ifNotExists, + withoutRowID: false) body(definition) let sql = try definition.sql(self) try execute(sql: sql) } #endif - + /// Renames a database table. /// /// See https://www.sqlite.org/lang_altertable.html @@ -150,10 +183,25 @@ extension Database { /// - ifNotExists: If false, no error is thrown if index already exists. /// - condition: If not nil, creates a partial index /// (see https://www.sqlite.org/partialindex.html). - public func create(index name: String, on table: String, columns: [String], unique: Bool = false, ifNotExists: Bool = false, condition: SQLExpressible? = nil) throws { + public func create( + index name: String, + on table: String, + columns: [String], + unique: Bool = false, + ifNotExists: Bool = false, + condition: SQLExpressible? = nil) + throws + { // Partial indexes were introduced in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - let definition = IndexDefinition(name: name, table: table, columns: columns, unique: unique, ifNotExists: ifNotExists, condition: condition?.sqlExpression) + // It is available from iOS 8.2 and OS X 10.10 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + let definition = IndexDefinition( + name: name, + table: table, + columns: columns, + unique: unique, + ifNotExists: ifNotExists, + condition: condition?.sqlExpression) let sql = definition.sql() try execute(sql: sql) } @@ -176,10 +224,24 @@ extension Database { /// - columns: The indexed columns. /// - unique: If true, creates a unique index. /// - ifNotExists: If false, no error is thrown if index already exists. - public func create(index name: String, on table: String, columns: [String], unique: Bool = false, ifNotExists: Bool = false) throws { + public func create( + index name: String, + on table: String, + columns: [String], + unique: Bool = false, + ifNotExists: Bool = false) + throws + { // Partial indexes were introduced in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - let definition = IndexDefinition(name: name, table: table, columns: columns, unique: unique, ifNotExists: ifNotExists, condition: nil) + // It is available from iOS 8.2 and OS X 10.10 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + let definition = IndexDefinition( + name: name, + table: table, + columns: columns, + unique: unique, + ifNotExists: ifNotExists, + condition: nil) let sql = definition.sql() try execute(sql: sql) } @@ -199,10 +261,25 @@ extension Database { /// - ifNotExists: If false, no error is thrown if index already exists. /// - condition: The condition that indexed rows must verify. @available(OSX 10.10, *) - public func create(index name: String, on table: String, columns: [String], unique: Bool = false, ifNotExists: Bool = false, condition: SQLExpressible) throws { + public func create( + index name: String, + on table: String, + columns: [String], + unique: Bool = false, + ifNotExists: Bool = false, + condition: SQLExpressible) + throws + { // Partial indexes were introduced in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - let definition = IndexDefinition(name: name, table: table, columns: columns, unique: unique, ifNotExists: ifNotExists, condition: condition.sqlExpression) + // It is available from iOS 8.2 and OS X 10.10 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + let definition = IndexDefinition( + name: name, + table: table, + columns: columns, + unique: unique, + ifNotExists: ifNotExists, + condition: condition.sqlExpression) let sql = definition.sql() try execute(sql: sql) } @@ -253,7 +330,18 @@ extension Database { /// /// See https://www.sqlite.org/lang_createtable.html public final class TableDefinition { - private typealias KeyConstraint = (columns: [String], conflictResolution: Database.ConflictResolution?) + private typealias KeyConstraint = ( + columns: [String], + conflictResolution: Database.ConflictResolution?) + + private struct ForeignKeyConstraint { + var columns: [String] + var table: String + var destinationColumns: [String]? + var deleteAction: Database.ForeignKeyAction? + var updateAction: Database.ForeignKeyAction? + var deferred: Bool + } private let name: String private let temporary: Bool @@ -262,7 +350,7 @@ public final class TableDefinition { private var columns: [ColumnDefinition] = [] private var primaryKeyConstraint: KeyConstraint? private var uniqueKeyConstraints: [KeyConstraint] = [] - private var foreignKeyConstraints: [(columns: [String], table: String, destinationColumns: [String]?, deleteAction: Database.ForeignKeyAction?, updateAction: Database.ForeignKeyAction?, deferred: Bool)] = [] + private var foreignKeyConstraints: [ForeignKeyConstraint] = [] private var checkConstraints: [SQLExpression] = [] init(name: String, temporary: Bool, ifNotExists: Bool, withoutRowID: Bool) { @@ -300,10 +388,14 @@ public final class TableDefinition { /// (see https://www.sqlite.org/lang_conflict.html). /// - returns: Self so that you can further refine the column definition. @discardableResult - public func autoIncrementedPrimaryKey(_ name: String, onConflict conflictResolution: Database.ConflictResolution? = nil) -> ColumnDefinition { + public func autoIncrementedPrimaryKey( + _ name: String, + onConflict conflictResolution: Database.ConflictResolution? = nil) + -> ColumnDefinition + { return column(name, .integer).primaryKey(onConflict: conflictResolution, autoincrement: true) } - + /// Appends a table column. /// /// try db.create(table: "player") { t in @@ -383,8 +475,21 @@ public final class TableDefinition { /// - updateAction: Optional action when the referenced row is updated. /// - deferred: If true, defines a deferred foreign key constraint. /// See https://www.sqlite.org/foreignkeys.html#fk_deferred. - public func foreignKey(_ columns: [String], references table: String, columns destinationColumns: [String]? = nil, onDelete deleteAction: Database.ForeignKeyAction? = nil, onUpdate updateAction: Database.ForeignKeyAction? = nil, deferred: Bool = false) { - foreignKeyConstraints.append((columns: columns, table: table, destinationColumns: destinationColumns, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred)) + public func foreignKey( + _ columns: [String], + references table: String, + columns destinationColumns: [String]? = nil, + onDelete deleteAction: Database.ForeignKeyAction? = nil, + onUpdate updateAction: Database.ForeignKeyAction? = nil, + deferred: Bool = false) + { + foreignKeyConstraints.append(ForeignKeyConstraint( + columns: columns, + table: table, + destinationColumns: destinationColumns, + deleteAction: deleteAction, + updateAction: updateAction, + deferred: deferred)) } /// Adds a CHECK constraint. @@ -451,12 +556,14 @@ public final class TableDefinition { do { var items: [String] = [] - try items.append(contentsOf: columns.map { try $0.sql(db, tableName: name, primaryKeyColumns: primaryKeyColumns) }) + try items.append(contentsOf: columns.map { + try $0.sql(db, tableName: name, primaryKeyColumns: primaryKeyColumns) + }) if let (columns, conflictResolution) = primaryKeyConstraint { var chunks: [String] = [] chunks.append("PRIMARY KEY") - chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + chunks.append("(\(columns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", ")))") if let conflictResolution = conflictResolution { chunks.append("ON CONFLICT") chunks.append(conflictResolution.rawValue) @@ -467,7 +574,7 @@ public final class TableDefinition { for (columns, conflictResolution) in uniqueKeyConstraints { var chunks: [String] = [] chunks.append("UNIQUE") - chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + chunks.append("(\(columns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", ")))") if let conflictResolution = conflictResolution { chunks.append("ON CONFLICT") chunks.append(conflictResolution.rawValue) @@ -475,28 +582,40 @@ public final class TableDefinition { items.append(chunks.joined(separator: " ")) } - for (columns, table, destinationColumns, deleteAction, updateAction, deferred) in foreignKeyConstraints { + for constraint in foreignKeyConstraints { var chunks: [String] = [] chunks.append("FOREIGN KEY") - chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + chunks.append("(\(constraint.columns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", ")))") chunks.append("REFERENCES") - if let destinationColumns = destinationColumns { - chunks.append("\(table.quotedDatabaseIdentifier)(\((destinationColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") - } else if table == name { - chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + if let destinationColumns = constraint.destinationColumns { + chunks.append(""" + \(constraint.table.quotedDatabaseIdentifier)(\ + \(destinationColumns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", "))\ + ) + """) + } else if constraint.table == name { + chunks.append(""" + \(constraint.table.quotedDatabaseIdentifier)(\ + \(primaryKeyColumns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", "))\ + ) + """) } else { - let primaryKey = try db.primaryKey(table) - chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKey.columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + let primaryKey = try db.primaryKey(constraint.table) + chunks.append(""" + \(constraint.table.quotedDatabaseIdentifier)(\ + \(primaryKey.columns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", "))\ + ) + """) } - if let deleteAction = deleteAction { + if let deleteAction = constraint.deleteAction { chunks.append("ON DELETE") chunks.append(deleteAction.rawValue) } - if let updateAction = updateAction { + if let updateAction = constraint.updateAction { chunks.append("ON UPDATE") chunks.append(updateAction.rawValue) } - if deferred { + if constraint.deferred { chunks.append("DEFERRABLE INITIALLY DEFERRED") } items.append(chunks.joined(separator: " ")) @@ -504,7 +623,7 @@ public final class TableDefinition { for checkExpression in checkConstraints { var chunks: [String] = [] - chunks.append("CHECK (\(checkExpression.quotedSQL(wrappedInParenthesis: false)))") + chunks.append("CHECK (\(checkExpression.quotedSQL()))") items.append(chunks.joined(separator: " ")) } @@ -603,13 +722,22 @@ public final class ColumnDefinition { case index case unique(Database.ConflictResolution) } + + private struct ForeignKeyConstraint { + var table: String + var column: String? + var deleteAction: Database.ForeignKeyAction? + var updateAction: Database.ForeignKeyAction? + var deferred: Bool + } + fileprivate let name: String private let type: Database.ColumnType? fileprivate var primaryKey: (conflictResolution: Database.ConflictResolution?, autoincrement: Bool)? private var index: Index = .none private var notNullConflictResolution: Database.ConflictResolution? private var checkConstraints: [SQLExpression] = [] - private var foreignKeyConstraints: [(table: String, column: String?, deleteAction: Database.ForeignKeyAction?, updateAction: Database.ForeignKeyAction?, deferred: Bool)] = [] + private var foreignKeyConstraints: [ForeignKeyConstraint] = [] private var defaultExpression: SQLExpression? private var collationName: String? @@ -633,7 +761,11 @@ public final class ColumnDefinition { /// - autoincrement: If true, the primary key is autoincremented. /// - returns: Self so that you can further refine the column definition. @discardableResult - public func primaryKey(onConflict conflictResolution: Database.ConflictResolution? = nil, autoincrement: Bool = false) -> Self { + public func primaryKey( + onConflict conflictResolution: Database.ConflictResolution? = nil, + autoincrement: Bool = false) + -> Self + { primaryKey = (conflictResolution: conflictResolution, autoincrement: autoincrement) return self } @@ -804,8 +936,19 @@ public final class ColumnDefinition { /// See https://www.sqlite.org/foreignkeys.html#fk_deferred. /// - returns: Self so that you can further refine the column definition. @discardableResult - public func references(_ table: String, column: String? = nil, onDelete deleteAction: Database.ForeignKeyAction? = nil, onUpdate updateAction: Database.ForeignKeyAction? = nil, deferred: Bool = false) -> Self { - foreignKeyConstraints.append((table: table, column: column, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred)) + public func references( + _ table: String, + column: String? = nil, + onDelete deleteAction: Database.ForeignKeyAction? = nil, + onUpdate updateAction: Database.ForeignKeyAction? = nil, + deferred: Bool = false) -> Self + { + foreignKeyConstraints.append(ForeignKeyConstraint( + table: table, + column: column, + deleteAction: deleteAction, + updateAction: updateAction, + deferred: deferred)) return self } @@ -853,11 +996,11 @@ public final class ColumnDefinition { } for checkConstraint in checkConstraints { - chunks.append("CHECK (\(checkConstraint.quotedSQL(wrappedInParenthesis: false)))") + chunks.append("CHECK (\(checkConstraint.quotedSQL()))") } if let defaultExpression = defaultExpression { - chunks.append("DEFAULT \(defaultExpression.quotedSQL(wrappedInParenthesis: false))") + chunks.append("DEFAULT \(defaultExpression.quotedSQL())") } if let collationName = collationName { @@ -865,29 +1008,37 @@ public final class ColumnDefinition { chunks.append(collationName) } - for (table, column, deleteAction, updateAction, deferred) in foreignKeyConstraints { + for constraint in foreignKeyConstraints { chunks.append("REFERENCES") - if let column = column { + if let column = constraint.column { // explicit reference - chunks.append("\(table.quotedDatabaseIdentifier)(\(column.quotedDatabaseIdentifier))") - } else if table.lowercased() == tableName.lowercased() { + chunks.append("\(constraint.table.quotedDatabaseIdentifier)(\(column.quotedDatabaseIdentifier))") + } else if constraint.table.lowercased() == tableName.lowercased() { // implicit autoreference - let primaryKeyColumns = try primaryKeyColumns ?? db.primaryKey(table).columns - chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + let primaryKeyColumns = try primaryKeyColumns ?? db.primaryKey(constraint.table).columns + chunks.append(""" + \(constraint.table.quotedDatabaseIdentifier)(\ + \(primaryKeyColumns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", "))\ + ) + """) } else { // implicit external reference - let primaryKeyColumns = try db.primaryKey(table).columns - chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + let primaryKeyColumns = try db.primaryKey(constraint.table).columns + chunks.append(""" + \(constraint.table.quotedDatabaseIdentifier)(\ + \(primaryKeyColumns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", "))\ + ) + """) } - if let deleteAction = deleteAction { + if let deleteAction = constraint.deleteAction { chunks.append("ON DELETE") chunks.append(deleteAction.rawValue) } - if let updateAction = updateAction { + if let updateAction = constraint.updateAction { chunks.append("ON UPDATE") chunks.append(updateAction.rawValue) } - if deferred { + if constraint.deferred { chunks.append("DEFERRABLE INITIALLY DEFERRED") } } @@ -931,9 +1082,13 @@ private struct IndexDefinition { } chunks.append(name.quotedDatabaseIdentifier) chunks.append("ON") - chunks.append("\(table.quotedDatabaseIdentifier)(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + chunks.append(""" + \(table.quotedDatabaseIdentifier)(\ + \(columns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", "))\ + ) + """) if let condition = condition { - chunks.append("WHERE \(condition.quotedSQL(wrappedInParenthesis: false))") + chunks.append("WHERE \(condition.quotedSQL())") } return chunks.joined(separator: " ") } diff --git a/GRDB/QueryInterface/Schema/VirtualTableModule.swift b/GRDB/QueryInterface/Schema/VirtualTableModule.swift index 06eaa3ea2..6534816b9 100644 --- a/GRDB/QueryInterface/Schema/VirtualTableModule.swift +++ b/GRDB/QueryInterface/Schema/VirtualTableModule.swift @@ -96,7 +96,13 @@ extension Database { /// - module: a VirtualTableModule /// - body: An optional closure that defines the virtual table. /// - throws: A DatabaseError whenever an SQLite error occurs. - public func create(virtualTable tableName: String, ifNotExists: Bool = false, using module: Module, _ body: ((Module.TableDefinition) -> Void)? = nil) throws { + public func create( + virtualTable tableName: String, + ifNotExists: Bool = false, + using module: Module, + _ body: ((Module.TableDefinition) -> Void)? = nil) + throws + { // Define virtual table let definition = module.makeTableDefinition() if let body = body { diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index 5ea8bf58f..136ddb7fc 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -545,7 +545,10 @@ extension TableRecord where Self: EncodableRecord { /// /// let team: Team = ... /// let players = try team.players.fetchAll(db) // [Player] - public func request(for association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { + public func request(for association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self + { let destinationRelation = association.sqlAssociation.destinationRelation(fromOriginRows: { db in try [Row(PersistenceContainer(db, self))] }) @@ -558,35 +561,50 @@ extension TableRecord { // MARK: - Associations /// Creates a request that prefetches an association. - public static func including(all association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { + public static func including(all association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self + { return all().including(all: association) } /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned association does not /// require that the associated database table contains a matching row. - public static func including(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { + public static func including(optional association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self + { return all().including(optional: association) } /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned association requires /// that the associated database table contains a matching row. - public static func including(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { + public static func including(required association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self + { return all().including(required: association) } /// Creates a request that includes an association. The columns of the /// associated record are not selected. The returned association does not /// require that the associated database table contains a matching row. - public static func joining(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { + public static func joining(optional association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self + { return all().joining(optional: association) } /// Creates a request that includes an association. The columns of the /// associated record are not selected. The returned association requires /// that the associated database table contains a matching row. - public static func joining(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { + public static func joining(required association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self + { return all().joining(required: association) } diff --git a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift index fef01e1ad..fd7adae20 100644 --- a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift @@ -52,7 +52,11 @@ extension TableRecord { /// /// // SELECT id, email FROM player /// let request = Player.select(sql: "id, email") - public static func select(sql: String, arguments: StatementArguments = StatementArguments()) -> QueryInterfaceRequest { + public static func select( + sql: String, + arguments: StatementArguments = StatementArguments()) + -> QueryInterfaceRequest + { return select(literal: SQLLiteral(sql: sql, arguments: arguments)) } @@ -72,7 +76,11 @@ extension TableRecord { /// let request = Player.select([max(Column("score"))], as: Int.self) /// let maxScore: Int? = try request.fetchOne(db) /// } - public static func select(_ selection: [SQLSelectable], as type: RowDecoder.Type) -> QueryInterfaceRequest { + public static func select( + _ selection: [SQLSelectable], + as type: RowDecoder.Type) + -> QueryInterfaceRequest + { return all().select(selection, as: type) } @@ -84,7 +92,11 @@ extension TableRecord { /// let request = Player.select(max(Column("score")), as: Int.self) /// let maxScore: Int? = try request.fetchOne(db) /// } - public static func select(_ selection: SQLSelectable..., as type: RowDecoder.Type) -> QueryInterfaceRequest { + public static func select( + _ selection: SQLSelectable..., + as type: RowDecoder.Type) + -> QueryInterfaceRequest + { return all().select(selection, as: type) } @@ -96,7 +108,12 @@ extension TableRecord { /// let request = Player.select(sql: "max(score)", as: Int.self) /// let maxScore: Int? = try request.fetchOne(db) /// } - public static func select(sql: String, arguments: StatementArguments = StatementArguments(), as type: RowDecoder.Type) -> QueryInterfaceRequest { + public static func select( + sql: String, + arguments: StatementArguments = StatementArguments(), + as type: RowDecoder.Type) + -> QueryInterfaceRequest + { return all().select(literal: SQLLiteral(sql: sql, arguments: arguments), as: type) } @@ -108,7 +125,11 @@ extension TableRecord { /// let request = Player.select(literal: SQLLiteral(sql: "max(score)"), as: Int.self) /// let maxScore: Int? = try request.fetchOne(db) /// } - public static func select(literal sqlLiteral: SQLLiteral, as type: RowDecoder.Type) -> QueryInterfaceRequest { + public static func select( + literal sqlLiteral: SQLLiteral, + as type: RowDecoder.Type) + -> QueryInterfaceRequest + { return all().select(literal: sqlLiteral, as: type) } @@ -152,7 +173,10 @@ extension TableRecord { /// The selection defaults to all columns. This default can be changed for /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. - public static func filter(key: PrimaryKeyType?) -> QueryInterfaceRequest { + public static func filter(key: PrimaryKeyType?) + -> QueryInterfaceRequest + where PrimaryKeyType: DatabaseValueConvertible + { return all().filter(key: key) } @@ -164,7 +188,10 @@ extension TableRecord { /// The selection defaults to all columns. This default can be changed for /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. - public static func filter(keys: Sequence) -> QueryInterfaceRequest where Sequence.Element: DatabaseValueConvertible { + public static func filter(keys: Sequence) + -> QueryInterfaceRequest + where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible + { return all().filter(keys: keys) } @@ -206,7 +233,11 @@ extension TableRecord { /// The selection defaults to all columns. This default can be changed for /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. - public static func filter(sql: String, arguments: StatementArguments = StatementArguments()) -> QueryInterfaceRequest { + public static func filter( + sql: String, + arguments: StatementArguments = StatementArguments()) + -> QueryInterfaceRequest + { return filter(literal: SQLLiteral(sql: sql, arguments: arguments)) } @@ -277,7 +308,11 @@ extension TableRecord { /// The selection defaults to all columns. This default can be changed for /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. - public static func order(sql: String, arguments: StatementArguments = StatementArguments()) -> QueryInterfaceRequest { + public static func order( + sql: String, + arguments: StatementArguments = StatementArguments()) + -> QueryInterfaceRequest + { return all().order(literal: SQLLiteral(sql: sql, arguments: arguments)) } diff --git a/GRDB/Record/EncodableRecord+Encodable.swift b/GRDB/Record/EncodableRecord+Encodable.swift index f38439a71..d0a2e522f 100644 --- a/GRDB/Record/EncodableRecord+Encodable.swift +++ b/GRDB/Record/EncodableRecord+Encodable.swift @@ -45,7 +45,7 @@ private class RecordEncoder: Encoder { fatalError("single value encoding is not supported") } - private struct KeyedContainer : KeyedEncodingContainerProtocol { + private struct KeyedContainer: KeyedEncodingContainerProtocol { var recordEncoder: RecordEncoder var userInfo: [CodingUserInfoKey: Any] { return Record.databaseEncodingUserInfo } @@ -55,6 +55,7 @@ private class RecordEncoder: Encoder { var codingPath: [CodingKey] { return [] } + // swiftlint:disable comma func encode(_ value: Bool, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: Int, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: Int8, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } @@ -69,13 +70,15 @@ private class RecordEncoder: Encoder { func encode(_ value: Float, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: Double, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: String, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + // swiftlint:enable comma - func encode(_ value: T, forKey key: Key) throws where T : Encodable { + func encode(_ value: T, forKey key: Key) throws where T: Encodable { try recordEncoder.encode(value, forKey: key) } func encodeNil(forKey key: Key) throws { recordEncoder.persist(nil, forKey: key) } + // swiftlint:disable comma func encodeIfPresent(_ value: Bool?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: Int?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: Int8?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } @@ -90,8 +93,9 @@ private class RecordEncoder: Encoder { func encodeIfPresent(_ value: Float?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: Double?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: String?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + // swiftlint:disable comma - func encodeIfPresent(_ value: T?, forKey key: Key) throws where T : Encodable { + func encodeIfPresent(_ value: T?, forKey key: Key) throws where T: Encodable { if let value = value { try recordEncoder.encode(value, forKey: key) } else { @@ -99,7 +103,11 @@ private class RecordEncoder: Encoder { } } - func nestedContainer(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer { + func nestedContainer( + keyedBy keyType: NestedKey.Type, + forKey key: Key) + -> KeyedEncodingContainer + { fatalError("Not implemented") } @@ -123,7 +131,7 @@ private class RecordEncoder: Encoder { } @inline(__always) - fileprivate func encode(_ value: T, forKey key: CodingKey) throws where T : Encodable { + fileprivate func encode(_ value: T, forKey key: CodingKey) throws where T: Encodable { if let date = value as? Date { persist(Record.databaseDateEncodingStrategy.encode(date), forKey: key) } else if let uuid = value as? UUID { @@ -151,8 +159,9 @@ private class RecordEncoder: Encoder { // database inspection. Thanks to SQLite weak typing, we won't // have any trouble decoding this string into data when we // eventually perform JSON decoding. - // TODO: possible optimization: avoid this conversion to string, and store raw data bytes as an SQLite string - let jsonString = String(data: jsonData, encoding: .utf8)! // force unwrap because json data is guaranteed to convert to String + // TODO: possible optimization: avoid this conversion to string, + // and store raw data bytes as an SQLite string + let jsonString = String(data: jsonData, encoding: .utf8)! persist(jsonString, forKey: key) } } @@ -174,7 +183,7 @@ private class ColumnEncoder: Encoder { self.key = key } - func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key : CodingKey { + func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key: CodingKey { // Keyed values require JSON encoding: we need to throw // JSONRequiredError. Since we can't throw right from here, let's // delegate the job to a dedicated container. @@ -214,7 +223,7 @@ extension ColumnEncoder: SingleValueEncodingContainer { func encode(_ value: Double) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: String) throws { recordEncoder.persist(value, forKey: key) } - func encode(_ value: T) throws where T : Encodable { + func encode(_ value: T) throws where T: Encodable { try recordEncoder.encode(value, forKey: key) } } @@ -233,7 +242,7 @@ private struct JSONRequiredEncoder: Encoder { self.codingPath = codingPath } - func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key : CodingKey { + func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key: CodingKey { let container = KeyedContainer(codingPath: codingPath) return KeyedEncodingContainer(container) } @@ -265,9 +274,14 @@ private struct JSONRequiredEncoder: Encoder { func encode(_ value: Float, forKey key: KeyType) throws { throw JSONRequiredError() } func encode(_ value: Double, forKey key: KeyType) throws { throw JSONRequiredError() } func encode(_ value: String, forKey key: KeyType) throws { throw JSONRequiredError() } - func encode(_ value: T, forKey key: KeyType) throws where T : Encodable { throw JSONRequiredError() } + func encode(_ value: T, forKey key: KeyType) throws where T: Encodable { throw JSONRequiredError() } - func nestedContainer(keyedBy keyType: NestedKey.Type, forKey key: KeyType) -> KeyedEncodingContainer where NestedKey : CodingKey { + func nestedContainer( + keyedBy keyType: NestedKey.Type, + forKey key: KeyType) + -> KeyedEncodingContainer + where NestedKey: CodingKey + { let container = KeyedContainer(codingPath: codingPath + [key]) return KeyedEncodingContainer(container) } @@ -302,13 +316,16 @@ extension JSONRequiredEncoder: SingleValueEncodingContainer { func encode(_ value: Float ) throws { throw JSONRequiredError() } func encode(_ value: Double) throws { throw JSONRequiredError() } func encode(_ value: String) throws { throw JSONRequiredError() } - func encode(_ value: T) throws where T : Encodable { throw JSONRequiredError() } + func encode(_ value: T) throws where T: Encodable { throw JSONRequiredError() } } extension JSONRequiredEncoder: UnkeyedEncodingContainer { var count: Int { return 0 } - mutating func nestedContainer(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer where NestedKey : CodingKey { + mutating func nestedContainer(keyedBy keyType: NestedKey.Type) + -> KeyedEncodingContainer + where NestedKey: CodingKey + { let container = KeyedContainer(codingPath: codingPath) return KeyedEncodingContainer(container) } @@ -329,9 +346,9 @@ fileprivate var iso8601Formatter: ISO8601DateFormatter = { return formatter }() -private extension DatabaseDateEncodingStrategy { +extension DatabaseDateEncodingStrategy { @inline(__always) - func encode(_ date: Date) -> DatabaseValueConvertible? { + fileprivate func encode(_ date: Date) -> DatabaseValueConvertible? { switch self { case .deferredToDate: return date.databaseValue @@ -357,9 +374,9 @@ private extension DatabaseDateEncodingStrategy { } } -private extension DatabaseUUIDEncodingStrategy { +extension DatabaseUUIDEncodingStrategy { @inline(__always) - func encode(_ uuid: UUID) -> DatabaseValueConvertible? { + fileprivate func encode(_ uuid: UUID) -> DatabaseValueConvertible? { switch self { case .deferredToUUID: return uuid.databaseValue diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index 378fe7950..ae3e635b9 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -171,7 +171,8 @@ extension EncodableRecord { /// same set of columns in their `encode(to:)` method, only the columns /// defined by the receiver record are considered. public func databaseChanges(from record: Record) -> [String: DatabaseValue] { - return Dictionary(uniqueKeysWithValues: PersistenceContainer(self).changesIterator(from: PersistenceContainer(record))) + let changes = PersistenceContainer(self).changesIterator(from: PersistenceContainer(record)) + return Dictionary(uniqueKeysWithValues: changes) } } diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index e37963192..fe1df46dd 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -1,10 +1,10 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif extension FetchableRecord where Self: Decodable { @@ -85,6 +85,7 @@ private struct RowDecoder: Decoder { return row[key.stringValue] == nil && (row.scopesTree[key.stringValue] == nil) } + // swiftlint:disable comma func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return decoder.row[key.stringValue] } func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return decoder.row[key.stringValue] } func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { return decoder.row[key.stringValue] } @@ -99,8 +100,9 @@ private struct RowDecoder: Decoder { func decode(_ type: Float.Type, forKey key: Key) throws -> Float { return decoder.row[key.stringValue] } func decode(_ type: Double.Type, forKey key: Key) throws -> Double { return decoder.row[key.stringValue] } func decode(_ type: String.Type, forKey key: Key) throws -> String { return decoder.row[key.stringValue] } + // swiftlint:enable comma - func decodeIfPresent(_ type: T.Type, forKey key: Key) throws -> T? where T : Decodable { + func decodeIfPresent(_ type: T.Type, forKey key: Key) throws -> T? where T: Decodable { let row = decoder.row let keyName = key.stringValue @@ -130,7 +132,7 @@ private struct RowDecoder: Decoder { return nil } - func decode(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable { + func decode(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable { let row = decoder.row let keyName = key.stringValue @@ -159,7 +161,7 @@ private struct RowDecoder: Decoder { let decoder = PrefetchedRowsDecoder(rows: prefetchedRows, codingPath: codingPath) return try T(from: decoder) } - + // Key is not a column, and not a scope. // // Should be throw an error? Well... The use case is the following: @@ -193,7 +195,9 @@ private struct RowDecoder: Decoder { return try decode(type, fromRow: row, codingPath: codingPath + [key]) } - func nestedContainer(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer where NestedKey : CodingKey { + func nestedContainer(keyedBy type: NestedKey.Type, forKey key: Key) + throws -> KeyedDecodingContainer where NestedKey: CodingKey + { fatalError("not implemented") } @@ -215,7 +219,13 @@ private struct RowDecoder: Decoder { // Helper methods @inline(__always) - private func decode(_ type: T.Type, fromRow row: Row, codingPath: [CodingKey]) throws -> T where T: Decodable { + private func decode( + _ type: T.Type, + fromRow row: Row, + codingPath: [CodingKey]) + throws -> T + where T: Decodable + { if let type = T.self as? FetchableRecord.Type { // Prefer FetchableRecord decoding over Decodable. return type.init(row: row) as! T @@ -234,7 +244,14 @@ private struct RowDecoder: Decoder { } @inline(__always) - private func decode(_ type: T.Type, fromRow row: Row, columnAtIndex index: Int, key: Key) throws -> T where T: Decodable { + private func decode( + _ type: T.Type, + fromRow row: Row, + columnAtIndex index: Int, + key: Key) + throws -> T + where T: Decodable + { do { // This decoding will fail for types that decode from keyed // or unkeyed containers, because we're decoding a single @@ -248,7 +265,10 @@ private struct RowDecoder: Decoder { } catch is JSONRequiredError { // Decode from JSON guard let data = row.dataNoCopy(atIndex: index) else { - fatalConversionError(to: T.self, from: row[index], conversionContext: ValueConversionContext(row).atColumn(index)) + fatalConversionError( + to: T.self, + from: row[index], + conversionContext: ValueConversionContext(row).atColumn(index)) } return try R .databaseJSONDecoder(for: key.stringValue) @@ -272,7 +292,7 @@ private struct PrefetchedRowsDecoder: Decoder { self.currentIndex = 0 } - func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer where Key : CodingKey { + func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer where Key: CodingKey { fatalError("keyed decoding from prefetched rows is not supported") } @@ -298,13 +318,16 @@ extension PrefetchedRowsDecoder: UnkeyedDecodingContainer { return false } - mutating func decode(_ type: T.Type) throws -> T where T : Decodable { + mutating func decode(_ type: T.Type) throws -> T where T: Decodable { defer { currentIndex += 1 } let decoder = RowDecoder(row: rows[currentIndex], codingPath: codingPath) return try T(from: decoder) } - mutating func nestedContainer(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer where NestedKey : CodingKey { + mutating func nestedContainer(keyedBy type: NestedKey.Type) + throws -> KeyedDecodingContainer + where NestedKey: CodingKey + { fatalError("not implemented") } @@ -361,7 +384,7 @@ extension ColumnDecoder: SingleValueDecodingContainer { func decode(_ type: Double.Type) throws -> Double { return row[columnIndex] } func decode(_ type: String.Type) throws -> String { return row[columnIndex] } - func decode(_ type: T.Type) throws -> T where T : Decodable { + func decode(_ type: T.Type) throws -> T where T: Decodable { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows decoding Date from String, or DatabaseValue from NULL. if type == Date.self { @@ -391,9 +414,9 @@ fileprivate var iso8601Formatter: ISO8601DateFormatter = { return formatter }() -private extension DatabaseDateDecodingStrategy { +extension DatabaseDateDecodingStrategy { @inline(__always) - func decodeIfPresent(fromRow row: Row, columnAtIndex index: Int) -> Date? { + fileprivate func decodeIfPresent(fromRow row: Row, columnAtIndex index: Int) -> Date? { if let sqliteStatement = row.sqliteStatement { return decodeIfPresent( sqliteStatement: sqliteStatement, @@ -406,7 +429,7 @@ private extension DatabaseDateDecodingStrategy { } @inline(__always) - func decode(fromRow row: Row, columnAtIndex index: Int) -> Date { + fileprivate func decode(fromRow row: Row, columnAtIndex index: Int) -> Date { if let sqliteStatement = row.sqliteStatement { return decode( sqliteStatement: sqliteStatement, @@ -419,7 +442,7 @@ private extension DatabaseDateDecodingStrategy { } @inline(__always) - func decode(sqliteStatement: SQLiteStatement, index: Int32) -> Date { + fileprivate func decode(sqliteStatement: SQLiteStatement, index: Int32) -> Date { switch self { case .deferredToDate: return Date(sqliteStatement: sqliteStatement, index: index) @@ -458,7 +481,7 @@ private extension DatabaseDateDecodingStrategy { } @inline(__always) - func decodeIfPresent(sqliteStatement: SQLiteStatement, index: Int32) -> Date? { + fileprivate func decodeIfPresent(sqliteStatement: SQLiteStatement, index: Int32) -> Date? { if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL { return nil } @@ -466,7 +489,11 @@ private extension DatabaseDateDecodingStrategy { } @inline(__always) - func decode(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date { + fileprivate func decode( + from dbValue: DatabaseValue, + conversionContext: @autoclosure () -> ValueConversionContext?) + -> Date + { if let date = dateFromDatabaseValue(dbValue) { return date } else { @@ -475,7 +502,11 @@ private extension DatabaseDateDecodingStrategy { } @inline(__always) - func decodeIfPresent(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date? { + fileprivate func decodeIfPresent( + from dbValue: DatabaseValue, + conversionContext: @autoclosure () -> ValueConversionContext?) + -> Date? + { if dbValue.isNull { return nil } else if let date = dateFromDatabaseValue(dbValue) { diff --git a/GRDB/Record/FetchableRecord+TableRecord.swift b/GRDB/Record/FetchableRecord+TableRecord.swift index 937736486..17457deab 100644 --- a/GRDB/Record/FetchableRecord+TableRecord.swift +++ b/GRDB/Record/FetchableRecord+TableRecord.swift @@ -77,7 +77,10 @@ extension FetchableRecord where Self: TableRecord { /// - keys: A sequence of primary keys. /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, keys: Sequence) throws -> RecordCursor where Sequence.Element: DatabaseValueConvertible { + public static func fetchCursor(_ db: Database, keys: Sequence) + throws -> RecordCursor + where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible + { return try filter(keys: keys).fetchCursor(db) } @@ -92,7 +95,9 @@ extension FetchableRecord where Self: TableRecord { /// - keys: A sequence of primary keys. /// - returns: An array of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, keys: Sequence) throws -> [Self] where Sequence.Element: DatabaseValueConvertible { + public static func fetchAll(_ db: Database, keys: Sequence) + throws -> [Self] + where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible { let keys = Array(keys) if keys.isEmpty { // Avoid hitting the database @@ -110,7 +115,10 @@ extension FetchableRecord where Self: TableRecord { /// - key: A primary key value. /// - returns: An optional record. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, key: PrimaryKeyType?) throws -> Self? { + public static func fetchOne(_ db: Database, key: PrimaryKeyType?) + throws -> Self? + where PrimaryKeyType: DatabaseValueConvertible + { guard let key = key else { // Avoid hitting the database return nil @@ -126,7 +134,10 @@ extension FetchableRecord where Self: TableRecord { /// Returns a cursor over records identified by the provided unique keys /// (primary key or any key with a unique index on it). /// - /// let players = try Player.fetchCursor(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // Cursor of Player + /// // Cursor of Player + /// let players = try Player.fetchCursor(db, keys: [ + /// ["email": "a@example.com"], + /// ["email": "b@example.com"]]) /// while let player = try players.next() { // Player /// ... /// } @@ -138,14 +149,19 @@ extension FetchableRecord where Self: TableRecord { /// - keys: An array of key dictionaries. /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> RecordCursor { + public static func fetchCursor(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) + throws -> RecordCursor + { return try filter(keys: keys).fetchCursor(db) } /// Returns an array of records identified by the provided unique keys /// (primary key or any key with a unique index on it). /// - /// let players = try Player.fetchAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // [Player] + /// // [Player] + /// let players = try Player.fetchAll(db, keys: [ + /// ["email": "a@example.com"], + /// ["email": "b@example.com"]]) /// /// The order of records in the returned array is undefined. /// diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index b72a6240d..b0e44598c 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -1,10 +1,10 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// Types that adopt FetchableRecord can be initialized from a database Row. @@ -160,7 +160,12 @@ extension FetchableRecord { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor { + public static func fetchCursor( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> RecordCursor + { return try RecordCursor(statement: statement, arguments: arguments, adapter: adapter) } @@ -175,7 +180,12 @@ extension FetchableRecord { /// - adapter: Optional RowAdapter /// - returns: An array of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { + public static func fetchAll( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Self] + { return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } @@ -190,7 +200,12 @@ extension FetchableRecord { /// - adapter: Optional RowAdapter /// - returns: An optional record. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { + public static func fetchOne( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> Self? + { return try fetchCursor(statement, arguments: arguments, adapter: adapter).next() } } @@ -218,7 +233,13 @@ extension FetchableRecord { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RecordCursor { + public static func fetchCursor( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> RecordCursor + { return try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -233,7 +254,13 @@ extension FetchableRecord { /// - adapter: Optional RowAdapter /// - returns: An array of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self] { + public static func fetchAll( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> [Self] + { return try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -248,7 +275,13 @@ extension FetchableRecord { /// - adapter: Optional RowAdapter /// - returns: An optional record. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self? { + public static func fetchOne( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> Self? + { return try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } } @@ -319,7 +352,7 @@ extension FetchableRecord { return nil } try supplementaryFetch([row]) - return Self.init(row: row) + return .init(row: row) } else { return try fetchOne(request.statement, adapter: request.adapter) } @@ -385,7 +418,7 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// try dbQueue.read { db in /// let players: RecordCursor = try Player.fetchCursor(db, sql: "SELECT * FROM player") /// } -public final class RecordCursor : Cursor { +public final class RecordCursor: Cursor { @usableFromInline let _statement: SelectStatement @usableFromInline let _row: Row // Reused for performance @usableFromInline let _sqliteStatement: SQLiteStatement diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index 645783cb4..46c07301f 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -1,7 +1,7 @@ import Foundation #if os(iOS) - import UIKit +import UIKit #endif /// You use FetchedRecordsController to track changes in the results of an @@ -85,7 +85,7 @@ public final class FetchedRecordsController { if let isSameRecord = isSameRecord { itemsAreIdenticalFactory = { _ in { isSameRecord($0.record, $1.record) } } } else { - itemsAreIdenticalFactory = { _ in { _,_ in false } } + itemsAreIdenticalFactory = { _ in { _, _ in false } } } try self.init( @@ -112,7 +112,7 @@ public final class FetchedRecordsController { self.databaseWriter = databaseWriter self.queue = queue } - + /// Executes the controller's fetch request. /// /// After executing this method, you can access the the fetched objects with @@ -162,7 +162,10 @@ public final class FetchedRecordsController { /// /// This method must be used from the controller's dispatch queue (the /// main queue unless stated otherwise in the controller's initializer). - public func setRequest(_ request: Request) throws where Request: FetchRequest, Request.RowDecoder == Record { + public func setRequest(_ request: Request) + throws + where Request: FetchRequest, Request.RowDecoder == Record + { self.request = ItemRequest(request) (self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in let region = try request.databaseRegion(db) @@ -196,7 +199,12 @@ public final class FetchedRecordsController { /// /// This method must be used from the controller's dispatch queue (the /// main queue unless stated otherwise in the controller's initializer). - public func setRequest(sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws { + public func setRequest( + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws + { try setRequest(SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -211,19 +219,27 @@ public final class FetchedRecordsController { /// removed, moved, or updated. /// - didChange: Invoked after records have been updated. public func trackChanges( - willChange: ((FetchedRecordsController) -> ())? = nil, - onChange: ((FetchedRecordsController, Record, FetchedRecordChange) -> ())? = nil, - didChange: ((FetchedRecordsController) -> ())? = nil) + willChange: ((FetchedRecordsController) -> Void)? = nil, + onChange: ((FetchedRecordsController, Record, FetchedRecordChange) -> Void)? = nil, + didChange: ((FetchedRecordsController) -> Void)? = nil) { - // I hate you SE-0110. - let wrappedWillChange: ((FetchedRecordsController, Void) -> ())? + // Without SE-0110, we could simply: + // + // trackChanges( + // fetchAlongside: { _ in }, + // willChange: willChange.map { callback in { (controller, _) in callback(controller) } }, + // onChange: onChange, + // didChange: didChange.map { callback in { (controller, _) in callback(controller) } }) + // + // But instead: + let wrappedWillChange: ((FetchedRecordsController, Void) -> Void)? if let willChange = willChange { wrappedWillChange = { (controller, _) in willChange(controller) } } else { wrappedWillChange = nil } - let wrappedDidChange: ((FetchedRecordsController, Void) -> ())? + let wrappedDidChange: ((FetchedRecordsController, Void) -> Void)? if let didChange = didChange { wrappedDidChange = { (controller, _) in didChange(controller) } } else { @@ -235,15 +251,8 @@ public final class FetchedRecordsController { willChange: wrappedWillChange, onChange: onChange, didChange: wrappedDidChange) - - // Without bloody SE-0110: -// trackChanges( -// fetchAlongside: { _ in }, -// willChange: willChange.map { callback in { (controller, _) in callback(controller) } }, -// onChange: onChange, -// didChange: didChange.map { callback in { (controller, _) in callback(controller) } }) } - + /// Registers changes notification callbacks. /// /// This method must be used from the controller's dispatch queue (the @@ -262,9 +271,9 @@ public final class FetchedRecordsController { /// - didChange: Invoked after records have been updated. public func trackChanges( fetchAlongside: @escaping (Database) throws -> T, - willChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> ())? = nil, - onChange: ((FetchedRecordsController, Record, FetchedRecordChange) -> ())? = nil, - didChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> ())? = nil) + willChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> Void)? = nil, + onChange: ((FetchedRecordsController, Record, FetchedRecordChange) -> Void)? = nil, + didChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> Void)? = nil) { // If some changes are currently processed, make sure they are // discarded because they would trigger previously set callbacks. @@ -276,20 +285,20 @@ public final class FetchedRecordsController { return } - var willProcessTransaction: () -> () = { } - var didProcessTransaction: () -> () = { } + var willProcessTransaction: () -> Void = { } + var didProcessTransaction: () -> Void = { } #if os(iOS) - if let application = application { - var backgroundTaskID: UIBackgroundTaskIdentifier! = nil - willProcessTransaction = { - backgroundTaskID = application.beginBackgroundTask { - application.endBackgroundTask(backgroundTaskID) - } - } - didProcessTransaction = { + if let application = application { + var backgroundTaskID: UIBackgroundTaskIdentifier! = nil + willProcessTransaction = { + backgroundTaskID = application.beginBackgroundTask { application.endBackgroundTask(backgroundTaskID) } } + didProcessTransaction = { + application.endBackgroundTask(backgroundTaskID) + } + } #endif let initialItems = fetchedItems @@ -312,7 +321,7 @@ public final class FetchedRecordsController { } } } - + /// Registers an error callback. /// /// Whenever the controller could not look for changes after a transaction @@ -325,7 +334,7 @@ public final class FetchedRecordsController { /// /// This method must be used from the controller's dispatch queue (the /// main queue unless stated otherwise in the controller's initializer). - public func trackErrors(_ errorHandler: @escaping (FetchedRecordsController, Error) -> ()) { + public func trackErrors(_ errorHandler: @escaping (FetchedRecordsController, Error) -> Void) { self.errorHandler = errorHandler } @@ -369,7 +378,7 @@ public final class FetchedRecordsController { /// Support for allowBackgroundChangeTracking(in:) var application: UIApplication? #endif - + /// The items fileprivate var fetchedItems: [Item]? @@ -378,19 +387,19 @@ public final class FetchedRecordsController { /// The record comparator factory (support for request change) private let itemsAreIdenticalFactory: ItemComparatorFactory - + /// The request fileprivate typealias ItemRequest = AnyFetchRequest> fileprivate var request: ItemRequest /// The observed database region - private var region : DatabaseRegion + private var region: DatabaseRegion /// The eventual current database observer private var observer: FetchedRecordsObserver? /// The eventual error handler - fileprivate var errorHandler: ((FetchedRecordsController, Error) -> ())? + fileprivate var errorHandler: ((FetchedRecordsController, Error) -> Void)? } extension FetchedRecordsController where Record: TableRecord { @@ -510,15 +519,15 @@ extension FetchedRecordsController where Record: TableRecord { /// FetchedRecordsController adopts TransactionObserverType so that it can /// monitor changes to its fetched records. -private final class FetchedRecordsObserver : TransactionObserver { +private final class FetchedRecordsObserver: TransactionObserver { var isValid: Bool var needsComputeChanges: Bool var items: [Item]! // ought to be not nil when observer has started tracking transactions let queue: DispatchQueue // protects items let region: DatabaseRegion - var fetchAndNotifyChanges: (FetchedRecordsObserver) -> () + var fetchAndNotifyChanges: (FetchedRecordsObserver) -> Void - init(region: DatabaseRegion, fetchAndNotifyChanges: @escaping (FetchedRecordsObserver) -> ()) { + init(region: DatabaseRegion, fetchAndNotifyChanges: @escaping (FetchedRecordsObserver) -> Void) { self.isValid = true self.items = nil self.needsComputeChanges = false @@ -565,12 +574,18 @@ private final class FetchedRecordsObserver : Transactio // MARK: - Changes +private typealias FetchCompletionHandler = ( + DatabaseResult<(fetchedItems: [Item], + fetchedAlongside: T, + observer: FetchedRecordsObserver)>) + -> Void + private func makeFetchFunction( controller: FetchedRecordsController, fetchAlongside: @escaping (Database) throws -> T, - willProcessTransaction: @escaping () -> (), - completion: @escaping (DatabaseResult<(fetchedItems: [Item], fetchedAlongside: T, observer: FetchedRecordsObserver)>) -> () - ) -> (FetchedRecordsObserver) -> () + willProcessTransaction: @escaping () -> Void, + completion: @escaping FetchCompletionHandler + ) -> (FetchedRecordsObserver) -> Void { // Make sure we keep a weak reference to the fetched records controller, // so that the user can use unowned references in callbacks: @@ -623,12 +638,12 @@ private func makeFetchAndNotifyChangesFunction( controller: FetchedRecordsController, fetchAlongside: @escaping (Database) throws -> T, itemsAreIdentical: @escaping ItemComparator, - willProcessTransaction: @escaping () -> (), - willChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> ())?, - onChange: ((FetchedRecordsController, Record, FetchedRecordChange) -> ())?, - didChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> ())?, - didProcessTransaction: @escaping () -> () - ) -> (FetchedRecordsObserver) -> () + willProcessTransaction: @escaping () -> Void, + willChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> Void)?, + onChange: ((FetchedRecordsController, Record, FetchedRecordChange) -> Void)?, + didChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> Void)?, + didProcessTransaction: @escaping () -> Void + ) -> (FetchedRecordsObserver) -> Void { // Make sure we keep a weak reference to the fetched records controller, // so that the user can use unowned references in callbacks: @@ -637,12 +652,16 @@ private func makeFetchAndNotifyChangesFunction( // // Should controller become strong at any point before callbacks are // called, such unowned reference would have an opportunity to crash. - return makeFetchFunction(controller: controller, fetchAlongside: fetchAlongside, willProcessTransaction: willProcessTransaction) { [weak controller] result in + return makeFetchFunction( + controller: controller, + fetchAlongside: fetchAlongside, + willProcessTransaction: willProcessTransaction) + { [weak controller] result in // Return if fetched records controller has been deallocated guard let callbackQueue = controller?.queue else { return } switch result { - case .failure(let error): + case let .failure(error): callbackQueue.async { // Now we can retain controller guard let strongController = controller else { return } @@ -650,7 +669,7 @@ private func makeFetchAndNotifyChangesFunction( didProcessTransaction() } - case .success((fetchedItems: let fetchedItems, fetchedAlongside: let fetchedAlongside, observer: let observer)): + case let .success((fetchedItems: fetchedItems, fetchedAlongside: fetchedAlongside, observer: observer)): // Return if there is no change let changes: [ItemChange] if onChange != nil { @@ -689,7 +708,12 @@ private func makeFetchAndNotifyChangesFunction( } } -private func computeChanges(from s: [Item], to t: [Item], itemsAreIdentical: ItemComparator) -> [ItemChange] { +private func computeChanges( + from s: [Item], + to t: [Item], + itemsAreIdentical: ItemComparator) + -> [ItemChange] +{ let m = s.count let n = t.count @@ -754,8 +778,12 @@ private func computeChanges(from s: [Item], to t: [Item] /// If *change* is a deletion or an insertion, and there is a matching inverse /// insertion/deletion with the same value in *changes*, a corresponding .move or .update is returned. /// As a convenience, the index of the matched change is returned as well. - func merge(change: ItemChange, in changes: [ItemChange], itemsAreIdentical: ItemComparator) -> (mergedChange: ItemChange, mergedIndex: Int)? { - + func merge( + change: ItemChange, + in changes: [ItemChange], + itemsAreIdentical: ItemComparator) + -> (mergedChange: ItemChange, mergedIndex: Int)? + { /// Returns the changes between two rows: a dictionary [key: oldValue] /// Precondition: both rows have the same columns func changedValues(from oldRow: Row, to newRow: Row) -> [String: DatabaseValue] { @@ -770,30 +798,52 @@ private func computeChanges(from s: [Item], to t: [Item] } switch change { - case .insertion(let newItem, let newIndexPath): + case let .insertion(newItem, newIndexPath): // Look for a matching deletion for (index, otherChange) in changes.enumerated() { - guard case .deletion(let oldItem, let oldIndexPath) = otherChange else { continue } + guard case let .deletion(oldItem, oldIndexPath) = otherChange else { continue } guard itemsAreIdentical(oldItem, newItem) else { continue } let rowChanges = changedValues(from: oldItem.row, to: newItem.row) if oldIndexPath == newIndexPath { - return (ItemChange.update(item: newItem, indexPath: oldIndexPath, changes: rowChanges), index) + return ( + ItemChange.update( + item: newItem, + indexPath: oldIndexPath, + changes: rowChanges), + index) } else { - return (ItemChange.move(item: newItem, indexPath: oldIndexPath, newIndexPath: newIndexPath, changes: rowChanges), index) + return ( + ItemChange.move( + item: newItem, + indexPath: oldIndexPath, + newIndexPath: newIndexPath, + changes: rowChanges), + index) } } return nil - case .deletion(let oldItem, let oldIndexPath): + case let .deletion(oldItem, oldIndexPath): // Look for a matching insertion for (index, otherChange) in changes.enumerated() { - guard case .insertion(let newItem, let newIndexPath) = otherChange else { continue } + guard case let .insertion(newItem, newIndexPath) = otherChange else { continue } guard itemsAreIdentical(oldItem, newItem) else { continue } let rowChanges = changedValues(from: oldItem.row, to: newItem.row) if oldIndexPath == newIndexPath { - return (ItemChange.update(item: newItem, indexPath: oldIndexPath, changes: rowChanges), index) + return ( + ItemChange.update( + item: newItem, + indexPath: oldIndexPath, + changes: rowChanges), + index) } else { - return (ItemChange.move(item: newItem, indexPath: oldIndexPath, newIndexPath: newIndexPath, changes: rowChanges), index) + return ( + ItemChange.move( + item: newItem, + indexPath: oldIndexPath, + newIndexPath: newIndexPath, + changes: rowChanges), + index) } } return nil @@ -807,7 +857,9 @@ private func computeChanges(from s: [Item], to t: [Item] var mergedChanges: [ItemChange] = [] var updateChanges: [ItemChange] = [] for change in changes { - if let (mergedChange, mergedIndex) = merge(change: change, in: mergedChanges, itemsAreIdentical: itemsAreIdentical) { + if let (mergedChange, mergedIndex) + = merge(change: change, in: mergedChanges, itemsAreIdentical: itemsAreIdentical) + { mergedChanges.remove(at: mergedIndex) switch mergedChange { case .update: @@ -829,10 +881,8 @@ private func identicalItemArrays(_ lhs: [Item], _ rhs: [Item IndexPath? { let item = Item(row: Row(record)) - guard let fetchedItems = fetchedItems, let index = fetchedItems.firstIndex(where: { itemsAreIdentical($0, item) }) else { - return nil + guard + let fetchedItems = fetchedItems, + let index = fetchedItems.firstIndex(where: { itemsAreIdentical($0, item) }) + else { + return nil } return IndexPath(indexes: [0, index]) } @@ -917,13 +970,13 @@ extension ItemChange { var fetchedRecordChange: FetchedRecordChange { switch self { - case .insertion(item: _, indexPath: let indexPath): + case let .insertion(item: _, indexPath: indexPath): return .insertion(indexPath: indexPath) - case .deletion(item: _, indexPath: let indexPath): + case let .deletion(item: _, indexPath: indexPath): return .deletion(indexPath: indexPath) - case .move(item: _, indexPath: let indexPath, newIndexPath: let newIndexPath, changes: let changes): + case let .move(item: _, indexPath: indexPath, newIndexPath: newIndexPath, changes: changes): return .move(indexPath: indexPath, newIndexPath: newIndexPath, changes: changes) - case .update(item: _, indexPath: let indexPath, changes: let changes): + case let .update(item: _, indexPath: indexPath, changes: changes): return .update(indexPath: indexPath, changes: changes) } } @@ -932,16 +985,16 @@ extension ItemChange { extension ItemChange: CustomStringConvertible { var description: String { switch self { - case .insertion(let item, let indexPath): + case let .insertion(item, indexPath): return "Insert \(item) at \(indexPath)" - case .deletion(let item, let indexPath): + case let .deletion(item, indexPath): return "Delete \(item) from \(indexPath)" - case .move(let item, let indexPath, let newIndexPath, changes: let changes): + case let .move(item, indexPath, newIndexPath, changes: changes): return "Move \(item) from \(indexPath) to \(newIndexPath) with changes: \(changes)" - case .update(let item, let indexPath, let changes): + case let .update(item, indexPath, changes): return "Update \(item) at \(indexPath) with changes: \(changes)" } } @@ -973,16 +1026,16 @@ public enum FetchedRecordChange { extension FetchedRecordChange: CustomStringConvertible { public var description: String { switch self { - case .insertion(let indexPath): + case let .insertion(indexPath): return "Insertion at \(indexPath)" - case .deletion(let indexPath): + case let .deletion(indexPath): return "Deletion from \(indexPath)" - case .move(let indexPath, let newIndexPath, changes: let changes): + case let .move(indexPath, newIndexPath, changes: changes): return "Move from \(indexPath) to \(newIndexPath) with changes: \(changes)" - case .update(let indexPath, let changes): + case let .update(indexPath, changes): return "Update at \(indexPath) with changes: \(changes)" } } @@ -1014,11 +1067,11 @@ public struct FetchedRecordsSectionInfo { // MARK: - Item -private final class Item : FetchableRecord, Equatable { +private final class Item: FetchableRecord, Equatable { let row: Row // Records are lazily loaded - lazy var record: T = T(row: self.row) + lazy var record = T(row: self.row) init(row: Row) { self.row = row.copy() diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index 1fb4772ea..e8dd673cd 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -1,6 +1,5 @@ extension Database.ConflictResolution { - @usableFromInline - var invalidatesLastInsertedRowID: Bool { + @usableFromInline var invalidatesLastInsertedRowID: Bool { switch self { case .abort, .fail, .rollback, .replace: return false @@ -55,7 +54,7 @@ public struct PersistenceConflictPolicy { } /// Types that adopt MutablePersistableRecord can be inserted, updated, and deleted. -public protocol MutablePersistableRecord : EncodableRecord, TableRecord { +public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// The policy that handles SQLite conflicts when records are inserted /// or updated. /// @@ -219,7 +218,10 @@ extension MutablePersistableRecord { /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database. - public func update(_ db: Database, columns: Sequence) throws where Sequence.Element: ColumnExpression { + public func update(_ db: Database, columns: Sequence) + throws + where Sequence: Swift.Sequence, Sequence.Element: ColumnExpression + { try update(db, columns: Set(columns.map { $0.name })) } @@ -230,7 +232,10 @@ extension MutablePersistableRecord { /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database. - public func update(_ db: Database, columns: Sequence) throws where Sequence.Element == String { + public func update(_ db: Database, columns: Sequence) + throws + where Sequence: Swift.Sequence, Sequence.Element == String + { try update(db, columns: Set(columns)) } @@ -303,7 +308,7 @@ extension MutablePersistableRecord { try change(&self) return try updateChanges(db, from: container) } - + /// Executes an INSERT or an UPDATE statement so that `self` is saved in /// the database. /// @@ -392,9 +397,13 @@ extension MutablePersistableRecord { @inlinable public func performUpdate(_ db: Database, columns: Set) throws { let dao = try DAO(db, self) - guard let statement = try dao.updateStatement(columns: columns, onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) else { - // Nil primary key - throw dao.makeRecordNotFoundError() + guard + let statement = try dao.updateStatement( + columns: columns, + onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) + else { + // Nil primary key + throw dao.makeRecordNotFoundError() } try statement.execute() if db.changesCount == 0 { @@ -463,7 +472,7 @@ extension MutablePersistableRecord { extension MutablePersistableRecord where Self: AnyObject { // MARK: - Record Comparison - + /// Mutates the record according to the provided closure, and then, if the /// record has any difference from its previous version, executes an /// UPDATE statement so that those differences and only those difference are @@ -534,7 +543,10 @@ extension MutablePersistableRecord { /// - keys: A sequence of primary keys. /// - returns: The number of deleted rows @discardableResult - public static func deleteAll(_ db: Database, keys: Sequence) throws -> Int where Sequence.Element: DatabaseValueConvertible { + public static func deleteAll(_ db: Database, keys: Sequence) + throws -> Int + where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible + { let keys = Array(keys) if keys.isEmpty { // Avoid hitting the database @@ -563,7 +575,10 @@ extension MutablePersistableRecord { /// - key: A primary key value. /// - returns: Whether a database row was deleted. @discardableResult - public static func deleteOne(_ db: Database, key: PrimaryKeyType?) throws -> Bool { + public static func deleteOne(_ db: Database, key: PrimaryKeyType?) + throws -> Bool + where PrimaryKeyType: DatabaseValueConvertible + { guard let key = key else { // Avoid hitting the database return false @@ -617,7 +632,7 @@ extension MutablePersistableRecord { /// /// Unlike MutablePersistableRecord, the insert() and save() methods are not /// mutating methods. -public protocol PersistableRecord : MutablePersistableRecord { +public protocol PersistableRecord: MutablePersistableRecord { /// Notifies the record that it was succesfully inserted. /// @@ -749,7 +764,7 @@ extension PersistableRecord { extension PersistenceContainer { /// Convenience initializer from a database connection and a record - init(_ db: Database,_ record: Record) throws { + init(_ db: Database, _ record: Record) throws { let databaseTableName = type(of: record).databaseTableName let columnCount = try db.columns(in: databaseTableName).count self.init(minimumCapacity: columnCount) @@ -916,9 +931,16 @@ extension InsertQuery { let sql: String switch onConflict { case .abort: - sql = "INSERT INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) VALUES (\(valuesSQL))" + sql = """ + INSERT INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) \ + VALUES (\(valuesSQL)) + """ default: - sql = "INSERT OR \(onConflict.rawValue) INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) VALUES (\(valuesSQL))" + sql = """ + INSERT OR \(onConflict.rawValue) \ + INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) \ + VALUES (\(valuesSQL)) + """ } InsertQuery.sqlCache.write { $0[self] = sql } return sql @@ -946,9 +968,17 @@ extension UpdateQuery { let sql: String switch onConflict { case .abort: - sql = "UPDATE \(tableName.quotedDatabaseIdentifier) SET \(updateSQL) WHERE \(whereSQL)" + sql = """ + UPDATE \(tableName.quotedDatabaseIdentifier) \ + SET \(updateSQL) \ + WHERE \(whereSQL) + """ default: - sql = "UPDATE OR \(onConflict.rawValue) \(tableName.quotedDatabaseIdentifier) SET \(updateSQL) WHERE \(whereSQL)" + sql = """ + UPDATE OR \(onConflict.rawValue) \(tableName.quotedDatabaseIdentifier) \ + SET \(updateSQL) \ + WHERE \(whereSQL) + """ } UpdateQuery.sqlCache.write { $0[self] = sql } return sql diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 4b220218e..2ee2b8a0b 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -2,7 +2,7 @@ /// Record is a class that wraps a table row, or the result of any query. It is /// designed to be subclassed. -open class Record : FetchableRecord, TableRecord, PersistableRecord { +open class Record: FetchableRecord, TableRecord, PersistableRecord { // MARK: - Initializers @@ -11,7 +11,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { } /// Creates a Record from a row. - required public init(row: Row) { + public required init(row: Row) { if row.isFetched { // Take care of the hasDatabaseChanges flag. // @@ -93,7 +93,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { return [AllColumns()] } - + /// Defines the values persisted in the database. /// /// Store in the *container* argument all values that should be stored in @@ -216,7 +216,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { /// Reference row for the *hasDatabaseChanges* property. var referenceRow: Row? - + // MARK: - CRUD /// Executes an INSERT statement. @@ -274,9 +274,13 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { // // But this would trigger two calls to `encode(to:)`. let dao = try DAO(db, self) - guard let statement = try dao.updateStatement(columns: columns, onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) else { - // Nil primary key - throw dao.makeRecordNotFoundError() + guard + let statement = try dao.updateStatement( + columns: columns, + onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) + else { + // Nil primary key + throw dao.makeRecordNotFoundError() } try statement.execute() if db.changesCount == 0 { @@ -302,7 +306,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database and record could not be updated. @discardableResult - final public func updateChanges(_ db: Database) throws -> Bool { + public final func updateChanges(_ db: Database) throws -> Bool { let changedColumns = Set(databaseChanges.keys) if changedColumns.isEmpty { return false @@ -331,7 +335,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { /// - parameter db: A database connection. /// - throws: A DatabaseError whenever an SQLite error occurs, or errors /// thrown by update(). - final public func save(_ db: Database) throws { + public final func save(_ db: Database) throws { try performSave(db) } diff --git a/GRDB/Utils/Inflections+English.swift b/GRDB/Utils/Inflections+English.swift index c9f527035..1d570786d 100644 --- a/GRDB/Utils/Inflections+English.swift +++ b/GRDB/Utils/Inflections+English.swift @@ -51,6 +51,7 @@ extension Inflections { // become more complete. This is a safety measure to keep existing // applications from breaking. // + // swiftlint:disable:next line_length // https://github.com/rails/rails/blob/b2eb1d1c55a59fee1e6c4cba7030d8ceb524267c/activesupport/lib/active_support/inflections.rb var inflections = Inflections() diff --git a/GRDB/Utils/Inflections.swift b/GRDB/Utils/Inflections.swift index f8dbabf33..da6c5b176 100644 --- a/GRDB/Utils/Inflections.swift +++ b/GRDB/Utils/Inflections.swift @@ -59,7 +59,11 @@ public struct Inflections { /// - options: Regular expression options (defaults to /// `[.caseInsensitive]`). /// - template: A replacement template string. - public mutating func plural(_ pattern: String, options: NSRegularExpression.Options = [.caseInsensitive], _ template: String) { + public mutating func plural( + _ pattern: String, + options: NSRegularExpression.Options = [.caseInsensitive], + _ template: String) + { let reg = try! NSRegularExpression(pattern: pattern, options: options) pluralizeRules.append((reg, template)) } @@ -75,7 +79,11 @@ public struct Inflections { /// - options: Regular expression options (defaults to /// `[.caseInsensitive]`). /// - template: A replacement template string. - public mutating func singular(_ pattern: String, options: NSRegularExpression.Options = [.caseInsensitive], _ template: String) { + public mutating func singular( + _ pattern: String, + options: NSRegularExpression.Options = [.caseInsensitive], + _ template: String) + { let reg = try! NSRegularExpression(pattern: pattern, options: options) singularizeRules.append((reg, template)) } @@ -155,7 +163,9 @@ public struct Inflections { /// inflections.pluralize("bar") // "bars" private mutating func uncountableWord(_ word: String) { let escWord = NSRegularExpression.escapedPattern(for: word) - uncountablesRegularExpressions[word] = try! NSRegularExpression(pattern: "\\b\(escWord)\\Z", options: [.caseInsensitive]) + uncountablesRegularExpressions[word] = try! NSRegularExpression( + pattern: "\\b\(escWord)\\Z", + options: [.caseInsensitive]) } private func isUncountable(_ string: String) -> Bool { @@ -181,7 +191,7 @@ public struct Inflections { \(string.suffix(from: endIndexOfDigitlessRadical)) """ } - + private func inflectWord(_ string: String, with rules: [(NSRegularExpression, String)]) -> String { if string.isEmpty { return string @@ -189,8 +199,8 @@ public struct Inflections { let range = NSRange(string.startIndex.. 0 { + let matchCount = reg.replaceMatches(in: result, options: [], range: range, withTemplate: template) + if matchCount > 0 { return String(result) } } @@ -203,7 +213,7 @@ public struct Inflections { /// startIndexOfLastWord("fooBar") -> "Bar" static func startIndexOfLastWord(_ string: String) -> String.Index { let range = NSRange(string.startIndex.. { keys.reserveCapacity(minimumCapacity) dictionary = Dictionary(minimumCapacity: minimumCapacity) } - + /// Returns the value associated with key, or nil. @usableFromInline subscript(_ key: Key) -> Value? { @@ -42,14 +42,14 @@ struct OrderedDictionary { } } } - + /// Returns the value associated with key, or the default value. @inlinable subscript(_ key: Key, default defaultValue: Value) -> Value { get { return dictionary[key] ?? defaultValue } set { self[key] = newValue } } - + /// Appends the given value for the given key. /// /// - precondition: There is no value associated with key yet. @@ -111,7 +111,8 @@ struct OrderedDictionary { } extension OrderedDictionary: Collection { - @usableFromInline typealias Index = Int + @usableFromInline + typealias Index = Int @usableFromInline var startIndex: Int { return 0 @@ -121,18 +122,21 @@ extension OrderedDictionary: Collection { return keys.count } - @usableFromInline func index(after i: Int) -> Int { + @usableFromInline + func index(after i: Int) -> Int { return i + 1 } - @usableFromInline subscript(position: Int) -> (key: Key, value: Value) { + @usableFromInline + subscript(position: Int) -> (key: Key, value: Value) { let key = keys[position] return (key: key, value: dictionary[key]!) } } extension OrderedDictionary: ExpressibleByDictionaryLiteral { - @usableFromInline init(dictionaryLiteral elements: (Key, Value)...) { + @usableFromInline + init(dictionaryLiteral elements: (Key, Value)...) { self.keys = elements.map { $0.0 } self.dictionary = Dictionary(uniqueKeysWithValues: elements) } diff --git a/GRDB/Utils/Pool.swift b/GRDB/Utils/Pool.swift index 444d9262d..8c9c49657 100644 --- a/GRDB/Utils/Pool.swift +++ b/GRDB/Utils/Pool.swift @@ -58,7 +58,7 @@ final class Pool { /// Returns a tuple (element, release) /// Client MUST call release() after the element has been used. - func get() throws -> (T, () -> ()) { + func get() throws -> (T, () -> Void) { _ = semaphore.wait(timeout: .distantFuture) do { let item = try items.write { items -> Item in @@ -97,7 +97,7 @@ final class Pool { /// Performs a block on each pool element, available or not. /// The block is run is some arbitrary dispatch queue. - func forEach(_ body: (T) throws -> ()) rethrows { + func forEach(_ body: (T) throws -> Void) rethrows { try items.read { items in for item in items { try body(item.element) @@ -112,7 +112,7 @@ final class Pool { /// Empty the pool. Currently used items won't be reused. /// Eventual block is executed before any other element is dequeued. - func clear(andThen block: () throws -> ()) rethrows { + func clear(andThen block: () throws -> Void) rethrows { try items.write { items in items.removeAll() try block() diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index ae666ec52..a29d65202 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -7,8 +7,7 @@ extension String { /// SQL query. /// /// db.execute(sql: "SELECT * FROM \(tableName.quotedDatabaseIdentifier)") - @inlinable - public var quotedDatabaseIdentifier: String { + @inlinable public var quotedDatabaseIdentifier: String { // See https://www.sqlite.org/lang_keywords.html return "\"\(self)\"" } @@ -38,7 +37,7 @@ public protocol _OptionalProtocol { /// This conformance is an implementation detail of GRDB. Don't rely on it. /// /// :nodoc: -extension Optional : _OptionalProtocol { +extension Optional: _OptionalProtocol { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public typealias _Wrapped = Wrapped @@ -49,7 +48,12 @@ extension Optional : _OptionalProtocol { /// Reserved for GRDB: do not use. @inlinable -func GRDBPrecondition(_ condition: @autoclosure() -> Bool, _ message: @autoclosure() -> String = "", file: StaticString = #file, line: UInt = #line) { +func GRDBPrecondition( + _ condition: @autoclosure() -> Bool, + _ message: @autoclosure() -> String = "", + file: StaticString = #file, + line: UInt = #line) +{ /// Custom precondition function which aims at solving /// https://bugs.swift.org/browse/SR-905 and /// https://github.com/groue/GRDB.swift/issues/37 @@ -87,7 +91,7 @@ extension DispatchQueue { DispatchQueue.main.setSpecific(key: key, value: ()) return key }() - + static var isMain: Bool { return DispatchQueue.getSpecific(key: mainKey) != nil } diff --git a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift index 78c0e0266..298832ba5 100644 --- a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift +++ b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift @@ -125,9 +125,9 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: } extension ValueObservation where Reducer == Void { - + // MARK: - DatabaseValueConvertible Observation - + /// Creates a ValueObservation which observes *request*, and notifies /// fresh values whenever the request is modified by a /// database transaction. @@ -335,12 +335,15 @@ extension ValueReducers { /// :nodoc: @available(*, deprecated, renamed: "ValueReducers.AllValues") -public typealias DatabaseValuesReducer = ValueReducers.AllValues where RowDecoder: DatabaseValueConvertible +public typealias DatabaseValuesReducer = ValueReducers.AllValues + where RowDecoder: DatabaseValueConvertible /// :nodoc: @available(*, deprecated, renamed: "ValueReducers.OneValue") -public typealias DatabaseValueReducer = ValueReducers.OneValue where RowDecoder: DatabaseValueConvertible +public typealias DatabaseValueReducer = ValueReducers.OneValue + where RowDecoder: DatabaseValueConvertible /// :nodoc: @available(*, deprecated, renamed: "ValueReducers.AllOptionalValues") -public typealias OptionalDatabaseValuesReducer = ValueReducers.AllOptionalValues where RowDecoder: DatabaseValueConvertible +public typealias OptionalDatabaseValuesReducer = ValueReducers.AllOptionalValues + where RowDecoder: DatabaseValueConvertible diff --git a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift index b588a62d0..f54b4cae5 100644 --- a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift +++ b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift @@ -250,8 +250,12 @@ extension ValueReducers { /// :nodoc: @available(*, deprecated, renamed: "ValueReducers.AllRecords") -public typealias FetchableRecordsReducer = ValueReducers.AllRecords where RowDecoder: FetchableRecord +public typealias FetchableRecordsReducer + = ValueReducers.AllRecords + where RowDecoder: FetchableRecord /// :nodoc: @available(*, deprecated, renamed: "ValueReducers.OneRecord") -public typealias FetchableRecordReducer = ValueReducers.OneRecord where RowDecoder: FetchableRecord +public typealias FetchableRecordReducer + = ValueReducers.OneRecord + where RowDecoder: FetchableRecord diff --git a/GRDB/ValueObservation/ValueObservation+Row.swift b/GRDB/ValueObservation/ValueObservation+Row.swift index fa0f1ae77..43f748231 100644 --- a/GRDB/ValueObservation/ValueObservation+Row.swift +++ b/GRDB/ValueObservation/ValueObservation+Row.swift @@ -60,7 +60,7 @@ extension FetchRequest where RowDecoder == Row { } extension ValueObservation where Reducer == Void { - + // MARK: - Row Observation /// Creates a ValueObservation which observes *request*, and notifies diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 8a152f1c2..c82e6e30d 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -208,7 +208,7 @@ extension ValueObservation where Reducer: ValueReducer { { return reader.add(observation: self, onError: onError, onChange: onChange) } - + // MARK: - Fetching Values /// Returns the observed value. diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift index 99754cb22..27eab3e17 100644 --- a/GRDB/ValueObservation/ValueObserver.swift +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -8,9 +8,9 @@ class ValueObserver: TransactionObserver { var region: DatabaseRegion! var reducer: Reducer! var notificationQueue: DispatchQueue? - + private var requiresWriteAccess: Bool - unowned private var writer: DatabaseWriter + private unowned var writer: DatabaseWriter private let reduceQueue: DispatchQueue private let onError: (Error) -> Void private let onChange: (Reducer.Value) -> Void diff --git a/GRDB/ValueObservation/ValueReducer/Combine.swift b/GRDB/ValueObservation/ValueReducer/Combine.swift index 178cc06fb..d79736075 100644 --- a/GRDB/ValueObservation/ValueReducer/Combine.swift +++ b/GRDB/ValueObservation/ValueReducer/Combine.swift @@ -23,7 +23,7 @@ extension ValueReducers { r2.fetch(db)) } - mutating public func value(_ fetched: Fetched) -> Value? { + public mutating func value(_ fetched: Fetched) -> Value? { let v1 = r1.value(fetched.0) let v2 = r2.value(fetched.1) defer { @@ -102,7 +102,7 @@ extension ValueReducers { r3.fetch(db)) } - mutating public func value(_ fetched: Fetched) -> Value? { + public mutating func value(_ fetched: Fetched) -> Value? { let v1 = r1.value(fetched.0) let v2 = r2.value(fetched.1) let v3 = r3.value(fetched.2) @@ -200,7 +200,7 @@ extension ValueReducers { r4.fetch(db)) } - mutating public func value(_ fetched: Fetched) -> Value? { + public mutating func value(_ fetched: Fetched) -> Value? { let v1 = r1.value(fetched.0) let v2 = r2.value(fetched.1) let v3 = r3.value(fetched.2) @@ -313,7 +313,7 @@ extension ValueReducers { r5.fetch(db)) } - mutating public func value(_ fetched: Fetched) -> Value? { + public mutating func value(_ fetched: Fetched) -> Value? { let v1 = r1.value(fetched.0) let v2 = r2.value(fetched.1) let v3 = r3.value(fetched.2) @@ -441,7 +441,7 @@ extension ValueReducers { r6.fetch(db)) } - mutating public func value(_ fetched: Fetched) -> Value? { + public mutating func value(_ fetched: Fetched) -> Value? { let v1 = r1.value(fetched.0) let v2 = r2.value(fetched.1) let v3 = r3.value(fetched.2) @@ -556,7 +556,7 @@ extension ValueReducers { r7.fetch(db)) } - mutating public func value(_ fetched: Fetched) -> Value? { + public mutating func value(_ fetched: Fetched) -> Value? { let v1 = r1.value(fetched.0) let v2 = r2.value(fetched.1) let v3 = r3.value(fetched.2) @@ -641,6 +641,7 @@ extension ValueReducers { R7: ValueReducer, R8: ValueReducer>: ValueReducer { + // swiftlint:disable:next line_length public typealias Fetched = (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched, R6.Fetched, R7.Fetched, R8.Fetched) public typealias Value = (R1.Value, R2.Value, R3.Value, R4.Value, R5.Value, R6.Value, R7.Value, R8.Value) var r1: R1 @@ -683,7 +684,7 @@ extension ValueReducers { r8.fetch(db)) } - mutating public func value(_ fetched: Fetched) -> Value? { + public mutating func value(_ fetched: Fetched) -> Value? { let v1 = r1.value(fetched.0) let v2 = r2.value(fetched.1) let v3 = r3.value(fetched.2) diff --git a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift b/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift index 0aec4ceff..fbffa9efa 100644 --- a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift +++ b/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift @@ -66,4 +66,5 @@ extension ValueReducers { /// :nodoc: @available(*, deprecated, renamed: "ValueReducers.RemoveDuplicates") -public typealias DistinctUntilChangedValueReducer = ValueReducers.RemoveDuplicates where Base: ValueReducer, Base.Value: Equatable +public typealias DistinctUntilChangedValueReducer = ValueReducers.RemoveDuplicates + where Base: ValueReducer, Base.Value: Equatable diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index ec118c411..ead8fd693 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -1108,9 +1108,9 @@ 5605F1501C672E4000235C62 /* NSNull.swift */, 5605F1511C672E4000235C62 /* NSNumber.swift */, 5605F1521C672E4000235C62 /* NSString.swift */, + 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */, 5657AB0E1D10899D006283EF /* URL.swift */, 56A8C22F1D1914540096E9D4 /* UUID.swift */, - 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */, ); path = Foundation; sourceTree = ""; @@ -1877,6 +1877,7 @@ F3BA7FFA1CFB25E4003DC1BA /* Frameworks */, F3BA7FFB1CFB25E4003DC1BA /* Headers */, F3BA7FFC1CFB25E4003DC1BA /* Resources */, + 56EB54FD22C9119B00850069 /* Swiftlint */, ); buildRules = ( ); @@ -1915,6 +1916,7 @@ F3BA80561CFB2BB2003DC1BA /* Frameworks */, F3BA80571CFB2BB2003DC1BA /* Headers */, F3BA80581CFB2BB2003DC1BA /* Resources */, + 56EB54FB22C9118600850069 /* Swiftlint */, ); buildRules = ( ); @@ -1951,16 +1953,16 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0730; - LastUpgradeCheck = 1020; + LastUpgradeCheck = 1030; ORGANIZATIONNAME = "Gwendal Roué"; TargetAttributes = { F3BA7FFD1CFB25E4003DC1BA = { CreatedOnToolsVersion = 7.3.1; - LastSwiftMigration = 0830; + LastSwiftMigration = 1020; }; F3BA80401CFB2AD7003DC1BA = { CreatedOnToolsVersion = 7.3.1; - LastSwiftMigration = 0800; + LastSwiftMigration = 1020; }; F3BA80591CFB2BB2003DC1BA = { CreatedOnToolsVersion = 7.3.1; @@ -2045,6 +2047,42 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ + 56EB54FB22C9118600850069 /* Swiftlint */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + name = Swiftlint; + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n"; + }; + 56EB54FD22C9119B00850069 /* Swiftlint */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + name = Swiftlint; + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n"; + }; EED476F01CFD0B290026A4EC /* Copy .example configuration files (if no USER customizations exist) */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; diff --git a/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustomSQLiteOSX.xcscheme b/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustomSQLiteOSX.xcscheme index 4682c9c62..f3821823a 100644 --- a/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustomSQLiteOSX.xcscheme +++ b/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustomSQLiteOSX.xcscheme @@ -1,6 +1,6 @@