diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index b7e420dfb..a2d27d0f7 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -45,7 +45,7 @@ extension Sequence { /// over self. public func flatMap( _ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) - -> FlattenCursor, SegmentOfResult>> + -> FlattenCursor, SegmentOfResult>> { AnyCursor(self).flatMap(transform) } @@ -159,7 +159,7 @@ 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> + -> MapCursor>, ElementOfResult> { map(transform).filter { $0 != nil }.map { $0! } } @@ -263,8 +263,8 @@ extension Cursor { /// Returns a cursor over the concatenated results of mapping transform /// over self. public func flatMap(_ transform: @escaping (Element) throws -> SegmentOfResult) - -> FlattenCursor>> - where SegmentOfResult: Sequence + -> FlattenCursor>> + where SegmentOfResult: Sequence { flatMap { try AnyCursor(transform($0)) } } @@ -272,8 +272,8 @@ extension Cursor { /// Returns a cursor over the concatenated results of mapping transform /// over self. public func flatMap(_ transform: @escaping (Element) throws -> SegmentOfResult) - -> FlattenCursor> - where SegmentOfResult: Cursor + -> FlattenCursor> + where SegmentOfResult: Cursor { map(transform).joined() } @@ -367,7 +367,7 @@ extension Cursor { public func reduce( _ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) - throws -> Result + throws -> Result { var accumulator = initialResult while let element = try next() { @@ -381,7 +381,7 @@ extension Cursor { public func reduce( into initialResult: Result, _ updateAccumulatingResult: (inout Result, Element) throws -> Void) - throws -> Result + throws -> Result { var accumulator = initialResult while let element = try next() { diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 3b071579f..70c70c713 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -238,7 +238,7 @@ extension Database { columns.append(column) } return IndexInfo(name: indexName, columns: columns, unique: unique) - } + } if indexes.isEmpty { // PRAGMA index_list doesn't throw any error when table does @@ -257,8 +257,8 @@ extension Database { public func table( _ tableName: String, hasUniqueKey columns: T) - throws -> Bool - where T.Iterator.Element == String + throws -> Bool + where T.Iterator.Element == String { try columnsForUniqueKey(Array(columns), in: tableName) != nil } @@ -286,9 +286,8 @@ extension Database { .mapping .append((origin: origin, destination: destination, seq: seq)) } else { - rawForeignKeys.append(( - destinationTable: table, - mapping: [(origin: origin, destination: destination, seq: seq)])) + let mapping = [(origin: origin, destination: destination, seq: seq)] + rawForeignKeys.append((destinationTable: table, mapping: mapping)) previousId = id } } @@ -427,8 +426,8 @@ extension Database { func columnsForUniqueKey( _ columns: T, in tableName: String) - throws -> [String]? - where T.Iterator.Element == String + throws -> [String]? + where T.Iterator.Element == String { let lowercasedColumns = Set(columns.map { $0.lowercased() }) if lowercasedColumns.isEmpty { diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 320020a8b..abfa3763a 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -268,7 +268,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib let db = Unmanaged.fromOpaque(dbPointer!).takeUnretainedValue() let callback = db.busyCallback! return callback(Int(numberOfTries)) ? 1 : 0 - }, + }, dbPointer) } } @@ -311,7 +311,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib return SQLITE_OK } return authorizer.authorize(actionCode, cString1, cString2, cString3, cString4) - }, + }, dbPointer) } @@ -402,7 +402,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib public var maximumStatementArgumentCount: Int { Int(sqlite3_limit(sqliteConnection, SQLITE_LIMIT_VARIABLE_NUMBER, -1)) } - + // MARK: - Functions /// Add or redefine an SQL function. @@ -446,7 +446,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib { (collationPointer, length1, buffer1, length2, buffer2) -> Int32 in let collation = Unmanaged.fromOpaque(collationPointer!).takeUnretainedValue() return Int32(collation.function(length1, buffer1, length2, buffer2).rawValue) - }, nil) + }, nil) guard code == SQLITE_OK else { // Assume a GRDB bug: there is no point throwing any error. fatalError(DatabaseError(resultCode: code, message: lastErrorMessage).description) @@ -648,18 +648,20 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib switch mask { case SQLITE_TRACE_STMT: if let sqliteStatement = p, let unexpandedSQL = x { - let statement = TraceEvent.Statement(impl: .trace_v2( - sqliteStatement: OpaquePointer(sqliteStatement), - unexpandedSQL: UnsafePointer(unexpandedSQL.assumingMemoryBound(to: CChar.self)), - sqlite3_expanded_sql: sqlite3_expanded_sql)) + let statement = TraceEvent.Statement( + impl: .trace_v2( + sqliteStatement: OpaquePointer(sqliteStatement), + unexpandedSQL: UnsafePointer(unexpandedSQL.assumingMemoryBound(to: CChar.self)), + sqlite3_expanded_sql: sqlite3_expanded_sql)) trace(TraceEvent.statement(statement)) } case SQLITE_TRACE_PROFILE: if let sqliteStatement = p, let durationP = x?.assumingMemoryBound(to: Int64.self) { - let statement = TraceEvent.Statement(impl: .trace_v2( - sqliteStatement: OpaquePointer(sqliteStatement), - unexpandedSQL: nil, - sqlite3_expanded_sql: sqlite3_expanded_sql)) + let statement = TraceEvent.Statement( + impl: .trace_v2( + sqliteStatement: OpaquePointer(sqliteStatement), + unexpandedSQL: nil, + sqlite3_expanded_sql: sqlite3_expanded_sql)) let duration = TimeInterval(durationP.pointee) / 1.0e9 #if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS) @@ -692,7 +694,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// in the log file @discardableResult public func checkpoint(_ kind: Database.CheckpointMode = .passive, on dbName: String? = "main") throws - -> (walFrameCount: Int, checkpointedFrameCount: Int) + -> (walFrameCount: Int, checkpointedFrameCount: Int) { SchedulingWatchdog.preconditionValidQueue(self) var walFrameCount: CInt = -1 @@ -814,9 +816,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib return } - if - let updateStatement = statement as? UpdateStatement, - updateStatement.releasesDatabaseLock + if let updateStatement = statement as? UpdateStatement, + updateStatement.releasesDatabaseLock { // Accept statements that release locks: // - COMMIT @@ -863,7 +864,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib func checkForAbortedTransaction( sql: @autoclosure () -> String? = nil, arguments: @autoclosure () -> StatementArguments? = nil) - throws + throws { if isInsideTransactionBlock && !isInsideTransaction { throw DatabaseError( @@ -1164,13 +1165,13 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib } return .commit } - }, + }, finally: { // Restore foreign keys if needed if foreignKeysEnabled { try execute(sql: "PRAGMA foreign_keys = ON") } - }) + }) #else try DatabaseQueue().backup(to: self) #endif @@ -1182,7 +1183,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib to dbDest: Database, afterBackupInit: (() -> Void)? = nil, afterBackupStep: (() -> Void)? = nil) - throws + throws { guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", sqliteConnection, "main") else { throw DatabaseError(resultCode: dbDest.lastErrorCode, message: dbDest.lastErrorMessage) @@ -1481,9 +1482,9 @@ extension Database { enum Impl { case trace_v1(String) case trace_v2( - sqliteStatement: SQLiteStatement, - unexpandedSQL: UnsafePointer?, - sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer?) + sqliteStatement: SQLiteStatement, + unexpandedSQL: UnsafePointer?, + sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer?) } let impl: Impl diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index e46e6ddd0..c46874706 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -126,7 +126,7 @@ public final class DatabaseFunction: Hashable { { definitionP in // Release the function definition Unmanaged.fromOpaque(definitionP!).release() - }) + }) guard code == SQLITE_OK else { // Assume a GRDB bug: there is no point throwing any error. diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index bdcd4e787..ea0ca970c 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -369,7 +369,7 @@ extension DatabasePool: DatabaseReader { } catch { block(.failure(error)) } - } + } } /// :nodoc: @@ -414,7 +414,7 @@ extension DatabasePool: DatabaseReader { } catch { block(.failure(error)) } - } + } } /// Synchronously executes a read-only block in a protected dispatch queue, @@ -748,7 +748,7 @@ extension DatabasePool: DatabaseReader { public func writeInTransaction( _ kind: Database.TransactionKind? = nil, _ updates: (Database) throws -> Database.TransactionCompletion) - throws + throws { try writer.sync { db in try db.inTransaction(kind) { @@ -793,7 +793,7 @@ extension DatabasePool: DatabaseReader { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> DatabaseCancellable { if configuration.readonly { return _addReadOnly( @@ -823,7 +823,7 @@ extension DatabasePool: DatabaseReader { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> ValueObserver // For testability + -> ValueObserver // For testability { assert(!configuration.readonly, "Use _addReadOnly(observation:) instead") assert(!observation.requiresWriteAccess, "Use _addWriteOnly(observation:) instead") @@ -903,7 +903,7 @@ extension DatabasePool: DatabaseReader { } catch { observer.notifyErrorAndComplete(error) } - } + } } #else if scheduler.immediateInitialValue() { diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index efdb6bb93..2bc1fab86 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -349,7 +349,7 @@ extension DatabaseQueue { public func inTransaction( _ kind: Database.TransactionKind? = nil, _ updates: (Database) throws -> Database.TransactionCompletion) - throws + throws { try writer.sync { db in try db.inTransaction(kind) { @@ -434,7 +434,7 @@ extension DatabaseQueue { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> DatabaseCancellable { if configuration.readonly { return _addReadOnly( diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index efbf95478..feef59b49 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -223,7 +223,7 @@ public protocol DatabaseReader: AnyObject { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> DatabaseCancellable } extension DatabaseReader { @@ -248,7 +248,7 @@ extension DatabaseReader { to dbDest: Database, afterBackupInit: (() -> Void)? = nil, afterBackupStep: (() -> Void)? = nil) - throws + throws { try read { dbFrom in try dbFrom.backup( @@ -276,7 +276,7 @@ extension DatabaseReader { @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) public func readPublisher( value: @escaping (Database) throws -> Output) - -> DatabasePublishers.Read + -> DatabasePublishers.Read { readPublisher(receiveOn: DispatchQueue.main, value: value) } @@ -296,8 +296,8 @@ extension DatabaseReader { public func readPublisher( receiveOn scheduler: S, value: @escaping (Database) throws -> Output) - -> DatabasePublishers.Read - where S: Scheduler + -> DatabasePublishers.Read + where S: Scheduler { Deferred { Future { fulfill in @@ -349,7 +349,7 @@ extension DatabaseReader { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> DatabaseCancellable { if scheduler.immediateInitialValue() { do { @@ -362,10 +362,9 @@ extension DatabaseReader { } else { var isCancelled = false _weakAsyncRead { dbResult in - guard - !isCancelled, - let dbResult = dbResult - else { return } + guard !isCancelled, + let dbResult = dbResult + else { return } let result = dbResult.flatMap { db in Result { try observation.fetchValue(db) } @@ -437,7 +436,7 @@ public final class AnyDatabaseReader: DatabaseReader { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> DatabaseCancellable { base._add( observation: observation, diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 8e61ddd94..1c18604ad 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -89,8 +89,8 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable { var tableRegionsIntersection: [String: TableRegion] = [:] for (table, tableRegion) in tableRegions { guard let otherTableRegion = otherTableRegions - .first(where: { (otherTable, _) in otherTable == table })? - .value else { continue } + .first(where: { (otherTable, _) in otherTable == table })? + .value else { continue } let tableRegionIntersection = tableRegion.intersection(otherTableRegion) guard !tableRegionIntersection.isEmpty else { continue } tableRegionsIntersection[table] = tableRegionIntersection diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index ebeb6e947..87809700f 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -86,7 +86,7 @@ extension DatabaseRegionObservation { public func start( in dbWriter: DatabaseWriter, onChange: @escaping (Database) -> Void) - throws -> TransactionObserver + throws -> TransactionObserver { // Use unsafeReentrantWrite so that observation can start from any // dispatch queue. @@ -103,7 +103,7 @@ extension DatabaseRegionObservation { @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) extension DatabaseRegionObservation { // MARK: - Publishing Impactful Transactions - + /// Returns a publisher that tracks changes in a database region. /// /// It emits database connections on a protected dispatch queue. @@ -179,7 +179,7 @@ extension DatabasePublishers { } private class DatabaseRegionSubscription: Subscription - where Downstream.Failure == Error, Downstream.Input == Database + where Downstream.Failure == Error, Downstream.Input == Database { private struct WaitingForDemand { let downstream: Downstream @@ -216,9 +216,9 @@ extension DatabasePublishers { downstream: Downstream) { state = .waitingForDemand(WaitingForDemand( - downstream: downstream, - writer: writer, - observation: observation)) + downstream: downstream, + writer: writer, + observation: observation)) } func request(_ demand: Subscribers.Demand) { @@ -230,9 +230,9 @@ extension DatabasePublishers { } do { state = .observing(Observing( - downstream: info.downstream, - writer: info.writer, - remainingDemand: demand)) + downstream: info.downstream, + writer: info.writer, + remainingDemand: demand)) observer = try info.observation.start( in: info.writer, onChange: { [weak self] in self?.receive($0) }) @@ -261,7 +261,7 @@ extension DatabasePublishers { private func receive(_ value: Database) { lock.synchronized { if case let .observing(info) = state, - info.remainingDemand > .none + info.remainingDemand > .none { let additionalDemand = info.downstream.receive(value) if case var .observing(info) = state { diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 33dff3b46..02370965b 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -126,7 +126,7 @@ extension DatabaseSnapshot { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> DatabaseCancellable { _addReadOnly( observation: observation, diff --git a/GRDB/Core/DatabaseValueConversion.swift b/GRDB/Core/DatabaseValueConversion.swift index 4c25c246f..0bdbbdf0b 100644 --- a/GRDB/Core/DatabaseValueConversion.swift +++ b/GRDB/Core/DatabaseValueConversion.swift @@ -82,7 +82,7 @@ func conversionErrorMessage( to: T.Type, from dbValue: DatabaseValue?, conversionContext: ValueConversionContext?) - -> String +-> String { var message: String var extras: [String] = [] @@ -128,7 +128,7 @@ func fatalConversionError( conversionContext: ValueConversionContext?, file: StaticString = #file, line: UInt = #line) - -> Never +-> Never { fatalError( conversionErrorMessage( @@ -147,7 +147,7 @@ func fatalConversionError( atColumn columnName: String, file: StaticString = #file, line: UInt = #line) - -> Never +-> Never { fatalConversionError( to: T.self, @@ -162,7 +162,7 @@ func fatalConversionError( index: Int32, file: StaticString = #file, line: UInt = #line) - -> Never +-> Never { let row = Row(sqliteStatement: sqliteStatement) fatalConversionError( @@ -179,7 +179,7 @@ func fatalConversionError( index: Int32, file: StaticString = #file, line: UInt = #line) - -> Never +-> Never { let row = Row(sqliteStatement: sqliteStatement) fatalConversionError( @@ -205,7 +205,7 @@ extension DatabaseValueConvertible { static func decode( from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) - -> Self + -> Self { if let value = fromDatabaseValue(dbValue) { return value @@ -236,7 +236,7 @@ extension DatabaseValueConvertible { static func decodeIfPresent( from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) - -> Self? + -> Self? { // Use fromDatabaseValue before checking for null: this allows DatabaseValue to convert NULL to .null. if let value = fromDatabaseValue(dbValue) { @@ -299,7 +299,7 @@ extension Row { func fastDecode( _ type: Value.Type, atUncheckedIndex index: Int) - -> Value + -> Value { impl.fastDecode(type, atUncheckedIndex: index) } @@ -308,7 +308,7 @@ extension Row { func fastDecodeIfPresent( _ type: Value.Type, atUncheckedIndex index: Int) - -> Value? + -> Value? { impl.fastDecodeIfPresent(type, atUncheckedIndex: index) } diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index ffc5f87a5..8ba472cec 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -179,7 +179,7 @@ extension DatabaseValueConvertible { _ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) - throws -> DatabaseValueCursor + throws -> DatabaseValueCursor { try DatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) } @@ -199,7 +199,7 @@ extension DatabaseValueConvertible { _ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) - throws -> [Self] + throws -> [Self] { try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } @@ -222,7 +222,7 @@ extension DatabaseValueConvertible { _ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) - throws -> Self? + 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) @@ -246,7 +246,7 @@ extension DatabaseValueConvertible where Self: Hashable { _ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) - throws -> Set + throws -> Set { try Set(fetchCursor(statement, arguments: arguments, adapter: adapter)) } @@ -280,7 +280,7 @@ extension DatabaseValueConvertible { sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) - throws -> DatabaseValueCursor + throws -> DatabaseValueCursor { try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -301,7 +301,7 @@ extension DatabaseValueConvertible { sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) - throws -> [Self] + throws -> [Self] { try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -325,7 +325,7 @@ extension DatabaseValueConvertible { sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) - throws -> Self? + throws -> Self? { try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -348,7 +348,7 @@ extension DatabaseValueConvertible where Self: Hashable { sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) - throws -> Set + throws -> Set { try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -536,7 +536,7 @@ extension Optional where Wrapped: DatabaseValueConvertible { _ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) - throws -> NullableDatabaseValueCursor + throws -> NullableDatabaseValueCursor { try NullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) } @@ -556,7 +556,7 @@ extension Optional where Wrapped: DatabaseValueConvertible { _ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) - throws -> [Wrapped?] + throws -> [Wrapped?] { try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } @@ -578,7 +578,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & Hashable { _ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) - throws -> Set + throws -> Set { try Set(fetchCursor(statement, arguments: arguments, adapter: adapter)) } @@ -612,7 +612,7 @@ extension Optional where Wrapped: DatabaseValueConvertible { sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) - throws -> NullableDatabaseValueCursor + throws -> NullableDatabaseValueCursor { try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -633,7 +633,7 @@ extension Optional where Wrapped: DatabaseValueConvertible { sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) - throws -> [Wrapped?] + throws -> [Wrapped?] { try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -656,7 +656,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & Hashable { sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) - throws -> Set + throws -> Set { try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -685,7 +685,7 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// - 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 + throws -> NullableDatabaseValueCursor { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchCursor(request.statement, adapter: request.adapter) diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 51ad4b8c8..ac3dcc8f5 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -317,7 +317,7 @@ extension DatabaseWriter { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> ValueObserver // For testability + -> ValueObserver // For testability { assert(!configuration.readonly, "Use _addReadOnly(observation:) instead") @@ -379,7 +379,7 @@ extension DatabaseWriter { @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) public func writePublisher( updates: @escaping (Database) throws -> Output) - -> DatabasePublishers.Write + -> DatabasePublishers.Write { writePublisher(receiveOn: DispatchQueue.main, updates: updates) } @@ -402,18 +402,18 @@ extension DatabaseWriter { public func writePublisher( receiveOn scheduler: S, updates: @escaping (Database) throws -> Output) - -> DatabasePublishers.Write - where S: Scheduler + -> DatabasePublishers.Write + where S: Scheduler { OnDemandFuture({ fulfill in self.asyncWrite(updates, completion: { _, result in fulfill(result) }) }) - // We don't want users to process emitted values on a - // database dispatch queue. - .receiveValues(on: scheduler) - .eraseToWritePublisher() + // We don't want users to process emitted values on a + // database dispatch queue. + .receiveValues(on: scheduler) + .eraseToWritePublisher() } /// Returns a Publisher that asynchronously writes into the database. @@ -431,7 +431,7 @@ extension DatabaseWriter { public func writePublisher( updates: @escaping (Database) throws -> T, thenRead value: @escaping (Database, T) throws -> Output) - -> DatabasePublishers.Write + -> DatabasePublishers.Write { writePublisher(receiveOn: DispatchQueue.main, updates: updates, thenRead: value) } @@ -455,8 +455,8 @@ extension DatabaseWriter { receiveOn scheduler: S, updates: @escaping (Database) throws -> T, thenRead value: @escaping (Database, T) throws -> Output) - -> DatabasePublishers.Write - where S: Scheduler + -> DatabasePublishers.Write + where S: Scheduler { OnDemandFuture({ fulfill in self.asyncWriteWithoutTransaction { db in @@ -475,10 +475,10 @@ extension DatabaseWriter { } } }) - // We don't want users to process emitted values on a - // database dispatch queue. - .receiveValues(on: scheduler) - .eraseToWritePublisher() + // We don't want users to process emitted values on a + // database dispatch queue. + .receiveValues(on: scheduler) + .eraseToWritePublisher() } } @@ -647,7 +647,7 @@ public final class AnyDatabaseWriter: DatabaseWriter { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> DatabaseCancellable { base._add( observation: observation, diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index 8c0900485..85c0b3a4d 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -248,7 +248,7 @@ public struct AnyFetchRequest: FetchRequest { extension AnyFetchRequest { /// Creates a request that wraps and forwards operations to `request`. public init(_ request: Request) - where Request.RowDecoder == RowDecoder + where Request.RowDecoder == RowDecoder { self.init(request: ConcreteFetchRequestEraser(request: request)) } diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index fdf1ef360..a73f16977 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -2,8 +2,8 @@ import Foundation /// A database row. public final class Row: Equatable, Hashable, RandomAccessCollection, - ExpressibleByDictionaryLiteral, CustomStringConvertible, - CustomDebugStringConvertible + ExpressibleByDictionaryLiteral, CustomStringConvertible, + CustomDebugStringConvertible { // It is not a violation of the Demeter law when another type uses this // property, which is exposed for optimizations. @@ -123,8 +123,8 @@ public final class Row: Equatable, Hashable, RandomAccessCollection, statement: SelectStatement) { self.init(impl: StatementCopyRowImpl( - sqliteStatement: sqliteStatement, - columnNames: statement.columnNames)) + sqliteStatement: sqliteStatement, + columnNames: statement.columnNames)) } init(impl: RowImpl) { @@ -414,8 +414,8 @@ extension Row { /// (see https://www.sqlite.org/datatype3.html). @inlinable public subscript(_ column: Column) - -> Value? - where + -> Value? + where Value: DatabaseValueConvertible & StatementColumnConvertible, Column: ColumnExpression { @@ -451,8 +451,8 @@ extension Row { /// (see https://www.sqlite.org/datatype3.html). @inlinable public subscript(_ column: Column) - -> Value - where + -> Value + where Value: DatabaseValueConvertible & StatementColumnConvertible, Column: ColumnExpression { @@ -625,8 +625,8 @@ extension Row { /// print(books[0].title) /// // Prints "Moby-Dick" public subscript(_ key: String) - -> Collection - where + -> Collection + where Collection: RangeReplaceableCollection, Collection.Element: FetchableRecord { @@ -847,7 +847,7 @@ extension Row { _ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) - throws -> RowCursor + throws -> RowCursor { try RowCursor(statement: statement, arguments: arguments, adapter: adapter) } @@ -867,7 +867,7 @@ extension Row { _ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) - throws -> [Row] + throws -> [Row] { // The cursor reuses a single mutable row. Return immutable copies. return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter).map { $0.copy() }) @@ -888,7 +888,7 @@ extension Row { _ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) - throws -> Set + throws -> Set { // The cursor reuses a single mutable row. Return immutable copies. return try Set(fetchCursor(statement, arguments: arguments, adapter: adapter).map { $0.copy() }) @@ -909,7 +909,7 @@ extension Row { _ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) - throws -> Row? + throws -> Row? { let cursor = try fetchCursor(statement, arguments: arguments, adapter: adapter) // Keep cursor alive until we can copy the fetched row @@ -956,7 +956,7 @@ extension Row { sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) - throws -> RowCursor + throws -> RowCursor { try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -981,7 +981,7 @@ extension Row { sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) - throws -> [Row] + throws -> [Row] { try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -1006,7 +1006,7 @@ extension Row { sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) - throws -> Set + throws -> Set { try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -1031,7 +1031,7 @@ extension Row { sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) - throws -> Row? + throws -> Row? { try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -1650,11 +1650,11 @@ protocol RowImpl { func fastDecode( _ type: Value.Type, atUncheckedIndex index: Int) - -> Value + -> Value func fastDecodeIfPresent( _ type: Value.Type, atUncheckedIndex index: Int) - -> Value? + -> Value? func dataNoCopy(atUncheckedIndex index: Int) -> Data? /// Returns the index of the leftmost column that matches *name* (case-insensitive) diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index ed7ddd08c..c3e6999b9 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -20,7 +20,7 @@ final class SerializedDatabase { schemaCache: DatabaseSchemaCache, defaultLabel: String, purpose: String? = nil) - throws + throws { // According to https://www.sqlite.org/threadsafe.html // diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 85e743bf8..6e8304333 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -282,11 +282,11 @@ extension Statement { let statementStart = buffer.baseAddress! var statementEnd: UnsafePointer? = nil guard let statement = try self.init( - database: db, - statementStart: statementStart, - statementEnd: &statementEnd, - prepFlags: prepFlags, - authorizer: authorizer) else + database: db, + statementStart: statementStart, + statementEnd: &statementEnd, + prepFlags: prepFlags, + authorizer: authorizer) else { throw DatabaseError( resultCode: .SQLITE_ERROR, @@ -634,7 +634,7 @@ public final class UpdateStatement: Statement { /// .filter(sql: "score > ?", arguments: [1000]) /// .fetchAll(db) public struct StatementArguments: CustomStringConvertible, Equatable, - ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral + ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral { private(set) var values: [DatabaseValue] = [] private(set) var namedValues: [String: DatabaseValue] = [:] @@ -714,7 +714,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable, /// - parameter sequence: A sequence of (key, value) pairs /// - returns: A StatementArguments. public init(_ sequence: Sequence) - where Sequence: Swift.Sequence, Sequence.Element == (String, DatabaseValueConvertible?) + where Sequence: Swift.Sequence, Sequence.Element == (String, DatabaseValueConvertible?) { namedValues = Dictionary(uniqueKeysWithValues: sequence.map { ($0.0, $0.1?.databaseValue ?? .null) }) } @@ -902,7 +902,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable, mutating func extractBindings( forStatement statement: Statement, allowingRemainingValues: Bool) - throws -> [DatabaseValue] + throws -> [DatabaseValue] { let initialValuesCount = values.count let bindings = try statement.sqliteArgumentNames.map { argumentName -> DatabaseValue in diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index f5bc3e15f..2d905f44b 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -10,7 +10,7 @@ protocol StatementAuthorizer: AnyObject { _ cString2: UnsafePointer?, _ cString3: UnsafePointer?, _ cString4: UnsafePointer?) - -> Int32 + -> Int32 } /// A class that gathers information about one statement during its compilation. @@ -38,13 +38,13 @@ final class StatementCompilationAuthorizer: StatementAuthorizer { _ cString2: UnsafePointer?, _ cString3: UnsafePointer?, _ cString4: UnsafePointer?) - -> Int32 + -> Int32 { -// print(""" -// StatementCompilationAuthorizer: \ -// \(AuthorizerActionCode(rawValue: actionCode)) \ -// \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) }) -// """) + // print(""" + // StatementCompilationAuthorizer: \ + // \(AuthorizerActionCode(rawValue: actionCode)) \ + // \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) }) + // """) switch actionCode { case SQLITE_DROP_TABLE, SQLITE_DROP_VTABLE, SQLITE_DROP_TEMP_TABLE, @@ -173,13 +173,13 @@ final class TruncateOptimizationBlocker: StatementAuthorizer { _ cString2: UnsafePointer?, _ cString3: UnsafePointer?, _ cString4: UnsafePointer?) - -> Int32 + -> Int32 { -// print(""" -// TruncateOptimizationBlocker: \ -// \(AuthorizerActionCode(rawValue: actionCode)) \ -// \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) }) -// """) + // print(""" + // TruncateOptimizationBlocker: \ + // \(AuthorizerActionCode(rawValue: 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 ccf3a4eb4..4889d58bb 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -110,7 +110,7 @@ public final class FastDatabaseValueCursor: Cursor - where Value: DatabaseValueConvertible & StatementColumnConvertible +where Value: DatabaseValueConvertible & StatementColumnConvertible { @usableFromInline let _statement: SelectStatement @usableFromInline let _columnIndex: Int32 @@ -190,7 +190,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { _ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) - throws -> FastDatabaseValueCursor + throws -> FastDatabaseValueCursor { try FastDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) } @@ -210,7 +210,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { _ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) - throws -> [Self] + throws -> [Self] { try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } @@ -230,7 +230,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { _ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) - throws -> Self? + throws -> Self? { // fetchOne returns nil if there is no row, or if there is a row with a null value let cursor = try FastNullableDatabaseValueCursor( @@ -257,7 +257,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash _ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) - throws -> Set + throws -> Set { try Set(fetchCursor(statement, arguments: arguments, adapter: adapter)) } @@ -291,7 +291,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) - throws -> FastDatabaseValueCursor + throws -> FastDatabaseValueCursor { try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -312,7 +312,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) - throws -> [Self] + throws -> [Self] { try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -333,7 +333,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) - throws -> Self? + throws -> Self? { try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -356,7 +356,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) - throws -> Set + throws -> Set { try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -385,7 +385,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - 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 + throws -> FastDatabaseValueCursor { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchCursor(request.statement, adapter: request.adapter) @@ -543,7 +543,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv _ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) - throws -> FastNullableDatabaseValueCursor + throws -> FastNullableDatabaseValueCursor { try FastNullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) } @@ -563,7 +563,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv _ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) - throws -> [Wrapped?] + throws -> [Wrapped?] { try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } @@ -585,7 +585,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv _ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) - throws -> Set + throws -> Set { try Set(fetchCursor(statement, arguments: arguments, adapter: adapter)) } @@ -619,7 +619,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) - throws -> FastNullableDatabaseValueCursor + throws -> FastNullableDatabaseValueCursor { try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -640,7 +640,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) - throws -> [Wrapped?] + throws -> [Wrapped?] { try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -663,7 +663,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) - throws -> Set + throws -> Set { try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -692,7 +692,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// - 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 + throws -> FastNullableDatabaseValueCursor { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchCursor(request.statement, adapter: request.adapter) @@ -732,7 +732,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv } extension FetchRequest - where +where RowDecoder: _OptionalProtocol, RowDecoder.Wrapped: DatabaseValueConvertible & StatementColumnConvertible { @@ -788,7 +788,7 @@ extension FetchRequest } extension FetchRequest - where +where RowDecoder: _OptionalProtocol, RowDecoder.Wrapped: DatabaseValueConvertible & StatementColumnConvertible & Hashable { diff --git a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift index 4cebcfc97..ffae7667a 100644 --- a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift +++ b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift @@ -77,7 +77,7 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC let optionalComponents = cString.withMemoryRebound( to: Int8.self, capacity: length + 1 /* trailing \0 */) { cString in - SQLiteDateParser().components(cString: cString, length: length) + SQLiteDateParser().components(cString: cString, length: length) } guard let components = optionalComponents else { fatalConversionError(to: DatabaseDateComponents.self, sqliteStatement: sqliteStatement, index: index) @@ -152,10 +152,10 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC return SQLiteDateParser().components(from: string) } - + // MARK: - Codable adoption - - + + /// Creates a new instance by decoding from the given decoder. /// /// - parameters: @@ -169,7 +169,7 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC } self = decodedValue } - + /// Encodes this value into the given encoder. /// /// - parameters: diff --git a/GRDB/Core/Support/Foundation/DatabaseValueConvertible+ReferenceConvertible.swift b/GRDB/Core/Support/Foundation/DatabaseValueConvertible+ReferenceConvertible.swift index 39244a1ae..8d9e44376 100644 --- a/GRDB/Core/Support/Foundation/DatabaseValueConvertible+ReferenceConvertible.swift +++ b/GRDB/Core/Support/Foundation/DatabaseValueConvertible+ReferenceConvertible.swift @@ -27,7 +27,7 @@ extension DatabaseValueConvertible where Self: ReferenceConvertible, Self.Refere } extension DatabaseValueConvertible - where +where Self: Decodable & ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible { @@ -38,7 +38,7 @@ extension DatabaseValueConvertible } extension DatabaseValueConvertible - where +where Self: Encodable & ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible { diff --git a/GRDB/Core/Support/Foundation/NSNumber.swift b/GRDB/Core/Support/Foundation/NSNumber.swift index 7c33a68fb..087fb9577 100644 --- a/GRDB/Core/Support/Foundation/NSNumber.swift +++ b/GRDB/Core/Support/Foundation/NSNumber.swift @@ -16,9 +16,9 @@ extension NSNumber: DatabaseValueConvertible { public var databaseValue: DatabaseValue { // Don't lose precision: store integers that fits in Int64 as Int64 if let decimal = self as? NSDecimalNumber, - decimal == decimal.rounding(accordingToBehavior: integerRoundingBehavior), // integer - decimal.compare(NSDecimalNumber(value: Int64.max)) != .orderedDescending, // decimal <= Int64.max - decimal.compare(NSDecimalNumber(value: Int64.min)) != .orderedAscending // decimal >= Int64.min + decimal == decimal.rounding(accordingToBehavior: integerRoundingBehavior), // integer + decimal.compare(NSDecimalNumber(value: Int64.max)) != .orderedDescending, // decimal <= Int64.max + decimal.compare(NSDecimalNumber(value: Int64.min)) != .orderedAscending // decimal >= Int64.min { return int64Value.databaseValue } diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index a67d8e23e..8ff5be601 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -56,10 +56,10 @@ final class SQLiteDateParser { -> DatabaseDateComponents.Format? { guard let year = parser.parseNNNN(), - parser.parse("-"), - let month = parser.parseNN(), - parser.parse("-"), - let day = parser.parseNN() + parser.parse("-"), + let month = parser.parseNN(), + parser.parse("-"), + let day = parser.parseNN() else { return nil } components.year = year @@ -89,8 +89,8 @@ final class SQLiteDateParser { -> DatabaseDateComponents.Format? { guard let hour = parser.parseNN(), - parser.parse(":"), - let minute = parser.parseNN() + parser.parse(":"), + let minute = parser.parseNN() else { return nil } components.hour = hour @@ -98,7 +98,7 @@ final class SQLiteDateParser { if parser.length == 0 || parseTimeZone(parser: &parser, into: &components) { return .HM } guard parser.parse(":"), - let second = parser.parseNN() + let second = parser.parseNN() else { return nil } components.second = second @@ -137,18 +137,18 @@ final class SQLiteDateParser { } if parser.parse("+"), - let hour = parser.parseNN(), - parser.parse(":"), - let minute = parser.parseNN() + let hour = parser.parseNN(), + parser.parse(":"), + let minute = parser.parseNN() { components.timeZone = TimeZone(secondsFromGMT: hour * 3600 + minute * 60) return true } if parser.parse("-"), - let hour = parser.parseNN(), - parser.parse(":"), - let minute = parser.parseNN() + let hour = parser.parseNN(), + parser.parse(":"), + let minute = parser.parseNN() { components.timeZone = TimeZone(secondsFromGMT: -(hour * 3600 + minute * 60)) return true @@ -166,7 +166,7 @@ final class SQLiteDateParser { cString += 1 length -= 1 } - + @inline(__always) mutating func parse(_ scalar: Unicode.Scalar) -> Bool { guard length > 0, cString[0] == UInt8(ascii: scalar) else { diff --git a/GRDB/Core/Support/Foundation/UUID.swift b/GRDB/Core/Support/Foundation/UUID.swift index 49fa07c55..195e3d641 100644 --- a/GRDB/Core/Support/Foundation/UUID.swift +++ b/GRDB/Core/Support/Foundation/UUID.swift @@ -60,7 +60,7 @@ extension UUID: StatementColumnConvertible { self.init(uuid: uuid.uuid) case SQLITE_BLOB: guard sqlite3_column_bytes(sqliteStatement, index) == 16, - let blob = sqlite3_column_blob(sqliteStatement, index) else + let blob = sqlite3_column_blob(sqliteStatement, index) else { fatalConversionError(to: UUID.self, sqliteStatement: sqliteStatement, index: index) } diff --git a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift index 99a2597a3..ce7dddb99 100644 --- a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift +++ b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift @@ -498,7 +498,7 @@ extension DatabaseFunction { return nil } return string.capitalized - } + } /// An SQL function that returns the Swift built-in lowercased /// String property. @@ -518,7 +518,7 @@ extension DatabaseFunction { return nil } return string.lowercased() - } + } /// An SQL function that returns the Swift built-in uppercased /// String property. @@ -538,7 +538,7 @@ extension DatabaseFunction { return nil } return string.uppercased() - } + } } extension DatabaseFunction { @@ -561,7 +561,7 @@ extension DatabaseFunction { return nil } return string.localizedCapitalized - } + } /// An SQL function that returns the Swift built-in /// localizedLowercased String property. @@ -582,7 +582,7 @@ extension DatabaseFunction { return nil } return string.localizedLowercase - } + } /// An SQL function that returns the Swift built-in /// localizedUppercased String property. @@ -603,7 +603,7 @@ extension DatabaseFunction { return nil } return string.localizedUppercase - } + } } @@ -638,7 +638,7 @@ extension DatabaseCollation { 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 /// according to the the Swift built-in caseInsensitiveCompare(_:) method. @@ -657,7 +657,7 @@ extension DatabaseCollation { public static let caseInsensitiveCompare = DatabaseCollation("swiftCaseInsensitiveCompare") { (lhs, rhs) in lhs.caseInsensitiveCompare(rhs) - } + } /// A collation, or SQL string comparison function, that compares strings /// according to the the Swift built-in localizedCaseInsensitiveCompare(_:) method. @@ -676,7 +676,7 @@ extension DatabaseCollation { public static let localizedCaseInsensitiveCompare = DatabaseCollation("swiftLocalizedCaseInsensitiveCompare") { (lhs, rhs) in return lhs.localizedCaseInsensitiveCompare(rhs) - } + } /// A collation, or SQL string comparison function, that compares strings /// according to the the Swift built-in localizedCompare(_:) method. @@ -695,7 +695,7 @@ extension DatabaseCollation { public static let localizedCompare = DatabaseCollation("swiftLocalizedCompare") { (lhs, rhs) in lhs.localizedCompare(rhs) - } + } /// A collation, or SQL string comparison function, that compares strings /// according to the the Swift built-in localizedStandardCompare(_:) method. @@ -714,5 +714,5 @@ extension DatabaseCollation { 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 d284e2924..68efda018 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -293,7 +293,7 @@ class DatabaseObservationBroker { // not ony update statements. transactionState = .none } - + if observesRowDeletion { return TruncateOptimizationBlocker() } else { @@ -357,7 +357,7 @@ class DatabaseObservationBroker { savepointStack.savepointDidRelease(name) if case .none = self.transactionState, // 2. sqlite3_commit_hook was not triggered - !database.isInsideTransaction // 3. database is no longer inside a transaction + !database.isInsideTransaction // 3. database is no longer inside a transaction { // 1+2+3 mean that an empty deferred transaction has been completed: // @@ -603,7 +603,7 @@ class DatabaseObservationBroker { break default: broker.transactionState = .rollback - // Next step: updateStatementDidExecute() + // Next step: updateStatementDidExecute() } }, brokerPointer) } @@ -615,12 +615,13 @@ class DatabaseObservationBroker { 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)) - }, + broker.databaseDidChange( + with: DatabaseEvent( + kind: DatabaseEvent.Kind(rawValue: updateKind)!, + rowID: rowID, + databaseNameCString: databaseNameCString, + tableNameCString: tableNameCString)) + }, brokerPointer) #if SQLITE_ENABLE_PREUPDATE_HOOK @@ -629,14 +630,15 @@ class DatabaseObservationBroker { // 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!, - kind: DatabasePreUpdateEvent.Kind(rawValue: updateKind)!, - initialRowID: initialRowID, - finalRowID: finalRowID, - databaseNameCString: databaseNameCString, - tableNameCString: tableNameCString)) - }, + broker.databaseWillChange( + with: DatabasePreUpdateEvent( + connection: databaseConnection!, + kind: DatabasePreUpdateEvent.Kind(rawValue: updateKind)!, + initialRowID: initialRowID, + finalRowID: finalRowID, + databaseNameCString: databaseNameCString, + tableNameCString: tableNameCString)) + }, brokerPointer) #endif } @@ -1218,7 +1220,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { 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? { @@ -1228,7 +1230,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { 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 { @@ -1248,7 +1250,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { private func preupdate_getValues( _ connection: SQLiteConnection, sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt) - -> [DatabaseValue]? + -> [DatabaseValue]? { let columnCount = self.columnCount guard columnCount > 0 else { return nil } @@ -1267,7 +1269,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { _ connection: SQLiteConnection, column: CInt, sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt) - -> DatabaseValue? + -> DatabaseValue? { var value: SQLiteValue? = nil guard sqlite_func(connection, column, &value) == SQLITE_OK else { return nil } @@ -1282,7 +1284,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { 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]? { @@ -1290,7 +1292,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { connection, sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in sqlite3_preupdate_new(connection, column, &value) - }) + }) } } diff --git a/GRDB/FTS/FTS3TokenizerDescriptor.swift b/GRDB/FTS/FTS3TokenizerDescriptor.swift index 2ce38af69..d647654f6 100644 --- a/GRDB/FTS/FTS3TokenizerDescriptor.swift +++ b/GRDB/FTS/FTS3TokenizerDescriptor.swift @@ -51,7 +51,7 @@ public struct FTS3TokenizerDescriptor { diacritics: FTS3.Diacritics = .removeLegacy, separators: Set = [], tokenCharacters: Set = []) - -> FTS3TokenizerDescriptor + -> FTS3TokenizerDescriptor { _unicode61(diacritics: diacritics, separators: separators, tokenCharacters: tokenCharacters) } @@ -60,7 +60,7 @@ public struct FTS3TokenizerDescriptor { diacritics: FTS3.Diacritics, separators: Set = [], tokenCharacters: Set = []) - -> FTS3TokenizerDescriptor + -> FTS3TokenizerDescriptor { var arguments: [String] = [] switch diacritics { diff --git a/GRDB/FTS/FTS5.swift b/GRDB/FTS/FTS5.swift index 902eadcc1..9abef7a2f 100644 --- a/GRDB/FTS/FTS5.swift +++ b/GRDB/FTS/FTS5.swift @@ -212,7 +212,7 @@ public struct FTS5: VirtualTableModule { _ 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 + -> UnsafePointer { var statement: SQLiteStatement? = nil var api: UnsafePointer? = nil diff --git a/GRDB/FTS/FTS5CustomTokenizer.swift b/GRDB/FTS/FTS5CustomTokenizer.swift index 6a29fdc0c..54f777dc3 100644 --- a/GRDB/FTS/FTS5CustomTokenizer.swift +++ b/GRDB/FTS/FTS5CustomTokenizer.swift @@ -85,7 +85,7 @@ extension Database { } catch { return SQLITE_ERROR } - }) + }) // Constructor must remain alive until deleteConstructor() is // called, as the last argument of the xCreateTokenizer() function. @@ -101,7 +101,7 @@ extension Database { azArg: UnsafeMutablePointer?>?, nArg: Int32, tokenizerHandle: UnsafeMutablePointer?) - -> Int32 + -> Int32 { guard let constructorPointer = constructorPointer else { return SQLITE_ERROR @@ -131,7 +131,7 @@ extension Database { nText: Int32, // swiftlint:disable:next line_length tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, Int32, UnsafePointer?, Int32, Int32, Int32) -> Int32)?) - -> Int32 + -> Int32 { guard let tokenizerPointer = tokenizerPointer else { return SQLITE_ERROR diff --git a/GRDB/FTS/FTS5Pattern.swift b/GRDB/FTS/FTS5Pattern.swift index 35d323119..53ce4ac3c 100644 --- a/GRDB/FTS/FTS5Pattern.swift +++ b/GRDB/FTS/FTS5Pattern.swift @@ -13,13 +13,10 @@ 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({ try $0.makeTokenizer(.ascii()) .nonSynonymTokens(in: string, for: .query) }) + else { + return nil } guard !tokens.isEmpty else { return nil } try? self.init(rawPattern: tokens.joined(separator: " OR ")) @@ -33,13 +30,10 @@ 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({ try $0.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) + else { + return nil } guard !tokens.isEmpty else { return nil } try? self.init(rawPattern: tokens.joined(separator: " ")) @@ -53,13 +47,10 @@ 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({ try $0.makeTokenizer(.ascii()) .nonSynonymTokens(in: string, for: .query) }) + else { + return nil } guard !tokens.isEmpty else { return nil } try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"") @@ -73,13 +64,10 @@ 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({ try $0.makeTokenizer(.ascii()) .nonSynonymTokens(in: string, for: .query) }) + else { + return nil } guard !tokens.isEmpty else { return nil } try? self.init(rawPattern: "^\"" + tokens.joined(separator: " ") + "\"") diff --git a/GRDB/FTS/FTS5Tokenizer.swift b/GRDB/FTS/FTS5Tokenizer.swift index 480895802..ddf7aa9ba 100644 --- a/GRDB/FTS/FTS5Tokenizer.swift +++ b/GRDB/FTS/FTS5Tokenizer.swift @@ -58,7 +58,7 @@ public protocol FTS5Tokenizer: AnyObject { pText: UnsafePointer?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) - -> Int32 + -> Int32 } private class TokenizeContext { @@ -99,22 +99,20 @@ extension FTS5Tokenizer { } // 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 + 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 - }) + }) if code != SQLITE_OK { throw DatabaseError(resultCode: code) } @@ -161,7 +159,7 @@ extension Database { _ car: String, _ cdr: [String], _ body: (ContiguousArray>) -> Result) - -> Result + -> Result { car.withCString { cString in if let car = cdr.first { @@ -209,7 +207,7 @@ extension Database { pText: UnsafePointer?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) - -> Int32 + -> Int32 { guard let xTokenize = xTokenizer.xTokenize else { return SQLITE_ERROR diff --git a/GRDB/FTS/FTS5TokenizerDescriptor.swift b/GRDB/FTS/FTS5TokenizerDescriptor.swift index a54fd0496..3f30c88d2 100644 --- a/GRDB/FTS/FTS5TokenizerDescriptor.swift +++ b/GRDB/FTS/FTS5TokenizerDescriptor.swift @@ -59,7 +59,7 @@ public struct FTS5TokenizerDescriptor { public static func ascii( separators: Set = [], tokenCharacters: Set = []) - -> FTS5TokenizerDescriptor { + -> FTS5TokenizerDescriptor { var components: [String] = ["ascii"] if !separators.isEmpty { // TODO: test "=" and "\"", "(" and ")" as separators, with @@ -136,7 +136,7 @@ public struct FTS5TokenizerDescriptor { diacritics: FTS5.Diacritics = .removeLegacy, separators: Set = [], tokenCharacters: Set = []) - -> FTS5TokenizerDescriptor + -> FTS5TokenizerDescriptor { var components: [String] = ["unicode61"] switch diacritics { diff --git a/GRDB/FTS/FTS5WrapperTokenizer.swift b/GRDB/FTS/FTS5WrapperTokenizer.swift index a4d9a42f7..d3d73392c 100644 --- a/GRDB/FTS/FTS5WrapperTokenizer.swift +++ b/GRDB/FTS/FTS5WrapperTokenizer.swift @@ -106,7 +106,7 @@ extension FTS5WrapperTokenizer { pText: UnsafePointer?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) - -> Int32 + -> Int32 { // `tokenCallback` is @convention(c). This requires a little setup // in order to transfer context. @@ -122,57 +122,55 @@ extension FTS5WrapperTokenizer { 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 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") - } + + // 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 - } + + return SQLITE_OK + } catch let error as DatabaseError { + return error.extendedResultCode.rawValue + } catch { + return SQLITE_ERROR + } } } } diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift index ea6d35aa0..f3e30e209 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -94,7 +94,7 @@ extension DatabaseMigrator { extension DatabasePool { @available(*, unavailable, message: "Use pool.writeWithoutTransaction { $0.checkpoint() } instead") public func checkpoint(_ kind: Database.CheckpointMode = .passive) throws { preconditionFailure() } - + #if os(iOS) @available(*, unavailable, message: "Memory management is now enabled by default. This method does nothing.") public func setupMemoryManagement(in application: UIApplication) { preconditionFailure() } @@ -235,8 +235,8 @@ extension SQLRequest { _ db: Database, request: Request, cached: Bool = false) - throws - where Request: FetchRequest, Request.RowDecoder == RowDecoder + throws + where Request: FetchRequest, Request.RowDecoder == RowDecoder { preconditionFailure() } @available(*, unavailable, message: "Use makePreparedRequest(db).statement.sql instead") @@ -310,7 +310,7 @@ extension ValueObservation { Combined>( _ other: ValueObservation, _ transform: @escaping (Reducer.Value, R1.Value) -> Combined) - -> ValueObservation> + -> ValueObservation> { preconditionFailure() } @available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") @@ -321,7 +321,7 @@ extension ValueObservation { _ observation1: ValueObservation, _ observation2: ValueObservation, _ transform: @escaping (Reducer.Value, R1.Value, R2.Value) -> Combined) - -> ValueObservation> + -> ValueObservation> { preconditionFailure() } @available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") @@ -334,7 +334,7 @@ extension ValueObservation { _ observation2: ValueObservation, _ observation3: ValueObservation, _ transform: @escaping (Reducer.Value, R1.Value, R2.Value, R3.Value) -> Combined) - -> ValueObservation> + -> ValueObservation> { preconditionFailure() } @available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") @@ -349,7 +349,7 @@ extension ValueObservation { _ observation3: ValueObservation, _ observation4: ValueObservation, _ transform: @escaping (Reducer.Value, R1.Value, R2.Value, R3.Value, R4.Value) -> Combined) - -> ValueObservation> + -> ValueObservation> { preconditionFailure() } @available(*, unavailable, message: "compactMap is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") @@ -370,7 +370,7 @@ extension ValueObservation where Reducer == ValueReducers.Auto { R2: _ValueReducer>( _ o1: ValueObservation, _ o2: ValueObservation) - -> ValueObservation> + -> ValueObservation> { preconditionFailure() } @available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") @@ -381,7 +381,7 @@ extension ValueObservation where Reducer == ValueReducers.Auto { _ o1: ValueObservation, _ o2: ValueObservation, _ o3: ValueObservation) - -> ValueObservation> + -> ValueObservation> { preconditionFailure() } @available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") @@ -394,7 +394,7 @@ extension ValueObservation where Reducer == ValueReducers.Auto { _ o2: ValueObservation, _ o3: ValueObservation, _ o4: ValueObservation) - -> ValueObservation> + -> ValueObservation> { preconditionFailure() } @available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") @@ -409,7 +409,7 @@ extension ValueObservation where Reducer == ValueReducers.Auto { _ o3: ValueObservation, _ o4: ValueObservation, _ o5: ValueObservation) - -> ValueObservation> + -> ValueObservation> { preconditionFailure() } @available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") @@ -426,7 +426,7 @@ extension ValueObservation where Reducer == ValueReducers.Auto { _ o4: ValueObservation, _ o5: ValueObservation, _ o6: ValueObservation) - -> ValueObservation> + -> ValueObservation> { preconditionFailure() } @available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") @@ -445,7 +445,7 @@ extension ValueObservation where Reducer == ValueReducers.Auto { _ o5: ValueObservation, _ o6: ValueObservation, _ o7: ValueObservation) - -> ValueObservation> + -> ValueObservation> { preconditionFailure() } @available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") @@ -466,75 +466,75 @@ extension ValueObservation where Reducer == ValueReducers.Auto { _ o6: ValueObservation, _ o7: ValueObservation, _ o8: ValueObservation) - -> ValueObservation> + -> ValueObservation> { preconditionFailure() } @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") public static func trackingCount(_ request: Request) - -> ValueObservation> + -> ValueObservation> { preconditionFailure() } @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") public static func trackingAll(_ request: Request) - -> ValueObservation> - where Request.RowDecoder: DatabaseValueConvertible + -> ValueObservation> + where Request.RowDecoder: DatabaseValueConvertible { preconditionFailure() } @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") public static func trackingOne(_ request: Request) - -> ValueObservation> - where Request.RowDecoder: DatabaseValueConvertible + -> ValueObservation> + where Request.RowDecoder: DatabaseValueConvertible { preconditionFailure() } @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") public static func trackingAll(_ request: Request) - -> ValueObservation> - where Request.RowDecoder: _OptionalProtocol, - Request.RowDecoder.Wrapped: DatabaseValueConvertible + -> ValueObservation> + where Request.RowDecoder: _OptionalProtocol, + Request.RowDecoder.Wrapped: DatabaseValueConvertible { preconditionFailure() } @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") public static func trackingAll(_ request: Request) - -> ValueObservation> - where Request.RowDecoder: FetchableRecord + -> ValueObservation> + where Request.RowDecoder: FetchableRecord { preconditionFailure() } @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") public static func trackingOne(_ request: Request) -> - ValueObservation> - where Request.RowDecoder: FetchableRecord + ValueObservation> + where Request.RowDecoder: FetchableRecord { preconditionFailure() } @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") public static func trackingAll(_ request: Request) - -> ValueObservation> - where Request.RowDecoder == Row + -> ValueObservation> + where Request.RowDecoder == Row { preconditionFailure() } @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") public static func trackingOne(_ request: Request) - -> ValueObservation> - where Request.RowDecoder == Row + -> ValueObservation> + where Request.RowDecoder == Row { preconditionFailure() } @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") public static func tracking( _ regions: DatabaseRegionConvertible..., fetch: @escaping (Database) throws -> Value) - -> ValueObservation> + -> ValueObservation> { preconditionFailure() } @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") public static func tracking( _ regions: [DatabaseRegionConvertible], fetch: @escaping (Database) throws -> Value) - -> ValueObservation> + -> ValueObservation> { preconditionFailure() } @available(*, unavailable, renamed: "tracking(_:)") public static func tracking( value: @escaping (Database) throws -> Value) - -> ValueObservation> + -> ValueObservation> { preconditionFailure() } } diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index a2b80a3db..f4b3e471e 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -210,8 +210,8 @@ public struct DatabaseMigrator { let appliedIdentifiers = try appliedMigrations(db) let knownIdentifiers = migrations.map(\.identifier) return Array(zip(appliedIdentifiers, knownIdentifiers) - .prefix(while: { $0 == $1 }) - .map { $0.0 }) + .prefix(while: { $0 == $1 }) + .map { $0.0 }) } /// Returns true if all migrations are applied. @@ -266,9 +266,9 @@ public struct DatabaseMigrator { // Subsequent migration must not be applied if let targetIndex = migrations.firstIndex(where: { $0.identifier == targetIdentifier }), - let lastAppliedIdentifier = appliedIdentifiers.last, - let lastAppliedIndex = migrations.firstIndex(where: { $0.identifier == lastAppliedIdentifier }), - targetIndex < lastAppliedIndex + let lastAppliedIdentifier = appliedIdentifiers.last, + let lastAppliedIndex = migrations.firstIndex(where: { $0.identifier == lastAppliedIdentifier }), + targetIndex < lastAppliedIndex { fatalError("database is already migrated beyond migration \(String(reflecting: targetIdentifier))") } diff --git a/GRDB/Migration/Migration.swift b/GRDB/Migration/Migration.swift index cc47a79c8..c4cdccfe4 100644 --- a/GRDB/Migration/Migration.swift +++ b/GRDB/Migration/Migration.swift @@ -59,12 +59,12 @@ struct Migration { // > 11. Commit the transaction started in step 2. return .commit } - }, + }, finally: { // > 12. If foreign keys constraints were originally enabled, // > reenable them now. try db.execute(sql: "PRAGMA foreign_keys = ON") - }) + }) } private func insertAppliedIdentifier(_ db: Database) throws { diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index af082227d..0eb305a5f 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -6,7 +6,7 @@ typealias AssociationAggregatePreparation = extension AssociationToMany { private func makeAggregate(_ expressionPromise: DatabasePromise) - -> AssociationAggregate + -> AssociationAggregate { AssociationAggregate { request in let tableAlias = TableAlias() @@ -279,7 +279,7 @@ private func combine( _ lhs: AssociationAggregate, _ rhs: AssociationAggregate, with combineExpressions : @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) throws -> SQLExpression) - -> AssociationAggregate +-> AssociationAggregate { AssociationAggregate { request in let lhsPromise = lhs.prepare(&request) @@ -311,7 +311,7 @@ public prefix func ! (aggregate: AssociationAggregate) - public func && ( lhs: AssociationAggregate, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { combine(lhs, rhs, with: &&) } @@ -321,7 +321,7 @@ public func && ( public func && ( lhs: AssociationAggregate, rhs: SQLExpressible) - -> AssociationAggregate +-> AssociationAggregate { lhs.map { $0 && rhs } } @@ -331,7 +331,7 @@ public func && ( public func && ( lhs: SQLExpressible, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { rhs.map { lhs && $0 } } @@ -345,7 +345,7 @@ public func && ( public func || ( lhs: AssociationAggregate, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { combine(lhs, rhs, with: ||) } @@ -355,7 +355,7 @@ public func || ( public func || ( lhs: AssociationAggregate, rhs: SQLExpressible) - -> AssociationAggregate +-> AssociationAggregate { lhs.map { $0 || rhs } } @@ -365,7 +365,7 @@ public func || ( public func || ( lhs: SQLExpressible, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { rhs.map { lhs || $0 } } @@ -380,7 +380,7 @@ public func || ( public func == ( lhs: AssociationAggregate, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { combine(lhs, rhs, with: ==) } @@ -393,7 +393,7 @@ public func == ( public func == ( lhs: AssociationAggregate, rhs: SQLExpressible) - -> AssociationAggregate +-> AssociationAggregate { lhs.map { $0 == rhs } } @@ -406,7 +406,7 @@ public func == ( public func == ( lhs: SQLExpressible, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { rhs.map { lhs == $0 } } @@ -437,7 +437,7 @@ public func == (lhs: Bool, rhs: AssociationAggregate) -> public func != ( lhs: AssociationAggregate, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { combine(lhs, rhs, with: !=) } @@ -450,7 +450,7 @@ public func != ( public func != ( lhs: AssociationAggregate, rhs: SQLExpressible) - -> AssociationAggregate +-> AssociationAggregate { lhs.map { $0 != rhs } } @@ -463,7 +463,7 @@ public func != ( public func != ( lhs: SQLExpressible, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { rhs.map { lhs != $0 } } @@ -494,7 +494,7 @@ public func != (lhs: Bool, rhs: AssociationAggregate) -> public func === ( lhs: AssociationAggregate, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { combine(lhs, rhs, with: ===) } @@ -507,7 +507,7 @@ public func === ( public func === ( lhs: AssociationAggregate, rhs: SQLExpressible) - -> AssociationAggregate +-> AssociationAggregate { lhs.map { $0 === rhs } } @@ -520,7 +520,7 @@ public func === ( public func === ( lhs: SQLExpressible, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { rhs.map { lhs === $0 } } @@ -533,7 +533,7 @@ public func === ( public func !== ( lhs: AssociationAggregate, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { combine(lhs, rhs, with: !==) } @@ -546,7 +546,7 @@ public func !== ( public func !== ( lhs: AssociationAggregate, rhs: SQLExpressible) - -> AssociationAggregate +-> AssociationAggregate { lhs.map { $0 !== rhs } } @@ -559,7 +559,7 @@ public func !== ( public func !== ( lhs: SQLExpressible, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { rhs.map { lhs !== $0 } } @@ -574,7 +574,7 @@ public func !== ( public func <= ( lhs: AssociationAggregate, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { combine(lhs, rhs, with: <=) } @@ -587,7 +587,7 @@ public func <= ( public func <= ( lhs: AssociationAggregate, rhs: SQLExpressible) - -> AssociationAggregate +-> AssociationAggregate { lhs.map { $0 <= rhs } } @@ -600,7 +600,7 @@ public func <= ( public func <= ( lhs: SQLExpressible, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { rhs.map { lhs <= $0 } } @@ -613,7 +613,7 @@ public func <= ( public func < ( lhs: AssociationAggregate, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { combine(lhs, rhs, with: <) } @@ -626,7 +626,7 @@ public func < ( public func < ( lhs: AssociationAggregate, rhs: SQLExpressible) - -> AssociationAggregate +-> AssociationAggregate { lhs.map { $0 < rhs } } @@ -639,7 +639,7 @@ public func < ( public func < ( lhs: SQLExpressible, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { rhs.map { lhs < $0 } } @@ -652,7 +652,7 @@ public func < ( public func > ( lhs: AssociationAggregate, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { combine(lhs, rhs, with: >) } @@ -665,7 +665,7 @@ public func > ( public func > ( lhs: AssociationAggregate, rhs: SQLExpressible) - -> AssociationAggregate +-> AssociationAggregate { lhs.map { $0 > rhs } } @@ -678,7 +678,7 @@ public func > ( public func > ( lhs: SQLExpressible, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { rhs.map { lhs > $0 } } @@ -691,7 +691,7 @@ public func > ( public func >= ( lhs: AssociationAggregate, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { combine(lhs, rhs, with: >=) } @@ -704,7 +704,7 @@ public func >= ( public func >= ( lhs: AssociationAggregate, rhs: SQLExpressible) - -> AssociationAggregate +-> AssociationAggregate { lhs.map { $0 >= rhs } } @@ -717,7 +717,7 @@ public func >= ( public func >= ( lhs: SQLExpressible, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { rhs.map { lhs >= $0 } } @@ -741,7 +741,7 @@ public prefix func - (aggregate: AssociationAggregate) - public func + ( lhs: AssociationAggregate, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { combine(lhs, rhs, with: +) } @@ -754,7 +754,7 @@ public func + ( public func + ( lhs: AssociationAggregate, rhs: SQLExpressible) - -> AssociationAggregate +-> AssociationAggregate { lhs.map { $0 + rhs } } @@ -767,7 +767,7 @@ public func + ( public func + ( lhs: SQLExpressible, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { rhs.map { lhs + $0 } } @@ -780,7 +780,7 @@ public func + ( public func - ( lhs: AssociationAggregate, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { combine(lhs, rhs, with: -) } @@ -793,7 +793,7 @@ public func - ( public func - ( lhs: AssociationAggregate, rhs: SQLExpressible) - -> AssociationAggregate +-> AssociationAggregate { lhs.map { $0 - rhs } } @@ -806,7 +806,7 @@ public func - ( public func - ( lhs: SQLExpressible, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { rhs.map { lhs - $0 } } @@ -819,7 +819,7 @@ public func - ( public func * ( lhs: AssociationAggregate, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { combine(lhs, rhs, with: *) } @@ -832,7 +832,7 @@ public func * ( public func * ( lhs: AssociationAggregate, rhs: SQLExpressible) - -> AssociationAggregate +-> AssociationAggregate { lhs.map { $0 * rhs } } @@ -845,7 +845,7 @@ public func * ( public func * ( lhs: SQLExpressible, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { rhs.map { lhs * $0 } } @@ -858,7 +858,7 @@ public func * ( public func / ( lhs: AssociationAggregate, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { combine(lhs, rhs, with: /) } @@ -871,7 +871,7 @@ public func / ( public func / ( lhs: AssociationAggregate, rhs: SQLExpressible) - -> AssociationAggregate +-> AssociationAggregate { lhs.map { $0 / rhs } } @@ -884,7 +884,7 @@ public func / ( public func / ( lhs: SQLExpressible, rhs: AssociationAggregate) - -> AssociationAggregate +-> AssociationAggregate { rhs.map { lhs / $0 } } @@ -897,7 +897,7 @@ public func / ( public func ?? ( lhs: AssociationAggregate, rhs: SQLExpressible) - -> AssociationAggregate +-> AssociationAggregate { // Preserve key lhs.map { $0 ?? rhs }.with(\.key, lhs.key) diff --git a/GRDB/QueryInterface/Request/CommonTableExpression.swift b/GRDB/QueryInterface/Request/CommonTableExpression.swift index 2fb7cf61d..f3cded51e 100644 --- a/GRDB/QueryInterface/Request/CommonTableExpression.swift +++ b/GRDB/QueryInterface/Request/CommonTableExpression.swift @@ -244,7 +244,7 @@ extension TableRecord { { JoinAssociation(to: cte.relationForAll, condition: .expression(condition)) } - + /// Creates an association to a common table expression that you can join /// or include in another request. /// diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index f762e9e10..2c8fc9387 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -101,7 +101,7 @@ extension QueryInterfaceRequest: SelectionRequest { /// let maxScore: Int? = try request.fetchOne(db) /// } public func select(_ selection: [SQLSelectable], as type: RowDecoder.Type = RowDecoder.self) - -> QueryInterfaceRequest + -> QueryInterfaceRequest { map(\.query, { $0.select(selection) }).asRequest(of: RowDecoder.self) } @@ -115,7 +115,7 @@ extension QueryInterfaceRequest: SelectionRequest { /// let maxScore: Int? = try request.fetchOne(db) /// } public func select(_ selection: SQLSelectable..., as type: RowDecoder.Type = RowDecoder.self) - -> QueryInterfaceRequest + -> QueryInterfaceRequest { select(selection, as: type) } @@ -132,7 +132,7 @@ extension QueryInterfaceRequest: SelectionRequest { sql: String, arguments: StatementArguments = StatementArguments(), as type: RowDecoder.Type = RowDecoder.self) - -> QueryInterfaceRequest + -> QueryInterfaceRequest { select(literal: SQLLiteral(sql: sql, arguments: arguments), as: type) } @@ -167,7 +167,7 @@ extension QueryInterfaceRequest: SelectionRequest { public func select( literal sqlLiteral: SQLLiteral, as type: RowDecoder.Type = RowDecoder.self) - -> QueryInterfaceRequest + -> QueryInterfaceRequest { select(sqlLiteral.sqlSelectable, as: type) } @@ -396,9 +396,9 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord { { let conflictResolution = conflictResolution ?? RowDecoder.persistenceConflictPolicy.conflictResolutionForUpdate guard let updateStatement = try SQLQueryGenerator(query: query).makeUpdateStatement( - db, - conflictResolution: conflictResolution, - assignments: assignments) else + db, + conflictResolution: conflictResolution, + assignments: assignments) else { // database not hit return 0 @@ -429,7 +429,7 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord { onConflict conflictResolution: Database.ConflictResolution? = nil, _ assignment: ColumnAssignment, _ otherAssignments: ColumnAssignment...) - throws -> Int + throws -> Int { try updateAll(db, onConflict: conflictResolution, [assignment] + otherAssignments) } @@ -560,7 +560,7 @@ private func prefetch( .joinMapping(originIsLeft: originIsLeft) let pivotColumns = pivotMapping.map(\.right) let leftColumns = pivotMapping.map(\.left) - + // We want to avoid the "Expression tree is too large" SQLite error // when the foreign key contains several columns, and there are many // base rows that overflow SQLITE_LIMIT_EXPR_DEPTH: diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 19e229f12..1a4d028aa 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -244,8 +244,8 @@ extension TableRequest where Self: FilteredRequest { /// Creates a request with the provided primary key *predicate*. public func filter(keys: Sequence) - -> Self - where Sequence.Element: DatabaseValueConvertible + -> Self + where Sequence.Element: DatabaseValueConvertible { let keys = Array(keys) if keys.isEmpty { diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift index 42307942a..b2f9eec47 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -39,7 +39,7 @@ struct SQLExpressionNot: SQLExpression { case .false: return SQLExpressionEqual(.equal, self, false.sqlExpression) - + case .falsey: // Support `NOT (NOT expression)` as a technique to build 0 or 1 return SQLExpressionNot(self) @@ -726,10 +726,9 @@ struct SQLExpressionContains: SQLExpression { } func _identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set? { - if - let expressions = collection._collectionExpressions, - let column = try expression._column(db, for: alias), - try db.columnIsRowID(column, of: alias.tableName) + if let expressions = collection._collectionExpressions, + let column = try expression._column(db, for: alias), + try db.columnIsRowID(column, of: alias.tableName) { return Set(expressions.compactMap { ($0 as? DatabaseValue).flatMap { Int64.fromDatabaseValue($0) } @@ -776,7 +775,7 @@ struct SQLExpressionContains: SQLExpression { } if let expressions = collection._collectionExpressions, - expressions.contains(where: \._isAggregate) + expressions.contains(where: \._isAggregate) { // SELECT expr IN (aggregate, ...) return true @@ -914,9 +913,8 @@ struct SQLExpressionFunction: SQLExpression { var _isConstantInRequest: Bool { let function = self.function.uppercased() - guard - ((function == "MAX" || function == "MIN") && arguments.count > 1) - || Self.knownPureFunctions.contains(function) + guard ((function == "MAX" || function == "MIN") && arguments.count > 1) + || Self.knownPureFunctions.contains(function) else { return false // Don't know - assume not constant } diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 0be28f59d..7ff6f2fb7 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -135,7 +135,7 @@ public protocol _SQLExpression { /// /// This property supports `_identifyingColums(_:for:)` var _isConstantInRequest: Bool { get } - + /// Returns true iff the expression is trivially true. /// /// When in doubt, returns false. @@ -213,7 +213,7 @@ extension SQLExpression { /// :nodoc: public var _isConstantInRequest: Bool { false } - + /// :nodoc: public var _isTrue: Bool { false } @@ -236,7 +236,7 @@ extension SQLExpression { /// :nodoc: public func _columnCount(_ db: Database) throws -> Int { 1 } - + /// :nodoc: public func _count(distinct: Bool) -> _SQLCount? { if distinct { diff --git a/GRDB/QueryInterface/SQL/SQLQuery.swift b/GRDB/QueryInterface/SQL/SQLQuery.swift index 558177cc6..43c9e4751 100644 --- a/GRDB/QueryInterface/SQL/SQLQuery.swift +++ b/GRDB/QueryInterface/SQL/SQLQuery.swift @@ -138,7 +138,7 @@ extension SQLQuery { return try QueryInterfaceRequest(query: countQuery).fetchOne(db)! } } - + // SELECT COUNT(*) FROM (self) func fetchTrivialCount(_ db: Database) throws -> Int { let request = QueryInterfaceRequest(query: unordered()) diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 154e63e35..f7dd793b0 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -368,11 +368,11 @@ extension SQLRelation { func removingChildrenForPrefetchedAssociations() -> Self { filteringChildren { - switch $0.kind { - case .allPrefetched, .allNotPrefetched: return false - case .oneRequired, .oneOptional: return true - } - } + switch $0.kind { + case .allPrefetched, .allNotPrefetched: return false + case .oneRequired, .oneOptional: return true + } + } } } diff --git a/GRDB/QueryInterface/SQL/SQLRowValue.swift b/GRDB/QueryInterface/SQL/SQLRowValue.swift index 97c250f2e..c35b47f43 100644 --- a/GRDB/QueryInterface/SQL/SQLRowValue.swift +++ b/GRDB/QueryInterface/SQL/SQLRowValue.swift @@ -57,7 +57,7 @@ struct SQLRowValue: SQLExpression { return false } - + func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { SQLRowValue(expressions.map { $0._qualifiedExpression(with: alias) }) } diff --git a/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift index 8c585f9c2..7f445252a 100644 --- a/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift @@ -109,7 +109,7 @@ struct SQLQualifiedAllColumns: SQLSelectable { } func _count(distinct: Bool) -> _SQLCount? { nil } - + func _countedSQL(_ context: SQLGenerationContext) throws -> String { if context.qualifier(for: alias) != nil { // SELECT COUNT(t.*) is invalid SQL @@ -143,7 +143,7 @@ struct SQLAliasedExpression: SQLSelectable { self.expression = expression self.name = name } - + func _columnCount(_ db: Database) throws -> Int { 1 } func _count(distinct: Bool) -> _SQLCount? { diff --git a/GRDB/QueryInterface/SQL/SQLSelectable.swift b/GRDB/QueryInterface/SQL/SQLSelectable.swift index 01f0933f0..ab486a373 100644 --- a/GRDB/QueryInterface/SQL/SQLSelectable.swift +++ b/GRDB/QueryInterface/SQL/SQLSelectable.swift @@ -19,7 +19,7 @@ public protocol _SQLSelectable { /// - parameter context: An SQL generation context which accepts /// statement arguments. func _countedSQL(_ context: SQLGenerationContext) throws -> String - + /// Returns true if the selectable is an aggregate. /// /// When in doubt, returns false. diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index 13121066e..b16b396ae 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -395,7 +395,7 @@ public class TableAlias: Hashable { public subscript(_ column: String) -> SQLExpression { Column(column)._qualifiedExpression(with: self) } - + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// An expression that evaluates to true if the record refered by this diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 2f316ba71..27867bbbc 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -213,7 +213,7 @@ struct SQLQueryGenerator: Refinable { selection: [SQLSelectable], filters: [SQLExpression], groupExpressions: [SQLExpression]) - throws -> Bool + throws -> Bool { if relation.joins.isEmpty == false { // Don't expect single results as soon as there is a join @@ -306,7 +306,7 @@ struct SQLQueryGenerator: Refinable { _ db: Database, conflictResolution: Database.ConflictResolution, assignments: [ColumnAssignment]) - throws -> UpdateStatement? + throws -> UpdateStatement? { switch try grouping(db) { case .none: @@ -374,7 +374,7 @@ struct SQLQueryGenerator: Refinable { _ db: Database, conflictResolution: Database.ConflictResolution, assignments: [ColumnAssignment]) - throws -> UpdateStatement? + throws -> UpdateStatement? { // Check for empty assignments after all programmer errors have // been checked. @@ -461,9 +461,7 @@ struct SQLQueryGenerator: Refinable { // Grouping something which is not a table: assume non unique grouping. let tableName = relation.source.tableName - guard - try db.tableExists(tableName) // skip views - else { + guard try db.tableExists(tableName) else { // skip views return .nonUnique } @@ -747,7 +745,7 @@ private struct SQLQualifiedJoin: Refinable { _ context: SQLGenerationContext, leftAlias: TableAlias, allowingInnerJoin allowsInnerJoin: Bool) - throws -> String + throws -> String { var allowsInnerJoin = allowsInnerJoin diff --git a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift index e53685a5f..f4326571e 100644 --- a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift @@ -8,7 +8,7 @@ extension SQLInterpolation { /// // SELECT * FROM player /// let request: SQLRequest = "SELECT * FROM \(Player.self)" public mutating func appendInterpolation(_ table: T.Type) - where T: TableRecord + where T: TableRecord { appendLiteral(table.databaseTableName.quotedDatabaseIdentifier) } @@ -28,7 +28,7 @@ extension SQLInterpolation { /// let player: Player = ... /// let request: SQLRequest = "INSERT INTO \(tableOf: player) ..." public mutating func appendInterpolation(tableOf record: T) - where T: TableRecord + where T: TableRecord { appendInterpolation(type(of: record)) } @@ -53,12 +53,12 @@ extension SQLInterpolation { /// let player: Player = ... /// let request: SQLRequest = "SELECT \(columnsOf: Player.self, tableAlias: "p") FROM player p" public mutating func appendInterpolation(columnsOf record: T.Type, tableAlias: String? = nil) - where T: TableRecord + where T: TableRecord { let alias = TableAlias(name: tableAlias ?? T.databaseTableName) elements.append(contentsOf: T.databaseSelection - .map { CollectionOfOne(.selectable($0._qualifiedSelectable(with: alias))) } - .joined(separator: CollectionOfOne(.sql(", ")))) + .map { CollectionOfOne(.selectable($0._qualifiedSelectable(with: alias))) } + .joined(separator: CollectionOfOne(.sql(", ")))) } // MARK: - SQLSelectable @@ -70,7 +70,7 @@ extension SQLInterpolation { /// SELECT \(AllColumns()) FROM player /// """ public mutating func appendInterpolation(_ selection: T) - where T: SQLSelectable + where T: SQLSelectable { elements.append(.selectable(selection)) } @@ -99,7 +99,7 @@ extension SQLInterpolation { /// SELECT * FROM player ORDER BY \(Column("name").desc) /// """ public mutating func appendInterpolation(_ orderingTerm: T) - where T: SQLOrderingTerm + where T: SQLOrderingTerm { elements.append(.orderingTerm(orderingTerm)) } @@ -114,7 +114,7 @@ extension SQLInterpolation { public mutating func appendInterpolation(_ orderingTerm: SQLOrderingTerm) { elements.append(.orderingTerm(orderingTerm)) } - + // MARK: - SQLExpressible /// Appends the expression SQL. @@ -124,7 +124,7 @@ extension SQLInterpolation { /// SELECT \(Column("name")) FROM player /// """ public mutating func appendInterpolation(_ expressible: T) - where T: SQLExpressible + where T: SQLExpressible { elements.append(.expression(expressible.sqlExpression)) } @@ -136,7 +136,7 @@ extension SQLInterpolation { /// SELECT \(Column("name")) FROM player /// """ public mutating func appendInterpolation(_ expressible: T) - where T: SQLExpressible & SQLSelectable & SQLOrderingTerm + where T: SQLExpressible & SQLSelectable & SQLOrderingTerm { elements.append(.expression(expressible.sqlExpression)) } @@ -165,7 +165,7 @@ extension SQLInterpolation { /// SELECT \(CodingKey.name) FROM player /// """ public mutating func appendInterpolation(_ key: T) - where T: CodingKey + where T: CodingKey { appendInterpolation(Column(key.stringValue)) } @@ -177,7 +177,7 @@ extension SQLInterpolation { /// SELECT \(CodingKey.name) FROM player /// """ public mutating func appendInterpolation(_ key: T) - where T: CodingKey & SQLExpressible & SQLSelectable & SQLOrderingTerm + where T: CodingKey & SQLExpressible & SQLSelectable & SQLOrderingTerm { appendInterpolation(Column(key.stringValue)) } @@ -206,7 +206,7 @@ extension SQLInterpolation { /// SELECT * FROM player WHERE score = (\(subquery)) /// """ public mutating func appendInterpolation(_ request: T) - where T: FetchRequest & SQLExpression + where T: FetchRequest & SQLExpression { elements.append(.subquery(DatabasePromise(value: request))) } @@ -229,7 +229,7 @@ extension SQLInterpolation { /// SELECT * FROM player WHERE id IN \(ids) /// """ public mutating func appendInterpolation(_ sequence: T) - where T: Sequence, T.Element: SQLExpressible + where T: Sequence, T.Element: SQLExpressible { appendInterpolation(sequence.lazy.map(\.sqlExpression)) } @@ -250,7 +250,7 @@ extension SQLInterpolation { /// SELECT * FROM player WHERE a IN \(expressions) /// """ public mutating func appendInterpolation(_ sequence: T) - where T: Sequence, T.Element == SQLExpression + where T: Sequence, T.Element == SQLExpression { let e: [SQLLiteral.Element] = sequence.map { .expression($0.sqlExpression) } if e.isEmpty { @@ -266,7 +266,7 @@ extension SQLInterpolation { // favor the expression side. Use case: Foundation.Data interpolation. /// :nodoc: public mutating func appendInterpolation(_ expressible: T) - where T: Sequence, T: SQLExpressible, T.Element: SQLExpressible + where T: Sequence, T: SQLExpressible, T.Element: SQLExpressible { elements.append(.expression(expressible.sqlExpression)) } diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index cd36fd66b..d7319ab0f 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -30,7 +30,7 @@ extension Database { ifNotExists: Bool = false, withoutRowID: Bool = false, body: (TableDefinition) -> Void) - throws + throws { let definition = TableDefinition( name: name, @@ -106,7 +106,7 @@ extension Database { unique: Bool = false, ifNotExists: Bool = false, condition: SQLExpressible? = nil) - throws + throws { let definition = IndexDefinition( name: name, @@ -225,7 +225,7 @@ public final class TableDefinition { public func autoIncrementedPrimaryKey( _ name: String, onConflict conflictResolution: Database.ConflictResolution? = nil) - -> ColumnDefinition + -> ColumnDefinition { column(name, .integer).primaryKey(onConflict: conflictResolution, autoincrement: true) } @@ -318,12 +318,12 @@ public final class TableDefinition { deferred: Bool = false) { foreignKeyConstraints.append(ForeignKeyConstraint( - columns: columns, - table: table, - destinationColumns: destinationColumns, - deleteAction: deleteAction, - updateAction: updateAction, - deferred: deferred)) + columns: columns, + table: table, + destinationColumns: destinationColumns, + deleteAction: deleteAction, + updateAction: updateAction, + deferred: deferred)) } /// Adds a CHECK constraint. @@ -667,7 +667,7 @@ public final class ColumnDefinition { public func primaryKey( onConflict conflictResolution: Database.ConflictResolution? = nil, autoincrement: Bool = false) - -> Self + -> Self { primaryKey = (conflictResolution: conflictResolution, autoincrement: autoincrement) return self @@ -908,11 +908,11 @@ public final class ColumnDefinition { deferred: Bool = false) -> Self { foreignKeyConstraints.append(ForeignKeyConstraint( - table: table, - column: column, - deleteAction: deleteAction, - updateAction: updateAction, - deferred: deferred)) + table: table, + column: column, + deleteAction: deleteAction, + updateAction: updateAction, + deferred: deferred)) return self } diff --git a/GRDB/QueryInterface/Schema/VirtualTableModule.swift b/GRDB/QueryInterface/Schema/VirtualTableModule.swift index 6534816b9..68299bce4 100644 --- a/GRDB/QueryInterface/Schema/VirtualTableModule.swift +++ b/GRDB/QueryInterface/Schema/VirtualTableModule.swift @@ -101,7 +101,7 @@ extension Database { ifNotExists: Bool = false, using module: Module, _ body: ((Module.TableDefinition) -> Void)? = nil) - throws + throws { // Define virtual table let definition = module.makeTableDefinition() diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index 986da99cf..8c64ba39f 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -59,7 +59,7 @@ extension TableRecord { _ destination: Destination.Type, key: String? = nil, using foreignKey: ForeignKey? = nil) - -> BelongsToAssociation + -> BelongsToAssociation { BelongsToAssociation(key: key, using: foreignKey) } @@ -124,7 +124,7 @@ extension TableRecord { _ destination: Destination.Type, key: String? = nil, using foreignKey: ForeignKey? = nil) - -> HasManyAssociation + -> HasManyAssociation { HasManyAssociation(key: key, using: foreignKey) } @@ -195,11 +195,11 @@ extension TableRecord { through pivot: Pivot, using target: Target, key: String? = nil) - -> HasManyThroughAssociation - where Pivot: Association, - Target: Association, - Pivot.OriginRowDecoder == Self, - Pivot.RowDecoder == Target.OriginRowDecoder + -> HasManyThroughAssociation + where Pivot: Association, + Target: Association, + Pivot.OriginRowDecoder == Self, + Pivot.RowDecoder == Target.OriginRowDecoder { let association = HasManyThroughAssociation( sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation)) @@ -271,7 +271,7 @@ extension TableRecord { _ destination: Destination.Type, key: String? = nil, using foreignKey: ForeignKey? = nil) - -> HasOneAssociation + -> HasOneAssociation { HasOneAssociation(key: key, using: foreignKey) } @@ -342,11 +342,11 @@ extension TableRecord { through pivot: Pivot, using target: Target, key: String? = nil) - -> HasOneThroughAssociation - where Pivot: AssociationToOne, - Target: AssociationToOne, - Pivot.OriginRowDecoder == Self, - Pivot.RowDecoder == Target.OriginRowDecoder + -> HasOneThroughAssociation + where Pivot: AssociationToOne, + Target: AssociationToOne, + Pivot.OriginRowDecoder == Self, + Pivot.RowDecoder == Target.OriginRowDecoder { let association = HasOneThroughAssociation( sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation)) @@ -483,8 +483,8 @@ 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 + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self { switch association._sqlAssociation.pivot.condition { case .expression: @@ -515,8 +515,8 @@ extension TableRecord { /// Creates a request that prefetches an association. public static func including(all association: A) - -> QueryInterfaceRequest - where A.OriginRowDecoder == Self + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self { all().including(all: association) } @@ -525,8 +525,8 @@ extension TableRecord { /// 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 + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self { all().including(optional: association) } @@ -535,8 +535,8 @@ extension TableRecord { /// 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 + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self { all().including(required: association) } @@ -545,8 +545,8 @@ extension TableRecord { /// 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 + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self { all().joining(optional: association) } @@ -555,8 +555,8 @@ extension TableRecord { /// 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 + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self { all().joining(required: association) } diff --git a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift index b2299d55a..c19907517 100644 --- a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift @@ -48,7 +48,7 @@ extension TableRecord { public static func select( sql: String, arguments: StatementArguments = StatementArguments()) - -> QueryInterfaceRequest + -> QueryInterfaceRequest { select(literal: SQLLiteral(sql: sql, arguments: arguments)) } @@ -72,7 +72,7 @@ extension TableRecord { public static func select( _ selection: [SQLSelectable], as type: RowDecoder.Type = RowDecoder.self) - -> QueryInterfaceRequest + -> QueryInterfaceRequest { all().select(selection, as: type) } @@ -88,7 +88,7 @@ extension TableRecord { public static func select( _ selection: SQLSelectable..., as type: RowDecoder.Type = RowDecoder.self) - -> QueryInterfaceRequest + -> QueryInterfaceRequest { all().select(selection, as: type) } @@ -105,7 +105,7 @@ extension TableRecord { sql: String, arguments: StatementArguments = StatementArguments(), as type: RowDecoder.Type = RowDecoder.self) - -> QueryInterfaceRequest + -> QueryInterfaceRequest { all().select(literal: SQLLiteral(sql: sql, arguments: arguments), as: type) } @@ -121,7 +121,7 @@ extension TableRecord { public static func select( literal sqlLiteral: SQLLiteral, as type: RowDecoder.Type = RowDecoder.self) - -> QueryInterfaceRequest + -> QueryInterfaceRequest { all().select(literal: sqlLiteral, as: type) } @@ -183,8 +183,8 @@ extension TableRecord { /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. public static func filter(key: PrimaryKeyType?) - -> QueryInterfaceRequest - where PrimaryKeyType: DatabaseValueConvertible + -> QueryInterfaceRequest + where PrimaryKeyType: DatabaseValueConvertible { all().filter(key: key) } @@ -198,8 +198,8 @@ extension TableRecord { /// 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: Swift.Sequence, Sequence.Element: DatabaseValueConvertible + -> QueryInterfaceRequest + where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible { all().filter(keys: keys) } @@ -245,7 +245,7 @@ extension TableRecord { public static func filter( sql: String, arguments: StatementArguments = StatementArguments()) - -> QueryInterfaceRequest + -> QueryInterfaceRequest { filter(literal: SQLLiteral(sql: sql, arguments: arguments)) } @@ -320,7 +320,7 @@ extension TableRecord { public static func order( sql: String, arguments: StatementArguments = StatementArguments()) - -> QueryInterfaceRequest + -> QueryInterfaceRequest { all().order(literal: SQLLiteral(sql: sql, arguments: arguments)) } diff --git a/GRDB/Record/EncodableRecord+Encodable.swift b/GRDB/Record/EncodableRecord+Encodable.swift index e50491e26..5d02b751c 100644 --- a/GRDB/Record/EncodableRecord+Encodable.swift +++ b/GRDB/Record/EncodableRecord+Encodable.swift @@ -101,7 +101,7 @@ private class RecordEncoder: Encoder { func nestedContainer( keyedBy keyType: NestedKey.Type, forKey key: Key) - -> KeyedEncodingContainer + -> KeyedEncodingContainer { fatalError("Not implemented") } @@ -264,8 +264,8 @@ private struct JSONRequiredEncoder: Encoder { func nestedContainer( keyedBy keyType: NestedKey.Type, forKey key: KeyType) - -> KeyedEncodingContainer - where NestedKey: CodingKey + -> KeyedEncodingContainer + where NestedKey: CodingKey { let container = KeyedContainer(codingPath: codingPath + [key]) return KeyedEncodingContainer(container) @@ -308,8 +308,8 @@ extension JSONRequiredEncoder: UnkeyedEncodingContainer { var count: Int { 0 } mutating func nestedContainer(keyedBy keyType: NestedKey.Type) - -> KeyedEncodingContainer - where NestedKey: CodingKey + -> KeyedEncodingContainer + where NestedKey: CodingKey { let container = KeyedContainer(codingPath: codingPath) return KeyedEncodingContainer(container) diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index 72fb9aeb4..373379a30 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -212,7 +212,7 @@ private struct _RowDecoder: Decoder { } func nestedContainer(keyedBy type: NestedKey.Type, forKey key: Key) - throws -> KeyedDecodingContainer where NestedKey: CodingKey + throws -> KeyedDecodingContainer where NestedKey: CodingKey { fatalError("not implemented") } @@ -239,8 +239,8 @@ private struct _RowDecoder: Decoder { _ type: T.Type, fromRow row: Row, codingPath: [CodingKey]) - throws -> T - where T: Decodable + throws -> T + where T: Decodable { if let type = T.self as? FetchableRecord.Type { // Prefer FetchableRecord decoding over Decodable. @@ -265,8 +265,8 @@ private struct _RowDecoder: Decoder { fromRow row: Row, columnAtIndex index: Int, key: Key) - throws -> T - where T: Decodable + throws -> T + where T: Decodable { do { // This decoding will fail for types that decode from keyed @@ -333,8 +333,8 @@ extension PrefetchedRowsDecoder: UnkeyedDecodingContainer { } mutating func nestedContainer(keyedBy type: NestedKey.Type) - throws -> KeyedDecodingContainer - where NestedKey: CodingKey + throws -> KeyedDecodingContainer + where NestedKey: CodingKey { fatalError("not implemented") } @@ -498,7 +498,7 @@ extension DatabaseDateDecodingStrategy { fileprivate func decode( from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) - -> Date + -> Date { if let date = dateFromDatabaseValue(dbValue) { return date @@ -511,7 +511,7 @@ extension DatabaseDateDecodingStrategy { fileprivate func decodeIfPresent( from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) - -> Date? + -> Date? { if dbValue.isNull { return nil diff --git a/GRDB/Record/FetchableRecord+TableRecord.swift b/GRDB/Record/FetchableRecord+TableRecord.swift index b6f5268a6..313dac39e 100644 --- a/GRDB/Record/FetchableRecord+TableRecord.swift +++ b/GRDB/Record/FetchableRecord+TableRecord.swift @@ -95,8 +95,8 @@ extension FetchableRecord where Self: TableRecord { /// - 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: Swift.Sequence, Sequence.Element: DatabaseValueConvertible + throws -> RecordCursor + where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible { try filter(keys: keys).fetchCursor(db) } @@ -113,8 +113,8 @@ extension FetchableRecord where Self: TableRecord { /// - 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: Swift.Sequence, Sequence.Element: DatabaseValueConvertible + throws -> [Self] + where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible { let keys = Array(keys) if keys.isEmpty { @@ -134,8 +134,8 @@ extension FetchableRecord where Self: TableRecord { /// - returns: An optional record. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ db: Database, key: PrimaryKeyType?) - throws -> Self? - where PrimaryKeyType: DatabaseValueConvertible + throws -> Self? + where PrimaryKeyType: DatabaseValueConvertible { guard let key = key else { // Avoid hitting the database @@ -156,8 +156,8 @@ extension FetchableRecord where Self: TableRecord & Hashable { /// - returns: A set of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchSet(_ db: Database, keys: Sequence) - throws -> Set - where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible + throws -> Set + where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible { let keys = Array(keys) if keys.isEmpty { @@ -191,7 +191,7 @@ extension FetchableRecord where Self: TableRecord { /// - 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 + throws -> RecordCursor { try filter(keys: keys).fetchCursor(db) } diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 1b51b297f..5c423bfe0 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -155,7 +155,7 @@ extension FetchableRecord { _ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) - throws -> RecordCursor + throws -> RecordCursor { try RecordCursor(statement: statement, arguments: arguments, adapter: adapter) } @@ -175,7 +175,7 @@ extension FetchableRecord { _ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) - throws -> [Self] + throws -> [Self] { try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } @@ -195,7 +195,7 @@ extension FetchableRecord { _ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) - throws -> Self? + throws -> Self? { try fetchCursor(statement, arguments: arguments, adapter: adapter).next() } @@ -217,7 +217,7 @@ extension FetchableRecord where Self: Hashable { _ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) - throws -> Set + throws -> Set { try Set(fetchCursor(statement, arguments: arguments, adapter: adapter)) } @@ -251,7 +251,7 @@ extension FetchableRecord { sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) - throws -> RecordCursor + throws -> RecordCursor { try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -272,7 +272,7 @@ extension FetchableRecord { sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) - throws -> [Self] + throws -> [Self] { try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -293,7 +293,7 @@ extension FetchableRecord { sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) - throws -> Self? + throws -> Self? { try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -316,7 +316,7 @@ extension FetchableRecord where Self: Hashable { sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) - throws -> Set + throws -> Set { try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index d603215da..a616b5c53 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -220,8 +220,8 @@ extension MutablePersistableRecord { /// 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: Swift.Sequence, Sequence.Element: ColumnExpression + throws + where Sequence: Swift.Sequence, Sequence.Element: ColumnExpression { try update(db, columns: Set(columns.map(\.name))) } @@ -234,8 +234,8 @@ extension MutablePersistableRecord { /// 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: Swift.Sequence, Sequence.Element == String + throws + where Sequence: Swift.Sequence, Sequence.Element == String { try update(db, columns: Set(columns)) } @@ -398,13 +398,12 @@ extension MutablePersistableRecord { @inlinable public func performUpdate(_ db: Database, columns: Set) throws { let dao = try DAO(db, self) - guard - let statement = try dao.updateStatement( + guard let statement = try dao.updateStatement( columns: columns, onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) - else { - // Nil primary key - throw dao.makeRecordNotFoundError() + else { + // Nil primary key + throw dao.makeRecordNotFoundError() } try statement.execute() if db.changesCount == 0 { @@ -541,7 +540,7 @@ extension MutablePersistableRecord { _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, _ assignments: [ColumnAssignment]) - throws -> Int + throws -> Int { try all().updateAll(db, onConflict: conflictResolution, assignments) } @@ -568,7 +567,7 @@ extension MutablePersistableRecord { onConflict conflictResolution: Database.ConflictResolution? = nil, _ assignment: ColumnAssignment, _ otherAssignments: ColumnAssignment...) - throws -> Int + throws -> Int { try updateAll(db, onConflict: conflictResolution, [assignment] + otherAssignments) } @@ -599,8 +598,8 @@ extension MutablePersistableRecord { /// - returns: The number of deleted rows @discardableResult public static func deleteAll(_ db: Database, keys: Sequence) - throws -> Int - where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible + throws -> Int + where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible { let keys = Array(keys) if keys.isEmpty { @@ -631,8 +630,8 @@ extension MutablePersistableRecord { /// - returns: Whether a database row was deleted. @discardableResult public static func deleteOne(_ db: Database, key: PrimaryKeyType?) - throws -> Bool - where PrimaryKeyType: DatabaseValueConvertible + throws -> Bool + where PrimaryKeyType: DatabaseValueConvertible { guard let key = key else { // Avoid hitting the database @@ -1022,16 +1021,16 @@ extension UpdateQuery { switch onConflict { case .abort: sql = """ - UPDATE \(tableName.quotedDatabaseIdentifier) \ - SET \(updateSQL) \ - WHERE \(whereSQL) - """ + UPDATE \(tableName.quotedDatabaseIdentifier) \ + SET \(updateSQL) \ + WHERE \(whereSQL) + """ default: sql = """ - UPDATE OR \(onConflict.rawValue) \(tableName.quotedDatabaseIdentifier) \ - SET \(updateSQL) \ - WHERE \(whereSQL) - """ + UPDATE OR \(onConflict.rawValue) \(tableName.quotedDatabaseIdentifier) \ + SET \(updateSQL) \ + WHERE \(whereSQL) + """ } Self.sqlCache[self] = sql return sql diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 1ec5052df..2fefeb07e 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -274,13 +274,12 @@ 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( + guard let statement = try dao.updateStatement( columns: columns, onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) - else { - // Nil primary key - throw dao.makeRecordNotFoundError() + else { + // Nil primary key + throw dao.makeRecordNotFoundError() } try statement.execute() if db.changesCount == 0 { diff --git a/GRDB/Utils/Inflections+English.swift b/GRDB/Utils/Inflections+English.swift index 815d659db..dc5b18874 100644 --- a/GRDB/Utils/Inflections+English.swift +++ b/GRDB/Utils/Inflections+English.swift @@ -122,7 +122,7 @@ extension Inflections { "rice", "sheep", "species", - ]) + ]) inflections.irregularSuffix("child", "children") inflections.irregularSuffix("foot", "feet") diff --git a/GRDB/Utils/LockedBox.swift b/GRDB/Utils/LockedBox.swift index a1bd933d9..37e3f0bbf 100644 --- a/GRDB/Utils/LockedBox.swift +++ b/GRDB/Utils/LockedBox.swift @@ -38,7 +38,7 @@ extension LockedBox where T: Numeric { return n } } - + @discardableResult func decrement() -> T { update { n in diff --git a/GRDB/Utils/OnDemandFuture.swift b/GRDB/Utils/OnDemandFuture.swift index bf37fafee..a43985051 100644 --- a/GRDB/Utils/OnDemandFuture.swift +++ b/GRDB/Utils/OnDemandFuture.swift @@ -107,7 +107,7 @@ private class OnDemandFutureSubscription: Subscription { sideEffect = { downstream.receive(completion: completion) } - + case .waitingForDemand, .finished: break } diff --git a/GRDB/Utils/ReceiveValuesOn.swift b/GRDB/Utils/ReceiveValuesOn.swift index 36a315aca..fa06c35b7 100644 --- a/GRDB/Utils/ReceiveValuesOn.swift +++ b/GRDB/Utils/ReceiveValuesOn.swift @@ -32,7 +32,7 @@ struct ReceiveValuesOn: Publisher { @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) private class ReceiveValuesOnSubscription: Subscription, Subscriber - where +where Upstream: Publisher, Context: Scheduler, Downstream: Subscriber, @@ -107,7 +107,7 @@ private class ReceiveValuesOnSubscription: Subscr } } } - + // MARK: Subscriber func receive(subscription: Subscription) { @@ -130,9 +130,9 @@ private class ReceiveValuesOnSubscription: Subscr switch state { case let .subscribed(target, _): sideEffect = { - target.context.schedule(options: target.options) { - self._receive(input) - } + target.context.schedule(options: target.options) { + self._receive(input) + } } case .waitingForRequest, .waitingForSubscription, .finished: break @@ -154,9 +154,9 @@ private class ReceiveValuesOnSubscription: Subscr break case let .subscribed(target, _): sideEffect = { - target.context.schedule(options: target.options) { - self._receive(completion: completion) - } + target.context.schedule(options: target.options) { + self._receive(completion: completion) + } } case .finished: break @@ -172,7 +172,7 @@ private class ReceiveValuesOnSubscription: Subscr case let .subscribed(target, _): // TODO: don't ignore demand sideEffect = { - _ = target.downstream.receive(input) + _ = target.downstream.receive(input) } case .finished: break diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index 8f27fc9af..64ecfd58b 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -171,26 +171,26 @@ extension NSRecursiveLock { func synchronized( _ message: @autoclosure () -> String = #function, _ block: () throws -> T) - rethrows -> T + rethrows -> T { lock() defer { unlock() } return try block() } -// // Verbose version which helps understanding locking bugs -// func synchronized(_ message: @autoclosure () -> String = "", _ block: () throws -> T) rethrows -> T { -// let queueName = String(validatingUTF8: __dispatch_queue_get_label(nil)) -// print("\(queueName ?? "n/d"): \(message()) acquiring \(self)") -// lock() -// print("\(queueName ?? "n/d"): \(message()) acquired \(self)") -// defer { -// print("\(queueName ?? "n/d"): \(message()) releasing \(self)") -// unlock() -// print("\(queueName ?? "n/d"): \(message()) released \(self)") -// } -// return try block() -// } + // // Verbose version which helps understanding locking bugs + // func synchronized(_ message: @autoclosure () -> String = "", _ block: () throws -> T) rethrows -> T { + // let queueName = String(validatingUTF8: __dispatch_queue_get_label(nil)) + // print("\(queueName ?? "n/d"): \(message()) acquiring \(self)") + // lock() + // print("\(queueName ?? "n/d"): \(message()) acquired \(self)") + // defer { + // print("\(queueName ?? "n/d"): \(message()) releasing \(self)") + // unlock() + // print("\(queueName ?? "n/d"): \(message()) released \(self)") + // } + // return try block() + // } /// Performs the side effect outside of the synchronized block. This allows /// avoiding deadlocks, when the side effect feedbacks. diff --git a/GRDB/ValueObservation/DatabaseCancellable.swift b/GRDB/ValueObservation/DatabaseCancellable.swift index 66926d45b..eaaa271f6 100644 --- a/GRDB/ValueObservation/DatabaseCancellable.swift +++ b/GRDB/ValueObservation/DatabaseCancellable.swift @@ -22,7 +22,7 @@ public class AnyDatabaseCancellable: DatabaseCancellable { public convenience init(_ cancellable: DatabaseCancellable) { self.init(cancel: cancellable.cancel) } - + deinit { _cancel?() } diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 9f9fbe6d3..a7950f933 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -144,7 +144,7 @@ extension ValueObservation: Refinable { didReceiveValue: ((Reducer.Value) -> Void)? = nil, didFail: ((Error) -> Void)? = nil, didCancel: (() -> Void)? = nil) - -> ValueObservation> + -> ValueObservation> { self .mapReducer({ reducer in @@ -171,7 +171,7 @@ extension ValueObservation: Refinable { public func print( _ prefix: String = "", to stream: TextOutputStream? = nil) - -> ValueObservation> + -> ValueObservation> { let prefix = prefix.isEmpty ? "" : "\(prefix): " var stream = stream ?? PrintOutputStream() @@ -245,7 +245,7 @@ extension ValueObservation { public func publisher( in reader: DatabaseReader, scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main)) - -> DatabasePublishers.Value + -> DatabasePublishers.Value { return DatabasePublishers.Value(self, in: reader, scheduling: scheduler) } @@ -268,7 +268,7 @@ extension DatabasePublishers { _ observation: ValueObservation, in reader: DatabaseReader, scheduling scheduler: ValueObservationScheduler) - where Reducer.Value == Output + where Reducer.Value == Output { start = { [weak reader] (onError, onChange) in guard let reader = reader else { @@ -291,7 +291,7 @@ extension DatabasePublishers { } private class ValueSubscription: Subscription - where Downstream.Failure == Error + where Downstream.Failure == Error { private struct WaitingForDemand { let downstream: Downstream @@ -326,8 +326,8 @@ extension DatabasePublishers { downstream: Downstream) { state = .waitingForDemand(WaitingForDemand( - downstream: downstream, - start: start)) + downstream: downstream, + start: start)) } func request(_ demand: Subscribers.Demand) { @@ -338,8 +338,8 @@ extension DatabasePublishers { return } state = .observing(Observing( - downstream: info.downstream, - remainingDemand: demand)) + downstream: info.downstream, + remainingDemand: demand)) let cancellable = info.start( { [weak self] error in self?.receiveCompletion(.failure(error)) }, { [weak self] value in self?.receive(value) }) @@ -378,7 +378,7 @@ extension DatabasePublishers { private func receive(_ value: Downstream.Input) { lock.synchronized { if case let .observing(info) = state, - info.remainingDemand > .none + info.remainingDemand > .none { let additionalDemand = info.downstream.receive(value) if case var .observing(info) = state { @@ -481,7 +481,7 @@ extension ValueObservation where Reducer == ValueReducers.Auto { /// the database. public static func trackingConstantRegion( _ fetch: @escaping (Database) throws -> Value) - -> ValueObservation> + -> ValueObservation> { .init(makeReducer: { .init(isSelectedRegionDeterministic: true, fetch: fetch) }) } @@ -506,7 +506,7 @@ extension ValueObservation where Reducer == ValueReducers.Auto { /// the database. public static func tracking( _ fetch: @escaping (Database) throws -> Value) - -> ValueObservation> + -> ValueObservation> { .init(makeReducer: { .init(isSelectedRegionDeterministic: false, fetch: fetch) }) } @@ -532,7 +532,7 @@ extension ValueObservation where Reducer == ValueReducers.Auto { @available(*, deprecated, renamed: "tracking(_:)") public static func trackingVaryingRegion( _ fetch: @escaping (Database) throws -> Value) - -> ValueObservation> + -> ValueObservation> { tracking(fetch) } diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift index 3503aaab3..75f788563 100644 --- a/GRDB/ValueObservation/ValueObserver.swift +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -7,10 +7,9 @@ final class ValueObserver { let events: ValueObservationEvents private var observedRegion: DatabaseRegion? { didSet { - if - let willTrackRegion = events.willTrackRegion, - let region = observedRegion, - region != oldValue + if let willTrackRegion = events.willTrackRegion, + let region = observedRegion, + region != oldValue { willTrackRegion(region) } @@ -206,7 +205,7 @@ extension ValueObserver { private func recordingSelectedRegionIfNeeded( _ db: Database, fetch: () throws -> T) - throws -> T + throws -> T { guard needsRecordingSelectedRegion else { return try fetch() diff --git a/GRDB/ValueObservation/ValueReducer/Map.swift b/GRDB/ValueObservation/ValueReducer/Map.swift index 89659b694..43fa98828 100644 --- a/GRDB/ValueObservation/ValueReducer/Map.swift +++ b/GRDB/ValueObservation/ValueReducer/Map.swift @@ -3,7 +3,7 @@ extension ValueObservation { /// given transformation which each element notified by this /// value observation. public func map(_ transform: @escaping (Reducer.Value) -> T) - -> ValueObservation> + -> ValueObservation> { mapReducer { ValueReducers.Map($0, transform) } } diff --git a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift b/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift index 0282de898..10dbb04a9 100644 --- a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift +++ b/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift @@ -2,7 +2,7 @@ extension ValueObservation where Reducer.Value: Equatable { /// Returns a ValueObservation which filters out consecutive equal values. public func removeDuplicates() - -> ValueObservation> + -> ValueObservation> { mapReducer { ValueReducers.RemoveDuplicates($0) } }