From 9aa67f9db938bc3081f5f068874a7411c78e4788 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 8 Mar 2020 21:34:26 +0100 Subject: [PATCH 1/5] SE-0255: Implicit returns from single-expression functions --- Documentation/AssociationsBasics.md | 31 ++-- .../GRDBDemoiOS/GRDBDemoiOS/Player.swift | 8 +- .../GRDBDemoiOS/PlayersViewController.swift | 2 +- Documentation/FTS5Tokenizers.md | 2 +- Documentation/FetchedRecordsController.md | 4 +- .../GoodPracticesForDesigningRecordTypes.md | 20 +-- .../Associations.playground/Contents.swift | 8 +- .../Contents.swift | 24 ++-- .../Issue156.playground/Contents.swift | 2 +- .../Contents.swift | 4 +- Documentation/SQLInterpolation.md | 28 ++-- Documentation/WhyAdoptGRDB.md | 2 +- GRDB/Core/Cursor.swift | 30 ++-- GRDB/Core/Database+Schema.swift | 16 +-- GRDB/Core/Database+Statements.swift | 16 +-- GRDB/Core/Database.swift | 4 +- GRDB/Core/DatabaseError.swift | 22 +-- GRDB/Core/DatabaseFunction.swift | 6 +- GRDB/Core/DatabasePool.swift | 17 +-- GRDB/Core/DatabaseQueue.swift | 18 +-- GRDB/Core/DatabaseReader.swift | 8 +- GRDB/Core/DatabaseRegion.swift | 8 +- GRDB/Core/DatabaseRegionObservation.swift | 2 +- GRDB/Core/DatabaseSchemaCache.swift | 8 +- GRDB/Core/DatabaseSnapshot.swift | 10 +- GRDB/Core/DatabaseValue.swift | 8 +- GRDB/Core/DatabaseValueConversion.swift | 8 +- GRDB/Core/DatabaseValueConvertible.swift | 12 +- GRDB/Core/DatabaseWriter.swift | 20 +-- GRDB/Core/FetchRequest.swift | 12 +- GRDB/Core/Row.swift | 122 +++++++--------- GRDB/Core/RowAdapter.swift | 44 +++--- GRDB/Core/SQLLiteral.swift | 22 +-- GRDB/Core/SQLRequest.swift | 4 +- GRDB/Core/SchedulingWatchdog.swift | 4 +- GRDB/Core/SerializedDatabase.swift | 6 +- GRDB/Core/Statement.swift | 12 +- GRDB/Core/StatementColumnConvertible.swift | 10 +- GRDB/Core/Support/CoreGraphics/CGFloat.swift | 2 +- GRDB/Core/Support/Foundation/Data.swift | 2 +- ...alueConvertible+ReferenceConvertible.swift | 4 +- GRDB/Core/Support/Foundation/Date.swift | 4 +- GRDB/Core/Support/Foundation/NSData.swift | 2 +- GRDB/Core/Support/Foundation/NSNull.swift | 8 +- GRDB/Core/Support/Foundation/NSString.swift | 2 +- .../Support/Foundation/SQLiteDateParser.swift | 2 +- GRDB/Core/Support/Foundation/URL.swift | 2 +- GRDB/Core/Support/Foundation/UUID.swift | 2 +- .../DatabaseValueConvertible+Decodable.swift | 10 +- .../DatabaseValueConvertible+Encodable.swift | 6 +- ...aseValueConvertible+RawRepresentable.swift | 4 +- .../StandardLibrary/StandardLibrary.swift | 46 +++--- GRDB/Core/TransactionObserver.swift | 58 ++++---- GRDB/FTS/FTS3.swift | 2 +- GRDB/FTS/FTS3Pattern.swift | 4 +- GRDB/FTS/FTS3TokenizerDescriptor.swift | 4 +- GRDB/FTS/FTS4.swift | 2 +- GRDB/FTS/FTS5.swift | 2 +- GRDB/FTS/FTS5CustomTokenizer.swift | 2 +- GRDB/FTS/FTS5Pattern.swift | 6 +- GRDB/FTS/FTS5Tokenizer.swift | 2 +- GRDB/FTS/FTS5TokenizerDescriptor.swift | 6 +- GRDB/Migration/DatabaseMigrator.swift | 2 +- GRDB/QueryInterface/FTS3+QueryInterface.swift | 4 +- GRDB/QueryInterface/FTS5+QueryInterface.swift | 2 +- .../Request/Association/Association.swift | 40 +++--- .../Association/AssociationAggregate.swift | 16 +-- .../QueryInterfaceRequest+Association.swift | 4 +- .../Request/QueryInterfaceRequest.swift | 50 +++---- .../Request/RequestProtocols.swift | 38 ++--- GRDB/QueryInterface/SQL/Column.swift | 8 +- GRDB/QueryInterface/SQL/DatabasePromise.swift | 4 +- GRDB/QueryInterface/SQL/SQLAssociation.swift | 16 +-- .../SQL/SQLCollatedExpression.swift | 16 +-- GRDB/QueryInterface/SQL/SQLCollection.swift | 4 +- GRDB/QueryInterface/SQL/SQLExpressible.swift | 12 +- .../SQL/SQLExpression+QueryInterface.swift | 38 ++--- GRDB/QueryInterface/SQL/SQLExpression.swift | 14 +- GRDB/QueryInterface/SQL/SQLFunctions.swift | 32 ++--- GRDB/QueryInterface/SQL/SQLOperators.swift | 134 +++++++++--------- GRDB/QueryInterface/SQL/SQLQuery.swift | 34 ++--- GRDB/QueryInterface/SQL/SQLRelation.swift | 48 +++---- .../SQL/SQLSelectable+QueryInterface.swift | 24 ++-- ...QLSpecificExpressible+QueryInterface.swift | 16 +-- .../SQLGeneration/SQLGenerationContext.swift | 12 +- .../SQLGeneration/SQLQueryGenerator.swift | 19 ++- .../TableRecord+Association.swift | 6 +- .../TableRecord+QueryInterfaceRequest.swift | 30 ++-- GRDB/Record/EncodableRecord+Encodable.swift | 46 +++--- GRDB/Record/EncodableRecord.swift | 28 ++-- GRDB/Record/FetchableRecord+Decodable.swift | 88 +++++------- GRDB/Record/FetchableRecord+TableRecord.swift | 6 +- GRDB/Record/FetchableRecord.swift | 10 +- GRDB/Record/FetchedRecordsController.swift | 4 +- GRDB/Record/PersistableRecord.swift | 12 +- GRDB/Record/Record.swift | 8 +- GRDB/Record/TableRecord.swift | 6 +- GRDB/Utils/Inflections.swift | 12 +- GRDB/Utils/LockedBox.swift | 6 +- GRDB/Utils/OrderedDictionary.swift | 27 ++-- GRDB/Utils/Pool.swift | 4 +- GRDB/Utils/ReadWriteBox.swift | 10 +- GRDB/Utils/Utils.swift | 6 +- ...Observation+DatabaseValueConvertible.swift | 14 +- .../ValueObservation+FetchableRecord.swift | 10 +- .../ValueObservation+Row.swift | 8 +- GRDB/ValueObservation/ValueObserver.swift | 2 +- .../ValueReducer/Combine.swift | 14 +- .../ValueReducer/CompactMap.swift | 4 +- .../ValueObservation/ValueReducer/Fetch.swift | 4 +- GRDB/ValueObservation/ValueReducer/Map.swift | 4 +- .../ValueReducer/RemoveDuplicates.swift | 4 +- .../ValueReducer/ValueReducer.swift | 4 +- README.md | 28 ++-- .../DatabaseValueConvertibleCrashTests.swift | 4 +- Tests/Crash/RecordCrashTests.swift | 12 +- Tests/GRDBTests/AnyCursorTests.swift | 4 +- ...ciationBelongsToDecodableRecordTests.swift | 2 +- .../GRDBTests/CompilationProtocolTests.swift | 4 +- .../GRDBTests/CompilationSubClassTests.swift | 8 +- Tests/GRDBTests/DatabaseAggregateTests.swift | 98 ++++--------- .../DatabaseDateDecodingStrategyTests.swift | 4 +- .../DatabaseDateEncodingStrategyTests.swift | 4 +- Tests/GRDBTests/DatabaseFunctionTests.swift | 4 +- Tests/GRDBTests/DatabaseSavepointTests.swift | 6 +- Tests/GRDBTests/DatabaseSnapshotTests.swift | 4 +- Tests/GRDBTests/DatabaseTimestampTests.swift | 2 +- .../DatabaseUUIDEncodingStrategyTests.swift | 4 +- .../DatabaseValueConvertibleFetchTests.swift | 4 +- ...atabaseValueConvertibleSubclassTests.swift | 12 +- Tests/GRDBTests/DerivableRequestTests.swift | 32 ++--- .../GRDBTests/FTS5WrapperTokenizerTests.swift | 6 +- Tests/GRDBTests/FetchRequestTests.swift | 22 ++- .../FetchableRecordDecodableTests.swift | 4 +- .../FetchedRecordsControllerTests.swift | 2 +- Tests/GRDBTests/GRDBTestCase.swift | 10 +- Tests/GRDBTests/InflectionsTests.swift | 4 +- Tests/GRDBTests/JoinSupportTests.swift | 10 +- ...MutablePersistableRecordChangesTests.swift | 2 +- ...tablePersistableRecordEncodableTests.swift | 2 +- ...RecordPersistenceConflictPolicyTests.swift | 4 +- .../QueryInterfaceExtensibilityTests.swift | 6 +- .../QueryInterfaceRequestTests.swift | 2 +- .../Record+QueryInterfaceRequestTests.swift | 2 +- Tests/GRDBTests/RecordEditedTests.swift | 4 +- .../RecordMinimalPrimaryKeyRowIDTests.swift | 2 +- .../RecordMinimalPrimaryKeySingleTests.swift | 2 +- .../RecordPersistenceConflictPolicy.swift | 2 +- .../RecordPrimaryKeyHiddenRowIDTests.swift | 4 +- .../RecordPrimaryKeyMultipleTests.swift | 2 +- .../GRDBTests/RecordPrimaryKeyNoneTests.swift | 2 +- .../RecordPrimaryKeyRowIDTests.swift | 2 +- .../RecordPrimaryKeySingleTests.swift | 2 +- ...leWithReplaceConflictResolutionTests.swift | 2 +- Tests/GRDBTests/RecordSubClassTests.swift | 2 +- .../RecordWithColumnNameManglingTests.swift | 2 +- Tests/GRDBTests/SQLLiteralTests.swift | 8 +- Tests/GRDBTests/SQLRequestTests.swift | 30 ++-- Tests/GRDBTests/SelectStatementTests.swift | 2 +- ...StatementColumnConvertibleFetchTests.swift | 4 +- Tests/GRDBTests/TableRecordTests.swift | 22 ++- .../TransactionObserverSavepointsTests.swift | 6 +- .../GRDBTests/TransactionObserverTests.swift | 26 +--- .../GRDBTests/TruncateOptimizationTests.swift | 6 +- ...rvationDatabaseValueConvertibleTests.swift | 4 +- .../ValueObservationRecordTests.swift | 4 +- Tests/GRDBTests/VirtualTableModuleTests.swift | 4 +- .../GRDBPerformance/PerformanceTests.swift | 2 +- .../GRDBProfiling/AppDelegate.swift | 8 +- 169 files changed, 990 insertions(+), 1208 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index f95ce9c3b..d48e2a5d9 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -91,14 +91,14 @@ With GRDB associations, we can streamline these operations (and others), by decl extension Author { static let books = hasMany(Book.self) var books: QueryInterfaceRequest { - return request(for: Author.books) + request(for: Author.books) } } extension Book { static let author = belongsTo(Author.self) var author: QueryInterfaceRequest { - return request(for: Book.author) + request(for: Book.author) } } ``` @@ -165,7 +165,7 @@ Generally speaking, associations use the [TableRecord], [FetchableRecord], and [ extension Book: EncodableRecord { // The request for the author of a book. var author: QueryInterfaceRequest { - return request(for: Book.author) + request(for: Book.author) } } @@ -327,7 +327,7 @@ As in the examples above, **HasManyThrough** association is always built from tw ```swift struct Document: TableRecord { static let paragraphs = hasMany( - Paragraph.self, + Paragraph.self, through: Document.hasMany(Section.self), using: Section.hasMany(Paragraph.self)) ... @@ -785,7 +785,7 @@ struct Book: TableRecord, EncodableRecord { /// The request for the author of a book var author: QueryInterfaceRequest { - return request(for: Book.author) + request(for: Book.author) } } ``` @@ -806,7 +806,7 @@ struct Author: TableRecord, EncodableRecord { /// The request for the books of an author var books: QueryInterfaceRequest { - return request(for: Author.books) + request(for: Author.books) } } @@ -1140,7 +1140,7 @@ extension Team { static let players = hasMany(Player.self).order(Column("position")) var players: QueryInterfaceRequest { - return request(for: Team.players) + request(for: Team.players) } } ``` @@ -1174,7 +1174,7 @@ extension Team { static let players = hasMany(Player.self, through: playerRoles, using: PlayerRole.player) var players: QueryInterfaceRequest { - return request(for: Team.players) + request(for: Team.players) } } @@ -1383,7 +1383,7 @@ For example, we can start by defining base requests as extensions to the [Deriva extension DerivableRequest where RowDecoder == Author { /// Filters authors by country func filter(country: String) -> Self { - return filter(Column("country") == country) + filter(Column("country") == country) } } @@ -1391,7 +1391,7 @@ extension DerivableRequest where RowDecoder == Author { extension DerivableRequest where RowDecoder == Book { /// Filters books by author country func filter(authorCountry: String) -> Self { - return joining(required: Book.author.filter(country: country)) + joining(required: Book.author.filter(country: country)) } /// Order books by author name and then book title @@ -1610,8 +1610,7 @@ And who is the most able to know those coding keys? BookInfo itself, thanks to i ```swift extension BookInfo { static func all() -> QueryInterfaceRequest { - return Book - .including(optional: Book.coverImage) + Book.including(optional: Book.coverImage) .including(required: Book.author .forKey(CodingKeys.authorInfo) // (1) .including(optional: Person.country)) @@ -1758,7 +1757,7 @@ When you need to compute aggregates **from a single record**, you use [regular a struct Author: TableRecord, EncodableRecord { static let books = hasMany(Book.self) var books: QueryInterfaceRequest { - return request(for: Author.books) + request(for: Author.books) } } @@ -2306,17 +2305,17 @@ Those methods are defined on extensions to the `DerivableRequest` protocol: ```swift extension DerivableRequest where RowDecoder == Author { func filter(country: String) -> Self { - return filter(Column("country") == country) + filter(Column("country") == country) } func orderedByName() -> Self { - return order(Column("name").collating(.localizedCaseInsensitiveCompare)) + order(Column("name").collating(.localizedCaseInsensitiveCompare)) } } extension DerivableRequest where RowDecoder == Book { func filter(country: String) -> Self { - return joining(required: Book.author.filter(country: country)) + joining(required: Book.author.filter(country: country)) } } ``` diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift index 0cb38bdd9..57994da4f 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift @@ -35,11 +35,11 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord { // See https://github.com/groue/GRDB.swift/blob/master/README.md#requests extension Player { static func orderedByName() -> QueryInterfaceRequest { - return Player.order(Columns.name) + Player.order(Columns.name) } static func orderedByScore() -> QueryInterfaceRequest { - return Player.order(Columns.score.desc, Columns.name) + Player.order(Columns.score.desc, Columns.name) } } @@ -57,10 +57,10 @@ extension Player { "Zazie", "ZoĆ©"] static func randomName() -> String { - return names.randomElement()! + names.randomElement()! } static func randomScore() -> Int { - return 10 * Int.random(in: 0...100) + 10 * Int.random(in: 0...100) } } diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift index 764f4771e..3463931ff 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift @@ -174,7 +174,7 @@ extension PlayersViewController { extension PlayersViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - return players.count + players.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { diff --git a/Documentation/FTS5Tokenizers.md b/Documentation/FTS5Tokenizers.md index c7b42b3f4..12e5fdc77 100644 --- a/Documentation/FTS5Tokenizers.md +++ b/Documentation/FTS5Tokenizers.md @@ -313,7 +313,7 @@ final class SynonymsTokenizer : FTS5WrapperTokenizer { } func synonyms(for token: String) -> Set? { - return synonyms.first { $0.contains(token) } + synonyms.first { $0.contains(token) } } func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws { diff --git a/Documentation/FetchedRecordsController.md b/Documentation/FetchedRecordsController.md index f61851d18..8f8ff42d1 100644 --- a/Documentation/FetchedRecordsController.md +++ b/Documentation/FetchedRecordsController.md @@ -227,11 +227,11 @@ The table view data source asks the fetched records controller to provide releva ```swift func numberOfSections(in tableView: UITableView) -> Int { - return fetchedRecordsController.sections.count + fetchedRecordsController.sections.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - return fetchedRecordsController.sections[section].numberOfRecords + fetchedRecordsController.sections[section].numberOfRecords } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 5824e3788..7ebd92353 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -197,7 +197,7 @@ extension DerivableRequest where RowDecoder == Author { /// Returns a request for all authors from a country func filter(country: String) -> Self { - return filter(Author.Columns.country == country) + filter(Author.Columns.country == country) } } ``` @@ -249,7 +249,7 @@ Not *every requests* can be expressed on `DerivableRequest`. For example, [Assoc extension QueryInterfaceRequest where RowDecoder == Author { /// Returns a request for all authors with at least one book func havingBooks() -> QueryInterfaceRequest { - return having(Author.books.isEmpty == false) + having(Author.books.isEmpty == false) } } ``` @@ -388,14 +388,14 @@ A last extension on your record types will further help navigation from records extension Author { /// The request for the author's books var books: QueryInterfaceRequest { - return request(for: Author.books) + request(for: Author.books) } } extension Book { /// The request for the author of the book var author: QueryInterfaceRequest { - return request(for: Book.author) + request(for: Book.author) } } ``` @@ -530,19 +530,19 @@ class ImprovedLibraryManager { } func author(id: Int64) throws -> Author? { - return try dbQueue.read { db in + try dbQueue.read { db in try Author.fetchOne(db, key: id) } } func book(id: Int64) throws -> Book? { - return try dbQueue.read { db in + try dbQueue.read { db in try Book.fetchOne(db, key: id) } } func books(writtenBy author: Author) throws -> [Book] { - return try dbQueue.read { db in + try dbQueue.read { db in try author.books.fetchAll(db) } } @@ -593,7 +593,7 @@ extension LibraryManager { } func authorList() throws -> [AuthorListItem] { - return try dbQueue.read { db in + try dbQueue.read { db in let request = Author .annotated(with: Author.books.count) .orderByName() @@ -610,7 +610,7 @@ extension LibraryManager { } func bookInfo(bookId: Int64) throws -> BookInfo? { - return try dbQueue.read { db in + try dbQueue.read { db in guard let book = try Book.fetchOne(db, key: bookId) else { return nil } @@ -630,7 +630,7 @@ extension LibraryManager { } func authorInfo(authorId: Int64) throws -> AuthorInfo? { - return try dbQueue.read { db in + try dbQueue.read { db in guard let author = try Author.fetchOne(db, key: authorId) else { return nil } diff --git a/Documentation/Playgrounds/Associations.playground/Contents.swift b/Documentation/Playgrounds/Associations.playground/Contents.swift index 95a45f867..d9e39f640 100644 --- a/Documentation/Playgrounds/Associations.playground/Contents.swift +++ b/Documentation/Playgrounds/Associations.playground/Contents.swift @@ -61,16 +61,12 @@ struct Book: Codable, FetchableRecord, MutablePersistableRecord { extension Author { static let books = hasMany(Book.self) - var books: QueryInterfaceRequest { - return request(for: Author.books) - } + var books: QueryInterfaceRequest { request(for: Author.books) } } extension Book { static let author = belongsTo(Author.self) - var author: QueryInterfaceRequest { - return request(for: Book.author) - } + var author: QueryInterfaceRequest { request(for: Book.author) } } //: Populate the database diff --git a/Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift b/Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift index d5a9e4acb..fb5ee1a6a 100644 --- a/Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift +++ b/Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift @@ -47,13 +47,13 @@ import GRDB //: Everything starts from our class hierarchy: class Base { - var description: String { return "Base" } + var description: String { "Base" } init() { } } class Foo: Base { var name: String - override var description: String { return "Foo: \(name)" } + override var description: String { "Foo: \(name)" } init(name: String) { self.name = name super.init() @@ -62,7 +62,7 @@ class Foo: Base { class Bar: Base { var score: Int - override var description: String { return "Bar: \(score)" } + override var description: String { "Bar: \(score)" } init(score: Int) { self.score = score super.init() @@ -302,15 +302,15 @@ extension FetchRequest where RowDecoder: MyDatabaseDecoder { // MARK: - FetchRequest fetching methods func fetchCursor(_ db: Database) throws -> MapCursor { - return try RowDecoder.fetchCursor(db, self) + try RowDecoder.fetchCursor(db, self) } func fetchAll(_ db: Database) throws -> [RowDecoder.DecodedType] { - return try RowDecoder.fetchAll(db, self) + try RowDecoder.fetchAll(db, self) } func fetchOne(_ db: Database) throws -> RowDecoder.DecodedType? { - return try RowDecoder.fetchOne(db, self) + try RowDecoder.fetchOne(db, self) } } @@ -335,15 +335,15 @@ extension MyDatabaseDecoder where Self: TableRecord { // MARK: - Static fetching methods static func fetchCursor(_ db: Database) throws -> MapCursor { - return try all().fetchCursor(db) + try all().fetchCursor(db) } static func fetchAll(_ db: Database) throws -> [DecodedType] { - return try all().fetchAll(db) + try all().fetchAll(db) } static func fetchOne(_ db: Database) throws -> DecodedType? { - return try all().fetchOne(db) + try all().fetchOne(db) } } @@ -366,15 +366,15 @@ extension MyDatabaseDecoder { // MARK: - Fetch from SQL static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> MapCursor { - return try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) + try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [DecodedType] { - return try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) + try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DecodedType? { - return try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) + try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } } diff --git a/Documentation/Playgrounds/Issue156.playground/Contents.swift b/Documentation/Playgrounds/Issue156.playground/Contents.swift index 60c89dbc7..eadcc2129 100644 --- a/Documentation/Playgrounds/Issue156.playground/Contents.swift +++ b/Documentation/Playgrounds/Issue156.playground/Contents.swift @@ -79,7 +79,7 @@ class TestDeleteAll: NSObject { struct MyRecord: FetchableRecord, TableRecord, PersistableRecord { static let MyColumn = Column("MyColumn") - static var databaseTableName: String { return String(describing: self) } + static var databaseTableName: String { String(describing: self) } let myColumn: String diff --git a/Documentation/Playgrounds/TransactionObserver.playground/Contents.swift b/Documentation/Playgrounds/TransactionObserver.playground/Contents.swift index e5aa0429a..da446d81d 100644 --- a/Documentation/Playgrounds/TransactionObserver.playground/Contents.swift +++ b/Documentation/Playgrounds/TransactionObserver.playground/Contents.swift @@ -34,9 +34,7 @@ try! migrator.migrate(dbQueue) class TableChangeObserver : NSObject, TransactionObserver { private var changedTableNames: Set = [] - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - return true - } + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { true } func databaseDidChange(with event: DatabaseEvent) { changedTableNames.insert(event.tableName) diff --git a/Documentation/SQLInterpolation.md b/Documentation/SQLInterpolation.md index 259648c60..841f2a5f0 100644 --- a/Documentation/SQLInterpolation.md +++ b/Documentation/SQLInterpolation.md @@ -184,25 +184,25 @@ extension Player: Decodable, FetchableRecord, TableRecord { /// The player with a given id static func filter(id: Int64) -> SQLRequest { - return "SELECT * FROM \(self) WHERE \(CodingKeys.id) = \(id)" + "SELECT * FROM \(self) WHERE \(CodingKeys.id) = \(id)" } /// All players with the given ids static func filter(ids: [Int64]) -> SQLRequest { - return "SELECT * FROM \(self) WHERE \(CodingKeys.id) IN \(ids)" + "SELECT * FROM \(self) WHERE \(CodingKeys.id) IN \(ids)" } /// The maximum score static func maximumScore() -> SQLRequest { - return "SELECT MAX(\(CodingKeys.score)) FROM \(self)" + "SELECT MAX(\(CodingKeys.score)) FROM \(self)" } /// All players whose score is the maximum score static func leaders() -> SQLRequest { - return """ - SELECT * FROM \(self) - WHERE \(CodingKeys.score) = \(maximumScore()) - """ + """ + SELECT * FROM \(self) + WHERE \(CodingKeys.score) = \(maximumScore()) + """ } /// A complex request @@ -247,7 +247,7 @@ Let's breakdown each one of those methods. extension Player: Decodable, FetchableRecord, TableRecord { /// The player with a given id static func filter(id: Int64) -> SQLRequest { - return "SELECT * FROM \(self) WHERE \(CodingKeys.id) = \(id)" + "SELECT * FROM \(self) WHERE \(CodingKeys.id) = \(id)" } } ``` @@ -271,7 +271,7 @@ Let's breakdown each one of those methods. extension Player: Decodable, FetchableRecord, TableRecord { /// All players with the given ids static func filter(ids: [Int64]) -> SQLRequest { - return "SELECT * FROM \(self) WHERE \(CodingKeys.id) IN \(ids)" + "SELECT * FROM \(self) WHERE \(CodingKeys.id) IN \(ids)" } } ``` @@ -293,7 +293,7 @@ Let's breakdown each one of those methods. extension Player: Decodable, FetchableRecord, TableRecord { /// The maximum score static func maximumScore() -> SQLRequest { - return "SELECT MAX(\(CodingKeys.score)) FROM \(self)" + "SELECT MAX(\(CodingKeys.score)) FROM \(self)" } } ``` @@ -315,10 +315,10 @@ Let's breakdown each one of those methods. extension Player: Decodable, FetchableRecord, TableRecord { /// All players whose score is the maximum score static func leaders() -> SQLRequest { - return """ - SELECT * FROM \(self) - WHERE \(CodingKeys.score) = \(maximumScore()) - """ + """ + SELECT * FROM \(self) + WHERE \(CodingKeys.score) = \(maximumScore()) + """ } } ``` diff --git a/Documentation/WhyAdoptGRDB.md b/Documentation/WhyAdoptGRDB.md index 54a7f4dad..91a6604aa 100644 --- a/Documentation/WhyAdoptGRDB.md +++ b/Documentation/WhyAdoptGRDB.md @@ -246,7 +246,7 @@ try db.execute(literal: "UPDATE player SET score = \(score) WHERE id = \(id)") extension Player { static func filter(name: String) -> SQLRequest { - return "SELECT * FROM \(self) WHERE \(CodingKeys.name) = \(name)" + "SELECT * FROM player WHERE name = \(name)" } } diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index 95705d5a2..806286759 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -92,7 +92,7 @@ extension Cursor { /// Returns a Boolean value indicating whether the cursor contains /// an element. public func isEmpty() throws -> Bool { - return try next() == nil + try next() == nil } /// Returns a Boolean value indicating whether the cursor contains an @@ -123,12 +123,12 @@ extension Cursor { /// // Prints: "0: foo" /// // Prints: "1: bar" public func enumerated() -> EnumeratedCursor { - return EnumeratedCursor(self) + EnumeratedCursor(self) } /// Returns the elements of the cursor that satisfy the given predicate. public func filter(_ isIncluded: @escaping (Element) throws -> Bool) -> FilterCursor { - return FilterCursor(self, isIncluded) + FilterCursor(self, isIncluded) } /// Returns the first element of the cursor that satisfies the given @@ -158,7 +158,7 @@ extension Cursor { /// `false` otherwise. Once `predicate` returns `false` it will not be /// called again. public func drop(while predicate: @escaping (Element) throws -> Bool) -> DropWhileCursor { - return DropWhileCursor(self, predicate: predicate) + DropWhileCursor(self, predicate: predicate) } /// Returns a cursor containing all but the given number of initial @@ -178,7 +178,7 @@ extension Cursor { /// - Returns: A cursor starting after the specified number of /// elements. public func dropFirst(_ n: Int) -> DropFirstCursor { - return DropFirstCursor(self, limit: n) + DropFirstCursor(self, limit: n) } /// Returns a cursor containing all but the first element of the cursor. @@ -193,7 +193,7 @@ extension Cursor { /// /// - Returns: A cursor starting after the first element of the cursor. public func dropFirst() -> DropFirstCursor { - return dropFirst(1) + dropFirst(1) } /// Returns an array containing all but the given number of final @@ -243,7 +243,7 @@ extension Cursor { /// /// - Returns: An array leaving off the last element of the cursor. public func dropLast() throws -> [Element] { - return try dropLast(1) + try dropLast(1) } /// Returns a cursor over the concatenated results of mapping transform @@ -274,7 +274,7 @@ extension Cursor { /// Returns a cursor over the results of the transform function applied to /// this cursor's elements. public func map(_ transform: @escaping (Element) throws -> T) -> MapCursor { - return MapCursor(self, transform) + MapCursor(self, transform) } /// Returns the maximum element in the cursor, using the given predicate as @@ -334,7 +334,7 @@ extension Cursor { /// - Returns: A cursor starting at the beginning of this cursor /// with at most `maxLength` elements. public func prefix(_ maxLength: Int) -> PrefixCursor { - return PrefixCursor(self, maxLength: maxLength) + PrefixCursor(self, maxLength: maxLength) } /// Returns a cursor of the initial consecutive elements that satisfy @@ -345,7 +345,7 @@ extension Cursor { /// `false` otherwise. Once `predicate` returns `false` it will not be /// called again. public func prefix(while predicate: @escaping (Element) throws -> Bool) -> PrefixWhileCursor { - return PrefixWhileCursor(self, predicate: predicate) + PrefixWhileCursor(self, predicate: predicate) } /// Returns the result of calling the given combining closure with each @@ -448,7 +448,7 @@ extension Cursor where Element: Comparable { /// `areInIncreasingOrder`. If the cursor has no elements, returns /// `nil`. public func max() throws -> Element? { - return try max(by: <) + try max(by: <) } /// Returns the minimum element in the cursor. @@ -460,7 +460,7 @@ extension Cursor where Element: Comparable { /// `areInIncreasingOrder`. If the cursor has no elements, returns /// `nil`. public func min() throws -> Element? { - return try min(by: <) + try min(by: <) } } @@ -469,7 +469,7 @@ extension Cursor where Element: Comparable { extension Cursor where Element: Cursor { /// Returns the elements of this cursor of cursors, concatenated. public func joined() -> FlattenCursor { - return FlattenCursor(self) + FlattenCursor(self) } } @@ -478,7 +478,7 @@ extension Cursor where Element: Cursor { extension Cursor where Element: Sequence { /// Returns the elements of this cursor of sequences, concatenated. public func joined() -> FlattenCursor>> { - return flatMap { $0 } + flatMap { $0 } } } @@ -545,7 +545,7 @@ public final class AnyCursor: Cursor { /// element exists. /// :nodoc: public func next() throws -> Element? { - return try element() + try element() } } diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index a84d00721..f9402ba52 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -28,7 +28,7 @@ extension Database { /// Returns whether a table exists. public func tableExists(_ name: String) throws -> Bool { - return try exists(type: .table, name: name) + try exists(type: .table, name: name) } /// Returns whether a table is an internal SQLite table. @@ -50,17 +50,17 @@ extension Database { /// /// Those are tables whose name begins with "grdb_". public func isGRDBInternalTable(_ tableName: String) -> Bool { - return tableName.starts(with: "grdb_") + tableName.starts(with: "grdb_") } /// Returns whether a view exists. public func viewExists(_ name: String) throws -> Bool { - return try exists(type: .view, name: name) + try exists(type: .view, name: name) } /// Returns whether a trigger exists. public func triggerExists(_ name: String) throws -> Bool { - return try exists(type: .trigger, name: name) + try exists(type: .trigger, name: name) } private func exists(type: SchemaObjectType, name: String) throws -> Bool { @@ -531,7 +531,7 @@ public struct PrimaryKeyInfo { private let impl: Impl static func rowID(_ column: String) -> PrimaryKeyInfo { - return PrimaryKeyInfo(impl: .rowID(column)) + PrimaryKeyInfo(impl: .rowID(column)) } static func regular(_ columns: [String]) -> PrimaryKeyInfo { @@ -589,12 +589,12 @@ public struct ForeignKeyInfo { /// The origin columns public var originColumns: [String] { - return mapping.map(\.origin) + mapping.map(\.origin) } /// The destination columns public var destinationColumns: [String] { - return mapping.map(\.destination) + mapping.map(\.destination) } } @@ -618,7 +618,7 @@ struct SchemaInfo: Equatable { /// All names for a given type func names(ofType type: SchemaObjectType) -> Set { - return objects.reduce(into: []) { (set, key) in + objects.reduce(into: []) { (set, key) in if key.type == type.rawValue { set.insert(key.name) } diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 6384c8751..20811e695 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -21,7 +21,7 @@ extension Database { /// - returns: A SelectStatement. /// - throws: A DatabaseError whenever SQLite could not parse the sql query. public func makeSelectStatement(sql: String) throws -> SelectStatement { - return try makeSelectStatement(sql: sql, prepFlags: 0) + try makeSelectStatement(sql: sql, prepFlags: 0) } /// Returns a new prepared statement that can be reused. @@ -36,7 +36,7 @@ extension Database { /// - returns: A SelectStatement. /// - throws: A DatabaseError whenever SQLite could not parse the sql query. func makeSelectStatement(sql: String, prepFlags: Int32) throws -> SelectStatement { - return try SelectStatement.prepare(self, sql: sql, prepFlags: prepFlags) + try SelectStatement.prepare(self, sql: sql, prepFlags: prepFlags) } /// Returns a prepared statement that can be reused. @@ -52,12 +52,12 @@ extension Database { /// - returns: An UpdateStatement. /// - throws: A DatabaseError whenever SQLite could not parse the sql query. public func cachedSelectStatement(sql: String) throws -> SelectStatement { - return try publicStatementCache.selectStatement(sql) + try publicStatementCache.selectStatement(sql) } /// Returns a cached statement that does not conflict with user's cached statements. func internalCachedSelectStatement(sql: String) throws -> SelectStatement { - return try internalStatementCache.selectStatement(sql) + try internalStatementCache.selectStatement(sql) } /// Returns a new prepared statement that can be reused. @@ -70,7 +70,7 @@ extension Database { /// - returns: An UpdateStatement. /// - throws: A DatabaseError whenever SQLite could not parse the sql query. public func makeUpdateStatement(sql: String) throws -> UpdateStatement { - return try makeUpdateStatement(sql: sql, prepFlags: 0) + try makeUpdateStatement(sql: sql, prepFlags: 0) } /// Returns a new prepared statement that can be reused. @@ -85,7 +85,7 @@ extension Database { /// - returns: An UpdateStatement. /// - throws: A DatabaseError whenever SQLite could not parse the sql query. func makeUpdateStatement(sql: String, prepFlags: Int32) throws -> UpdateStatement { - return try UpdateStatement.prepare(self, sql: sql, prepFlags: prepFlags) + try UpdateStatement.prepare(self, sql: sql, prepFlags: prepFlags) } /// Returns a prepared statement that can be reused. @@ -101,12 +101,12 @@ extension Database { /// - returns: An UpdateStatement. /// - throws: A DatabaseError whenever SQLite could not parse the sql query. public func cachedUpdateStatement(sql: String) throws -> UpdateStatement { - return try publicStatementCache.updateStatement(sql) + try publicStatementCache.updateStatement(sql) } /// Returns a cached statement that does not conflict with user's cached statements. func internalCachedUpdateStatement(sql: String) throws -> UpdateStatement { - return try internalStatementCache.updateStatement(sql) + try internalStatementCache.updateStatement(sql) } /// Executes one or several SQL statements, separated by semi-colons. diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 02abfcf55..fd13ca932 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -126,10 +126,10 @@ public final class Database { lazy var publicStatementCache = StatementCache(database: self) /// The last error code - public var lastErrorCode: ResultCode { return ResultCode(rawValue: sqlite3_errcode(sqliteConnection)) } + public var lastErrorCode: ResultCode { ResultCode(rawValue: sqlite3_errcode(sqliteConnection)) } /// The last error message - public var lastErrorMessage: String? { return String(cString: sqlite3_errmsg(sqliteConnection)) } + public var lastErrorMessage: String? { String(cString: sqlite3_errmsg(sqliteConnection)) } /// Statement authorizer. Use withAuthorizer(_:_:). fileprivate var _authorizer: StatementAuthorizer? diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index 3d2caea51..47c371ed1 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -20,12 +20,10 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible { /// let resultCode = .SQLITE_CONSTRAINT_FOREIGNKEY /// resultCode.primaryResultCode == .SQLITE_CONSTRAINT // true public var primaryResultCode: ResultCode { - return ResultCode(rawValue: rawValue & 0xFF) + ResultCode(rawValue: rawValue & 0xFF) } - var isPrimary: Bool { - return self == primaryResultCode - } + var isPrimary: Bool { self == primaryResultCode } /// Returns true if the code on the left matches the code on the right. /// @@ -159,7 +157,7 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible { // CustomStringConvertible extension ResultCode { var errorString: String? { - return String(cString: sqlite3_errstr(rawValue)) + String(cString: sqlite3_errstr(rawValue)) } /// :nodoc: @@ -190,7 +188,7 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError { /// /// See also `extendedResultCode`. public var resultCode: ResultCode { - return extendedResultCode.primaryResultCode + extendedResultCode.primaryResultCode } /// The SQLite extended error code (see @@ -281,19 +279,13 @@ extension DatabaseError { /// NSError bridging: the domain of the error. /// :nodoc: - public static var errorDomain: String { - return "GRDB.DatabaseError" - } + public static var errorDomain: String { "GRDB.DatabaseError" } /// NSError bridging: the error code within the given domain. /// :nodoc: - public var errorCode: Int { - return Int(extendedResultCode.rawValue) - } + public var errorCode: Int { Int(extendedResultCode.rawValue) } /// NSError bridging: the user-info dictionary. /// :nodoc: - public var errorUserInfo: [String: Any] { - return [NSLocalizedDescriptionKey: description] - } + public var errorUserInfo: [String: Any] { [NSLocalizedDescriptionKey: description] } } diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index 1a63ac385..15e80bf46 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -14,11 +14,11 @@ public final class DatabaseFunction: Hashable { let nArg: Int32 // -1 for variadic functions } - public var name: String { return identity.name } + public var name: String { identity.name } private let identity: Identity let pure: Bool private let kind: Kind - private var eTextRep: Int32 { return (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) } + private var eTextRep: Int32 { (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) } /// Returns an SQL function. /// @@ -343,7 +343,7 @@ extension DatabaseFunction { /// Two functions are equal if they share the same name and arity. /// :nodoc: public static func == (lhs: DatabaseFunction, rhs: DatabaseFunction) -> Bool { - return lhs.identity == rhs.identity + lhs.identity == rhs.identity } } diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 09073e356..8f086efcf 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -23,13 +23,14 @@ public final class DatabasePool: DatabaseWriter { // MARK: - Database Information - /// The path to the database. - public var path: String { - return writer.path + /// The database configuration + public var configuration: Configuration { + writer.configuration } - public var configuration: Configuration { - return writer.configuration + /// The path to the database. + public var path: String { + writer.path } // MARK: - Initializer @@ -637,7 +638,7 @@ extension DatabasePool: DatabaseReader { /// - parameter updates: The updates to the database. /// - throws: The error thrown by the updates. public func writeWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { - return try writer.sync(updates) + try writer.sync(updates) } /// Synchronously executes database updates in a protected dispatch queue, @@ -654,7 +655,7 @@ extension DatabasePool: DatabaseReader { /// - parameter updates: The updates to the database. /// - throws: The error thrown by the updates. public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { - return try readerPool.barrier { + try readerPool.barrier { try writer.sync(updates) } } @@ -711,7 +712,7 @@ extension DatabasePool: DatabaseReader { /// This method is reentrant. It should be avoided because it fosters /// dangerous concurrency practices. public func unsafeReentrantWrite(_ updates: (Database) throws -> T) rethrows -> T { - return try writer.reentrantSync(updates) + try writer.reentrantSync(updates) } /// Asynchronously executes database updates in a protected dispatch queue, diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 50f3e3cf5..86553a34e 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -12,12 +12,12 @@ public final class DatabaseQueue: DatabaseWriter { /// The database configuration public var configuration: Configuration { - return writer.configuration + writer.configuration } /// The path to the database file; it is ":memory:" for in-memory databases. public var path: String { - return writer.path + writer.path } // MARK: - Initializers @@ -195,7 +195,7 @@ extension DatabaseQueue { /// - parameter block: A block that accesses the database. /// - throws: The error thrown by the block. public func read(_ block: (Database) throws -> T) rethrows -> T { - return try writer.sync { db in + try writer.sync { db in try db.readOnly { try block(db) } } } @@ -245,7 +245,7 @@ extension DatabaseQueue { /// /// :nodoc: public func unsafeRead(_ block: (Database) throws -> T) rethrows -> T { - return try writer.sync(block) + try writer.sync(block) } /// Synchronously executes a block in a protected dispatch queue, and @@ -260,7 +260,7 @@ extension DatabaseQueue { /// /// :nodoc: public func unsafeReentrantRead(_ block: (Database) throws -> T) rethrows -> T { - return try writer.reentrantSync(block) + try writer.reentrantSync(block) } public func concurrentRead(_ block: @escaping (Database) throws -> T) -> DatabaseFuture { @@ -351,7 +351,7 @@ extension DatabaseQueue { /// - parameter updates: The updates to the database. /// - throws: The error thrown by the updates. public func writeWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { - return try writer.sync(updates) + try writer.sync(updates) } /// Synchronously executes database updates in a protected dispatch queue, @@ -365,7 +365,7 @@ extension DatabaseQueue { /// - parameter updates: The updates to the database. /// - throws: The error thrown by the updates. public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { - return try writer.sync(updates) + try writer.sync(updates) } /// Synchronously executes database updates in a protected dispatch queue, @@ -381,7 +381,7 @@ extension DatabaseQueue { /// - parameter block: A block that accesses the database. /// - throws: The error thrown by the block. public func inDatabase(_ updates: (Database) throws -> T) rethrows -> T { - return try writer.sync(updates) + try writer.sync(updates) } /// Synchronously executes database updates in a protected dispatch queue, and @@ -395,7 +395,7 @@ extension DatabaseQueue { /// This method is reentrant. It is unsafe because it fosters dangerous /// concurrency practices. public func unsafeReentrantWrite(_ updates: (Database) throws -> T) rethrows -> T { - return try writer.reentrantSync(updates) + try writer.reentrantSync(updates) } /// Asynchronously executes database updates in a protected dispatch queue, diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index f1dbfa8e9..5d25b4ba6 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -308,7 +308,7 @@ public final class AnyDatabaseReader: DatabaseReader { /// :nodoc: public var configuration: Configuration { - return base.configuration + base.configuration } // MARK: - Interrupting Database Operations @@ -322,7 +322,7 @@ public final class AnyDatabaseReader: DatabaseReader { /// :nodoc: public func read(_ block: (Database) throws -> T) throws -> T { - return try base.read(block) + try base.read(block) } /// :nodoc: @@ -332,12 +332,12 @@ public final class AnyDatabaseReader: DatabaseReader { /// :nodoc: public func unsafeRead(_ block: (Database) throws -> T) throws -> T { - return try base.unsafeRead(block) + try base.unsafeRead(block) } /// :nodoc: public func unsafeReentrantRead(_ block: (Database) throws -> T) throws -> T { - return try base.unsafeReentrantRead(block) + try base.unsafeReentrantRead(block) } // MARK: - Functions diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 9a739e2ff..6c4d2c609 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -170,7 +170,7 @@ extension DatabaseRegion { /// Returns whether the content in the region would be impacted if the /// database were modified by an event of this kind. public func isModified(byEventsOfKind eventKind: DatabaseEventKind) -> Bool { - return intersection(eventKind.modifiedRegion).isEmpty == false + intersection(eventKind.modifiedRegion).isEmpty == false } /// Returns whether the content in the region is impacted by this event. @@ -319,7 +319,7 @@ public protocol DatabaseRegionConvertible { extension DatabaseRegion: DatabaseRegionConvertible { /// :nodoc: public func databaseRegion(_ db: Database) throws -> DatabaseRegion { - return self + self } } @@ -337,7 +337,7 @@ public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible { /// :nodoc: public func databaseRegion(_ db: Database) throws -> DatabaseRegion { - return try _region(db) + try _region(db) } } @@ -345,7 +345,7 @@ public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible { extension DatabaseRegion { static func union(_ regions: DatabaseRegion...) -> DatabaseRegion { - return regions.reduce(into: DatabaseRegion()) { union, region in + regions.reduce(into: DatabaseRegion()) { union, region in union.formUnion(region) } } diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index b7985bae7..be5e864ad 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -105,7 +105,7 @@ private class DatabaseRegionObserver: TransactionObserver { } func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - return region.isModified(byEventsOfKind: eventKind) + region.isModified(byEventsOfKind: eventKind) } func databaseDidChange(with event: DatabaseEvent) { diff --git a/GRDB/Core/DatabaseSchemaCache.swift b/GRDB/Core/DatabaseSchemaCache.swift index dd7916ec7..7425675b9 100644 --- a/GRDB/Core/DatabaseSchemaCache.swift +++ b/GRDB/Core/DatabaseSchemaCache.swift @@ -15,7 +15,7 @@ struct DatabaseSchemaCache { } func primaryKey(_ table: String) -> PrimaryKeyInfo? { - return primaryKeys[table] + primaryKeys[table] } mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String) { @@ -23,7 +23,7 @@ struct DatabaseSchemaCache { } func columns(in table: String) -> [ColumnInfo]? { - return columns[table] + columns[table] } mutating func set(columns: [ColumnInfo], forTable table: String) { @@ -31,7 +31,7 @@ struct DatabaseSchemaCache { } func indexes(on table: String) -> [IndexInfo]? { - return indexes[table] + indexes[table] } mutating func set(indexes: [IndexInfo], forTable table: String) { @@ -39,7 +39,7 @@ struct DatabaseSchemaCache { } func foreignKeys(on table: String) -> [ForeignKeyInfo]? { - return foreignKeys[table] + foreignKeys[table] } mutating func set(foreignKeys: [ForeignKeyInfo], forTable table: String) { diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 96363dfa2..f58e47176 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -11,7 +11,7 @@ public class DatabaseSnapshot: DatabaseReader { /// The database configuration public var configuration: Configuration { - return serializedDatabase.configuration + serializedDatabase.configuration } init(path: String, configuration: Configuration = Configuration(), defaultLabel: String, purpose: String) throws { @@ -65,7 +65,7 @@ extension DatabaseSnapshot { /// - parameter block: A block that accesses the database. /// - throws: The error thrown by the block. public func read(_ block: (Database) throws -> T) rethrows -> T { - return try serializedDatabase.sync(block) + try serializedDatabase.sync(block) } /// Asynchronously executes a read-only block in a protected dispatch queue. @@ -86,12 +86,12 @@ extension DatabaseSnapshot { /// :nodoc: public func unsafeRead(_ block: (Database) throws -> T) rethrows -> T { - return try serializedDatabase.sync(block) + try serializedDatabase.sync(block) } /// :nodoc: public func unsafeReentrantRead(_ block: (Database) throws -> T) throws -> T { - return try serializedDatabase.reentrantSync(block) + try serializedDatabase.reentrantSync(block) } // MARK: - Functions @@ -167,7 +167,7 @@ extension DatabaseSnapshot { /// An observer that does nothing, support for /// `DatabaseSnapshot.add(observation:onError:onChange:)`. private class SnapshotValueObserver: TransactionObserver { - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { return false } + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { false } func databaseDidChange(with event: DatabaseEvent) { } func databaseDidCommit(_ db: Database) { } func databaseDidRollback(_ db: Database) { } diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index aee43d0f6..5d1363332 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -209,12 +209,12 @@ extension DatabaseValue { extension DatabaseValue { /// Returns self public var databaseValue: DatabaseValue { - return self + self } /// Returns the database value public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> DatabaseValue? { - return dbValue + dbValue } } @@ -223,7 +223,7 @@ extension DatabaseValue { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public var sqlExpression: SQLExpression { - return self + self } } @@ -277,7 +277,7 @@ extension DatabaseValue { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - return self + self } } diff --git a/GRDB/Core/DatabaseValueConversion.swift b/GRDB/Core/DatabaseValueConversion.swift index 50f25cd4f..5b486099b 100644 --- a/GRDB/Core/DatabaseValueConversion.swift +++ b/GRDB/Core/DatabaseValueConversion.swift @@ -21,11 +21,11 @@ struct ValueConversionContext: KeyPathRefining { private var column: Column? func atColumn(_ columnIndex: Int) -> ValueConversionContext { - return with(\.column, .columnIndex(columnIndex)) + with(\.column, .columnIndex(columnIndex)) } func atColumn(_ columnName: String) -> ValueConversionContext { - return with(\.column, .columnName(columnName)) + with(\.column, .columnName(columnName)) } var columnIndex: Int? { @@ -224,7 +224,7 @@ extension DatabaseValueConvertible { @usableFromInline static func decode(from row: Row, atUncheckedIndex index: Int) -> Self { - return decode( + decode( from: row.impl.databaseValue(atUncheckedIndex: index), conversionContext: ValueConversionContext(row).atColumn(index)) } @@ -258,7 +258,7 @@ extension DatabaseValueConvertible { @usableFromInline static func decodeIfPresent(from row: Row, atUncheckedIndex index: Int) -> Self? { - return decodeIfPresent( + decodeIfPresent( from: row.impl.databaseValue(atUncheckedIndex: index), conversionContext: ValueConversionContext(row).atColumn(index)) } diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 301904d3c..a4d57c5ee 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -36,7 +36,7 @@ extension DatabaseValueConvertible { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public var sqlExpression: SQLExpression { - return databaseValue + databaseValue } } @@ -404,7 +404,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor { - return try RowDecoder.fetchCursor(db, self) + try RowDecoder.fetchCursor(db, self) } /// An array of fetched values. @@ -416,7 +416,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { /// - returns: An array of values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchAll(_ db: Database) throws -> [RowDecoder] { - return try RowDecoder.fetchAll(db, self) + try RowDecoder.fetchAll(db, self) } /// The first fetched value. @@ -431,7 +431,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchOne(_ db: Database) throws -> RowDecoder? { - return try RowDecoder.fetchOne(db, self) + try RowDecoder.fetchOne(db, self) } } @@ -620,7 +620,7 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor { - return try Optional.fetchCursor(db, self) + try Optional.fetchCursor(db, self) } /// An array of fetched optional values. @@ -632,6 +632,6 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: /// - returns: An array of values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] { - return try Optional.fetchAll(db, self) + try Optional.fetchAll(db, self) } } diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 8e64898df..4a2b069f5 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -205,7 +205,7 @@ extension DatabaseWriter { /// - throws: The error thrown by the updates, or by the /// wrapping transaction. public func write(_ updates: (Database) throws -> T) throws -> T { - return try writeWithoutTransaction { db in + try writeWithoutTransaction { db in var result: T? try db.inTransaction { result = try updates(db) @@ -568,7 +568,7 @@ public final class AnyDatabaseWriter: DatabaseWriter { /// :nodoc: public var configuration: Configuration { - return base.configuration + base.configuration } // MARK: - Interrupting Database Operations @@ -582,7 +582,7 @@ public final class AnyDatabaseWriter: DatabaseWriter { /// :nodoc: public func read(_ block: (Database) throws -> T) throws -> T { - return try base.read(block) + try base.read(block) } /// :nodoc: @@ -592,17 +592,17 @@ public final class AnyDatabaseWriter: DatabaseWriter { /// :nodoc: public func unsafeRead(_ block: (Database) throws -> T) throws -> T { - return try base.unsafeRead(block) + try base.unsafeRead(block) } /// :nodoc: public func unsafeReentrantRead(_ block: (Database) throws -> T) throws -> T { - return try base.unsafeReentrantRead(block) + try base.unsafeReentrantRead(block) } /// :nodoc: public func concurrentRead(_ block: @escaping (Database) throws -> T) -> DatabaseFuture { - return base.concurrentRead(block) + base.concurrentRead(block) } /// :nodoc: @@ -614,17 +614,17 @@ public final class AnyDatabaseWriter: DatabaseWriter { /// :nodoc: public func write(_ updates: (Database) throws -> T) throws -> T { - return try base.write(updates) + try base.write(updates) } /// :nodoc: public func writeWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { - return try base.writeWithoutTransaction(updates) + try base.writeWithoutTransaction(updates) } /// :nodoc: public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { - return try base.barrierWriteWithoutTransaction(updates) + try base.barrierWriteWithoutTransaction(updates) } /// :nodoc: @@ -642,7 +642,7 @@ public final class AnyDatabaseWriter: DatabaseWriter { /// :nodoc: public func unsafeReentrantWrite(_ updates: (Database) throws -> T) rethrows -> T { - return try base.unsafeReentrantWrite(updates) + try base.unsafeReentrantWrite(updates) } // MARK: - Functions diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index 2854b89ae..cb00116ac 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -75,7 +75,7 @@ extension FetchRequest { /// Returns an adapted request. public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest { - return AdaptedFetchRequest(self, adapter) + AdaptedFetchRequest(self, adapter) } /// Returns the number of rows fetched by the request. @@ -131,12 +131,12 @@ public struct AdaptedFetchRequest: FetchRequest { /// :nodoc: public func fetchCount(_ db: Database) throws -> Int { - return try base.fetchCount(db) + try base.fetchCount(db) } /// :nodoc: public func databaseRegion(_ db: Database) throws -> DatabaseRegion { - return try base.databaseRegion(db) + try base.databaseRegion(db) } } @@ -162,16 +162,16 @@ public struct AnyFetchRequest: FetchRequest { /// :nodoc: public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { - return try _preparedRequest(db, singleResult) + try _preparedRequest(db, singleResult) } /// :nodoc: public func fetchCount(_ db: Database) throws -> Int { - return try _fetchCount(db) + try _fetchCount(db) } /// :nodoc: public func databaseRegion(_ db: Database) throws -> DatabaseRegion { - return try _databaseRegion(db) + try _databaseRegion(db) } } diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 13bfdf89e..000e108f2 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -78,15 +78,13 @@ public final class Row: Equatable, Hashable, RandomAccessCollection, /// the iteration of a query: make sure to make a copy of it whenever you /// want to keep a specific one: `row.copy()`. public func copy() -> Row { - return impl.copiedRow(self) + impl.copiedRow(self) } // MARK: - Not Public /// Returns true if and only if the row was fetched from a database. - var isFetched: Bool { - return impl.isFetched - } + var isFetched: Bool { impl.isFetched } /// Creates a row that maps an SQLite statement. Further calls to /// sqlite3_step() modify the row. @@ -142,19 +140,19 @@ extension Row { /// Columns appear in the same order as they occur as the `.0` member /// of column-value pairs in `self`. public var columnNames: LazyMapCollection { - return lazy.map { $0.0 } + lazy.map { $0.0 } } /// Returns true if and only if the row has that column. /// /// This method is case-insensitive. public func hasColumn(_ columnName: String) -> Bool { - return index(ofColumn: columnName) != nil + index(ofColumn: columnName) != nil } @usableFromInline func index(ofColumn name: String) -> Int? { - return impl.index(ofColumn: name) + impl.index(ofColumn: name) } } @@ -502,7 +500,7 @@ extension Row { /// The returned data does not owns its bytes: it must not be used longer /// than the row's lifetime. public func dataNoCopy(_ column: Column) -> Data? { - return dataNoCopy(named: column.name) + dataNoCopy(named: column.name) } } @@ -515,7 +513,7 @@ extension Row { /// Values appear in the same order as they occur as the `.1` member /// of column-value pairs in `self`. public var databaseValues: LazyMapCollection { - return lazy.map { $0.1 } + lazy.map { $0.1 } } } @@ -701,7 +699,7 @@ extension Row { /// row.scopes["bar"] // [bar:2] /// row.scopes["baz"] // nil public var scopes: ScopesView { - return impl.scopes(prefetchedRows: prefetchedRows) + impl.scopes(prefetchedRows: prefetchedRows) } /// Returns a view on the scopes tree defined by row adapters. @@ -724,7 +722,7 @@ extension Row { /// row.scopesTree["bar"] // [bar:2] /// row.scopesTree["baz"] // [baz:3] public var scopesTree: ScopesTreeView { - return ScopesTreeView(scopes: scopes) + ScopesTreeView(scopes: scopes) } /// Returns a copy of the row, without any scopes. @@ -755,7 +753,7 @@ extension Row { /// This property can turn out useful when you debug the consumption of /// adapted rows, such as rows fetched from joined requests. public var unadapted: Row { - return impl.unadaptedRow(self) + impl.unadaptedRow(self) } } @@ -1093,7 +1091,7 @@ extension FetchRequest where RowDecoder == Row { /// - returns: A cursor over fetched rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchCursor(_ db: Database) throws -> RowCursor { - return try Row.fetchCursor(db, self) + try Row.fetchCursor(db, self) } /// An array of fetched rows. @@ -1105,7 +1103,7 @@ extension FetchRequest where RowDecoder == Row { /// - returns: An array of fetched rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchAll(_ db: Database) throws -> [Row] { - return try Row.fetchAll(db, self) + try Row.fetchAll(db, self) } /// The first fetched row. @@ -1117,7 +1115,7 @@ extension FetchRequest where RowDecoder == Row { /// - returns: An optional row. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchOne(_ db: Database) throws -> Row? { - return try Row.fetchOne(db, self) + try Row.fetchOne(db, self) } } @@ -1142,16 +1140,12 @@ extension Row { /// The index of the first (ColumnName, DatabaseValue) pair. /// :nodoc: - public var startIndex: RowIndex { - return Index(0) - } + public var startIndex: RowIndex { RowIndex(0) } /// The "past-the-end" index, successor of the index of the last /// (ColumnName, DatabaseValue) pair. /// :nodoc: - public var endIndex: RowIndex { - return Index(count) - } + public var endIndex: RowIndex { RowIndex(count) } /// Accesses the (ColumnName, DatabaseValue) pair at given index. public subscript(position: RowIndex) -> (String, DatabaseValue) { @@ -1225,14 +1219,14 @@ extension Row { extension Row { /// :nodoc: public var description: String { - return "[" + "[" + map { (column, dbValue) in "\(column):\(dbValue)" }.joined(separator: " ") + "]" } /// :nodoc: public var debugDescription: String { - return debugDescription(level: 0) + debugDescription(level: 0) } private func debugDescription(level: Int) -> String { @@ -1284,12 +1278,12 @@ public struct RowIndex: Comparable, Strideable { extension RowIndex { /// :nodoc: public static func == (lhs: RowIndex, rhs: RowIndex) -> Bool { - return lhs.index == rhs.index + lhs.index == rhs.index } /// :nodoc: public static func < (lhs: RowIndex, rhs: RowIndex) -> Bool { - return lhs.index < rhs.index + lhs.index < rhs.index } } @@ -1297,12 +1291,12 @@ extension RowIndex { extension RowIndex { /// :nodoc: public func distance(to other: RowIndex) -> Int { - return other.index - index + other.index - index } /// :nodoc: public func advanced(by n: Int) -> RowIndex { - return RowIndex(index + n) + RowIndex(index + n) } } @@ -1339,7 +1333,7 @@ extension Row { /// The scopes defined on this row. public var names: Dictionary.Keys { - return scopes.keys + scopes.keys } init() { @@ -1354,17 +1348,17 @@ extension Row { /// :nodoc: public var startIndex: Index { - return scopes.startIndex + scopes.startIndex } /// :nodoc: public var endIndex: Index { - return scopes.endIndex + scopes.endIndex } /// :nodoc: public func index(after i: Index) -> Index { - return scopes.index(after: i) + scopes.index(after: i) } /// :nodoc: @@ -1500,7 +1494,7 @@ extension Row { /// True if there is no prefetched associated rows. public var isEmpty: Bool { - return prefetches.isEmpty + prefetches.isEmpty } /// The keys for available prefetched rows @@ -1666,20 +1660,16 @@ private struct ArrayRowImpl: RowImpl { self.columns = columns } - var count: Int { - return columns.count - } + var count: Int { columns.count } - var isFetched: Bool { - return false - } + var isFetched: Bool { false } func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue { - return columns[index].1 + columns[index].1 } func columnName(atUncheckedIndex index: Int) -> String { - return columns[index].0 + columns[index].0 } func index(ofColumn name: String) -> Int? { @@ -1688,7 +1678,7 @@ private struct ArrayRowImpl: RowImpl { } func copiedRow(_ row: Row) -> Row { - return row + row } } @@ -1708,20 +1698,16 @@ private struct StatementCopyRowImpl: RowImpl { self.columnNames = columnNames } - var count: Int { - return columnNames.count - } + var count: Int { columnNames.count } - var isFetched: Bool { - return true - } + var isFetched: Bool { true } func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue { - return dbValues[index] + dbValues[index] } func columnName(atUncheckedIndex index: Int) -> String { - return columnNames[index] + columnNames[index] } func index(ofColumn name: String) -> Int? { @@ -1730,7 +1716,7 @@ private struct StatementCopyRowImpl: RowImpl { } func copiedRow(_ row: Row) -> Row { - return row + row } } @@ -1755,12 +1741,10 @@ private struct StatementRowImpl: RowImpl { } var count: Int { - return Int(sqlite3_column_count(sqliteStatement)) + Int(sqlite3_column_count(sqliteStatement)) } - var isFetched: Bool { - return true - } + var isFetched: Bool { true } func hasNull(atUncheckedIndex index: Int) -> Bool { // Avoid extracting values, because this modifies the SQLite statement. @@ -1779,7 +1763,7 @@ private struct StatementRowImpl: RowImpl { } func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue { - return DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index)) + DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index)) } func fastDecode( @@ -1797,7 +1781,7 @@ private struct StatementRowImpl: RowImpl { } func columnName(atUncheckedIndex index: Int) -> String { - return statement.columnNames[index] + statement.columnNames[index] } func index(ofColumn name: String) -> Int? { @@ -1808,22 +1792,22 @@ private struct StatementRowImpl: RowImpl { } func copiedRow(_ row: Row) -> Row { - return Row(copiedFromSQLiteStatement: sqliteStatement, statement: statement) + Row(copiedFromSQLiteStatement: sqliteStatement, statement: statement) } } // This one is not optimized at all, since it is only used in fatal conversion errors, so far private struct SQLiteStatementRowImpl: RowImpl { let sqliteStatement: SQLiteStatement - var count: Int { return Int(sqlite3_column_count(sqliteStatement)) } - var isFetched: Bool { return true } + var count: Int { Int(sqlite3_column_count(sqliteStatement)) } + var isFetched: Bool { true } func columnName(atUncheckedIndex index: Int) -> String { - return String(cString: sqlite3_column_name(sqliteStatement, Int32(index))) + String(cString: sqlite3_column_name(sqliteStatement, Int32(index))) } func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue { - return DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index)) + DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index)) } func dataNoCopy(atUncheckedIndex index: Int) -> Data? { @@ -1848,13 +1832,9 @@ private struct SQLiteStatementRowImpl: RowImpl { /// See Row.init() private struct EmptyRowImpl: RowImpl { - var count: Int { - return 0 - } + var count: Int { 0 } - var isFetched: Bool { - return false - } + var isFetched: Bool { false } func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue { // Programmer error @@ -1866,11 +1846,7 @@ private struct EmptyRowImpl: RowImpl { fatalError("row index out of range") } - func index(ofColumn name: String) -> Int? { - return nil - } + func index(ofColumn name: String) -> Int? { nil } - func copiedRow(_ row: Row) -> Row { - return row - } + func copiedRow(_ row: Row) -> Row { row } } diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index 87662cd31..f987db864 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -89,11 +89,11 @@ public struct LayoutedColumnMapping { } func baseColumnIndex(atMappingIndex index: Int) -> Int { - return layoutColumns[index].0 + layoutColumns[index].0 } func columnName(atMappingIndex index: Int) -> String { - return layoutColumns[index].1 + layoutColumns[index].1 } } @@ -104,16 +104,12 @@ extension LayoutedColumnMapping: LayoutedRowAdapter { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Returns self. - public var mapping: LayoutedColumnMapping { - return self - } + public var mapping: LayoutedColumnMapping { self } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Returns the empty dictionary. - public var scopes: [String: LayoutedRowAdapter] { - return [:] - } + public var scopes: [String: LayoutedRowAdapter] { [:] } } /// :nodoc: @@ -175,13 +171,13 @@ extension SelectStatement: RowLayout { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public var layoutColumns: [(Int, String)] { - return Array(columnNames.enumerated()) + Array(columnNames.enumerated()) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func layoutIndex(ofColumn name: String) -> Int? { - return index(ofColumn: name) + index(ofColumn: name) } } @@ -247,7 +243,7 @@ extension RowAdapter { extension RowAdapter { func baseColumnIndex(atIndex index: Int, layout: RowLayout) throws -> Int { - return try layoutedAdapter(from: layout).mapping.baseColumnIndex(atMappingIndex: index) + try layoutedAdapter(from: layout).mapping.baseColumnIndex(atMappingIndex: index) } } @@ -259,7 +255,7 @@ public struct EmptyRowAdapter: RowAdapter { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { - return LayoutedColumnMapping(layoutColumns: []) + LayoutedColumnMapping(layoutColumns: []) } } @@ -325,7 +321,7 @@ public struct SuffixRowAdapter: RowAdapter { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { - return LayoutedColumnMapping(layoutColumns: layout.layoutColumns.suffix(from: index)) + LayoutedColumnMapping(layoutColumns: layout.layoutColumns.suffix(from: index)) } } @@ -355,7 +351,7 @@ public struct RangeRowAdapter: RowAdapter { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { - return LayoutedColumnMapping(layoutColumns: layout.layoutColumns[range]) + LayoutedColumnMapping(layoutColumns: layout.layoutColumns[range]) } } @@ -454,7 +450,7 @@ struct ChainedAdapter: RowAdapter { let second: RowAdapter func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { - return try second.layoutedAdapter(from: first.layoutedAdapter(from: layout).mapping) + try second.layoutedAdapter(from: first.layoutedAdapter(from: layout).mapping) } } @@ -484,16 +480,12 @@ struct AdaptedRowImpl: RowImpl { self.mapping = adapter.mapping } - var count: Int { - return mapping.layoutColumns.count - } + var count: Int { mapping.layoutColumns.count } - var isFetched: Bool { - return base.isFetched - } + var isFetched: Bool { base.isFetched } func scopes(prefetchedRows: Row.PrefetchedRowsView) -> Row.ScopesView { - return Row.ScopesView(row: base, scopes: adapter.scopes, prefetchedRows: prefetchedRows) + Row.ScopesView(row: base, scopes: adapter.scopes, prefetchedRows: prefetchedRows) } func hasNull(atUncheckedIndex index: Int) -> Bool { @@ -528,15 +520,15 @@ struct AdaptedRowImpl: RowImpl { } func columnName(atUncheckedIndex index: Int) -> String { - return mapping.columnName(atMappingIndex: index) + mapping.columnName(atMappingIndex: index) } func index(ofColumn name: String) -> Int? { - return mapping.layoutIndex(ofColumn: name) + mapping.layoutIndex(ofColumn: name) } func copiedRow(_ row: Row) -> Row { - return Row(base: base.copy(), adapter: adapter) + Row(base: base.copy(), adapter: adapter) } func unscopedRow(_ row: Row) -> Row { @@ -545,6 +537,6 @@ struct AdaptedRowImpl: RowImpl { } func unadaptedRow(_ row: Row) -> Row { - return base.unadapted + base.unadapted } } diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index c01cff782..313418cb5 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -21,7 +21,7 @@ public struct SQLLiteral { // TODO: remove and use default case argument when compiler >= 5.1 static func sql(_ sql: String) -> Element { - return .sql(sql, StatementArguments()) + .sql(sql, StatementArguments()) } fileprivate func sql(_ context: inout SQLGenerationContext) -> String { @@ -103,11 +103,11 @@ public struct SQLLiteral { } func sql(_ context: inout SQLGenerationContext) -> String { - return elements.map { $0.sql(&context) }.joined() + elements.map { $0.sql(&context) }.joined() } fileprivate func qualified(with alias: TableAlias) -> SQLLiteral { - return SQLLiteral(elements: elements.map { $0.qualified(with: alias) }) + SQLLiteral(elements: elements.map { $0.qualified(with: alias) }) } } @@ -159,15 +159,15 @@ extension SQLLiteral { /// SQLLiteral(sql: "? + ?", arguments: [1, 2]).sqlExpression /// SQLLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]).sqlExpression public var sqlExpression: SQLExpression { - return _SQLExpressionLiteral(sqlLiteral: self) + _SQLExpressionLiteral(sqlLiteral: self) } var sqlSelectable: SQLSelectable { - return _SQLSelectionLiteral(sqlLiteral: self) + _SQLSelectionLiteral(sqlLiteral: self) } var sqlOrderingTerm: SQLOrderingTerm { - return _SQLOrderingLiteral(sqlLiteral: self) + _SQLOrderingLiteral(sqlLiteral: self) } } @@ -265,7 +265,7 @@ private struct _SQLExpressionLiteral: SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - return sqlLiteral.qualified(with: alias).sqlExpression + sqlLiteral.qualified(with: alias).sqlExpression } } @@ -280,7 +280,7 @@ private struct _SQLSelectionLiteral: SQLSelectable { } func resultColumnSQL(_ context: inout SQLGenerationContext) -> String { - return sqlLiteral.sql(&context) + sqlLiteral.sql(&context) } func countedSQL(_ context: inout SQLGenerationContext) -> String { @@ -308,7 +308,7 @@ private struct _SQLSelectionLiteral: SQLSelectable { } func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { - return sqlLiteral.qualified(with: alias).sqlSelectable + sqlLiteral.qualified(with: alias).sqlSelectable } } @@ -330,10 +330,10 @@ private struct _SQLOrderingLiteral: SQLOrderingTerm { } func orderingTermSQL(_ context: inout SQLGenerationContext) -> String { - return sqlLiteral.sql(&context) + sqlLiteral.sql(&context) } func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { - return sqlLiteral.qualified(with: alias).sqlOrderingTerm + sqlLiteral.qualified(with: alias).sqlOrderingTerm } } diff --git a/GRDB/Core/SQLRequest.swift b/GRDB/Core/SQLRequest.swift index f2b606593..565c5c7ce 100644 --- a/GRDB/Core/SQLRequest.swift +++ b/GRDB/Core/SQLRequest.swift @@ -19,14 +19,14 @@ public struct SQLRequest: FetchRequest { /// let id = 42 /// let request: SQLRequest = "SELECT * FROM player WHERE id = \(id)" /// request.sql // "SELECT * FROM player WHERE id = ?" - public var sql: String { return sqlLiteral.sql } + public var sql: String { sqlLiteral.sql } /// The request argument /// /// let id = 42 /// let request: SQLRequest = "SELECT * FROM player WHERE id = \(id)" /// request.arguments // [42] - public var arguments: StatementArguments { return sqlLiteral.arguments } + public var arguments: StatementArguments { sqlLiteral.arguments } /// The request adapter public var adapter: RowAdapter? diff --git a/GRDB/Core/SchedulingWatchdog.swift b/GRDB/Core/SchedulingWatchdog.swift index 087926c45..3d857daf0 100644 --- a/GRDB/Core/SchedulingWatchdog.swift +++ b/GRDB/Core/SchedulingWatchdog.swift @@ -53,10 +53,10 @@ final class SchedulingWatchdog { } static var current: SchedulingWatchdog? { - return DispatchQueue.getSpecific(key: watchDogKey) + DispatchQueue.getSpecific(key: watchDogKey) } func allows(_ db: Database) -> Bool { - return allowedDatabases.contains { $0 === db } + allowedDatabases.contains { $0 === db } } } diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index e90724d49..f5a1a5383 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -6,9 +6,7 @@ final class SerializedDatabase { private let db: Database /// The database configuration - var configuration: Configuration { - return db.configuration - } + var configuration: Configuration { db.configuration } /// The path to the database file var path: String @@ -188,7 +186,7 @@ final class SerializedDatabase { /// Returns true if any only if the current dispatch queue is valid. var onValidQueue: Bool { - return SchedulingWatchdog.current?.allows(db) ?? false + SchedulingWatchdog.current?.allows(db) ?? false } /// Executes the block in the current queue. diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 724fc9158..e9f201b06 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -32,7 +32,7 @@ public class Statement { } var isReadonly: Bool { - return sqlite3_stmt_readonly(sqliteStatement) != 0 + sqlite3_stmt_readonly(sqliteStatement) != 0 } unowned let database: Database @@ -124,7 +124,7 @@ public class Statement { /// The statement arguments. public var arguments: StatementArguments { - get { return _arguments } + get { _arguments } set { // Force arguments validity: it is a programmer error to provide // arguments that do not match the statement. @@ -367,7 +367,7 @@ public final class SelectStatement: Statement { /// The number of columns in the resulting rows. public var columnCount: Int { - return Int(sqlite3_column_count(self.sqliteStatement)) + Int(sqlite3_column_count(self.sqliteStatement)) } /// The column names, ordered from left to right. @@ -386,14 +386,14 @@ public final class SelectStatement: Statement { /// Returns the index of the leftmost column named `name`, in a /// case-insensitive way. public func index(ofColumn name: String) -> Int? { - return columnIndexes[name.lowercased()] + columnIndexes[name.lowercased()] } /// Creates a cursor over the statement which does not produce any /// value. Each call to the next() cursor method calls the sqlite3_step() /// C function. func makeCursor(arguments: StatementArguments? = nil) throws -> StatementCursor { - return try StatementCursor(statement: self, arguments: arguments) + try StatementCursor(statement: self, arguments: arguments) } /// Utility function for cursors @@ -648,7 +648,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable, private(set) var namedValues: [String: DatabaseValue] = [:] public var isEmpty: Bool { - return values.isEmpty && namedValues.isEmpty + values.isEmpty && namedValues.isEmpty } diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 95aa91a86..12245ea59 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -408,7 +408,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchCursor(_ db: Database) throws -> FastDatabaseValueCursor { - return try RowDecoder.fetchCursor(db, self) + try RowDecoder.fetchCursor(db, self) } /// An array of fetched values. @@ -420,7 +420,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// - returns: An array of values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchAll(_ db: Database) throws -> [RowDecoder] { - return try RowDecoder.fetchAll(db, self) + try RowDecoder.fetchAll(db, self) } /// The first fetched value. @@ -435,7 +435,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchOne(_ db: Database) throws -> RowDecoder? { - return try RowDecoder.fetchOne(db, self) + try RowDecoder.fetchOne(db, self) } } @@ -628,7 +628,7 @@ extension FetchRequest /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchCursor(_ db: Database) throws -> FastNullableDatabaseValueCursor { - return try Optional.fetchCursor(db, self) + try Optional.fetchCursor(db, self) } /// An array of fetched optional values. @@ -640,6 +640,6 @@ extension FetchRequest /// - returns: An array of values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] { - return try Optional.fetchAll(db, self) + try Optional.fetchAll(db, self) } } diff --git a/GRDB/Core/Support/CoreGraphics/CGFloat.swift b/GRDB/Core/Support/CoreGraphics/CGFloat.swift index a7f7c6bc4..124b15681 100644 --- a/GRDB/Core/Support/CoreGraphics/CGFloat.swift +++ b/GRDB/Core/Support/CoreGraphics/CGFloat.swift @@ -6,7 +6,7 @@ extension CGFloat: DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return Double(self).databaseValue + Double(self).databaseValue } /// Returns a CGFloat initialized from *dbValue*, if possible. diff --git a/GRDB/Core/Support/Foundation/Data.swift b/GRDB/Core/Support/Foundation/Data.swift index 281fdd920..d6dc5ee46 100644 --- a/GRDB/Core/Support/Foundation/Data.swift +++ b/GRDB/Core/Support/Foundation/Data.swift @@ -21,7 +21,7 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return DatabaseValue(storage: .blob(self)) + DatabaseValue(storage: .blob(self)) } /// Returns a Data initialized from *dbValue*, if it contains diff --git a/GRDB/Core/Support/Foundation/DatabaseValueConvertible+ReferenceConvertible.swift b/GRDB/Core/Support/Foundation/DatabaseValueConvertible+ReferenceConvertible.swift index 4a3e3c53b..39244a1ae 100644 --- a/GRDB/Core/Support/Foundation/DatabaseValueConvertible+ReferenceConvertible.swift +++ b/GRDB/Core/Support/Foundation/DatabaseValueConvertible+ReferenceConvertible.swift @@ -17,12 +17,12 @@ extension DatabaseValueConvertible where Self: ReferenceConvertible, Self.Refere /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return (self as! ReferenceType).databaseValue + (self as! ReferenceType).databaseValue } /// Returns a value initialized from *dbValue*, if possible. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { - return ReferenceType.fromDatabaseValue(dbValue).flatMap { cast($0) } + ReferenceType.fromDatabaseValue(dbValue).flatMap { cast($0) } } } diff --git a/GRDB/Core/Support/Foundation/Date.swift b/GRDB/Core/Support/Foundation/Date.swift index c51b103fd..e590da162 100644 --- a/GRDB/Core/Support/Foundation/Date.swift +++ b/GRDB/Core/Support/Foundation/Date.swift @@ -14,7 +14,7 @@ extension NSDate: DatabaseValueConvertible { /// Returns a database value that contains the date encoded as /// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone. public var databaseValue: DatabaseValue { - return (self as Date).databaseValue + (self as Date).databaseValue } /// Returns a date initialized from dbValue, if possible. @@ -42,7 +42,7 @@ extension Date: DatabaseValueConvertible { /// Returns a database value that contains the date encoded as /// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone. public var databaseValue: DatabaseValue { - return storageDateFormatter.string(from: self).databaseValue + storageDateFormatter.string(from: self).databaseValue } /// Returns a date initialized from dbValue, if possible. diff --git a/GRDB/Core/Support/Foundation/NSData.swift b/GRDB/Core/Support/Foundation/NSData.swift index 5a29bc4a4..b3f08a3a8 100644 --- a/GRDB/Core/Support/Foundation/NSData.swift +++ b/GRDB/Core/Support/Foundation/NSData.swift @@ -6,7 +6,7 @@ extension NSData: DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return (self as Data).databaseValue + (self as Data).databaseValue } /// Returns an NSData initialized from *dbValue*, if it contains diff --git a/GRDB/Core/Support/Foundation/NSNull.swift b/GRDB/Core/Support/Foundation/NSNull.swift index af531bab5..ec27ab934 100644 --- a/GRDB/Core/Support/Foundation/NSNull.swift +++ b/GRDB/Core/Support/Foundation/NSNull.swift @@ -4,12 +4,8 @@ import Foundation extension NSNull: DatabaseValueConvertible { /// Returns DatabaseValue.null. - public var databaseValue: DatabaseValue { - return .null - } + public var databaseValue: DatabaseValue { .null } /// Returns nil. - public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { - return nil - } + public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { nil } } diff --git a/GRDB/Core/Support/Foundation/NSString.swift b/GRDB/Core/Support/Foundation/NSString.swift index ba9941012..7b956a265 100644 --- a/GRDB/Core/Support/Foundation/NSString.swift +++ b/GRDB/Core/Support/Foundation/NSString.swift @@ -6,7 +6,7 @@ extension NSString: DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return (self as String).databaseValue + (self as String).databaseValue } /// Returns an NSString initialized from *dbValue*, if possible. diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index b6630fe39..82cfbb244 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -15,7 +15,7 @@ class SQLiteDateParser { } func components(from dateString: String) -> DatabaseDateComponents? { - return dateString.withCString { cString in + dateString.withCString { cString in components(cString: cString, length: strlen(cString)) } } diff --git a/GRDB/Core/Support/Foundation/URL.swift b/GRDB/Core/Support/Foundation/URL.swift index 6990562e1..13ea34509 100644 --- a/GRDB/Core/Support/Foundation/URL.swift +++ b/GRDB/Core/Support/Foundation/URL.swift @@ -7,7 +7,7 @@ extension NSURL: DatabaseValueConvertible { /// Returns a value that can be stored in the database. /// (the URL's absoluteString). public var databaseValue: DatabaseValue { - return absoluteString?.databaseValue ?? .null + absoluteString?.databaseValue ?? .null } /// Returns an NSURL initialized from *dbValue*, if possible. diff --git a/GRDB/Core/Support/Foundation/UUID.swift b/GRDB/Core/Support/Foundation/UUID.swift index c8c8b47fb..392528f00 100644 --- a/GRDB/Core/Support/Foundation/UUID.swift +++ b/GRDB/Core/Support/Foundation/UUID.swift @@ -36,7 +36,7 @@ extension NSUUID: DatabaseValueConvertible { /// UUID adopts DatabaseValueConvertible extension UUID: DatabaseValueConvertible { public var databaseValue: DatabaseValue { - return withUnsafeBytes(of: uuid) { + withUnsafeBytes(of: uuid) { Data(bytes: $0.baseAddress!, count: $0.count).databaseValue } } diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift index b37fb8d80..bdf087905 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift @@ -5,9 +5,7 @@ private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer { /// Decodes a null value. /// /// - returns: Whether the encountered value was null. - func decodeNil() -> Bool { - return dbValue.isNull - } + func decodeNil() -> Bool { dbValue.isNull } /// Decodes a single value of the given type. /// @@ -161,7 +159,7 @@ private struct DatabaseValueDecoder: Decoder { // Decoder let codingPath: [CodingKey] - var userInfo: [CodingUserInfoKey: Any] { return [:] } + var userInfo: [CodingUserInfoKey: Any] { [:] } func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer { throw DecodingError.typeMismatch( @@ -176,13 +174,13 @@ private struct DatabaseValueDecoder: Decoder { } func singleValueContainer() throws -> SingleValueDecodingContainer { - return DatabaseValueDecodingContainer(dbValue: dbValue, codingPath: codingPath) + DatabaseValueDecodingContainer(dbValue: dbValue, codingPath: codingPath) } } extension DatabaseValueConvertible where Self: Decodable { public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? { - return try? self.init(from: DatabaseValueDecoder(dbValue: databaseValue, codingPath: [])) + try? self.init(from: DatabaseValueDecoder(dbValue: databaseValue, codingPath: [])) } } diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift index bd37c0bde..d4496c4ef 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift @@ -1,7 +1,7 @@ private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer { let encode: (DatabaseValue) -> Void - var codingPath: [CodingKey] { return [] } + var codingPath: [CodingKey] { [] } /// Encodes a null value. /// @@ -50,7 +50,7 @@ private struct DatabaseValueEncoder: Encoder { /// The path of coding keys taken to get to this point in encoding. /// A `nil` value indicates an unkeyed container. - var codingPath: [CodingKey] { return [] } + var codingPath: [CodingKey] { [] } /// Any contextual information set by the user for encoding. var userInfo: [CodingUserInfoKey: Any] = [:] @@ -88,7 +88,7 @@ private struct DatabaseValueEncoder: Encoder { /// - precondition: May not be called after a value has been encoded through /// a previous `self.singleValueContainer()` call. func singleValueContainer() -> SingleValueEncodingContainer { - return DatabaseValueEncodingContainer(encode: encode) + DatabaseValueEncodingContainer(encode: encode) } } diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+RawRepresentable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+RawRepresentable.swift index 0bb05cbc2..7c0178e26 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+RawRepresentable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+RawRepresentable.swift @@ -14,11 +14,11 @@ extension DatabaseValueConvertible where Self: RawRepresentable, Self.RawValue: /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return rawValue.databaseValue + rawValue.databaseValue } /// Returns a value initialized from *dbValue*, if possible. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { - return RawValue.fromDatabaseValue(dbValue).flatMap { self.init(rawValue: $0) } + RawValue.fromDatabaseValue(dbValue).flatMap { self.init(rawValue: $0) } } } diff --git a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift index 0914b0dcf..0db75637f 100644 --- a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift +++ b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift @@ -23,7 +23,7 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return (self ? 1 : 0).databaseValue + (self ? 1 : 0).databaseValue } /// Returns a Bool initialized from *dbValue*, if possible. @@ -115,12 +115,12 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return Int64(self).databaseValue + Int64(self).databaseValue } /// Returns an Int initialized from *dbValue*, if possible. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int? { - return Int64.fromDatabaseValue(dbValue).flatMap { Int(exactly: $0) } + Int64.fromDatabaseValue(dbValue).flatMap { Int(exactly: $0) } } } @@ -144,12 +144,12 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return Int64(self).databaseValue + Int64(self).databaseValue } /// Returns an Int8 initialized from *dbValue*, if possible. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int8? { - return Int64.fromDatabaseValue(dbValue).flatMap { Int8(exactly: $0) } + Int64.fromDatabaseValue(dbValue).flatMap { Int8(exactly: $0) } } } @@ -173,12 +173,12 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return Int64(self).databaseValue + Int64(self).databaseValue } /// Returns an Int16 initialized from *dbValue*, if possible. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int16? { - return Int64.fromDatabaseValue(dbValue).flatMap { Int16(exactly: $0) } + Int64.fromDatabaseValue(dbValue).flatMap { Int16(exactly: $0) } } } @@ -202,12 +202,12 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return Int64(self).databaseValue + Int64(self).databaseValue } /// Returns an Int32 initialized from *dbValue*, if possible. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int32? { - return Int64.fromDatabaseValue(dbValue).flatMap { Int32(exactly: $0) } + Int64.fromDatabaseValue(dbValue).flatMap { Int32(exactly: $0) } } } @@ -226,7 +226,7 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return DatabaseValue(storage: .int64(self)) + DatabaseValue(storage: .int64(self)) } /// Returns an Int64 initialized from *dbValue*, if possible. @@ -264,12 +264,12 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return Int64(self).databaseValue + Int64(self).databaseValue } /// Returns an Int initialized from *dbValue*, if possible. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt? { - return Int64.fromDatabaseValue(dbValue).flatMap { UInt(exactly: $0) } + Int64.fromDatabaseValue(dbValue).flatMap { UInt(exactly: $0) } } } @@ -293,12 +293,12 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return Int64(self).databaseValue + Int64(self).databaseValue } /// Returns an UInt8 initialized from *dbValue*, if possible. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt8? { - return Int64.fromDatabaseValue(dbValue).flatMap { UInt8(exactly: $0) } + Int64.fromDatabaseValue(dbValue).flatMap { UInt8(exactly: $0) } } } @@ -322,12 +322,12 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return Int64(self).databaseValue + Int64(self).databaseValue } /// Returns an UInt16 initialized from *dbValue*, if possible. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt16? { - return Int64.fromDatabaseValue(dbValue).flatMap { UInt16(exactly: $0) } + Int64.fromDatabaseValue(dbValue).flatMap { UInt16(exactly: $0) } } } @@ -351,12 +351,12 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return Int64(self).databaseValue + Int64(self).databaseValue } /// Returns an UInt32 initialized from *dbValue*, if possible. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt32? { - return Int64.fromDatabaseValue(dbValue).flatMap { UInt32(exactly: $0) } + Int64.fromDatabaseValue(dbValue).flatMap { UInt32(exactly: $0) } } } @@ -380,12 +380,12 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return Int64(self).databaseValue + Int64(self).databaseValue } /// Returns an UInt64 initialized from *dbValue*, if possible. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt64? { - return Int64.fromDatabaseValue(dbValue).flatMap { UInt64(exactly: $0) } + Int64.fromDatabaseValue(dbValue).flatMap { UInt64(exactly: $0) } } } @@ -404,7 +404,7 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return DatabaseValue(storage: .double(self)) + DatabaseValue(storage: .double(self)) } /// Returns a Double initialized from *dbValue*, if possible. @@ -435,7 +435,7 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return Double(self).databaseValue + Double(self).databaseValue } /// Returns a Float initialized from *dbValue*, if possible. @@ -466,7 +466,7 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return DatabaseValue(storage: .string(self)) + DatabaseValue(storage: .string(self)) } /// Returns a String initialized from *dbValue*, if possible. diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 29b18c3e7..77dde8e49 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -54,7 +54,7 @@ extension Database { } // Ignore individual changes and transaction rollbacks - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { return false } + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { false } func databaseDidChange(with event: DatabaseEvent) { } func databaseDidRollback(_ db: Database) { } @@ -794,10 +794,10 @@ final class TransactionObservation { private weak var weakObserver: TransactionObserver? private var strongObserver: TransactionObserver? - private var observer: TransactionObserver? { return strongObserver ?? weakObserver } + private var observer: TransactionObserver? { strongObserver ?? weakObserver } fileprivate var isObserving: Bool { - return observer != nil + observer != nil } init(observer: TransactionObserver, extent: Database.TransactionObservationExtent) { @@ -814,7 +814,7 @@ final class TransactionObservation { } func isWrapping(_ observer: TransactionObserver) -> Bool { - return self.observer === observer + self.observer === observer } func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { @@ -934,10 +934,10 @@ public struct DatabaseEvent { public let kind: Kind /// The database name - public var databaseName: String { return impl.databaseName } + public var databaseName: String { impl.databaseName } /// The table name - public var tableName: String { return impl.tableName } + public var tableName: String { impl.tableName } /// The rowID of the changed row. public let rowID: Int64 @@ -951,7 +951,7 @@ public struct DatabaseEvent { /// } /// } public func copy() -> DatabaseEvent { - return impl.copy(self) + impl.copy(self) } fileprivate init(kind: Kind, rowID: Int64, impl: DatabaseEventImpl) { @@ -999,11 +999,11 @@ private struct MetalDatabaseEventImpl: DatabaseEventImpl { let databaseNameCString: UnsafePointer? let tableNameCString: UnsafePointer? - var databaseName: String { return String(cString: databaseNameCString!) } - var tableName: String { return String(cString: tableNameCString!) } + var databaseName: String { String(cString: databaseNameCString!) } + var tableName: String { String(cString: tableNameCString!) } func copy(_ event: DatabaseEvent) -> DatabaseEvent { - return DatabaseEvent( + DatabaseEvent( kind: event.kind, rowID: event.rowID, impl: CopiedDatabaseEventImpl( @@ -1016,9 +1016,7 @@ private struct MetalDatabaseEventImpl: DatabaseEventImpl { private struct CopiedDatabaseEventImpl: DatabaseEventImpl { let databaseName: String let tableName: String - func copy(_ event: DatabaseEvent) -> DatabaseEvent { - return event - } + func copy(_ event: DatabaseEvent) -> DatabaseEvent { event } } #if SQLITE_ENABLE_PREUPDATE_HOOK @@ -1041,13 +1039,13 @@ public struct DatabasePreUpdateEvent { public let kind: Kind /// The database name - public var databaseName: String { return impl.databaseName } + public var databaseName: String { impl.databaseName } /// The table name - public var tableName: String { return impl.tableName } + public var tableName: String { impl.tableName } /// The number of columns in the row that is being inserted, updated, or deleted. - public var count: Int { return Int(impl.columnsCount) } + public var count: Int { Int(impl.columnsCount) } /// The triggering depth of the row update /// Returns: @@ -1056,7 +1054,7 @@ public struct DatabasePreUpdateEvent { /// 1 for inserts, updates, or deletes invoked by top-level triggers; /// 2 for changes resulting from triggers called by top-level triggers; /// ... and so forth - public var depth: CInt { return impl.depth } + public var depth: CInt { impl.depth } /// The initial rowID of the row being changed for .Update and .Delete changes, /// and nil for .Insert changes. @@ -1119,7 +1117,7 @@ public struct DatabasePreUpdateEvent { /// } /// } public func copy() -> DatabasePreUpdateEvent { - return impl.copy(self) + impl.copy(self) } fileprivate init(kind: Kind, initialRowID: Int64?, finalRowID: Int64?, impl: DatabasePreUpdateEventImpl) { @@ -1194,11 +1192,11 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { let databaseNameCString: UnsafePointer? let tableNameCString: UnsafePointer? - var databaseName: String { return String(cString: databaseNameCString!) } - var tableName: String { return String(cString: tableNameCString!) } + var databaseName: String { String(cString: databaseNameCString!) } + var tableName: String { String(cString: tableNameCString!) } - var columnsCount: CInt { return sqlite3_preupdate_count(connection) } - var depth: CInt { return sqlite3_preupdate_depth(connection) } + var columnsCount: CInt { sqlite3_preupdate_count(connection) } + var depth: CInt { sqlite3_preupdate_depth(connection) } var initialDatabaseValues: [DatabaseValue]? { guard kind == .update || kind == .delete else { return nil } return preupdate_getValues_old(connection) @@ -1232,7 +1230,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { } func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent { - return DatabasePreUpdateEvent( + DatabasePreUpdateEvent( kind: event.kind, initialRowID: event.initialRowID, finalRowID: event.finalRowID, @@ -1278,7 +1276,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { } private func preupdate_getValues_old(_ connection: SQLiteConnection) -> [DatabaseValue]? { - return preupdate_getValues( + preupdate_getValues( connection, sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in sqlite3_preupdate_old(connection, column, &value) @@ -1286,7 +1284,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { } private func preupdate_getValues_new(_ connection: SQLiteConnection) -> [DatabaseValue]? { - return preupdate_getValues( + preupdate_getValues( connection, sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in sqlite3_preupdate_new(connection, column, &value) @@ -1303,12 +1301,10 @@ private struct CopiedDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { let initialDatabaseValues: [DatabaseValue]? let finalDatabaseValues: [DatabaseValue]? - func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { return initialDatabaseValues?[index] } - func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { return finalDatabaseValues?[index] } + func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { initialDatabaseValues?[index] } + func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { finalDatabaseValues?[index] } - func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent { - return event - } + func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent { event } } #endif @@ -1363,7 +1359,7 @@ class SavepointStack { private var savepoints: [(name: String, index: Int)] = [] /// If true, there is no current save point. - var isEmpty: Bool { return savepoints.isEmpty } + var isEmpty: Bool { savepoints.isEmpty } func clear() { eventsBuffer.removeAll() diff --git a/GRDB/FTS/FTS3.swift b/GRDB/FTS/FTS3.swift index edc39bac3..1ebddf61e 100644 --- a/GRDB/FTS/FTS3.swift +++ b/GRDB/FTS/FTS3.swift @@ -43,7 +43,7 @@ public struct FTS3: VirtualTableModule { /// /// See Database.create(virtualTable:using:) public func makeTableDefinition() -> FTS3TableDefinition { - return FTS3TableDefinition() + FTS3TableDefinition() } /// Reserved; part of the VirtualTableModule protocol. diff --git a/GRDB/FTS/FTS3Pattern.swift b/GRDB/FTS/FTS3Pattern.swift index 47bf9f454..eac831d5b 100644 --- a/GRDB/FTS/FTS3Pattern.swift +++ b/GRDB/FTS/FTS3Pattern.swift @@ -74,13 +74,13 @@ public struct FTS3Pattern { extension FTS3Pattern: DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return rawPattern.databaseValue + rawPattern.databaseValue } /// Returns an FTS3Pattern initialized from *dbValue*, if it contains /// a suitable value. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> FTS3Pattern? { - return String + String .fromDatabaseValue(dbValue) .flatMap { try? FTS3Pattern(rawPattern: $0) } } diff --git a/GRDB/FTS/FTS3TokenizerDescriptor.swift b/GRDB/FTS/FTS3TokenizerDescriptor.swift index 06bbd0259..8cb023336 100644 --- a/GRDB/FTS/FTS3TokenizerDescriptor.swift +++ b/GRDB/FTS/FTS3TokenizerDescriptor.swift @@ -89,14 +89,14 @@ public struct FTS3TokenizerDescriptor { } func tokenize(_ string: String) -> [String] { - return _tokenize(string) + _tokenize(string) } /// Returns an array of tokens found in the string argument. /// /// FTS3TokenizerDescriptor.simple.tokenize("foo bar") // ["foo", "bar"] private func _tokenize(_ string: String) -> [String] { - return DatabaseQueue().inDatabase { db in + DatabaseQueue().inDatabase { db in var tokenizerChunks: [String] = [] tokenizerChunks.append(name) for option in arguments { diff --git a/GRDB/FTS/FTS4.swift b/GRDB/FTS/FTS4.swift index fcaff61bc..71b45c50f 100644 --- a/GRDB/FTS/FTS4.swift +++ b/GRDB/FTS/FTS4.swift @@ -29,7 +29,7 @@ public struct FTS4: VirtualTableModule { /// /// See Database.create(virtualTable:using:) public func makeTableDefinition() -> FTS4TableDefinition { - return FTS4TableDefinition() + FTS4TableDefinition() } /// Reserved; part of the VirtualTableModule protocol. diff --git a/GRDB/FTS/FTS5.swift b/GRDB/FTS/FTS5.swift index e649e1f51..60fe091e0 100644 --- a/GRDB/FTS/FTS5.swift +++ b/GRDB/FTS/FTS5.swift @@ -55,7 +55,7 @@ public struct FTS5: VirtualTableModule { /// Don't use this method. public func makeTableDefinition() -> FTS5TableDefinition { - return FTS5TableDefinition() + FTS5TableDefinition() } /// Don't use this method. diff --git a/GRDB/FTS/FTS5CustomTokenizer.swift b/GRDB/FTS/FTS5CustomTokenizer.swift index ebfc24d5c..802640e2c 100644 --- a/GRDB/FTS/FTS5CustomTokenizer.swift +++ b/GRDB/FTS/FTS5CustomTokenizer.swift @@ -39,7 +39,7 @@ extension FTS5CustomTokenizer { /// t.tokenizer = tokenizer /// } public static func tokenizerDescriptor(arguments: [String] = []) -> FTS5TokenizerDescriptor { - return FTS5TokenizerDescriptor(components: [name] + arguments) + FTS5TokenizerDescriptor(components: [name] + arguments) } } diff --git a/GRDB/FTS/FTS5Pattern.swift b/GRDB/FTS/FTS5Pattern.swift index 6a49b2235..35d323119 100644 --- a/GRDB/FTS/FTS5Pattern.swift +++ b/GRDB/FTS/FTS5Pattern.swift @@ -128,20 +128,20 @@ extension Database { /// try db.makeFTS5Pattern(rawPattern: "and", forTable: "document") // OK /// try db.makeFTS5Pattern(rawPattern: "AND", forTable: "document") // malformed MATCH expression: [AND] public func makeFTS5Pattern(rawPattern: String, forTable table: String) throws -> FTS5Pattern { - return try FTS5Pattern(rawPattern: rawPattern, allowedColumns: columns(in: table).map(\.name)) + try FTS5Pattern(rawPattern: rawPattern, allowedColumns: columns(in: table).map(\.name)) } } extension FTS5Pattern: DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { - return rawPattern.databaseValue + rawPattern.databaseValue } /// Returns an FTS5Pattern initialized from *dbValue*, if it /// contains a suitable value. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> FTS5Pattern? { - return String + String .fromDatabaseValue(dbValue) .flatMap { try? FTS5Pattern(rawPattern: $0) } } diff --git a/GRDB/FTS/FTS5Tokenizer.swift b/GRDB/FTS/FTS5Tokenizer.swift index b5fbea527..35aec81c5 100644 --- a/GRDB/FTS/FTS5Tokenizer.swift +++ b/GRDB/FTS/FTS5Tokenizer.swift @@ -86,7 +86,7 @@ extension FTS5Tokenizer { /// - .query: Tokenize like the search pattern of the MATCH operator. /// - parameter tokenizer: A FTS5TokenizerDescriptor such as .ascii() func tokenize(_ string: String, for tokenization: FTS5Tokenization) throws -> [(String, FTS5TokenFlags)] { - return try ContiguousArray(string.utf8).withUnsafeBufferPointer { buffer -> [(String, FTS5TokenFlags)] in + try ContiguousArray(string.utf8).withUnsafeBufferPointer { buffer -> [(String, FTS5TokenFlags)] in guard let addr = buffer.baseAddress else { return [] } diff --git a/GRDB/FTS/FTS5TokenizerDescriptor.swift b/GRDB/FTS/FTS5TokenizerDescriptor.swift index 7ef83c9ff..5e498b1b0 100644 --- a/GRDB/FTS/FTS5TokenizerDescriptor.swift +++ b/GRDB/FTS/FTS5TokenizerDescriptor.swift @@ -23,12 +23,10 @@ public struct FTS5TokenizerDescriptor { /// /// // "unicode61" /// FTS5TokenizerDescriptor.unicode61(removeDiacritics: false)).name - var name: String { - return components[0] - } + var name: String { components[0] } var arguments: [String] { - return Array(components.suffix(from: 1)) + Array(components.suffix(from: 1)) } /// Creates an FTS5 tokenizer descriptor. diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 25b1e6ba0..a812e3243 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -190,7 +190,7 @@ public struct DatabaseMigrator { /// - parameter db: A database connection. /// - throws: An eventual database error. public func hasCompletedMigrations(_ db: Database) throws -> Bool { - return try completedMigrations(db).last == migrations.last?.identifier + try completedMigrations(db).last == migrations.last?.identifier } // MARK: - Non public diff --git a/GRDB/QueryInterface/FTS3+QueryInterface.swift b/GRDB/QueryInterface/FTS3+QueryInterface.swift index 9faee9094..7e87699a6 100644 --- a/GRDB/QueryInterface/FTS3+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS3+QueryInterface.swift @@ -37,7 +37,7 @@ extension TableRecord { /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. public static func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest { - return all().matching(pattern) + all().matching(pattern) } } @@ -50,6 +50,6 @@ extension ColumnExpression { /// If the search pattern is nil, SQLite will evaluate the expression /// to false. public func match(_ pattern: FTS3Pattern?) -> SQLExpression { - return SQLExpressionBinary(.match, self, pattern ?? DatabaseValue.null) + SQLExpressionBinary(.match, self, pattern ?? DatabaseValue.null) } } diff --git a/GRDB/QueryInterface/FTS5+QueryInterface.swift b/GRDB/QueryInterface/FTS5+QueryInterface.swift index e8d74aa79..000b536dd 100644 --- a/GRDB/QueryInterface/FTS5+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS5+QueryInterface.swift @@ -38,7 +38,7 @@ extension TableRecord { /// If the search pattern is nil, the request does not match any /// database row. public static func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest { - return all().matching(pattern) + all().matching(pattern) } } #endif diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index 2070a1e49..26dbd9418 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -46,33 +46,33 @@ public protocol Association: DerivableRequest { extension Association { /// :nodoc: public func _including(all association: SQLAssociation) -> Self { - return mapDestinationRelation { $0._including(all: association) } + mapDestinationRelation { $0._including(all: association) } } /// :nodoc: public func _including(optional association: SQLAssociation) -> Self { - return mapDestinationRelation { $0._including(optional: association) } + mapDestinationRelation { $0._including(optional: association) } } /// :nodoc: public func _including(required association: SQLAssociation) -> Self { - return mapDestinationRelation { $0._including(required: association) } + mapDestinationRelation { $0._including(required: association) } } /// :nodoc: public func _joining(optional association: SQLAssociation) -> Self { - return mapDestinationRelation { $0._joining(optional: association) } + mapDestinationRelation { $0._joining(optional: association) } } /// :nodoc: public func _joining(required association: SQLAssociation) -> Self { - return mapDestinationRelation { $0._joining(required: association) } + mapDestinationRelation { $0._joining(required: association) } } } extension Association { private func mapDestinationRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self { - return .init(sqlAssociation: sqlAssociation.map(\.destination.relation, transform)) + .init(sqlAssociation: sqlAssociation.map(\.destination.relation, transform)) } } @@ -102,9 +102,7 @@ extension Association { /// for row in Row.fetchAll(db, request) { /// let team: Team = row["custom"] /// } - var key: SQLAssociationKey { - return sqlAssociation.destination.key - } + var key: SQLAssociationKey { sqlAssociation.destination.key } /// Creates an association which selects *selection*. /// @@ -128,7 +126,7 @@ extension Association { /// .select([Column("color")]) /// var request = Player.including(required: association) public func select(_ selection: [SQLSelectable]) -> Self { - return mapDestinationRelation { $0.select(selection) } + mapDestinationRelation { $0.select(selection) } } /// Creates an association which appends *selection*. @@ -145,7 +143,7 @@ extension Association { /// .annotated(with: [Column("name")]) /// var request = Player.including(required: association) public func annotated(with selection: [SQLSelectable]) -> Self { - return mapDestinationRelation { $0.annotated(with: selection) } + mapDestinationRelation { $0.annotated(with: selection) } } /// Creates an association with the provided *predicate promise* added to @@ -161,7 +159,7 @@ extension Association { /// let association = Player.team.filter { db in true } /// var request = Player.including(required: association) public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { - return mapDestinationRelation { $0.filter(predicate) } + mapDestinationRelation { $0.filter(predicate) } } /// Creates an association with the provided *orderings promise*. @@ -189,7 +187,7 @@ extension Association { /// .order{ _ in [Column("name")] } /// var request = Player.including(required: association) public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self { - return mapDestinationRelation { $0.order(orderings) } + mapDestinationRelation { $0.order(orderings) } } /// Creates an association that reverses applied orderings. @@ -213,7 +211,7 @@ extension Association { /// let association = Player.team.reversed() /// var request = Player.including(required: association) public func reversed() -> Self { - return mapDestinationRelation { $0.reversed() } + mapDestinationRelation { $0.reversed() } } /// Creates an association without any ordering. @@ -228,7 +226,7 @@ extension Association { /// let association = Player.team.order(Column("name")).unordered() /// var request = Player.including(required: association) public func unordered() -> Self { - return mapDestinationRelation { $0.unordered() } + mapDestinationRelation { $0.unordered() } } /// Creates an association with the given key. @@ -254,7 +252,7 @@ extension Association { /// let playerInfos = PlayerInfo.all().fetchAll(db) /// print(playerInfos.first?.team) public func forKey(_ codingKey: CodingKey) -> Self { - return forKey(codingKey.stringValue) + forKey(codingKey.stringValue) } /// Creates an association that allows you to define expressions that target @@ -286,14 +284,14 @@ extension Association { /// .including(required: Player.team.aliased(teamAlias)) /// .filter(sql: "custom.color = ?", arguments: ["red"]) public func aliased(_ alias: TableAlias) -> Self { - return mapDestinationRelation { $0.qualified(with: alias) } + mapDestinationRelation { $0.qualified(with: alias) } } } // TableRequest extension Association { /// :nodoc: - public var databaseTableName: String { return RowDecoder.databaseTableName } + public var databaseTableName: String { RowDecoder.databaseTableName } } // MARK: - AssociationToOne @@ -326,7 +324,7 @@ extension AssociationToMany { extension AssociationToMany { private func makeAggregate(_ expression: SQLExpression) -> AssociationAggregate { - return AssociationAggregate { request in + AssociationAggregate { request in let tableAlias = TableAlias() let request = request .joining(optional: self.aliased(tableAlias)) @@ -352,7 +350,7 @@ extension AssociationToMany { /// /// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db) public var count: AssociationAggregate { - return makeAggregate(SQLExpressionCountDistinct(Column.rowID)) + makeAggregate(SQLExpressionCountDistinct(Column.rowID)) .forKey("\(key.singularizedName)Count") } @@ -372,7 +370,7 @@ extension AssociationToMany { /// let teams: [Team] = try Team.having(!Team.players.isEmpty()) /// let teams: [Team] = try Team.having(Team.players.isEmpty() == false) public var isEmpty: AssociationAggregate { - return makeAggregate(SQLExpressionIsEmpty(SQLExpressionCountDistinct(Column.rowID))) + makeAggregate(SQLExpressionIsEmpty(SQLExpressionCountDistinct(Column.rowID))) .forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)") } diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index 7ac1c68a0..e31d01c73 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -81,7 +81,7 @@ extension AssociationAggregate: KeyPathRefining { /// let numberOfBooks: Int = row["numberOfBooks"] /// } public func forKey(_ key: String) -> AssociationAggregate { - return with(\.key, key) + with(\.key, key) } /// Returns an aggregate that is selected in a column named like the given @@ -100,7 +100,7 @@ extension AssociationAggregate: KeyPathRefining { /// } /// } public func forKey(_ key: CodingKey) -> AssociationAggregate { - return forKey(key.stringValue) + forKey(key.stringValue) } } @@ -112,7 +112,7 @@ extension AssociationAggregate: KeyPathRefining { /// /// Author.having(!Author.books.isEmpty) public prefix func ! (aggregate: AssociationAggregate) -> AssociationAggregate { - return AssociationAggregate { request in + AssociationAggregate { request in let (request, expression) = aggregate.prepare(request) return (request: request, expression: !expression) } @@ -262,7 +262,7 @@ public func == ( /// /// Author.having(Author.books.isEmpty == false) public func == (lhs: AssociationAggregate, rhs: Bool) -> AssociationAggregate { - return AssociationAggregate { request in + AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression == rhs) } @@ -274,7 +274,7 @@ public func == (lhs: AssociationAggregate, rhs: Bool) -> /// /// Author.having(false == Author.books.isEmpty) public func == (lhs: Bool, rhs: AssociationAggregate) -> AssociationAggregate { - return AssociationAggregate { request in + AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs == expression) } @@ -335,7 +335,7 @@ public func != ( /// /// Author.having(Author.books.isEmpty != true) public func != (lhs: AssociationAggregate, rhs: Bool) -> AssociationAggregate { - return AssociationAggregate { request in + AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression != rhs) } @@ -347,7 +347,7 @@ public func != (lhs: AssociationAggregate, rhs: Bool) -> /// /// Author.having(true != Author.books.isEmpty) public func != (lhs: Bool, rhs: AssociationAggregate) -> AssociationAggregate { - return AssociationAggregate { request in + AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs != expression) } @@ -657,7 +657,7 @@ public func >= ( /// /// Author.annotated(with: -Author.books.count) public prefix func - (aggregate: AssociationAggregate) -> AssociationAggregate { - return AssociationAggregate { request in + AssociationAggregate { request in let (request, expression) = aggregate.prepare(request) return (request: request, expression:-expression) } diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift index 403376c33..dd33bd864 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift @@ -18,7 +18,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { /// var request = Player.all() /// request = request.annotated(with: Player.books.count) public func annotated(with aggregates: AssociationAggregate...) -> QueryInterfaceRequest { - return annotated(with: aggregates) + annotated(with: aggregates) } /// Creates a request which appends *aggregates* to the current selection. @@ -28,7 +28,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { /// var request = Player.all() /// request = request.annotated(with: [Player.books.count]) public func annotated(with aggregates: [AssociationAggregate]) -> QueryInterfaceRequest { - return aggregates.reduce(self) { request, aggregate in + aggregates.reduce(self) { request, aggregate in request.annotated(with: aggregate) } } diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 828ff4e2c..8d0951811 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -78,7 +78,7 @@ extension QueryInterfaceRequest: FetchRequest { /// - parameter db: A database connection. /// :nodoc: public func fetchCount(_ db: Database) throws -> Int { - return try query.fetchCount(db) + try query.fetchCount(db) } /// Returns the database region that the request looks into. @@ -132,7 +132,7 @@ extension QueryInterfaceRequest: SelectionRequest { /// .select([Column("id")]) /// .select([Column("email")]) public func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest { - return map(\.query, { $0.select(selection) }) + map(\.query, { $0.select(selection) }) } /// Creates a request which selects *selection*, and fetches values of @@ -223,7 +223,7 @@ extension QueryInterfaceRequest: SelectionRequest { /// .select([Column("id"), Column("email")]) /// .annotated(with: [Column("name")]) public func annotated(with selection: [SQLSelectable]) -> QueryInterfaceRequest { - return map(\.query, { $0.annotated(with: selection) }) + map(\.query, { $0.annotated(with: selection) }) } } @@ -237,7 +237,7 @@ extension QueryInterfaceRequest: FilteredRequest { /// var request = Player.all() /// request = request.filter { db in true } public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { - return map(\.query, { $0.filter(predicate) }) + map(\.query, { $0.filter(predicate) }) } } @@ -258,7 +258,7 @@ extension QueryInterfaceRequest: OrderedRequest { /// .reversed() /// .order{ _ in [Column("name")] } public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceRequest { - return map(\.query, { $0.order(orderings) }) + map(\.query, { $0.order(orderings) }) } /// Creates a request that reverses applied orderings. @@ -273,7 +273,7 @@ extension QueryInterfaceRequest: OrderedRequest { /// var request = Player.all() /// request = request.reversed() public func reversed() -> QueryInterfaceRequest { - return map(\.query, { $0.reversed() }) + map(\.query, { $0.reversed() }) } /// Creates a request without any ordering. @@ -282,7 +282,7 @@ extension QueryInterfaceRequest: OrderedRequest { /// var request = Player.all().order(Column("name")) /// request = request.unordered() public func unordered() -> QueryInterfaceRequest { - return map(\.query, { $0.unordered() }) + map(\.query, { $0.unordered() }) } } @@ -291,40 +291,40 @@ extension QueryInterfaceRequest: AggregatingRequest { /// Creates a request grouped according to *expressions promise*. public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> QueryInterfaceRequest { - return map(\.query, { $0.group(expressions) }) + map(\.query, { $0.group(expressions) }) } /// Creates a request with the provided *predicate* added to the /// eventual set of already applied predicates. public func having(_ predicate: SQLExpressible) -> QueryInterfaceRequest { - return map(\.query, { $0.having(predicate) }) + map(\.query, { $0.having(predicate) }) } } extension QueryInterfaceRequest: _JoinableRequest { /// :nodoc: public func _including(all association: SQLAssociation) -> QueryInterfaceRequest { - return map(\.query, { $0._including(all: association) }) + map(\.query, { $0._including(all: association) }) } /// :nodoc: public func _including(optional association: SQLAssociation) -> QueryInterfaceRequest { - return map(\.query, { $0._including(optional: association) }) + map(\.query, { $0._including(optional: association) }) } /// :nodoc: public func _including(required association: SQLAssociation) -> QueryInterfaceRequest { - return map(\.query, { $0._including(required: association) }) + map(\.query, { $0._including(required: association) }) } /// :nodoc: public func _joining(optional association: SQLAssociation) -> QueryInterfaceRequest { - return map(\.query, { $0._joining(optional: association) }) + map(\.query, { $0._joining(optional: association) }) } /// :nodoc: public func _joining(required association: SQLAssociation) -> QueryInterfaceRequest { - return map(\.query, { $0._joining(required: association) }) + map(\.query, { $0._joining(required: association) }) } } @@ -344,7 +344,7 @@ extension QueryInterfaceRequest: KeyPathRefining { /// var request = Player.select(Column("name")) /// request = request.distinct() public func distinct() -> QueryInterfaceRequest { - return map(\.query, { $0.distinct() }) + map(\.query, { $0.distinct() }) } /// Creates a request which expects a single result. @@ -355,7 +355,7 @@ extension QueryInterfaceRequest: KeyPathRefining { /// /// :nodoc: public func expectingSingleResult() -> QueryInterfaceRequest { - return map(\.query, { $0.expectingSingleResult() }) + map(\.query, { $0.expectingSingleResult() }) } @@ -367,7 +367,7 @@ extension QueryInterfaceRequest: KeyPathRefining { /// /// Any previous limit is replaced. public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { - return map(\.query, { $0.limit(limit, offset: offset) }) + map(\.query, { $0.limit(limit, offset: offset) }) } /// Creates a request that allows you to define expressions that target @@ -388,7 +388,7 @@ extension QueryInterfaceRequest: KeyPathRefining { /// .aliased(playerAlias) /// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")]) public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { - return map(\.query, { $0.qualified(with: alias) }) + map(\.query, { $0.qualified(with: alias) }) } /// Creates a request bound to type Target. @@ -405,7 +405,7 @@ extension QueryInterfaceRequest: KeyPathRefining { /// - parameter type: The fetched type Target /// - returns: A typed request bound to type Target. public func asRequest(of type: RowDecoder.Type) -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query) + QueryInterfaceRequest(query: query) } } @@ -613,7 +613,7 @@ extension Array where Element == Row { extension Row { /// - precondition: Columns all exist in the row. fileprivate func indexes(ofColumns columns: [String]) -> [Int] { - return columns.map { column -> Int in + columns.map { column -> Int in guard let index = index(ofColumn: column) else { fatalError("Column \(column) is not selected") } @@ -658,7 +658,7 @@ public struct ColumnAssignment { /// try Player.updateAll(db, Column("score") <- 0) /// } public func <- (column: ColumnExpression, value: SQLExpressible) -> ColumnAssignment { - return ColumnAssignment(column: column, value: value) + ColumnAssignment(column: column, value: value) } /// Creates an assignment that adds a value @@ -671,7 +671,7 @@ public func <- (column: ColumnExpression, value: SQLExpressible) -> ColumnAssign /// try Player.updateAll(db, Column("score") += 1) /// } public func += (column: ColumnExpression, value: SQLExpressible) -> ColumnAssignment { - return column <- column + value + column <- column + value } /// Creates an assignment that subtracts a value @@ -684,7 +684,7 @@ public func += (column: ColumnExpression, value: SQLExpressible) -> ColumnAssign /// try Player.updateAll(db, Column("score") -= 1) /// } public func -= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssignment { - return column <- column - value + column <- column - value } /// Creates an assignment that multiplies by a value @@ -697,7 +697,7 @@ public func -= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssign /// try Player.updateAll(db, Column("score") *= 2) /// } public func *= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssignment { - return column <- column * value + column <- column * value } /// Creates an assignment that divides by a value @@ -710,5 +710,5 @@ public func *= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssign /// try Player.updateAll(db, Column("score") /= 2) /// } public func /= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssignment { - return column <- column / value + column <- column / value } diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 043f9fd6e..ae0dc95ea 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -45,7 +45,7 @@ extension SelectionRequest { /// .select(Column("id")) /// .select(Column("email")) public func select(_ selection: SQLSelectable...) -> Self { - return select(selection) + select(selection) } /// Creates a request which selects *sql*. @@ -61,7 +61,7 @@ extension SelectionRequest { /// .select(sql: "id") /// .select(sql: "email") public func select(sql: String, arguments: StatementArguments = StatementArguments()) -> Self { - return select(literal: SQLLiteral(sql: sql, arguments: arguments)) + select(literal: SQLLiteral(sql: sql, arguments: arguments)) } /// Creates a request which selects an SQL *literal*. @@ -102,7 +102,7 @@ extension SelectionRequest { /// .select([Column("id"), Column("email")]) /// .annotated(with: Column("name")) public func annotated(with selection: SQLSelectable...) -> Self { - return annotated(with: selection) + annotated(with: selection) } } @@ -135,7 +135,7 @@ public protocol FilteredRequest { /// :nodoc: extension FilteredRequest { public func expectingSingleResult() -> Self { - return self + self } /// Creates a request with the provided *predicate* added to the @@ -145,7 +145,7 @@ extension FilteredRequest { /// var request = Player.all() /// request = request.filter(Column("email") == "arthur@example.com") public func filter(_ predicate: SQLExpressible) -> Self { - return filter { _ in predicate } + filter { _ in predicate } } /// Creates a request with the provided *predicate* added to the @@ -155,7 +155,7 @@ extension FilteredRequest { /// var request = Player.all() /// request = request.filter(sql: "email = ?", arguments: ["arthur@example.com"]) public func filter(sql: String, arguments: StatementArguments = StatementArguments()) -> Self { - return filter(literal: SQLLiteral(sql: sql, arguments: arguments)) + filter(literal: SQLLiteral(sql: sql, arguments: arguments)) } /// Creates a request with the provided *predicate* added to the @@ -183,7 +183,7 @@ extension FilteredRequest { /// var request = Player.all() /// request = request.none() public func none() -> Self { - return filter(false) + filter(false) } } @@ -353,17 +353,17 @@ public protocol AggregatingRequest { extension AggregatingRequest { /// Creates a request grouped according to *expressions*. public func group(_ expressions: [SQLExpressible]) -> Self { - return group { _ in expressions } + group { _ in expressions } } /// Creates a request grouped according to *expressions*. public func group(_ expressions: SQLExpressible...) -> Self { - return group(expressions) + group(expressions) } /// Creates a request with a new grouping. public func group(sql: String, arguments: StatementArguments = StatementArguments()) -> Self { - return group(literal: SQLLiteral(sql: sql, arguments: arguments)) + group(literal: SQLLiteral(sql: sql, arguments: arguments)) } /// Creates a request with a new grouping. @@ -375,7 +375,7 @@ extension AggregatingRequest { /// Creates a request with the provided *sql* added to the /// eventual set of already applied predicates. public func having(sql: String, arguments: StatementArguments = StatementArguments()) -> Self { - return having(literal: SQLLiteral(sql: sql, arguments: arguments)) + having(literal: SQLLiteral(sql: sql, arguments: arguments)) } /// Creates a request with the provided *sql* added to the @@ -446,7 +446,7 @@ extension OrderedRequest { /// .reversed() /// .order(Column("name")) public func order(_ orderings: SQLOrderingTerm...) -> Self { - return order { _ in orderings } + order { _ in orderings } } /// Creates a request with the provided *orderings*. @@ -463,7 +463,7 @@ extension OrderedRequest { /// .reversed() /// .order(Column("name")) public func order(_ orderings: [SQLOrderingTerm]) -> Self { - return order { _ in orderings } + order { _ in orderings } } /// Creates a request sorted according to *sql*. @@ -479,7 +479,7 @@ extension OrderedRequest { /// .order(sql: "email") /// .order(sql: "name") public func order(sql: String, arguments: StatementArguments = StatementArguments()) -> Self { - return order(literal: SQLLiteral(sql: sql, arguments: arguments)) + order(literal: SQLLiteral(sql: sql, arguments: arguments)) } /// Creates a request sorted according to an SQL *literal*. @@ -556,35 +556,35 @@ public protocol JoinableRequest: _JoinableRequest { extension JoinableRequest { /// Creates a request that prefetches an association. public func including(all association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return _including(all: association.sqlAssociation) + _including(all: association.sqlAssociation) } /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned request does not /// require that the associated database table contains a matching row. public func including(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return _including(optional: association.sqlAssociation) + _including(optional: association.sqlAssociation) } /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned request requires /// that the associated database table contains a matching row. public func including(required association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return _including(required: association.sqlAssociation) + _including(required: association.sqlAssociation) } /// Creates a request that joins an association. The columns of the /// associated record are not selected. The returned request does not /// require that the associated database table contains a matching row. public func joining(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return _joining(optional: association.sqlAssociation) + _joining(optional: association.sqlAssociation) } /// Creates a request that joins an association. The columns of the /// associated record are not selected. The returned request requires /// that the associated database table contains a matching row. public func joining(required association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return _joining(required: association.sqlAssociation) + _joining(required: association.sqlAssociation) } } diff --git a/GRDB/QueryInterface/SQL/Column.swift b/GRDB/QueryInterface/SQL/Column.swift index a694a7b6d..a0e1f36b1 100644 --- a/GRDB/QueryInterface/SQL/Column.swift +++ b/GRDB/QueryInterface/SQL/Column.swift @@ -28,13 +28,13 @@ extension ColumnExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String { - return name.quotedDatabaseIdentifier + name.quotedDatabaseIdentifier } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - return QualifiedColumn(name, alias: alias) + QualifiedColumn(name, alias: alias) } } @@ -94,7 +94,5 @@ struct QualifiedColumn: ColumnExpression { /// } /// } extension ColumnExpression where Self: RawRepresentable, Self.RawValue == String { - public var name: String { - return rawValue - } + public var name: String { rawValue } } diff --git a/GRDB/QueryInterface/SQL/DatabasePromise.swift b/GRDB/QueryInterface/SQL/DatabasePromise.swift index d3194fc8f..f5f1ca31c 100644 --- a/GRDB/QueryInterface/SQL/DatabasePromise.swift +++ b/GRDB/QueryInterface/SQL/DatabasePromise.swift @@ -37,13 +37,13 @@ struct DatabasePromise { /// Returns a promise whose value is transformed by the given closure. func map(_ transform: @escaping (T) throws -> U) -> DatabasePromise { - return DatabasePromise { db in + DatabasePromise { db in try transform(self.resolve(db)) } } func flatMap(_ transform: @escaping (T) -> DatabasePromise) -> DatabasePromise { - return DatabasePromise { db in + DatabasePromise { db in try transform(self.resolve(db)).resolve(db) } } diff --git a/GRDB/QueryInterface/SQL/SQLAssociation.swift b/GRDB/QueryInterface/SQL/SQLAssociation.swift index b49cb3d72..635647af6 100644 --- a/GRDB/QueryInterface/SQL/SQLAssociation.swift +++ b/GRDB/QueryInterface/SQL/SQLAssociation.swift @@ -54,17 +54,15 @@ public /* TODO: internal */ struct SQLAssociation { // All steps, from pivot to destination. Never empty. private(set) var steps: [SQLAssociationStep] - var keyPath: [String] { - return steps.map(\.keyName) - } + var keyPath: [String] { steps.map(\.keyName) } var destination: SQLAssociationStep { - get { return steps[steps.count - 1] } + get { steps[steps.count - 1] } set { steps[steps.count - 1] = newValue } } var pivot: SQLAssociationStep { - get { return steps[0] } + get { steps[0] } set { steps[0] = newValue } } @@ -89,12 +87,12 @@ public /* TODO: internal */ struct SQLAssociation { /// Changes the destination key func forDestinationKey(_ key: SQLAssociationKey) -> SQLAssociation { - return with(\.destination.key, key) + with(\.destination.key, key) } /// Returns a new association func through(_ other: SQLAssociation) -> SQLAssociation { - return SQLAssociation(steps: other.steps + steps) + SQLAssociation(steps: other.steps + steps) } /// Given an origin alias and rows, returns the destination of the @@ -205,9 +203,7 @@ struct SQLAssociationStep: KeyPathRefining { var relation: SQLRelation var cardinality: SQLAssociationCardinality - var keyName: String { - return key.name(for: cardinality) - } + var keyName: String { key.name(for: cardinality) } } enum SQLAssociationCardinality { diff --git a/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift b/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift index 1cdc5cc2b..81b0f7cf3 100644 --- a/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift @@ -25,7 +25,7 @@ public struct SQLCollatedExpression { /// /// See https://github.com/groue/GRDB.swift/#the-query-interface public var asc: SQLOrderingTerm { - return SQLOrdering.asc(sqlExpression) + SQLOrdering.asc(sqlExpression) } /// Returns an ordering suitable for QueryInterfaceRequest.order() @@ -37,7 +37,7 @@ public struct SQLCollatedExpression { /// /// See https://github.com/groue/GRDB.swift/#the-query-interface public var desc: SQLOrderingTerm { - return SQLOrdering.desc(sqlExpression) + SQLOrdering.desc(sqlExpression) } #if GRDBCUSTOMSQLITE @@ -50,7 +50,7 @@ public struct SQLCollatedExpression { /// /// See https://github.com/groue/GRDB.swift/#the-query-interface public var ascNullsLast: SQLOrderingTerm { - return SQLOrdering.ascNullsLast(sqlExpression) + SQLOrdering.ascNullsLast(sqlExpression) } /// Returns an ordering suitable for QueryInterfaceRequest.order() @@ -62,7 +62,7 @@ public struct SQLCollatedExpression { /// /// See https://github.com/groue/GRDB.swift/#the-query-interface public var descNullsFirst: SQLOrderingTerm { - return SQLOrdering.descNullsFirst(sqlExpression) + SQLOrdering.descNullsFirst(sqlExpression) } #endif @@ -72,7 +72,7 @@ public struct SQLCollatedExpression { } var sqlExpression: SQLExpression { - return SQLExpressionCollate(expression, collationName: collationName) + SQLExpressionCollate(expression, collationName: collationName) } } @@ -82,18 +82,18 @@ extension SQLCollatedExpression: SQLOrderingTerm { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public var reversed: SQLOrderingTerm { - return desc + desc } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func orderingTermSQL(_ context: inout SQLGenerationContext) -> String { - return sqlExpression.orderingTermSQL(&context) + sqlExpression.orderingTermSQL(&context) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { - return SQLCollatedExpression(expression.qualifiedExpression(with: alias), collationName: collationName) + SQLCollatedExpression(expression.qualifiedExpression(with: alias), collationName: collationName) } } diff --git a/GRDB/QueryInterface/SQL/SQLCollection.swift b/GRDB/QueryInterface/SQL/SQLCollection.swift index 73cae7fb7..5e2992316 100644 --- a/GRDB/QueryInterface/SQL/SQLCollection.swift +++ b/GRDB/QueryInterface/SQL/SQLCollection.swift @@ -27,7 +27,7 @@ extension SQLCollection { /// /// Returns a SQLExpressionContains which applies the `IN` SQL operator. public func contains(_ value: SQLExpressible) -> SQLExpression { - return SQLExpressionContains(value, self) + SQLExpressionContains(value, self) } } @@ -45,7 +45,7 @@ struct SQLExpressionsArray: SQLCollection { } func collectionSQL(_ context: inout SQLGenerationContext) -> String { - return expressions + expressions .map { $0.expressionSQL(&context, wrappedInParenthesis: false) } .joined(separator: ", ") } diff --git a/GRDB/QueryInterface/SQL/SQLExpressible.swift b/GRDB/QueryInterface/SQL/SQLExpressible.swift index a0bb76240..6a6a3746e 100644 --- a/GRDB/QueryInterface/SQL/SQLExpressible.swift +++ b/GRDB/QueryInterface/SQL/SQLExpressible.swift @@ -59,13 +59,13 @@ extension SQLExpressible where Self: SQLOrderingTerm { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public var reversed: SQLOrderingTerm { - return SQLOrdering.desc(sqlExpression) + SQLOrdering.desc(sqlExpression) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func orderingTermSQL(_ context: inout SQLGenerationContext) -> String { - return sqlExpression.expressionSQL(&context, wrappedInParenthesis: false) + sqlExpression.expressionSQL(&context, wrappedInParenthesis: false) } } @@ -76,24 +76,24 @@ extension SQLExpressible where Self: SQLSelectable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func resultColumnSQL(_ context: inout SQLGenerationContext) -> String { - return sqlExpression.expressionSQL(&context, wrappedInParenthesis: false) + sqlExpression.expressionSQL(&context, wrappedInParenthesis: false) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func countedSQL(_ context: inout SQLGenerationContext) -> String { - return sqlExpression.expressionSQL(&context, wrappedInParenthesis: false) + sqlExpression.expressionSQL(&context, wrappedInParenthesis: false) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func count(distinct: Bool) -> SQLCount? { - return sqlExpression.count(distinct: distinct) + sqlExpression.count(distinct: distinct) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func columnCount(_ db: Database) throws -> Int { - return 1 + 1 } } diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift index 0918a57ac..0731c0773 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -80,7 +80,7 @@ public struct SQLExpressionUnary: SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - return SQLExpressionUnary(op, expression.qualifiedExpression(with: alias)) + SQLExpressionUnary(op, expression.qualifiedExpression(with: alias)) } } @@ -190,7 +190,7 @@ public struct SQLExpressionBinary: SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - return SQLExpressionBinary(op, lhs.qualifiedExpression(with: alias), rhs.qualifiedExpression(with: alias)) + SQLExpressionBinary(op, lhs.qualifiedExpression(with: alias), rhs.qualifiedExpression(with: alias)) } } @@ -280,7 +280,7 @@ struct SQLExpressionBinaryReduce: SQLExpression { } func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - return SQLExpressionBinaryReduce(op, expressions.map { $0.qualifiedExpression(with: alias) }) + SQLExpressionBinaryReduce(op, expressions.map { $0.qualifiedExpression(with: alias) }) } func matchedRowIds(rowIdName: String?) -> Set? { @@ -343,7 +343,7 @@ extension Sequence where Element == SQLExpression { /// // SELECT * FROM player WHERE 0 /// Player.filter([].joined(operator: .or)) public func joined(operator: SQLAssociativeBinaryOperator) -> SQLExpression { - return SQLExpressionBinaryReduce(`operator`, Array(self)) + SQLExpressionBinaryReduce(`operator`, Array(self)) } } @@ -388,11 +388,11 @@ struct SQLExpressionEqual: SQLExpression { } var negated: SQLExpression { - return SQLExpressionEqual(op.negated, lhs, rhs) + SQLExpressionEqual(op.negated, lhs, rhs) } func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - return SQLExpressionEqual(op, lhs.qualifiedExpression(with: alias), rhs.qualifiedExpression(with: alias)) + SQLExpressionEqual(op, lhs.qualifiedExpression(with: alias), rhs.qualifiedExpression(with: alias)) } func matchedRowIds(rowIdName: String?) -> Set? { @@ -459,11 +459,11 @@ struct SQLExpressionContains: SQLExpression { } var negated: SQLExpression { - return SQLExpressionContains(expression, collection, negated: !isNegated) + SQLExpressionContains(expression, collection, negated: !isNegated) } func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - return SQLExpressionContains(expression.qualifiedExpression(with: alias), collection, negated: isNegated) + SQLExpressionContains(expression.qualifiedExpression(with: alias), collection, negated: isNegated) } func matchedRowIds(rowIdName: String?) -> Set? { @@ -529,11 +529,11 @@ struct SQLExpressionBetween: SQLExpression { } var negated: SQLExpression { - return SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated) + SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated) } func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - return SQLExpressionBetween( + SQLExpressionBetween( expression.qualifiedExpression(with: alias), lowerBound.qualifiedExpression(with: alias), upperBound.qualifiedExpression(with: alias), @@ -621,7 +621,7 @@ public struct SQLExpressionFunction: SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - return SQLExpressionFunction(functionName, arguments: arguments.map { $0.qualifiedExpression(with: alias) }) + SQLExpressionFunction(functionName, arguments: arguments.map { $0.qualifiedExpression(with: alias) }) } } @@ -640,11 +640,11 @@ struct SQLExpressionCount: SQLExpression { } func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String { - return "COUNT(" + counted.countedSQL(&context) + ")" + "COUNT(" + counted.countedSQL(&context) + ")" } func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - return SQLExpressionCount(counted.qualifiedSelectable(with: alias)) + SQLExpressionCount(counted.qualifiedSelectable(with: alias)) } } @@ -662,11 +662,11 @@ struct SQLExpressionCountDistinct: SQLExpression { } func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String { - return "COUNT(DISTINCT " + counted.expressionSQL(&context, wrappedInParenthesis: false) + ")" + "COUNT(DISTINCT " + counted.expressionSQL(&context, wrappedInParenthesis: false) + ")" } func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - return SQLExpressionCountDistinct(counted.qualifiedExpression(with: alias)) + SQLExpressionCountDistinct(counted.qualifiedExpression(with: alias)) } } @@ -686,7 +686,7 @@ struct SQLExpressionIsEmpty: SQLExpression { } var negated: SQLExpression { - return SQLExpressionIsEmpty(countExpression, isEmpty: !isEmpty) + SQLExpressionIsEmpty(countExpression, isEmpty: !isEmpty) } func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String { @@ -700,7 +700,7 @@ struct SQLExpressionIsEmpty: SQLExpression { } func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - return SQLExpressionIsEmpty(countExpression.qualifiedExpression(with: alias), isEmpty: isEmpty) + SQLExpressionIsEmpty(countExpression.qualifiedExpression(with: alias), isEmpty: isEmpty) } } @@ -722,7 +722,7 @@ struct TableMatchExpression: SQLExpression { } func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - return TableMatchExpression( + TableMatchExpression( alias: self.alias, pattern: pattern.qualifiedExpression(with: alias)) } @@ -755,6 +755,6 @@ struct SQLExpressionCollate: SQLExpression { } func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - return SQLExpressionCollate(expression.qualifiedExpression(with: alias), collationName: collationName) + SQLExpressionCollate(expression.qualifiedExpression(with: alias), collationName: collationName) } } diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index ac9fed167..19cabbc40 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -54,7 +54,7 @@ extension SQLExpression { /// /// :nodoc: public var negated: SQLExpression { - return SQLExpressionNot(self) + SQLExpressionNot(self) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) @@ -63,7 +63,7 @@ extension SQLExpression { /// /// :nodoc: public func matchedRowIds(rowIdName: String?) -> Set? { - return nil + nil } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) @@ -72,7 +72,7 @@ extension SQLExpression { /// /// :nodoc: public func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { - return qualifiedExpression(with: alias) + qualifiedExpression(with: alias) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) @@ -81,7 +81,7 @@ extension SQLExpression { /// /// :nodoc: public func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { - return qualifiedExpression(with: alias) + qualifiedExpression(with: alias) } } @@ -92,7 +92,7 @@ extension SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public var sqlExpression: SQLExpression { - return self + self } } @@ -134,10 +134,10 @@ struct SQLExpressionNot: SQLExpression { } var negated: SQLExpression { - return expression + expression } func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - return SQLExpressionNot(expression.qualifiedExpression(with: alias)) + SQLExpressionNot(expression.qualifiedExpression(with: alias)) } } diff --git a/GRDB/QueryInterface/SQL/SQLFunctions.swift b/GRDB/QueryInterface/SQL/SQLFunctions.swift index 1a30251a3..9178f6521 100644 --- a/GRDB/QueryInterface/SQL/SQLFunctions.swift +++ b/GRDB/QueryInterface/SQL/SQLFunctions.swift @@ -5,7 +5,7 @@ extension DatabaseFunction { /// /// See https://github.com/groue/GRDB.swift/#sql-functions public func callAsFunction(_ arguments: SQLExpressible...) -> SQLExpression { - return SQLExpressionFunction(SQLFunctionName(name), arguments: arguments.map(\.sqlExpression)) + SQLExpressionFunction(SQLFunctionName(name), arguments: arguments.map(\.sqlExpression)) } } @@ -22,7 +22,7 @@ extension SQLFunctionName { /// // ABS(amount) /// abs(Column("amount")) public func abs(_ value: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionFunction(.abs, arguments: value) + SQLExpressionFunction(.abs, arguments: value) } @@ -38,7 +38,7 @@ extension SQLFunctionName { /// // AVG(length) /// average(Column("length")) public func average(_ value: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionFunction(.avg, arguments: value) + SQLExpressionFunction(.avg, arguments: value) } @@ -49,7 +49,7 @@ public func average(_ value: SQLSpecificExpressible) -> SQLExpression { /// // COUNT(email) /// count(Column("email")) public func count(_ counted: SQLSelectable) -> SQLExpression { - return SQLExpressionCount(counted) + SQLExpressionCount(counted) } @@ -60,7 +60,7 @@ public func count(_ counted: SQLSelectable) -> SQLExpression { /// // COUNT(DISTINCT email) /// count(distinct: Column("email")) public func count(distinct value: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionCountDistinct(value.sqlExpression) + SQLExpressionCountDistinct(value.sqlExpression) } @@ -76,7 +76,7 @@ extension SQLFunctionName { /// // IFNULL(name, 'Anonymous') /// Column("name") ?? "Anonymous" public func ?? (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionFunction(.ifNull, arguments: lhs, rhs) + SQLExpressionFunction(.ifNull, arguments: lhs, rhs) } @@ -92,7 +92,7 @@ extension SQLFunctionName { /// // LENGTH(name) /// length(Column("name")) public func length(_ value: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionFunction(.length, arguments: value) + SQLExpressionFunction(.length, arguments: value) } @@ -108,7 +108,7 @@ extension SQLFunctionName { /// // MAX(score) /// max(Column("score")) public func max(_ value: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionFunction(.max, arguments: value) + SQLExpressionFunction(.max, arguments: value) } @@ -124,7 +124,7 @@ extension SQLFunctionName { /// // MIN(score) /// min(Column("score")) public func min(_ value: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionFunction(.min, arguments: value) + SQLExpressionFunction(.min, arguments: value) } @@ -140,7 +140,7 @@ extension SQLFunctionName { /// // SUM(amount) /// sum(Column("amount")) public func sum(_ value: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionFunction(.sum, arguments: value) + SQLExpressionFunction(.sum, arguments: value) } @@ -155,7 +155,7 @@ extension SQLSpecificExpressible { /// let request = Player.select(nameColumn.capitalized) /// let names = try String.fetchAll(dbQueue, request) // [String] public var capitalized: SQLExpression { - return DatabaseFunction.capitalize(sqlExpression) + DatabaseFunction.capitalize(sqlExpression) } /// Returns an SQL expression that applies the Swift's built-in @@ -165,7 +165,7 @@ extension SQLSpecificExpressible { /// let request = Player.select(nameColumn.lowercased()) /// let names = try String.fetchAll(dbQueue, request) // [String] public var lowercased: SQLExpression { - return DatabaseFunction.lowercase(sqlExpression) + DatabaseFunction.lowercase(sqlExpression) } /// Returns an SQL expression that applies the Swift's built-in @@ -175,7 +175,7 @@ extension SQLSpecificExpressible { /// let request = Player.select(nameColumn.uppercased()) /// let names = try String.fetchAll(dbQueue, request) // [String] public var uppercased: SQLExpression { - return DatabaseFunction.uppercase(sqlExpression) + DatabaseFunction.uppercase(sqlExpression) } } @@ -189,7 +189,7 @@ extension SQLSpecificExpressible { /// let names = try String.fetchAll(dbQueue, request) // [String] @available(iOS 9.0, OSX 10.11, watchOS 3.0, *) public var localizedCapitalized: SQLExpression { - return DatabaseFunction.localizedCapitalize(sqlExpression) + DatabaseFunction.localizedCapitalize(sqlExpression) } /// Returns an SQL expression that applies the Swift's built-in @@ -200,7 +200,7 @@ extension SQLSpecificExpressible { /// let names = try String.fetchAll(dbQueue, request) // [String] @available(iOS 9.0, OSX 10.11, watchOS 3.0, *) public var localizedLowercased: SQLExpression { - return DatabaseFunction.localizedLowercase(sqlExpression) + DatabaseFunction.localizedLowercase(sqlExpression) } /// Returns an SQL expression that applies the Swift's built-in @@ -211,6 +211,6 @@ extension SQLSpecificExpressible { /// let names = try String.fetchAll(dbQueue, request) // [String] @available(iOS 9.0, OSX 10.11, watchOS 3.0, *) public var localizedUppercased: SQLExpression { - return DatabaseFunction.localizedUppercase(sqlExpression) + DatabaseFunction.localizedUppercase(sqlExpression) } } diff --git a/GRDB/QueryInterface/SQL/SQLOperators.swift b/GRDB/QueryInterface/SQL/SQLOperators.swift index ea8085bd9..c0ba964d2 100644 --- a/GRDB/QueryInterface/SQL/SQLOperators.swift +++ b/GRDB/QueryInterface/SQL/SQLOperators.swift @@ -32,7 +32,7 @@ private func isEqual(_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpressio /// // name IS NULL /// Column("name") == nil public func == (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { - return isEqual(lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null) + isEqual(lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null) } /// An SQL expression that compares two expressions with the `=` SQL operator. @@ -45,7 +45,7 @@ public func == (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpress /// // name IS NULL /// Column("name").collating(.nocase) == nil public func == (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpression { - return SQLExpressionCollate(lhs.expression == rhs, collationName: lhs.collationName) + SQLExpressionCollate(lhs.expression == rhs, collationName: lhs.collationName) } /// An SQL expression that checks the boolean value of an expression. @@ -75,7 +75,7 @@ public func == (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression { /// // name IS NULL /// nil == Column("name") public func == (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { - return isEqual(lhs?.sqlExpression ?? DatabaseValue.null, rhs.sqlExpression) + isEqual(lhs?.sqlExpression ?? DatabaseValue.null, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `=` SQL operator. @@ -88,7 +88,7 @@ public func == (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpress /// // name IS NULL /// nil == Column("name").collating(.nocase) public func == (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression { - return SQLExpressionCollate(lhs == rhs.expression, collationName: rhs.collationName) + SQLExpressionCollate(lhs == rhs.expression, collationName: rhs.collationName) } /// An SQL expression that checks the boolean value of an expression. @@ -113,7 +113,7 @@ public func == (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression { /// // email = login /// Column("email") == Column("login") public func == (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return isEqual(lhs.sqlExpression, rhs.sqlExpression) + isEqual(lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `<>` SQL operator. @@ -126,7 +126,7 @@ public func == (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// // name IS NOT NULL /// Column("name") != nil public func != (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { - return isEqual(lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null).negated + isEqual(lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null).negated } /// An SQL expression that compares two expressions with the `<>` SQL operator. @@ -139,7 +139,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpress /// // name IS NOT NULL /// Column("name").collating(.nocase) != nil public func != (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpression { - return SQLExpressionCollate(lhs.expression != rhs, collationName: lhs.collationName) + SQLExpressionCollate(lhs.expression != rhs, collationName: lhs.collationName) } /// An SQL expression that checks the boolean value of an expression. @@ -169,7 +169,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression { /// // name IS NOT NULL /// nil != Column("name") public func != (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { - return isEqual(lhs?.sqlExpression ?? DatabaseValue.null, rhs.sqlExpression).negated + isEqual(lhs?.sqlExpression ?? DatabaseValue.null, rhs.sqlExpression).negated } /// An SQL expression that compares two expressions with the `<>` SQL operator. @@ -182,7 +182,7 @@ public func != (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpress /// // name IS NOT NULL /// nil != Column("name").collating(.nocase) public func != (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression { - return SQLExpressionCollate(lhs != rhs.expression, collationName: rhs.collationName) + SQLExpressionCollate(lhs != rhs.expression, collationName: rhs.collationName) } /// An SQL expression that checks the boolean value of an expression. @@ -207,7 +207,7 @@ public func != (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression { /// // email <> login /// Column("email") != Column("login") public func != (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return isEqual(lhs.sqlExpression, rhs.sqlExpression).negated + isEqual(lhs.sqlExpression, rhs.sqlExpression).negated } /// An SQL expression that compares two expressions with the `IS` SQL operator. @@ -215,7 +215,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// // name IS 'Arthur' /// Column("name") === "Arthur" public func === (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { - return SQLExpressionEqual(.is, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null) + SQLExpressionEqual(.is, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null) } /// An SQL expression that compares two expressions with the `IS` SQL operator. @@ -223,7 +223,7 @@ public func === (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpres /// // name IS 'Arthur' COLLATE NOCASE /// Column("name").collating(.nocase) === "Arthur" public func === (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpression { - return SQLExpressionCollate(lhs.expression === rhs, collationName: lhs.collationName) + SQLExpressionCollate(lhs.expression === rhs, collationName: lhs.collationName) } /// An SQL expression that compares two expressions with the `IS` SQL operator. @@ -243,7 +243,7 @@ public func === (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpres /// // name IS 'Arthur' COLLATE NOCASE /// "Arthur" === Column("name").collating(.nocase) public func === (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression { - return SQLExpressionCollate(lhs === rhs.expression, collationName: rhs.collationName) + SQLExpressionCollate(lhs === rhs.expression, collationName: rhs.collationName) } /// An SQL expression that compares two expressions with the `IS` SQL operator. @@ -251,7 +251,7 @@ public func === (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpress /// // email IS login /// Column("email") === Column("login") public func === (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionEqual(.is, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionEqual(.is, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `IS NOT` SQL operator. @@ -259,7 +259,7 @@ public func === (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQ /// // name IS NOT 'Arthur' /// Column("name") !== "Arthur" public func !== (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { - return SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null) + SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null) } /// An SQL expression that compares two expressions with the `IS NOT` SQL operator. @@ -267,7 +267,7 @@ public func !== (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpres /// // name IS NOT 'Arthur' COLLATE NOCASE /// Column("name").collating(.nocase) !== "Arthur" public func !== (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpression { - return SQLExpressionCollate(lhs.expression !== rhs, collationName: lhs.collationName) + SQLExpressionCollate(lhs.expression !== rhs, collationName: lhs.collationName) } /// An SQL expression that compares two expressions with the `IS NOT` SQL operator. @@ -287,7 +287,7 @@ public func !== (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpres /// // name IS NOT 'Arthur' COLLATE NOCASE /// "Arthur" !== Column("name").collating(.nocase) public func !== (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression { - return SQLExpressionCollate(lhs !== rhs.expression, collationName: rhs.collationName) + SQLExpressionCollate(lhs !== rhs.expression, collationName: rhs.collationName) } /// An SQL expression that compares two expressions with the `IS NOT` SQL operator. @@ -295,7 +295,7 @@ public func !== (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpress /// // email IS NOT login /// Column("email") !== Column("login") public func !== (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs.sqlExpression) } @@ -320,7 +320,7 @@ extension SQLBinaryOperator { /// // score < 18 /// Column("score") < 18 public func < (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionBinary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `<` SQL operator. @@ -328,7 +328,7 @@ public func < (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// // name < 'Arthur' COLLATE NOCASE /// Column("name").collating(.nocase) < "Arthur" public func < (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionCollate(lhs.expression < rhs, collationName: lhs.collationName) + SQLExpressionCollate(lhs.expression < rhs, collationName: lhs.collationName) } /// An SQL expression that compares two expressions with the `<` SQL operator. @@ -336,7 +336,7 @@ public func < (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression /// // 18 < score /// 18 < Column("score") public func < (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `<` SQL operator. @@ -344,7 +344,7 @@ public func < (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// // 'Arthur' < name COLLATE NOCASE /// "Arthur" < Column("name").collating(.nocase) public func < (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression { - return SQLExpressionCollate(lhs < rhs.expression, collationName: rhs.collationName) + SQLExpressionCollate(lhs < rhs.expression, collationName: rhs.collationName) } /// An SQL expression that compares two expressions with the `<` SQL operator. @@ -352,7 +352,7 @@ public func < (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression /// // width < height /// Column("width") < Column("height") public func < (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `<=` SQL operator. @@ -360,7 +360,7 @@ public func < (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// // score <= 18 /// Column("score") <= 18 public func <= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionBinary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `<=` SQL operator. @@ -368,7 +368,7 @@ public func <= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// // name <= 'Arthur' COLLATE NOCASE /// Column("name").collating(.nocase) <= "Arthur" public func <= (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionCollate(lhs.expression <= rhs, collationName: lhs.collationName) + SQLExpressionCollate(lhs.expression <= rhs, collationName: lhs.collationName) } /// An SQL expression that compares two expressions with the `<=` SQL operator. @@ -376,7 +376,7 @@ public func <= (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpressio /// // 18 <= score /// 18 <= Column("score") public func <= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `<=` SQL operator. @@ -384,7 +384,7 @@ public func <= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// // 'Arthur' <= name COLLATE NOCASE /// "Arthur" <= Column("name").collating(.nocase) public func <= (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression { - return SQLExpressionCollate(lhs <= rhs.expression, collationName: rhs.collationName) + SQLExpressionCollate(lhs <= rhs.expression, collationName: rhs.collationName) } /// An SQL expression that compares two expressions with the `<=` SQL operator. @@ -392,7 +392,7 @@ public func <= (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpressio /// // width <= height /// Column("width") <= Column("height") public func <= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `>` SQL operator. @@ -400,7 +400,7 @@ public func <= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// // score > 18 /// Column("score") > 18 public func > (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionBinary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `>` SQL operator. @@ -408,7 +408,7 @@ public func > (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// // name > 'Arthur' COLLATE NOCASE /// Column("name").collating(.nocase) > "Arthur" public func > (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionCollate(lhs.expression > rhs, collationName: lhs.collationName) + SQLExpressionCollate(lhs.expression > rhs, collationName: lhs.collationName) } /// An SQL expression that compares two expressions with the `>` SQL operator. @@ -416,7 +416,7 @@ public func > (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression /// // 18 > score /// 18 > Column("score") public func > (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `>` SQL operator. @@ -424,7 +424,7 @@ public func > (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// // 'Arthur' > name COLLATE NOCASE /// "Arthur" > Column("name").collating(.nocase) public func > (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression { - return SQLExpressionCollate(lhs > rhs.expression, collationName: rhs.collationName) + SQLExpressionCollate(lhs > rhs.expression, collationName: rhs.collationName) } /// An SQL expression that compares two expressions with the `>` SQL operator. @@ -432,7 +432,7 @@ public func > (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression /// // width > height /// Column("width") > Column("height") public func > (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `>=` SQL operator. @@ -440,7 +440,7 @@ public func > (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// // score >= 18 /// Column("score") >= 18 public func >= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `>=` SQL operator. @@ -448,7 +448,7 @@ public func >= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// // name >= 'Arthur' COLLATE NOCASE /// Column("name").collating(.nocase) >= "Arthur" public func >= (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionCollate(lhs.expression >= rhs, collationName: lhs.collationName) + SQLExpressionCollate(lhs.expression >= rhs, collationName: lhs.collationName) } /// An SQL expression that compares two expressions with the `>=` SQL operator. @@ -456,7 +456,7 @@ public func >= (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpressio /// // 18 >= score /// 18 >= Column("score") public func >= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `>=` SQL operator. @@ -464,7 +464,7 @@ public func >= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// // 'Arthur' >= name COLLATE NOCASE /// "Arthur" >= Column("name").collating(.nocase) public func >= (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression { - return SQLExpressionCollate(lhs >= rhs.expression, collationName: rhs.collationName) + SQLExpressionCollate(lhs >= rhs.expression, collationName: rhs.collationName) } /// An SQL expression that compares two expressions with the `>=` SQL operator. @@ -472,7 +472,7 @@ public func >= (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpressio /// // width >= height /// Column("width") >= Column("height") public func >= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } @@ -484,7 +484,7 @@ extension Range where Bound: SQLExpressible { /// // email >= 'A' AND email < 'B' /// ("A"..<"B").contains(Column("email")) public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { - return (element >= lowerBound) && (element < upperBound) + (element >= lowerBound) && (element < upperBound) } /// An SQL expression that checks the inclusion of an expression in a range. @@ -492,7 +492,7 @@ extension Range where Bound: SQLExpressible { /// // email >= 'A' COLLATE NOCASE AND email < 'B' COLLATE NOCASE /// ("A"..<"B").contains(Column("email").collating(.nocase)) public func contains(_ element: SQLCollatedExpression) -> SQLExpression { - return (element >= lowerBound) && (element < upperBound) + (element >= lowerBound) && (element < upperBound) } } @@ -502,7 +502,7 @@ extension ClosedRange where Bound: SQLExpressible { /// // email BETWEEN 'A' AND 'B' /// ("A"..."B").contains(Column("email")) public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBetween(element.sqlExpression, lowerBound.sqlExpression, upperBound.sqlExpression) + SQLExpressionBetween(element.sqlExpression, lowerBound.sqlExpression, upperBound.sqlExpression) } /// An SQL expression that checks the inclusion of an expression in a range. @@ -510,7 +510,7 @@ extension ClosedRange where Bound: SQLExpressible { /// // email BETWEEN 'A' AND 'B' COLLATE NOCASE /// ("A"..."B").contains(Column("email").collating(.nocase)) public func contains(_ element: SQLCollatedExpression) -> SQLExpression { - return SQLExpressionCollate(contains(element.expression), collationName: element.collationName) + SQLExpressionCollate(contains(element.expression), collationName: element.collationName) } } @@ -520,7 +520,7 @@ extension CountableRange where Bound: SQLExpressible { /// // id BETWEEN 1 AND 9 /// (1..<10).contains(Column("id")) public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { - return (element >= lowerBound) && (element < upperBound) + (element >= lowerBound) && (element < upperBound) } } @@ -530,7 +530,7 @@ extension CountableClosedRange where Bound: SQLExpressible { /// // id BETWEEN 1 AND 10 /// (1...10).contains(Column("id")) public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBetween(element.sqlExpression, lowerBound.sqlExpression, upperBound.sqlExpression) + SQLExpressionBetween(element.sqlExpression, lowerBound.sqlExpression, upperBound.sqlExpression) } } @@ -541,7 +541,7 @@ extension Sequence where Self.Iterator.Element: SQLExpressible { /// // id IN (1,2,3) /// [1, 2, 3].contains(Column("id")) public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionsArray(self).contains(element.sqlExpression) + SQLExpressionsArray(self).contains(element.sqlExpression) } /// An SQL expression that checks the inclusion of an expression in @@ -550,7 +550,7 @@ extension Sequence where Self.Iterator.Element: SQLExpressible { /// // name IN ('A', 'B') COLLATE NOCASE /// ["A", "B"].contains(Column("name").collating(.nocase)) public func contains(_ element: SQLCollatedExpression) -> SQLExpression { - return SQLExpressionCollate(contains(element.expression), collationName: element.collationName) + SQLExpressionCollate(contains(element.expression), collationName: element.collationName) } } @@ -599,7 +599,7 @@ extension SQLUnaryOperator { /// // width * 2 /// Column("width") * 2 public func * (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionBinaryReduce(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) + SQLExpressionBinaryReduce(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic multiplication. @@ -607,7 +607,7 @@ public func * (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// // 2 * width /// 2 * Column("width") public func * (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinaryReduce(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) + SQLExpressionBinaryReduce(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic multiplication. @@ -615,7 +615,7 @@ public func * (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// // width * height /// Column("width") * Column("height") public func * (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinaryReduce(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) + SQLExpressionBinaryReduce(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic division. @@ -623,7 +623,7 @@ public func * (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// // width / 2 /// Column("width") / 2 public func / (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionBinary(.divide, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.divide, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL arithmetic division. @@ -631,7 +631,7 @@ public func / (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// // 2 / width /// 2 / Column("width") public func / (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.divide, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.divide, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL arithmetic division. @@ -639,7 +639,7 @@ public func / (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// // width / height /// Column("width") / Column("height") public func / (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.divide, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.divide, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL arithmetic addition. @@ -647,7 +647,7 @@ public func / (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// // width + 2 /// Column("width") + 2 public func + (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionBinaryReduce(.add, [lhs.sqlExpression, rhs.sqlExpression]) + SQLExpressionBinaryReduce(.add, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic addition. @@ -655,7 +655,7 @@ public func + (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// // 2 + width /// 2 + Column("width") public func + (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinaryReduce(.add, [lhs.sqlExpression, rhs.sqlExpression]) + SQLExpressionBinaryReduce(.add, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic addition. @@ -663,7 +663,7 @@ public func + (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// // width + height /// Column("width") + Column("height") public func + (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinaryReduce(.add, [lhs.sqlExpression, rhs.sqlExpression]) + SQLExpressionBinaryReduce(.add, [lhs.sqlExpression, rhs.sqlExpression]) } /// A negated SQL arithmetic expression. @@ -671,7 +671,7 @@ public func + (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// // -width /// -Column("width") public prefix func - (value: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionUnary(.minus, value.sqlExpression) + SQLExpressionUnary(.minus, value.sqlExpression) } /// An SQL arithmetic substraction. @@ -679,7 +679,7 @@ public prefix func - (value: SQLSpecificExpressible) -> SQLExpression { /// // width - 2 /// Column("width") - 2 public func - (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionBinary(.subtract, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.subtract, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL arithmetic substraction. @@ -687,7 +687,7 @@ public func - (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// // 2 - width /// 2 - Column("width") public func - (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.subtract, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.subtract, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL arithmetic substraction. @@ -695,7 +695,7 @@ public func - (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// // width - height /// Column("width") - Column("height") public func - (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.subtract, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.subtract, lhs.sqlExpression, rhs.sqlExpression) } @@ -730,7 +730,7 @@ extension SQLAssociativeBinaryOperator { /// // favorite AND 0 /// Column("favorite") && false public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionBinaryReduce(.and, [lhs.sqlExpression, rhs.sqlExpression]) + SQLExpressionBinaryReduce(.and, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `AND` SQL operator. @@ -738,7 +738,7 @@ public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// // 0 AND favorite /// false && Column("favorite") public func && (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinaryReduce(.and, [lhs.sqlExpression, rhs.sqlExpression]) + SQLExpressionBinaryReduce(.and, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `AND` SQL operator. @@ -746,7 +746,7 @@ public func && (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// // email IS NOT NULL AND favorite /// Column("email") != nil && Column("favorite") public func && (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinaryReduce(.and, [lhs.sqlExpression, rhs.sqlExpression]) + SQLExpressionBinaryReduce(.and, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -754,7 +754,7 @@ public func && (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// // favorite OR 1 /// Column("favorite") || true public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionBinaryReduce(.or, [lhs.sqlExpression, rhs.sqlExpression]) + SQLExpressionBinaryReduce(.or, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -762,7 +762,7 @@ public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// // 0 OR favorite /// true || Column("favorite") public func || (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinaryReduce(.or, [lhs.sqlExpression, rhs.sqlExpression]) + SQLExpressionBinaryReduce(.or, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -770,7 +770,7 @@ public func || (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// // email IS NULL OR hidden /// Column("email") == nil || Column("hidden") public func || (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinaryReduce(.or, [lhs.sqlExpression, rhs.sqlExpression]) + SQLExpressionBinaryReduce(.or, [lhs.sqlExpression, rhs.sqlExpression]) } /// A negated logical SQL expression with the `NOT` SQL operator. @@ -783,7 +783,7 @@ public func || (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// // id NOT BETWEEN 1 AND 10 /// !((1...10).contains(Column("id"))) public prefix func ! (value: SQLSpecificExpressible) -> SQLExpression { - return value.sqlExpression.negated + value.sqlExpression.negated } // MARK: - Like Operator @@ -801,7 +801,7 @@ extension SQLSpecificExpressible { /// // email LIKE '%@example.com" /// Column("email").like("%@example.com") public func like(_ pattern: SQLExpressible) -> SQLExpression { - return SQLExpressionBinary(.like, self, pattern) + SQLExpressionBinary(.like, self, pattern) } } diff --git a/GRDB/QueryInterface/SQL/SQLQuery.swift b/GRDB/QueryInterface/SQL/SQLQuery.swift index 3594182b2..12bb95cbe 100644 --- a/GRDB/QueryInterface/SQL/SQLQuery.swift +++ b/GRDB/QueryInterface/SQL/SQLQuery.swift @@ -31,83 +31,83 @@ struct SQLQuery { extension SQLQuery: KeyPathRefining { func distinct() -> SQLQuery { - return with(\.isDistinct, true) + with(\.isDistinct, true) } func expectingSingleResult() -> SQLQuery { - return with(\.expectsSingleResult, true) + with(\.expectsSingleResult, true) } func limit(_ limit: Int, offset: Int? = nil) -> SQLQuery { - return with(\.limit, SQLLimit(limit: limit, offset: offset)) + with(\.limit, SQLLimit(limit: limit, offset: offset)) } func qualified(with alias: TableAlias) -> SQLQuery { // We do not need to qualify group and having clauses. They will be // in SQLQueryGenerator.init() - return map(\.relation, { $0.qualified(with: alias) }) + map(\.relation, { $0.qualified(with: alias) }) } } extension SQLQuery: SelectionRequest { func select(_ selection: [SQLSelectable]) -> SQLQuery { - return map(\.relation, { $0.select(selection) }) + map(\.relation, { $0.select(selection) }) } func annotated(with selection: [SQLSelectable]) -> SQLQuery { - return map(\.relation, { $0.annotated(with: selection) }) + map(\.relation, { $0.annotated(with: selection) }) } } extension SQLQuery: FilteredRequest { func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> SQLQuery { - return map(\.relation, { $0.filter(predicate) }) + map(\.relation, { $0.filter(predicate) }) } } extension SQLQuery: OrderedRequest { func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> SQLQuery { - return map(\.relation, { $0.order(orderings) }) + map(\.relation, { $0.order(orderings) }) } func reversed() -> SQLQuery { - return map(\.relation, { $0.reversed() }) + map(\.relation, { $0.reversed() }) } func unordered() -> SQLQuery { - return map(\.relation, { $0.unordered() }) + map(\.relation, { $0.unordered() }) } } extension SQLQuery: AggregatingRequest { func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> SQLQuery { - return with(\.groupPromise, DatabasePromise { db in try expressions(db).map(\.sqlExpression) }) + with(\.groupPromise, DatabasePromise { db in try expressions(db).map(\.sqlExpression) }) } func having(_ predicate: SQLExpressible) -> SQLQuery { - return mapInto(\.havingExpressions, { $0.append(predicate.sqlExpression) }) + mapInto(\.havingExpressions, { $0.append(predicate.sqlExpression) }) } } extension SQLQuery: _JoinableRequest { func _including(all association: SQLAssociation) -> SQLQuery { - return map(\.relation, { $0._including(all: association) }) + map(\.relation, { $0._including(all: association) }) } func _including(optional association: SQLAssociation) -> SQLQuery { - return map(\.relation, { $0._including(optional: association) }) + map(\.relation, { $0._including(optional: association) }) } func _including(required association: SQLAssociation) -> SQLQuery { - return map(\.relation, { $0._including(required: association) }) + map(\.relation, { $0._including(required: association) }) } func _joining(optional association: SQLAssociation) -> SQLQuery { - return map(\.relation, { $0._joining(optional: association) }) + map(\.relation, { $0._joining(optional: association) }) } func _joining(required association: SQLAssociation) -> SQLQuery { - return map(\.relation, { $0._joining(required: association) }) + map(\.relation, { $0._joining(required: association) }) } } diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 47be63aba..e28d67e3d 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -158,7 +158,7 @@ struct SQLRelation { var children: OrderedDictionary var prefetchedAssociations: [SQLAssociation] { - return children.flatMap { key, child -> [SQLAssociation] in + children.flatMap { key, child -> [SQLAssociation] in switch child.kind { case .allPrefetched: return [child.makeAssociationForKey(key)] @@ -193,22 +193,21 @@ struct SQLRelation { extension SQLRelation: KeyPathRefining { func select(_ selection: [SQLSelectable]) -> SQLRelation { - return with(\.selection, selection) + with(\.selection, selection) } /// Removes all selections from chidren func selectOnly(_ selection: [SQLSelectable]) -> SQLRelation { - return self - .with(\.selection, selection) + self.with(\.selection, selection) .map(\.children, { $0.mapValues { $0.map(\.relation, { $0.selectOnly([]) }) } }) } func annotated(with selection: [SQLSelectable]) -> SQLRelation { - return mapInto(\.selection, { $0.append(contentsOf: selection) }) + mapInto(\.selection, { $0.append(contentsOf: selection) }) } func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> SQLRelation { - return map(\.filtersPromise, { filtersPromise in + map(\.filtersPromise, { filtersPromise in filtersPromise.flatMap { filters in DatabasePromise { try filters + [predicate($0).sqlExpression] } } @@ -216,21 +215,20 @@ extension SQLRelation: KeyPathRefining { } func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> SQLRelation { - return with(\.ordering, SQLRelation.Ordering(orderings: orderings)) + with(\.ordering, SQLRelation.Ordering(orderings: orderings)) } func reversed() -> SQLRelation { - return map(\.ordering, \.reversed) + map(\.ordering, \.reversed) } func unordered() -> SQLRelation { - return self - .with(\.ordering, SQLRelation.Ordering()) + self.with(\.ordering, SQLRelation.Ordering()) .map(\.children, { $0.mapValues { $0.map(\.relation, { $0.unordered() }) } }) } func qualified(with alias: TableAlias) -> SQLRelation { - return map(\.source, { $0.qualified(with: alias) }) + map(\.source, { $0.qualified(with: alias) }) } } @@ -351,33 +349,33 @@ extension SQLRelation { } func removingChild(forKey key: String) -> SQLRelation { - return mapInto(\.children, { $0.removeValue(forKey: key) }) + mapInto(\.children, { $0.removeValue(forKey: key) }) } func filteringChildren(_ included: (Child) throws -> Bool) rethrows -> SQLRelation { - return try map(\.children, { try $0.filter { try included($1) } }) + try map(\.children, { try $0.filter { try included($1) } }) } } extension SQLRelation: _JoinableRequest { func _including(all association: SQLAssociation) -> SQLRelation { - return appendingChild(for: association, kind: .allPrefetched) + appendingChild(for: association, kind: .allPrefetched) } func _including(optional association: SQLAssociation) -> SQLRelation { - return appendingChild(for: association, kind: .oneOptional) + appendingChild(for: association, kind: .oneOptional) } func _including(required association: SQLAssociation) -> SQLRelation { - return appendingChild(for: association, kind: .oneRequired) + appendingChild(for: association, kind: .oneRequired) } func _joining(optional association: SQLAssociation) -> SQLRelation { - return appendingChild(for: association.map(\.destination.relation, { $0.select([]) }), kind: .oneOptional) + appendingChild(for: association.map(\.destination.relation, { $0.select([]) }), kind: .oneOptional) } func _joining(required association: SQLAssociation) -> SQLRelation { - return appendingChild(for: association.map(\.destination.relation, { $0.select([]) }), kind: .oneRequired) + appendingChild(for: association.map(\.destination.relation, { $0.select([]) }), kind: .oneRequired) } } @@ -443,9 +441,7 @@ extension SQLRelation { private var elements: [Element] = [] var isReversed: Bool - var isEmpty: Bool { - return elements.isEmpty - } + var isEmpty: Bool { elements.isEmpty } private init(elements: [Element], isReversed: Bool) { self.elements = elements @@ -465,19 +461,19 @@ extension SQLRelation { } var reversed: Ordering { - return Ordering( + Ordering( elements: elements, isReversed: !isReversed) } func qualified(with alias: TableAlias) -> Ordering { - return Ordering( + Ordering( elements: elements.map { $0.qualified(with: alias) }, isReversed: isReversed) } func appending(_ ordering: Ordering) -> Ordering { - return Ordering( + Ordering( elements: elements + [.ordering(ordering)], isReversed: isReversed) } @@ -543,7 +539,7 @@ struct SQLAssociationCondition: Equatable { var originIsLeft: Bool var reversed: SQLAssociationCondition { - return SQLAssociationCondition( + SQLAssociationCondition( foreignKeyRequest: foreignKeyRequest, originIsLeft: !originIsLeft) } @@ -572,7 +568,7 @@ struct SQLAssociationCondition: Equatable { /// - Returns: An array of SQL expression that should be joined with /// the AND operator. func expressions(_ db: Database, leftAlias: TableAlias, rightAlias: TableAlias) throws -> [SQLExpression] { - return try columnMappings(db).map { + try columnMappings(db).map { QualifiedColumn($0.right, alias: rightAlias) == QualifiedColumn($0.left, alias: leftAlias) } } diff --git a/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift index 311e87d16..cc856588f 100644 --- a/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift @@ -22,13 +22,13 @@ extension AllColumns: SQLSelectable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func resultColumnSQL(_ context: inout SQLGenerationContext) -> String { - return "*" + "*" } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func countedSQL(_ context: inout SQLGenerationContext) -> String { - return "*" + "*" } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) @@ -48,7 +48,7 @@ extension AllColumns: SQLSelectable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { - return QualifiedAllColumns(alias: alias) + QualifiedAllColumns(alias: alias) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) @@ -102,9 +102,7 @@ extension QualifiedAllColumns: SQLSelectable { return "*" } - func count(distinct: Bool) -> SQLCount? { - return nil - } + func count(distinct: Bool) -> SQLCount? { nil } func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { // Never requalify @@ -112,7 +110,7 @@ extension QualifiedAllColumns: SQLSelectable { } func columnCount(_ db: Database) throws -> Int { - return try db.columns(in: alias.tableName).count + try db.columns(in: alias.tableName).count } } @@ -128,22 +126,20 @@ struct SQLAliasedExpression: SQLSelectable { } func resultColumnSQL(_ context: inout SQLGenerationContext) -> String { - return expression.resultColumnSQL(&context) + " AS " + name.quotedDatabaseIdentifier + expression.resultColumnSQL(&context) + " AS " + name.quotedDatabaseIdentifier } func countedSQL(_ context: inout SQLGenerationContext) -> String { - return expression.countedSQL(&context) + expression.countedSQL(&context) } func count(distinct: Bool) -> SQLCount? { - return expression.count(distinct: distinct) + expression.count(distinct: distinct) } func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { - return SQLAliasedExpression(expression.qualifiedExpression(with: alias), name: name) + SQLAliasedExpression(expression.qualifiedExpression(with: alias), name: name) } - func columnCount(_ db: Database) throws -> Int { - return 1 - } + func columnCount(_ db: Database) throws -> Int { 1 } } diff --git a/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift index b1db8666d..de005629d 100644 --- a/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift @@ -7,14 +7,14 @@ extension SQLSpecificExpressible { /// /// See https://github.com/groue/GRDB.swift/#the-query-interface public var asc: SQLOrderingTerm { - return SQLOrdering.asc(sqlExpression) + SQLOrdering.asc(sqlExpression) } /// Returns a value that can be used as an argument to QueryInterfaceRequest.order() /// /// See https://github.com/groue/GRDB.swift/#the-query-interface public var desc: SQLOrderingTerm { - return SQLOrdering.desc(sqlExpression) + SQLOrdering.desc(sqlExpression) } #if GRDBCUSTOMSQLITE @@ -22,14 +22,14 @@ extension SQLSpecificExpressible { /// /// See https://github.com/groue/GRDB.swift/#the-query-interface public var ascNullsLast: SQLOrderingTerm { - return SQLOrdering.ascNullsLast(sqlExpression) + SQLOrdering.ascNullsLast(sqlExpression) } /// Returns a value that can be used as an argument to QueryInterfaceRequest.order() /// /// See https://github.com/groue/GRDB.swift/#the-query-interface public var descNullsFirst: SQLOrderingTerm { - return SQLOrdering.descNullsFirst(sqlExpression) + SQLOrdering.descNullsFirst(sqlExpression) } #endif } @@ -50,7 +50,7 @@ extension SQLSpecificExpressible { /// let area: Int = row["area"] /// } public func forKey(_ key: String) -> SQLSelectable { - return SQLAliasedExpression(sqlExpression, name: key) + SQLAliasedExpression(sqlExpression, name: key) } /// Give the expression the same SQL name as the coding key. @@ -72,7 +72,7 @@ extension SQLSpecificExpressible { /// // SELECT width, height, (width * height) AS area FROM shape /// let shapes: [Shape] = try Shape.fetchAll(db) public func forKey(_ key: CodingKey) -> SQLSelectable { - return forKey(key.stringValue) + forKey(key.stringValue) } } @@ -88,7 +88,7 @@ extension SQLSpecificExpressible { /// /// Player.filter(Column("email").collating(.nocase) == "contact@example.com") public func collating(_ collation: Database.CollationName) -> SQLCollatedExpression { - return SQLCollatedExpression(sqlExpression, collationName: collation) + SQLCollatedExpression(sqlExpression, collationName: collation) } /// Returns a collated expression. @@ -97,6 +97,6 @@ extension SQLSpecificExpressible { /// /// Player.filter(Column("name").collating(.localizedStandardCompare) == "HervĆ©") public func collating(_ collation: DatabaseCollation) -> SQLCollatedExpression { - return SQLCollatedExpression(sqlExpression, collationName: Database.CollationName(collation.name)) + SQLCollatedExpression(sqlExpression, collationName: Database.CollationName(collation.name)) } } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index c2b211e4e..102c7a570 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -6,7 +6,7 @@ /// :nodoc: public struct SQLGenerationContext { var arguments: StatementArguments { - return _arguments ?? StatementArguments() + _arguments ?? StatementArguments() } private var _arguments: StatementArguments? private var resolvedNames: [TableAlias: String] @@ -32,7 +32,7 @@ public struct SQLGenerationContext { /// Used for SQLQueryGenerator static func queryContext(aliases: [TableAlias]) -> SQLGenerationContext { - return SQLGenerationContext( + SQLGenerationContext( _arguments: [], resolvedNames: aliases.resolvedNames, qualifierNeeded: aliases.count > 1) @@ -70,7 +70,7 @@ public struct SQLGenerationContext { /// WHERE MATCH pattern func resolvedName(for alias: TableAlias) -> String { - return resolvedNames[alias] ?? alias.identityName + resolvedNames[alias] ?? alias.identityName } /// FROM tableName @@ -149,12 +149,12 @@ public class TableAlias: Hashable { // exposed to SQLGenerationContext fileprivate var identityName: String { - return userName ?? tableName + userName ?? tableName } // exposed to SQLGenerationContext fileprivate var hasUserName: Bool { - return userName != nil + userName != nil } var tableName: String { @@ -283,7 +283,7 @@ public class TableAlias: Hashable { /// :nodoc: public static func == (lhs: TableAlias, rhs: TableAlias) -> Bool { - return ObjectIdentifier(lhs.root) == ObjectIdentifier(rhs.root) + ObjectIdentifier(lhs.root) == ObjectIdentifier(rhs.root) } } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 8e80d528e..5a098c209 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -97,7 +97,7 @@ struct SQLQueryGenerator { } func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try (makeSelectStatement(db), rowAdapter(db)) + try (makeSelectStatement(db), rowAdapter(db)) } private func optimizedDatabaseRegion(_ db: Database, _ databaseRegion: DatabaseRegion) throws -> DatabaseRegion { @@ -406,7 +406,7 @@ struct SQLQueryGenerator { /// let author: Author = row["author"] /// } private func rowAdapter(_ db: Database) throws -> RowAdapter? { - return try relation.rowAdapter(db, fromIndex: 0)?.adapter + try relation.rowAdapter(db, fromIndex: 0)?.adapter } } @@ -421,11 +421,11 @@ struct SQLQueryGenerator { /// • selection private struct SQLQualifiedRelation { /// The source alias - var sourceAlias: TableAlias { return source.alias } + var sourceAlias: TableAlias { source.alias } /// All aliases, including aliases of joined relations var allAliases: [TableAlias] { - return joins.reduce(into: source.allAliases) { + joins.reduce(into: source.allAliases) { $0.append(contentsOf: $1.value.relation.allAliases) } } @@ -446,7 +446,7 @@ private struct SQLQualifiedRelation { /// | /// • selection var selection: [SQLSelectable] { - return joins.reduce(into: sourceSelection) { + joins.reduce(into: sourceSelection) { $0.append(contentsOf: $1.value.relation.selection) } } @@ -467,7 +467,7 @@ private struct SQLQualifiedRelation { /// | /// • ordering var ordering: SQLRelation.Ordering { - return joins.reduce(sourceOrdering) { + joins.reduce(sourceOrdering) { $0.appending($1.value.relation.ordering) } } @@ -574,8 +574,7 @@ private struct SQLQualifiedRelation { /// Removes all selections from joins func selectOnly(_ selection: [SQLSelectable]) -> SQLQualifiedRelation { - return self - .with(\.sourceSelection, selection.map { $0.qualifiedSelectable(with: sourceAlias) }) + self.with(\.sourceSelection, selection.map { $0.qualifiedSelectable(with: sourceAlias) }) .map(\.joins, { $0.mapValues { $0.selectOnly([]) } }) } } @@ -641,12 +640,12 @@ private struct SQLQualifiedJoin { let relation: SQLQualifiedRelation func sql(_ db: Database, _ context: inout SQLGenerationContext, leftAlias: TableAlias) throws -> String { - return try sql(db, &context, leftAlias: leftAlias, allowingInnerJoin: true) + try sql(db, &context, leftAlias: leftAlias, allowingInnerJoin: true) } /// Removes all selections from joins func selectOnly(_ selection: [SQLSelectable]) -> SQLQualifiedJoin { - return SQLQualifiedJoin( + SQLQualifiedJoin( kind: kind, condition: condition, relation: relation.selectOnly(selection)) diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index ae43d6c4d..594c89aeb 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -553,7 +553,7 @@ extension TableRecord { /// // FROM player LEFT JOIN book ... /// var request = Player.annotated(with: Player.books.count) public static func annotated(with aggregates: AssociationAggregate...) -> QueryInterfaceRequest { - return all().annotated(with: aggregates) + all().annotated(with: aggregates) } /// Creates a request with *aggregates* appended to the selection. @@ -562,7 +562,7 @@ extension TableRecord { /// // FROM player LEFT JOIN book ... /// var request = Player.annotated(with: [Player.books.count]) public static func annotated(with aggregates: [AssociationAggregate]) -> QueryInterfaceRequest { - return all().annotated(with: aggregates) + all().annotated(with: aggregates) } /// Creates a request with the provided aggregate *predicate*. @@ -577,6 +577,6 @@ extension TableRecord { /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. public static func having(_ predicate: AssociationAggregate) -> QueryInterfaceRequest { - return all().having(predicate) + all().having(predicate) } } diff --git a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift index 150848e5f..7d8332ddd 100644 --- a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift @@ -19,7 +19,7 @@ extension TableRecord { /// Creates a request which fetches no record. public static func none() -> QueryInterfaceRequest { - return all().none() // don't laugh + all().none() // don't laugh } /// Creates a request which selects *selection*. @@ -27,7 +27,7 @@ extension TableRecord { /// // SELECT id, email FROM player /// let request = Player.select(Column("id"), Column("email")) public static func select(_ selection: SQLSelectable...) -> QueryInterfaceRequest { - return all().select(selection) + all().select(selection) } /// Creates a request which selects *selection*. @@ -35,7 +35,7 @@ extension TableRecord { /// // SELECT id, email FROM player /// let request = Player.select([Column("id"), Column("email")]) public static func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest { - return all().select(selection) + all().select(selection) } /// Creates a request which selects *sql*. @@ -55,7 +55,7 @@ extension TableRecord { /// // SELECT id, email FROM player /// let request = Player.select(literal: SQLLiteral(sql: "id, email")) public static func select(literal sqlLiteral: SQLLiteral) -> QueryInterfaceRequest { - return all().select(literal: sqlLiteral) + all().select(literal: sqlLiteral) } /// Creates a request which selects *selection*, and fetches values of @@ -130,7 +130,7 @@ extension TableRecord { /// .select([Column("id"), Column("email")]) /// .annotated(with: [Column("name")]) public static func annotated(with selection: [SQLSelectable]) -> QueryInterfaceRequest { - return all().annotated(with: selection) + all().annotated(with: selection) } /// Creates a request which appends *selection*. @@ -140,7 +140,7 @@ extension TableRecord { /// .select([Column("id"), Column("email")]) /// .annotated(with: Column("name")) public static func annotated(with selection: SQLSelectable...) -> QueryInterfaceRequest { - return all().annotated(with: selection) + all().annotated(with: selection) } /// Creates a request with the provided *predicate*. @@ -152,7 +152,7 @@ extension TableRecord { /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. public static func filter(_ predicate: SQLExpressible) -> QueryInterfaceRequest { - return all().filter(predicate) + all().filter(predicate) } /// Creates a request with the provided primary key *predicate*. @@ -197,7 +197,7 @@ extension TableRecord { /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. public static func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest { - return all().filter(key: key) + all().filter(key: key) } /// Creates a request with the provided primary key *predicate*. @@ -212,7 +212,7 @@ extension TableRecord { /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. public static func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest { - return all().filter(keys: keys) + all().filter(keys: keys) } /// Creates a request with the provided *predicate*. @@ -259,7 +259,7 @@ extension TableRecord { /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. public static func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest { - return all().order(orderings) + all().order(orderings) } /// Creates a request sorted according to the @@ -272,7 +272,7 @@ extension TableRecord { /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. public static func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest { - return all().order(orderings) + all().order(orderings) } /// Creates a request sorted by primary key. @@ -287,7 +287,7 @@ extension TableRecord { /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. public static func orderByPrimaryKey() -> QueryInterfaceRequest { - return all().orderByPrimaryKey() + all().orderByPrimaryKey() } /// Creates a request sorted according to *sql*. @@ -321,7 +321,7 @@ extension TableRecord { /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. public static func order(literal sqlLiteral: SQLLiteral) -> QueryInterfaceRequest { - return all().order(literal: sqlLiteral) + all().order(literal: sqlLiteral) } /// Creates a request which fetches *limit* rows, starting at @@ -334,7 +334,7 @@ extension TableRecord { /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. public static func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { - return all().limit(limit, offset: offset) + all().limit(limit, offset: offset) } /// Creates a request that allows you to define expressions that target @@ -354,6 +354,6 @@ extension TableRecord { /// .aliased(playerAlias) /// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")]) public static func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { - return all().aliased(alias) + all().aliased(alias) } } diff --git a/GRDB/Record/EncodableRecord+Encodable.swift b/GRDB/Record/EncodableRecord+Encodable.swift index 85fbb95e9..01adf4983 100644 --- a/GRDB/Record/EncodableRecord+Encodable.swift +++ b/GRDB/Record/EncodableRecord+Encodable.swift @@ -12,10 +12,10 @@ extension EncodableRecord where Self: Encodable { /// The encoder that encodes a record into GRDB's PersistenceContainer private class RecordEncoder: Encoder { - var codingPath: [CodingKey] { return [] } - var userInfo: [CodingUserInfoKey: Any] { return Record.databaseEncodingUserInfo } + var codingPath: [CodingKey] { [] } + var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } private var _persistenceContainer: PersistenceContainer - var persistenceContainer: PersistenceContainer { return _persistenceContainer } + var persistenceContainer: PersistenceContainer { _persistenceContainer } init(persistenceContainer: PersistenceContainer) { _persistenceContainer = persistenceContainer @@ -47,13 +47,13 @@ private class RecordEncoder: Encoder { private struct KeyedContainer: KeyedEncodingContainerProtocol { var recordEncoder: RecordEncoder - var userInfo: [CodingUserInfoKey: Any] { return Record.databaseEncodingUserInfo } + var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } init(recordEncoder: RecordEncoder) { self.recordEncoder = recordEncoder } - var codingPath: [CodingKey] { return [] } + var codingPath: [CodingKey] { [] } // swiftlint:disable comma func encode(_ value: Bool, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } @@ -174,8 +174,8 @@ private class RecordEncoder: Encoder { private class ColumnEncoder: Encoder { var recordEncoder: RecordEncoder var key: CodingKey - var codingPath: [CodingKey] { return [key] } - var userInfo: [CodingUserInfoKey: Any] { return Record.databaseEncodingUserInfo } + var codingPath: [CodingKey] { [key] } + var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } var requiresJSON = false init(recordEncoder: RecordEncoder, key: CodingKey) { @@ -200,9 +200,7 @@ private class ColumnEncoder: Encoder { return JSONRequiredEncoder(codingPath: codingPath) } - func singleValueContainer() -> SingleValueEncodingContainer { - return self - } + func singleValueContainer() -> SingleValueEncodingContainer { self } } extension ColumnEncoder: SingleValueEncodingContainer { @@ -236,7 +234,7 @@ private struct JSONRequiredError: Error { } /// The encoder that always ends up with a JSONRequiredError private struct JSONRequiredEncoder: Encoder { var codingPath: [CodingKey] - var userInfo: [CodingUserInfoKey: Any] { return Record.databaseEncodingUserInfo } + var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } init(codingPath: [CodingKey]) { self.codingPath = codingPath @@ -247,17 +245,13 @@ private struct JSONRequiredEncoder: Encoder { return KeyedEncodingContainer(container) } - func unkeyedContainer() -> UnkeyedEncodingContainer { - return self - } + func unkeyedContainer() -> UnkeyedEncodingContainer { self } - func singleValueContainer() -> SingleValueEncodingContainer { - return self - } + func singleValueContainer() -> SingleValueEncodingContainer { self } struct KeyedContainer: KeyedEncodingContainerProtocol { var codingPath: [CodingKey] - var userInfo: [CodingUserInfoKey: Any] { return Record.databaseEncodingUserInfo } + var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } func encodeNil(forKey key: KeyType) throws { throw JSONRequiredError() } func encode(_ value: Bool, forKey key: KeyType) throws { throw JSONRequiredError() } @@ -287,15 +281,15 @@ private struct JSONRequiredEncoder: Encoder { } func nestedUnkeyedContainer(forKey key: KeyType) -> UnkeyedEncodingContainer { - return JSONRequiredEncoder(codingPath: codingPath) + JSONRequiredEncoder(codingPath: codingPath) } func superEncoder() -> Encoder { - return JSONRequiredEncoder(codingPath: codingPath) + JSONRequiredEncoder(codingPath: codingPath) } func superEncoder(forKey key: KeyType) -> Encoder { - return JSONRequiredEncoder(codingPath: codingPath) + JSONRequiredEncoder(codingPath: codingPath) } } } @@ -320,7 +314,7 @@ extension JSONRequiredEncoder: SingleValueEncodingContainer { } extension JSONRequiredEncoder: UnkeyedEncodingContainer { - var count: Int { return 0 } + var count: Int { 0 } mutating func nestedContainer(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer @@ -330,13 +324,9 @@ extension JSONRequiredEncoder: UnkeyedEncodingContainer { return KeyedEncodingContainer(container) } - mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { - return self - } + mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { self } - mutating func superEncoder() -> Encoder { - return self - } + mutating func superEncoder() -> Encoder { self } } @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index 181cc2161..d9cb84a9c 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -121,7 +121,7 @@ public protocol EncodableRecord { extension EncodableRecord { public static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] { - return [:] + [:] } public static func databaseJSONEncoder(for column: String) -> JSONEncoder { @@ -137,18 +137,18 @@ extension EncodableRecord { } public static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { - return .deferredToDate + .deferredToDate } public static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { - return .deferredToUUID + .deferredToUUID } } extension EncodableRecord { /// A dictionary whose keys are the columns encoded in the `encode(to:)` method. public var databaseDictionary: [String: DatabaseValue] { - return Dictionary(PersistenceContainer(self).storage).mapValues { $0?.databaseValue ?? .null } + Dictionary(PersistenceContainer(self).storage).mapValues { $0?.databaseValue ?? .null } } } @@ -159,7 +159,7 @@ extension EncodableRecord { /// Returns a boolean indicating whether this record and the other record /// have the same database representation. public func databaseEquals(_ record: Self) -> Bool { - return PersistenceContainer(self).changesIterator(from: PersistenceContainer(record)).next() == nil + PersistenceContainer(self).changesIterator(from: PersistenceContainer(record)).next() == nil } /// A dictionary of values changed from the other record. @@ -203,7 +203,7 @@ public struct PersistenceContainer { /// is considered undefined behavior. @inlinable public subscript(_ column: String) -> DatabaseValueConvertible? { - get { return storage[column] ?? nil } + get { storage[column] ?? nil } set { storage.updateValue(newValue, forKey: column) } } @@ -214,7 +214,7 @@ public struct PersistenceContainer { /// is considered undefined behavior. @inlinable public subscript(_ column: Column) -> DatabaseValueConvertible? { - get { return self[column.name] } + get { self[column.name] } set { self[column.name] = newValue } } @@ -233,14 +233,10 @@ public struct PersistenceContainer { } /// Columns stored in the container, ordered like values. - var columns: [String] { - return Array(storage.keys) - } + var columns: [String] { Array(storage.keys) } /// Values stored in the container, ordered like columns. - var values: [DatabaseValueConvertible?] { - return Array(storage.values) - } + var values: [DatabaseValueConvertible?] { Array(storage.values) } /// Accesses the value associated with the given column, in a /// case-insensitive fashion. @@ -281,13 +277,11 @@ public struct PersistenceContainer { return nil } - var isEmpty: Bool { - return storage.isEmpty - } + var isEmpty: Bool { storage.isEmpty } /// An iterator over the (column, value) pairs func makeIterator() -> IndexingIterator> { - return storage.makeIterator() + storage.makeIterator() } func changesIterator(from container: PersistenceContainer) -> AnyIterator<(String, DatabaseValue)> { diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index c88648f32..7a302a9a4 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -32,10 +32,10 @@ class RowDecoder { private struct _RowDecoder: Decoder { var row: Row var codingPath: [CodingKey] - var userInfo: [CodingUserInfoKey: Any] { return R.databaseDecodingUserInfo } + var userInfo: [CodingUserInfoKey: Any] { R.databaseDecodingUserInfo } func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer { - return KeyedDecodingContainer(KeyedContainer(decoder: self)) + KeyedDecodingContainer(KeyedContainer(decoder: self)) } func unkeyedContainer() throws -> UnkeyedDecodingContainer { @@ -73,7 +73,7 @@ private struct _RowDecoder: Decoder { class KeyedContainer: KeyedDecodingContainerProtocol { let decoder: _RowDecoder - var codingPath: [CodingKey] { return decoder.codingPath } + var codingPath: [CodingKey] { decoder.codingPath } var decodedRootKey: CodingKey? init(decoder: _RowDecoder) { @@ -99,20 +99,20 @@ private struct _RowDecoder: Decoder { } // swiftlint:disable comma - func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return decoder.row[key.stringValue] } - func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return decoder.row[key.stringValue] } - func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { return decoder.row[key.stringValue] } - func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { return decoder.row[key.stringValue] } - func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { return decoder.row[key.stringValue] } - func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { return decoder.row[key.stringValue] } - func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { return decoder.row[key.stringValue] } - func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { return decoder.row[key.stringValue] } - func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { return decoder.row[key.stringValue] } - func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { return decoder.row[key.stringValue] } - func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { return decoder.row[key.stringValue] } - func decode(_ type: Float.Type, forKey key: Key) throws -> Float { return decoder.row[key.stringValue] } - func decode(_ type: Double.Type, forKey key: Key) throws -> Double { return decoder.row[key.stringValue] } - func decode(_ type: String.Type, forKey key: Key) throws -> String { return decoder.row[key.stringValue] } + func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { decoder.row[key.stringValue] } + func decode(_ type: Int.Type, forKey key: Key) throws -> Int { decoder.row[key.stringValue] } + func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { decoder.row[key.stringValue] } + func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { decoder.row[key.stringValue] } + func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { decoder.row[key.stringValue] } + func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { decoder.row[key.stringValue] } + func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { decoder.row[key.stringValue] } + func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { decoder.row[key.stringValue] } + func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { decoder.row[key.stringValue] } + func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { decoder.row[key.stringValue] } + func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { decoder.row[key.stringValue] } + func decode(_ type: Float.Type, forKey key: Key) throws -> Float { decoder.row[key.stringValue] } + func decode(_ type: Double.Type, forKey key: Key) throws -> Double { decoder.row[key.stringValue] } + func decode(_ type: String.Type, forKey key: Key) throws -> String { decoder.row[key.stringValue] } // swiftlint:enable comma func decodeIfPresent(_ type: T.Type, forKey key: Key) throws -> T? where T: Decodable { @@ -303,7 +303,7 @@ private struct PrefetchedRowsDecoder: Decoder { var rows: [Row] var codingPath: [CodingKey] var currentIndex: Int - var userInfo: [CodingUserInfoKey: Any] { return R.databaseDecodingUserInfo } + var userInfo: [CodingUserInfoKey: Any] { R.databaseDecodingUserInfo } init(rows: [Row], codingPath: [CodingKey]) { self.rows = rows @@ -315,9 +315,7 @@ private struct PrefetchedRowsDecoder: Decoder { fatalError("keyed decoding from prefetched rows is not supported") } - func unkeyedContainer() throws -> UnkeyedDecodingContainer { - return self - } + func unkeyedContainer() throws -> UnkeyedDecodingContainer { self } func singleValueContainer() throws -> SingleValueDecodingContainer { fatalError("single value decoding from prefetched rows is not supported") @@ -325,17 +323,11 @@ private struct PrefetchedRowsDecoder: Decoder { } extension PrefetchedRowsDecoder: UnkeyedDecodingContainer { - var count: Int? { - return rows.count - } + var count: Int? { rows.count } - var isAtEnd: Bool { - return currentIndex >= rows.count - } + var isAtEnd: Bool { currentIndex >= rows.count } - mutating func decodeNil() throws -> Bool { - return false - } + mutating func decodeNil() throws -> Bool { false } mutating func decode(_ type: T.Type) throws -> T where T: Decodable { defer { currentIndex += 1 } @@ -366,7 +358,7 @@ private struct ColumnDecoder: Decoder { var row: Row var columnIndex: Int var codingPath: [CodingKey] - var userInfo: [CodingUserInfoKey: Any] { return R.databaseDecodingUserInfo } + var userInfo: [CodingUserInfoKey: Any] { R.databaseDecodingUserInfo } func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer { // We need to switch to JSON decoding @@ -378,30 +370,28 @@ private struct ColumnDecoder: Decoder { throw JSONRequiredError() } - func singleValueContainer() throws -> SingleValueDecodingContainer { - return self - } + func singleValueContainer() throws -> SingleValueDecodingContainer { self } } extension ColumnDecoder: SingleValueDecodingContainer { func decodeNil() -> Bool { - return row.hasNull(atIndex: columnIndex) + row.hasNull(atIndex: columnIndex) } - func decode(_ type: Bool.Type ) throws -> Bool { return row[columnIndex] } - func decode(_ type: Int.Type ) throws -> Int { return row[columnIndex] } - func decode(_ type: Int8.Type ) throws -> Int8 { return row[columnIndex] } - func decode(_ type: Int16.Type ) throws -> Int16 { return row[columnIndex] } - func decode(_ type: Int32.Type ) throws -> Int32 { return row[columnIndex] } - func decode(_ type: Int64.Type ) throws -> Int64 { return row[columnIndex] } - func decode(_ type: UInt.Type ) throws -> UInt { return row[columnIndex] } - func decode(_ type: UInt8.Type ) throws -> UInt8 { return row[columnIndex] } - func decode(_ type: UInt16.Type) throws -> UInt16 { return row[columnIndex] } - func decode(_ type: UInt32.Type) throws -> UInt32 { return row[columnIndex] } - func decode(_ type: UInt64.Type) throws -> UInt64 { return row[columnIndex] } - func decode(_ type: Float.Type ) throws -> Float { return row[columnIndex] } - func decode(_ type: Double.Type) throws -> Double { return row[columnIndex] } - func decode(_ type: String.Type) throws -> String { return row[columnIndex] } + func decode(_ type: Bool.Type ) throws -> Bool { row[columnIndex] } + func decode(_ type: Int.Type ) throws -> Int { row[columnIndex] } + func decode(_ type: Int8.Type ) throws -> Int8 { row[columnIndex] } + func decode(_ type: Int16.Type ) throws -> Int16 { row[columnIndex] } + func decode(_ type: Int32.Type ) throws -> Int32 { row[columnIndex] } + func decode(_ type: Int64.Type ) throws -> Int64 { row[columnIndex] } + func decode(_ type: UInt.Type ) throws -> UInt { row[columnIndex] } + func decode(_ type: UInt8.Type ) throws -> UInt8 { row[columnIndex] } + func decode(_ type: UInt16.Type) throws -> UInt16 { row[columnIndex] } + func decode(_ type: UInt32.Type) throws -> UInt32 { row[columnIndex] } + func decode(_ type: UInt64.Type) throws -> UInt64 { row[columnIndex] } + func decode(_ type: Float.Type ) throws -> Float { row[columnIndex] } + func decode(_ type: Double.Type) throws -> Double { row[columnIndex] } + func decode(_ type: String.Type) throws -> String { row[columnIndex] } func decode(_ type: T.Type) throws -> T where T: Decodable { // Prefer DatabaseValueConvertible decoding over Decodable. diff --git a/GRDB/Record/FetchableRecord+TableRecord.swift b/GRDB/Record/FetchableRecord+TableRecord.swift index 17457deab..452ca1946 100644 --- a/GRDB/Record/FetchableRecord+TableRecord.swift +++ b/GRDB/Record/FetchableRecord+TableRecord.swift @@ -25,7 +25,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) throws -> RecordCursor { - return try all().fetchCursor(db) + try all().fetchCursor(db) } /// An array of all records fetched from the database. @@ -40,7 +40,7 @@ extension FetchableRecord where Self: TableRecord { /// - parameter db: A database connection. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database) throws -> [Self] { - return try all().fetchAll(db) + try all().fetchAll(db) } /// The first found record. @@ -55,7 +55,7 @@ extension FetchableRecord where Self: TableRecord { /// - parameter db: A database connection. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ db: Database) throws -> Self? { - return try all().fetchOne(db) + try all().fetchOne(db) } } diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index ebf27ca89..06727c031 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -116,7 +116,7 @@ public protocol FetchableRecord { extension FetchableRecord { public static var databaseDecodingUserInfo: [CodingUserInfoKey: Any] { - return [:] + [:] } /// Returns a JSONDecoder with the following properties: @@ -133,7 +133,7 @@ extension FetchableRecord { } public static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { - return .deferredToDate + .deferredToDate } } @@ -382,7 +382,7 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchCursor(_ db: Database) throws -> RecordCursor { - return try RowDecoder.fetchCursor(db, self) + try RowDecoder.fetchCursor(db, self) } /// An array of fetched records. @@ -394,7 +394,7 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// - returns: An array of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchAll(_ db: Database) throws -> [RowDecoder] { - return try RowDecoder.fetchAll(db, self) + try RowDecoder.fetchAll(db, self) } /// The first fetched record. @@ -406,7 +406,7 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// - returns: An optional record. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchOne(_ db: Database) throws -> RowDecoder? { - return try RowDecoder.fetchOne(db, self) + try RowDecoder.fetchOne(db, self) } } diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index 5001cedde..95c602062 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -541,7 +541,7 @@ private final class FetchedRecordsObserver: Transaction } func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - return region.isModified(byEventsOfKind: eventKind) + region.isModified(byEventsOfKind: eventKind) } /// Part of the TransactionObserverType protocol @@ -1076,6 +1076,6 @@ private final class Item: FetchableRecord, Equatable { } static func == (lhs: Item, rhs: Item) -> Bool { - return lhs.row == rhs.row + lhs.row == rhs.row } } diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index f21dc91b6..e94c9aab6 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -182,7 +182,7 @@ extension MutablePersistableRecord { /// The default value specifies ABORT policy for both insertions and /// updates, which has GRDB generate regular INSERT and UPDATE queries. public static var persistenceConflictPolicy: PersistenceConflictPolicy { - return PersistenceConflictPolicy(insert: .abort, update: .abort) + PersistenceConflictPolicy(insert: .abort, update: .abort) } /// Notifies the record that it was succesfully inserted. @@ -276,7 +276,7 @@ extension MutablePersistableRecord { /// - SeeAlso: updateChanges(_:with:) @discardableResult public func updateChanges(_ db: Database, from record: Record) throws -> Bool { - return try updateChanges(db, from: PersistenceContainer(db, record)) + try updateChanges(db, from: PersistenceContainer(db, record)) } /// Mutates the record according to the provided closure, and then, if the @@ -322,7 +322,7 @@ extension MutablePersistableRecord { /// The default implementation for delete() invokes performDelete(). @discardableResult public func delete(_ db: Database) throws -> Bool { - return try performDelete(db) + try performDelete(db) } /// Returns true if and only if the primary key matches a row in @@ -330,7 +330,7 @@ extension MutablePersistableRecord { /// /// The default implementation for exists() invokes performExists(). public func exists(_ db: Database) throws -> Bool { - return try performExists(db) + try performExists(db) } // MARK: - Record Comparison @@ -515,7 +515,7 @@ extension MutablePersistableRecord { /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. @discardableResult public static func deleteAll(_ db: Database) throws -> Int { - return try all().deleteAll(db) + try all().deleteAll(db) } // MARK: Batch Update @@ -674,7 +674,7 @@ extension MutablePersistableRecord { /// - returns: Whether a database row was deleted. @discardableResult public static func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool { - return try deleteAll(db, keys: [key]) > 0 + try deleteAll(db, keys: [key]) > 0 } } diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 2ee2b8a0b..1ec5052df 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -57,7 +57,7 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// /// See https://www.sqlite.org/lang_conflict.html open class var persistenceConflictPolicy: PersistenceConflictPolicy { - return PersistenceConflictPolicy(insert: .abort, update: .abort) + PersistenceConflictPolicy(insert: .abort, update: .abort) } /// The default request selection. @@ -90,7 +90,7 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// // SELECT *, rowid FROM player /// try ExtendedPlayer.fetchAll(db) open class var databaseSelection: [SQLSelectable] { - return [AllColumns()] + [AllColumns()] } @@ -175,7 +175,7 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// false does not prevent it from turning true on subsequent modifications /// of the record. public var hasDatabaseChanges: Bool { - get { return databaseChangesIterator().next() != nil } + get { databaseChangesIterator().next() != nil } set { referenceRow = newValue ? nil : Row(self) } } @@ -189,7 +189,7 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// /// See `hasDatabaseChanges` for more information. public var databaseChanges: [String: DatabaseValue?] { - return Dictionary(uniqueKeysWithValues: databaseChangesIterator()) + Dictionary(uniqueKeysWithValues: databaseChangesIterator()) } // A change iterator that is used by both hasDatabaseChanges and diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index 8abbf876b..dc2b3c98a 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -89,12 +89,12 @@ extension TableRecord { /// - HTTPRequest -> "httpRequest" /// - TOEFL -> "toefl" public static var databaseTableName: String { - return defaultDatabaseTableName + defaultDatabaseTableName } /// Default value: `[AllColumns()]`. public static var databaseSelection: [SQLSelectable] { - return [AllColumns()] + [AllColumns()] } } @@ -106,7 +106,7 @@ extension TableRecord { /// /// - parameter db: A database connection. public static func fetchCount(_ db: Database) throws -> Int { - return try all().fetchCount(db) + try all().fetchCount(db) } } diff --git a/GRDB/Utils/Inflections.swift b/GRDB/Utils/Inflections.swift index da6c5b176..af1f05fd3 100644 --- a/GRDB/Utils/Inflections.swift +++ b/GRDB/Utils/Inflections.swift @@ -12,19 +12,19 @@ extension String { /// "player" -> "players" /// "players" -> "players" var pluralized: String { - return Inflections.default.pluralize(self) + Inflections.default.pluralize(self) } /// "player" -> "player" /// "players" -> "player" var singularized: String { - return Inflections.default.singularize(self) + Inflections.default.singularize(self) } /// "bar" -> "bar" /// "foo12" -> "foo" var digitlessRadical: String { - return String(prefix(upTo: Inflections.endIndexOfDigitlessRadical(self))) + String(prefix(upTo: Inflections.endIndexOfDigitlessRadical(self))) } } @@ -38,7 +38,7 @@ public struct Inflections { // For testability var uncountables: Set { - return Set(uncountablesRegularExpressions.keys) + Set(uncountablesRegularExpressions.keys) } // MARK: - Initialization @@ -144,12 +144,12 @@ public struct Inflections { /// /// Inflections.default.pluralize("player") // "players" public func pluralize(_ string: String) -> String { - return inflectString(string, with: pluralizeRules) + inflectString(string, with: pluralizeRules) } /// Returns a singularized string. public func singularize(_ string: String) -> String { - return inflectString(string, with: singularizeRules) + inflectString(string, with: singularizeRules) } // MARK: - Utils diff --git a/GRDB/Utils/LockedBox.swift b/GRDB/Utils/LockedBox.swift index 84ea6435b..0fd3f5b87 100644 --- a/GRDB/Utils/LockedBox.swift +++ b/GRDB/Utils/LockedBox.swift @@ -6,7 +6,7 @@ final class LockedBox { private var lock = NSLock() var value: T { - get { return read { $0 } } + get { read { $0 } } set { write { $0 = newValue } } } @@ -30,7 +30,7 @@ final class LockedBox { extension LockedBox where T: Numeric { @discardableResult func increment() -> T { - return write { n in + write { n in n += 1 return n } @@ -38,7 +38,7 @@ extension LockedBox where T: Numeric { @discardableResult func decrement() -> T { - return write { n in + write { n in n -= 1 return n } diff --git a/GRDB/Utils/OrderedDictionary.swift b/GRDB/Utils/OrderedDictionary.swift index bb1c72582..a700c2f54 100644 --- a/GRDB/Utils/OrderedDictionary.swift +++ b/GRDB/Utils/OrderedDictionary.swift @@ -13,9 +13,7 @@ struct OrderedDictionary { @usableFromInline /* private(set) */ var keys: [Key] @usableFromInline /* private(set) */ var dictionary: [Key: Value] - var values: [Value] { - return keys.map { dictionary[$0]! } - } + var values: [Value] { keys.map { dictionary[$0]! } } private init(keys: [Key], dictionary: [Key: Value]) { assert(Set(keys) == Set(dictionary.keys)) @@ -39,7 +37,7 @@ struct OrderedDictionary { /// Returns the value associated with key, or nil. @usableFromInline subscript(_ key: Key) -> Value? { - get { return dictionary[key] } + get { dictionary[key] } set { if let value = newValue { updateValue(value, forKey: key) @@ -52,7 +50,7 @@ struct OrderedDictionary { /// Returns the value associated with key, or the default value. @inlinable subscript(_ key: Key, default defaultValue: Value) -> Value { - get { return dictionary[key] ?? defaultValue } + get { dictionary[key] ?? defaultValue } set { self[key] = newValue } } @@ -98,7 +96,7 @@ struct OrderedDictionary { /// Returns a new ordered dictionary containing the keys of this dictionary /// with the values transformed by the given closure. func mapValues(_ transform: (Value) throws -> T) rethrows -> OrderedDictionary { - return try reduce(into: .init()) { dict, pair in + try reduce(into: .init()) { dict, pair in let value = try transform(pair.value) dict.appendValue(value, forKey: pair.key) } @@ -108,7 +106,7 @@ struct OrderedDictionary { /// that have non-nil values as the result of transformation by the /// given closure. func compactMapValues(_ transform: (Value) throws -> T?) rethrows -> OrderedDictionary { - return try reduce(into: .init()) { dict, pair in + try reduce(into: .init()) { dict, pair in if let value = try transform(pair.value) { dict.appendValue(value, forKey: pair.key) } @@ -126,18 +124,11 @@ extension OrderedDictionary: Collection { @usableFromInline typealias Index = Int - @usableFromInline var startIndex: Int { - return 0 - } - - @usableFromInline var endIndex: Int { - return keys.count - } + @usableFromInline var startIndex: Int { 0 } + @usableFromInline var endIndex: Int { keys.count } @usableFromInline - func index(after i: Int) -> Int { - return i + 1 - } + func index(after i: Int) -> Int { i + 1 } @usableFromInline subscript(position: Int) -> (key: Key, value: Value) { @@ -157,7 +148,7 @@ extension OrderedDictionary: ExpressibleByDictionaryLiteral { extension OrderedDictionary: Equatable where Value: Equatable { @usableFromInline static func == (lhs: OrderedDictionary, rhs: OrderedDictionary) -> Bool { - return (lhs.keys == rhs.keys) && (lhs.dictionary == rhs.dictionary) + (lhs.keys == rhs.keys) && (lhs.dictionary == rhs.dictionary) } } diff --git a/GRDB/Utils/Pool.swift b/GRDB/Utils/Pool.swift index fe4df973b..a76579912 100644 --- a/GRDB/Utils/Pool.swift +++ b/GRDB/Utils/Pool.swift @@ -63,7 +63,7 @@ final class Pool { /// Returns a tuple (element, release) /// Client must call release(), only once, after the element has been used. func get() throws -> (element: T, release: () -> Void) { - return try barrierQueue.sync { + try barrierQueue.sync { itemsSemaphore.wait() itemsGroup.enter() do { @@ -126,7 +126,7 @@ final class Pool { /// Blocks until no element is used, and runs the `barrier` function before /// any other element is dequeued. func barrier(execute barrier: () throws -> T) rethrows -> T { - return try barrierQueue.sync(flags: [.barrier]) { + try barrierQueue.sync(flags: [.barrier]) { itemsGroup.wait() return try barrier() } diff --git a/GRDB/Utils/ReadWriteBox.swift b/GRDB/Utils/ReadWriteBox.swift index 1e11f2ea7..f540908c2 100644 --- a/GRDB/Utils/ReadWriteBox.swift +++ b/GRDB/Utils/ReadWriteBox.swift @@ -6,7 +6,7 @@ final class ReadWriteBox { private var queue: DispatchQueue var value: T { - get { return read { $0 } } + get { read { $0 } } set { write { $0 = newValue } } } @@ -16,13 +16,13 @@ final class ReadWriteBox { } func read(_ block: (T) throws -> U) rethrows -> U { - return try queue.sync { + try queue.sync { try block(_value) } } func write(_ block: (inout T) throws -> U) rethrows -> U { - return try queue.sync(flags: [.barrier]) { + try queue.sync(flags: [.barrier]) { try block(&_value) } } @@ -31,7 +31,7 @@ final class ReadWriteBox { extension ReadWriteBox where T: Numeric { @discardableResult func increment() -> T { - return write { n in + write { n in n += 1 return n } @@ -39,7 +39,7 @@ extension ReadWriteBox where T: Numeric { @discardableResult func decrement() -> T { - return write { n in + write { n in n -= 1 return n } diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index 902322636..a82ca5459 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -18,7 +18,7 @@ extension String { /// databaseQuestionMarks(count: 3) // "?,?,?" @inlinable public func databaseQuestionMarks(count: Int) -> String { - return repeatElement("?", count: count).joined(separator: ",") + repeatElement("?", count: count).joined(separator: ",") } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) @@ -64,7 +64,7 @@ func GRDBPrecondition( // Workaround Swift inconvenience around factory methods of non-final classes func cast(_ value: T) -> U? { - return value as? U + value as? U } extension RangeReplaceableCollection { @@ -93,7 +93,7 @@ extension DispatchQueue { }() static var isMain: Bool { - return DispatchQueue.getSpecific(key: mainKey) != nil + DispatchQueue.getSpecific(key: mainKey) != nil } } diff --git a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift index 5946ef3b4..e43d1eadf 100644 --- a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift +++ b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift @@ -26,7 +26,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { /// /// - returns: a ValueObservation. public func observationForAll() -> ValueObservation> { - return ValueObservation.tracking(self, reducer: { _ in + ValueObservation.tracking(self, reducer: { _ in ValueReducers.AllValues { try DatabaseValue.fetchAll($0, self) } }) } @@ -55,7 +55,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { /// - parameter request: the observed request. /// - returns: a ValueObservation. public func observationForFirst() -> ValueObservation> { - return ValueObservation.tracking(self, reducer: { _ in + ValueObservation.tracking(self, reducer: { _ in ValueReducers.OneValue { try DatabaseValue.fetchOne($0, self) } }) } @@ -89,7 +89,7 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: /// /// - returns: a ValueObservation. public func observationForAll() -> ValueObservation> { - return ValueObservation.tracking(self, reducer: { _ in + ValueObservation.tracking(self, reducer: { _ in ValueReducers.AllOptionalValues { try DatabaseValue.fetchAll($0, self) } }) } @@ -118,7 +118,7 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: /// /// - returns: a ValueObservation. public func observationForFirst() -> ValueObservation> { - return ValueObservation.tracking(self, reducer: { _ in + ValueObservation.tracking(self, reducer: { _ in ValueReducers.OneValue { try DatabaseValue.fetchOne($0, self) } }) } @@ -142,7 +142,7 @@ extension ValueReducers { } public func fetch(_ db: Database) throws -> [DatabaseValue] { - return try _fetch(db) + try _fetch(db) } public mutating func value(_ dbValues: [DatabaseValue]) -> [RowDecoder]? { @@ -175,7 +175,7 @@ extension ValueReducers { } public func fetch(_ db: Database) throws -> DatabaseValue? { - return try _fetch(db) + try _fetch(db) } public mutating func value(_ dbValue: DatabaseValue?) -> RowDecoder?? { @@ -216,7 +216,7 @@ extension ValueReducers { } public func fetch(_ db: Database) throws -> [DatabaseValue] { - return try _fetch(db) + try _fetch(db) } public mutating func value(_ dbValues: [DatabaseValue]) -> [RowDecoder?]? { diff --git a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift index 75c82eea5..eb6182e8e 100644 --- a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift +++ b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift @@ -26,7 +26,7 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// /// - returns: a ValueObservation. public func observationForAll() -> ValueObservation> { - return ValueObservation.tracking(self, reducer: { _ in + ValueObservation.tracking(self, reducer: { _ in ValueReducers.AllRecords { try Row.fetchAll($0, self) } }) } @@ -54,7 +54,7 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// /// - returns: a ValueObservation. public func observationForFirst() -> ValueObservation> { - return ValueObservation.tracking(self, reducer: { _ in + ValueObservation.tracking(self, reducer: { _ in ValueReducers.OneRecord { try Row.fetchOne($0, self) } }) } @@ -87,7 +87,7 @@ extension TableRecord where Self: FetchableRecord { /// /// - returns: a ValueObservation. public static func observationForAll() -> ValueObservation> { - return all().observationForAll() + all().observationForAll() } /// Creates a ValueObservation which observes the table record, and notifies @@ -136,7 +136,7 @@ extension ValueReducers { } public func fetch(_ db: Database) throws -> [Row] { - return try _fetch(db) + try _fetch(db) } public mutating func value(_ rows: [Row]) -> [RowDecoder]? { @@ -166,7 +166,7 @@ extension ValueReducers { } public func fetch(_ db: Database) throws -> Row? { - return try _fetch(db) + try _fetch(db) } public mutating func value(_ row: Row?) -> RowDecoder?? { diff --git a/GRDB/ValueObservation/ValueObservation+Row.swift b/GRDB/ValueObservation/ValueObservation+Row.swift index 9a4a6a763..d6087109b 100644 --- a/GRDB/ValueObservation/ValueObservation+Row.swift +++ b/GRDB/ValueObservation/ValueObservation+Row.swift @@ -25,7 +25,7 @@ extension FetchRequest where RowDecoder == Row { /// /// - returns: a ValueObservation. public func observationForAll() -> ValueObservation { - return ValueObservation.tracking(self, reducer: { _ in + ValueObservation.tracking(self, reducer: { _ in ValueReducers.AllRows(fetch: self.fetchAll) }) } @@ -53,7 +53,7 @@ extension FetchRequest where RowDecoder == Row { /// /// - returns: a ValueObservation. public func observationForFirst() -> ValueObservation { - return ValueObservation.tracking(self, reducer: { _ in + ValueObservation.tracking(self, reducer: { _ in ValueReducers.OneRow(fetch: self.fetchOne) }) } @@ -75,7 +75,7 @@ extension ValueReducers { } public func fetch(_ db: Database) throws -> [Row] { - return try _fetch(db) + try _fetch(db) } public mutating func value(_ rows: [Row]) -> [Row]? { @@ -103,7 +103,7 @@ extension ValueReducers { } public func fetch(_ db: Database) throws -> Row? { - return try _fetch(db) + try _fetch(db) } public mutating func value(_ row: Row?) -> Row?? { diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift index e726ace7a..232d9de7a 100644 --- a/GRDB/ValueObservation/ValueObserver.swift +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -158,7 +158,7 @@ class ValueObserver: TransactionObserver { class ValueObserverToken: TransactionObserver { // Useless junk - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { return false } + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { false } func databaseDidChange(with event: DatabaseEvent) { } func databaseDidCommit(_ db: Database) { } func databaseDidRollback(_ db: Database) { } diff --git a/GRDB/ValueObservation/ValueReducer/Combine.swift b/GRDB/ValueObservation/ValueReducer/Combine.swift index d15cd102f..7c03e2f10 100644 --- a/GRDB/ValueObservation/ValueReducer/Combine.swift +++ b/GRDB/ValueObservation/ValueReducer/Combine.swift @@ -18,7 +18,7 @@ extension ValueReducers { } public func fetch(_ db: Database) throws -> Fetched { - return try ( + try ( r1.fetch(db), r2.fetch(db)) } @@ -101,7 +101,7 @@ extension ValueReducers { } public func fetch(_ db: Database) throws -> Fetched { - return try ( + try ( r1.fetch(db), r2.fetch(db), r3.fetch(db)) @@ -205,7 +205,7 @@ extension ValueReducers { } public func fetch(_ db: Database) throws -> Fetched { - return try ( + try ( r1.fetch(db), r2.fetch(db), r3.fetch(db), @@ -326,7 +326,7 @@ extension ValueReducers { } public func fetch(_ db: Database) throws -> Fetched { - return try ( + try ( r1.fetch(db), r2.fetch(db), r3.fetch(db), @@ -464,7 +464,7 @@ extension ValueReducers { } public func fetch(_ db: Database) throws -> Fetched { - return try ( + try ( r1.fetch(db), r2.fetch(db), r3.fetch(db), @@ -591,7 +591,7 @@ extension ValueReducers { } public func fetch(_ db: Database) throws -> Fetched { - return try ( + try ( r1.fetch(db), r2.fetch(db), r3.fetch(db), @@ -733,7 +733,7 @@ extension ValueReducers { } public func fetch(_ db: Database) throws -> Fetched { - return try ( + try ( r1.fetch(db), r2.fetch(db), r3.fetch(db), diff --git a/GRDB/ValueObservation/ValueReducer/CompactMap.swift b/GRDB/ValueObservation/ValueReducer/CompactMap.swift index 00ed7eafd..b8308438e 100644 --- a/GRDB/ValueObservation/ValueReducer/CompactMap.swift +++ b/GRDB/ValueObservation/ValueReducer/CompactMap.swift @@ -15,7 +15,7 @@ extension ValueReducer { /// Returns a reducer which outputs the non-nil results of calling the given /// transformation which each element emitted by this reducer. public func compactMap(_ transform: @escaping (Value) -> T?) -> ValueReducers.CompactMap { - return ValueReducers.CompactMap(self, transform) + ValueReducers.CompactMap(self, transform) } } @@ -35,7 +35,7 @@ extension ValueReducers { } public func fetch(_ db: Database) throws -> Base.Fetched { - return try base.fetch(db) + try base.fetch(db) } public mutating func value(_ fetched: Base.Fetched) -> Value? { diff --git a/GRDB/ValueObservation/ValueReducer/Fetch.swift b/GRDB/ValueObservation/ValueReducer/Fetch.swift index 0a4620ea8..304c1ff6f 100644 --- a/GRDB/ValueObservation/ValueReducer/Fetch.swift +++ b/GRDB/ValueObservation/ValueReducer/Fetch.swift @@ -12,11 +12,11 @@ extension ValueReducers { } public func fetch(_ db: Database) throws -> Value { - return try _fetch(db) + try _fetch(db) } public func value(_ fetched: Value) -> Value? { - return fetched + fetched } } } diff --git a/GRDB/ValueObservation/ValueReducer/Map.swift b/GRDB/ValueObservation/ValueReducer/Map.swift index 2e1f1d7e9..634b9192f 100644 --- a/GRDB/ValueObservation/ValueReducer/Map.swift +++ b/GRDB/ValueObservation/ValueReducer/Map.swift @@ -15,7 +15,7 @@ extension ValueReducer { /// Returns a reducer which outputs the results of calling the given /// transformation which each element emitted by this reducer. public func map(_ transform: @escaping (Value) -> T) -> ValueReducers.Map { - return ValueReducers.Map(self, transform) + ValueReducers.Map(self, transform) } } @@ -38,7 +38,7 @@ extension ValueReducers { } public func fetch(_ db: Database) throws -> Base.Fetched { - return try base.fetch(db) + try base.fetch(db) } public mutating func value(_ fetched: Base.Fetched) -> Value? { diff --git a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift b/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift index d7fd33a72..bcfbb46b6 100644 --- a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift +++ b/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift @@ -12,7 +12,7 @@ extension ValueReducer where Value: Equatable { /// /// Returns a ValueReducer which filters out consecutive equal values. public func removeDuplicates() -> ValueReducers.RemoveDuplicates { - return ValueReducers.RemoveDuplicates(self) + ValueReducers.RemoveDuplicates(self) } } @@ -31,7 +31,7 @@ extension ValueReducers { } public func fetch(_ db: Database) throws -> Base.Fetched { - return try base.fetch(db) + try base.fetch(db) } public mutating func value(_ fetched: Base.Fetched) -> Base.Value? { diff --git a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift index 198a9b611..d9ebffeb7 100644 --- a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift +++ b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift @@ -78,12 +78,12 @@ public struct AnyValueReducer: ValueReducer { /// :nodoc: public func fetch(_ db: Database) throws -> Fetched { - return try _fetch(db) + try _fetch(db) } /// :nodoc: public func value(_ fetched: Fetched) -> Value? { - return _value(fetched) + _value(fetched) } } diff --git a/README.md b/README.md index f0f5e6733..37e95cdb4 100644 --- a/README.md +++ b/README.md @@ -1879,7 +1879,7 @@ struct MaxLength : DatabaseAggregate { } func finalize() -> DatabaseValueConvertible? { - return maxLength + maxLength } } @@ -2472,9 +2472,7 @@ Subclasses of the [Record](#record-class) class must always override their super ```swift class Place: Record { - override class var databaseTableName: String { - return "place" - } + override class var databaseTableName: String { "place" } } print(Place.databaseTableName) // prints "place" ``` @@ -2910,9 +2908,7 @@ class Place: Record { } /// The table name - override class var databaseTableName: String { - return "place" - } + override class var databaseTableName: String { "place" } /// The table columns enum Columns: String, ColumnExpression { @@ -3226,7 +3222,7 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](Doc // When you subclass Record, you need an override: class Book : Record { override class var databaseSelection: [SQLSelectable] { - return [AllColums(), Column.rowID] + [AllColums(), Column.rowID] } } ``` @@ -3530,9 +3526,7 @@ class Place: Record { } /// The table name - override class var databaseTableName: String { - return "place" - } + override class var databaseTableName: String { "place" } /// The table columns enum Columns: String, ColumnExpression { @@ -4814,7 +4808,7 @@ let request = Player.all() ```swift extension Player { static func filter(color: Color) -> SQLRequest { - return SQLRequest( + SQLRequest( sql: "SELECT * FROM player WHERE color = ?" arguments: [color]) } @@ -4829,7 +4823,7 @@ let request = Player.all() ```swift extension Player { static func filter(color: Color) -> SQLRequest { - return "SELECT * FROM player WHERE color = \(color)" + "SELECT * FROM player WHERE color = \(color)" } } ``` @@ -5318,7 +5312,7 @@ extension PlayerInfo { /// Fetches all player infos static func fetchAll(_ db: Database) throws -> [PlayerInfo] { - return try all().fetchAll(db) + try all().fetchAll(db) } } ``` @@ -5389,7 +5383,7 @@ extension PlayerInfo { /// Fetches all player infos static func fetchAll(_ db: Database) throws -> [PlayerInfo] { - return try all().fetchAll(db) + try all().fetchAll(db) } } @@ -6380,7 +6374,7 @@ class PlayerObserver: TransactionObserver { var playerTableWasModified = false func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - return eventKind.tableName == "player" + eventKind.tableName == "player" } func databaseDidChange(with event: DatabaseEvent) { @@ -7247,7 +7241,7 @@ Those guarantees hold as long as you follow three rules: ```swift // SAFE CONCURRENCY func fetchCurrentUser(_ db: Database) throws -> User? { - return try User.fetchOne(db) + try User.fetchOne(db) } // dbQueue is a singleton defined somewhere in your app let user = try dbQueue.read { db in // or dbPool.read diff --git a/Tests/Crash/DatabaseValueConvertibleCrashTests.swift b/Tests/Crash/DatabaseValueConvertibleCrashTests.swift index 213d0cc30..4f39fe4d8 100644 --- a/Tests/Crash/DatabaseValueConvertibleCrashTests.swift +++ b/Tests/Crash/DatabaseValueConvertibleCrashTests.swift @@ -11,9 +11,7 @@ private struct IntConvertible: DatabaseValueConvertible { init(int: Int) { self.int = int } - var databaseValue: DatabaseValue { - return int.databaseValue - } + var databaseValue: DatabaseValue { int.databaseValue } static func fromDatabaseValue(_ dbValue: DatabaseValue) -> IntConvertible? { guard let int = Int.fromDatabaseValue(dbValue) else { return nil diff --git a/Tests/Crash/RecordCrashTests.swift b/Tests/Crash/RecordCrashTests.swift index 70ed00929..06cd0e890 100644 --- a/Tests/Crash/RecordCrashTests.swift +++ b/Tests/Crash/RecordCrashTests.swift @@ -9,19 +9,19 @@ private class RecordWithoutDatabaseTableName: Record { } private class RecordWithInexistingDatabaseTable: Record { override class var databaseTableName: String { - return "foo" + "foo" } } private class RecordWithEmptyPersistentDictionary : Record { override class var databaseTableName: String { - return "records" + "records" } } private class RecordWithNilPrimaryKey : Record { override class var databaseTableName: String { - return "records" + "records" } override func encode(to container: inout PersistenceContainer) { @@ -31,7 +31,7 @@ private class RecordWithNilPrimaryKey : Record { private class RecordForTableWithoutPrimaryKey : Record { override class var databaseTableName: String { - return "records" + "records" } override func encode(to container: inout PersistenceContainer) { @@ -41,7 +41,7 @@ private class RecordForTableWithoutPrimaryKey : Record { private class RecordForTableWithMultipleColumnsPrimaryKey : Record { override class var databaseTableName: String { - return "records" + "records" } override func encode(to container: inout PersistenceContainer) { @@ -51,7 +51,7 @@ private class RecordForTableWithMultipleColumnsPrimaryKey : Record { private class RecordWithRowIDPrimaryKeyNotExposedInPersistentDictionary : Record { override class var databaseTableName: String { - return "records" + "records" } override func encode(to container: inout PersistenceContainer) { diff --git a/Tests/GRDBTests/AnyCursorTests.swift b/Tests/GRDBTests/AnyCursorTests.swift index 9ed9fa3c0..33ca04a81 100644 --- a/Tests/GRDBTests/AnyCursorTests.swift +++ b/Tests/GRDBTests/AnyCursorTests.swift @@ -44,7 +44,7 @@ class AnyCursorTests: GRDBTestCase { // This helper function makes sure AnyCursor initializer accepts any cursor, // and not only AnyCursor: func makeAnyCursor(_ cursor: C) -> AnyCursor where C.Element == Int { - return AnyCursor(cursor) + AnyCursor(cursor) } let cursor = AnyCursor(base) XCTAssertEqual(try cursor.next()!, 0) @@ -60,7 +60,7 @@ class AnyCursorTests: GRDBTestCase { return i } func makeAnyCursor(_ cursor: C) -> AnyCursor where C.Element == Int { - return AnyCursor(cursor) + AnyCursor(cursor) } let cursor = makeAnyCursor(base) XCTAssertEqual(try cursor.next()!, 0) diff --git a/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift index 022832854..b29126406 100644 --- a/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift @@ -33,7 +33,7 @@ private struct PlayerWithOptionalTeam: Decodable, FetchableRecord { extension QueryInterfaceRequest where T == Player { func filter(teamName: String) -> QueryInterfaceRequest { - return joining(required: PlayerWithOptionalTeam.team.filter(Column("name") == teamName)) + joining(required: PlayerWithOptionalTeam.team.filter(Column("name") == teamName)) } func orderedByTeamName() -> QueryInterfaceRequest { diff --git a/Tests/GRDBTests/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift index 5771f8212..fee86a797 100644 --- a/Tests/GRDBTests/CompilationProtocolTests.swift +++ b/Tests/GRDBTests/CompilationProtocolTests.swift @@ -22,7 +22,7 @@ private class UserCursor : Cursor { extension UserCursor { // Test presence of the Element associated type - static var elementType: Element.Type { return Element.self } + static var elementType: Element.Type { Element.self } } // MARK: - DatabaseAggregate @@ -146,7 +146,7 @@ private class UserTableRecord2 : TableRecord { // MARK: - TransactionObserver private class UserTransactionObserver : TransactionObserver { - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { return false } + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { false } func databaseDidChange(with event: DatabaseEvent) { } func databaseDidCommit(_ db: Database) { } func databaseDidRollback(_ db: Database) { } diff --git a/Tests/GRDBTests/CompilationSubClassTests.swift b/Tests/GRDBTests/CompilationSubClassTests.swift index 7e48c49a1..7421c4db2 100644 --- a/Tests/GRDBTests/CompilationSubClassTests.swift +++ b/Tests/GRDBTests/CompilationSubClassTests.swift @@ -12,13 +12,13 @@ private class UserRecord : Record { override init() { super.init() } required init(row: Row) { super.init(row: row) } - override class var databaseTableName: String { return super.databaseTableName } - override class var persistenceConflictPolicy: PersistenceConflictPolicy { return super.persistenceConflictPolicy } - override class var databaseSelection: [SQLSelectable] { return super.databaseSelection } + override class var databaseTableName: String { super.databaseTableName } + override class var persistenceConflictPolicy: PersistenceConflictPolicy { super.persistenceConflictPolicy } + override class var databaseSelection: [SQLSelectable] { super.databaseSelection } override func encode(to container: inout PersistenceContainer) { super.encode(to: &container) } override func didInsert(with rowID: Int64, for column: String?) { super.didInsert(with: rowID, for: column) } override func copy() -> Self { preconditionFailure() } override func insert(_ db: Database) throws { try super.insert(db) } override func update(_ db: Database, columns: Set) throws { try super.update(db, columns: columns) } - override func delete(_ db: Database) throws -> Bool { return try super.delete(db) } + override func delete(_ db: Database) throws -> Bool { try super.delete(db) } } diff --git a/Tests/GRDBTests/DatabaseAggregateTests.swift b/Tests/GRDBTests/DatabaseAggregateTests.swift index 0db6d2706..870f5fe46 100644 --- a/Tests/GRDBTests/DatabaseAggregateTests.swift +++ b/Tests/GRDBTests/DatabaseAggregateTests.swift @@ -6,9 +6,7 @@ import XCTest #endif private struct CustomValueType : DatabaseValueConvertible { - var databaseValue: DatabaseValue { - return "CustomValueType".databaseValue - } + var databaseValue: DatabaseValue { "CustomValueType".databaseValue } static func fromDatabaseValue(_ dbValue: DatabaseValue) -> CustomValueType? { guard let string = String.fromDatabaseValue(dbValue), string == "CustomValueType" else { return nil @@ -24,9 +22,7 @@ class DatabaseAggregateTests: GRDBTestCase { func testAggregateReturningNull() throws { struct Aggregate : DatabaseAggregate { func step(_ values: [DatabaseValue]) { } - func finalize() -> DatabaseValueConvertible? { - return nil - } + func finalize() -> DatabaseValueConvertible? { nil } } let dbQueue = try makeDatabaseQueue() let fn = DatabaseFunction("f", argumentCount: 0, aggregate: Aggregate.self) @@ -39,9 +35,7 @@ class DatabaseAggregateTests: GRDBTestCase { func testAggregateReturningInt64() throws { struct Aggregate : DatabaseAggregate { func step(_ values: [DatabaseValue]) { } - func finalize() -> DatabaseValueConvertible? { - return Int64(1) - } + func finalize() -> DatabaseValueConvertible? { Int64(1) } } let dbQueue = try makeDatabaseQueue() let fn = DatabaseFunction("f", argumentCount: 0, aggregate: Aggregate.self) @@ -55,9 +49,7 @@ class DatabaseAggregateTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() struct Aggregate : DatabaseAggregate { func step(_ values: [DatabaseValue]) { } - func finalize() -> DatabaseValueConvertible? { - return 1e100 - } + func finalize() -> DatabaseValueConvertible? { 1e100 } } let fn = DatabaseFunction("f", argumentCount: 0, aggregate: Aggregate.self) dbQueue.add(function: fn) @@ -69,9 +61,7 @@ class DatabaseAggregateTests: GRDBTestCase { func testAggregateReturningString() throws { struct Aggregate : DatabaseAggregate { func step(_ values: [DatabaseValue]) { } - func finalize() -> DatabaseValueConvertible? { - return "foo" - } + func finalize() -> DatabaseValueConvertible? { "foo" } } let dbQueue = try makeDatabaseQueue() let fn = DatabaseFunction("f", argumentCount: 0, aggregate: Aggregate.self) @@ -85,7 +75,7 @@ class DatabaseAggregateTests: GRDBTestCase { struct Aggregate : DatabaseAggregate { func step(_ values: [DatabaseValue]) { } func finalize() -> DatabaseValueConvertible? { - return "foo".data(using: .utf8) + "foo".data(using: .utf8) } } let dbQueue = try makeDatabaseQueue() @@ -99,9 +89,7 @@ class DatabaseAggregateTests: GRDBTestCase { func testAggregateReturningCustomValueType() throws { struct Aggregate : DatabaseAggregate { func step(_ values: [DatabaseValue]) { } - func finalize() -> DatabaseValueConvertible? { - return CustomValueType() - } + func finalize() -> DatabaseValueConvertible? { CustomValueType() } } let dbQueue = try makeDatabaseQueue() let fn = DatabaseFunction("f", argumentCount: 0, aggregate: Aggregate.self) @@ -119,9 +107,7 @@ class DatabaseAggregateTests: GRDBTestCase { mutating func step(_ dbValues: [DatabaseValue]) { result = dbValues[0].isNull } - func finalize() -> DatabaseValueConvertible? { - return result - } + func finalize() -> DatabaseValueConvertible? { result } } let dbQueue = try makeDatabaseQueue() let fn = DatabaseFunction("f", argumentCount: 1, aggregate: Aggregate.self) @@ -142,9 +128,7 @@ class DatabaseAggregateTests: GRDBTestCase { mutating func step(_ dbValues: [DatabaseValue]) { result = Int64.fromDatabaseValue(dbValues[0]) } - func finalize() -> DatabaseValueConvertible? { - return result - } + func finalize() -> DatabaseValueConvertible? { result } } let dbQueue = try makeDatabaseQueue() let fn = DatabaseFunction("f", argumentCount: 1, aggregate: Aggregate.self) @@ -162,9 +146,7 @@ class DatabaseAggregateTests: GRDBTestCase { mutating func step(_ dbValues: [DatabaseValue]) { result = Double.fromDatabaseValue(dbValues[0]) } - func finalize() -> DatabaseValueConvertible? { - return result - } + func finalize() -> DatabaseValueConvertible? { result } } let dbQueue = try makeDatabaseQueue() let fn = DatabaseFunction("f", argumentCount: 1, aggregate: Aggregate.self) @@ -182,9 +164,7 @@ class DatabaseAggregateTests: GRDBTestCase { mutating func step(_ dbValues: [DatabaseValue]) { result = String.fromDatabaseValue(dbValues[0]) } - func finalize() -> DatabaseValueConvertible? { - return result - } + func finalize() -> DatabaseValueConvertible? { result } } let dbQueue = try makeDatabaseQueue() let fn = DatabaseFunction("f", argumentCount: 1, aggregate: Aggregate.self) @@ -201,9 +181,7 @@ class DatabaseAggregateTests: GRDBTestCase { mutating func step(_ dbValues: [DatabaseValue]) { result = Data.fromDatabaseValue(dbValues[0]) } - func finalize() -> DatabaseValueConvertible? { - return result - } + func finalize() -> DatabaseValueConvertible? { result } } let dbQueue = try makeDatabaseQueue() let fn = DatabaseFunction("f", argumentCount: 1, aggregate: Aggregate.self) @@ -221,9 +199,7 @@ class DatabaseAggregateTests: GRDBTestCase { mutating func step(_ dbValues: [DatabaseValue]) { result = CustomValueType.fromDatabaseValue(dbValues[0]) } - func finalize() -> DatabaseValueConvertible? { - return result - } + func finalize() -> DatabaseValueConvertible? { result } } let dbQueue = try makeDatabaseQueue() let fn = DatabaseFunction("f", argumentCount: 1, aggregate: Aggregate.self) @@ -239,9 +215,7 @@ class DatabaseAggregateTests: GRDBTestCase { func testAggregateWithoutArgument() throws { struct Aggregate : DatabaseAggregate { func step(_ dbValues: [DatabaseValue]) { } - func finalize() -> DatabaseValueConvertible? { - return "foo" - } + func finalize() -> DatabaseValueConvertible? { "foo" } } let dbQueue = try makeDatabaseQueue() let fn = DatabaseFunction("f", argumentCount: 0, aggregate: Aggregate.self) @@ -266,9 +240,7 @@ class DatabaseAggregateTests: GRDBTestCase { mutating func step(_ dbValues: [DatabaseValue]) { result = String.fromDatabaseValue(dbValues[0])?.uppercased() } - func finalize() -> DatabaseValueConvertible? { - return result - } + func finalize() -> DatabaseValueConvertible? { result } } let dbQueue = try makeDatabaseQueue() let fn = DatabaseFunction("f", argumentCount: 1, aggregate: Aggregate.self) @@ -296,9 +268,7 @@ class DatabaseAggregateTests: GRDBTestCase { let ints = dbValues.compactMap { Int.fromDatabaseValue($0) } result = ints.reduce(0, +) } - func finalize() -> DatabaseValueConvertible? { - return result - } + func finalize() -> DatabaseValueConvertible? { result } } let dbQueue = try makeDatabaseQueue() let fn = DatabaseFunction("f", argumentCount: 2, aggregate: Aggregate.self) @@ -323,9 +293,7 @@ class DatabaseAggregateTests: GRDBTestCase { mutating func step(_ dbValues: [DatabaseValue]) { result = dbValues.count } - func finalize() -> DatabaseValueConvertible? { - return result - } + func finalize() -> DatabaseValueConvertible? { result } } let dbQueue = try makeDatabaseQueue() let fn = DatabaseFunction("f", aggregate: Aggregate.self) @@ -344,9 +312,7 @@ class DatabaseAggregateTests: GRDBTestCase { func step(_ dbValues: [DatabaseValue]) throws { throw DatabaseError(message: "custom error message") } - func finalize() -> DatabaseValueConvertible? { - fatalError() - } + func finalize() -> DatabaseValueConvertible? { fatalError() } } let dbQueue = try makeDatabaseQueue() let fn = DatabaseFunction("f", aggregate: Aggregate.self) @@ -367,9 +333,7 @@ class DatabaseAggregateTests: GRDBTestCase { func step(_ dbValues: [DatabaseValue]) throws { throw DatabaseError(resultCode: ResultCode(rawValue: 123)) } - func finalize() -> DatabaseValueConvertible? { - fatalError() - } + func finalize() -> DatabaseValueConvertible? { fatalError() } } let dbQueue = try makeDatabaseQueue() let fn = DatabaseFunction("f", aggregate: Aggregate.self) @@ -390,9 +354,7 @@ class DatabaseAggregateTests: GRDBTestCase { func step(_ dbValues: [DatabaseValue]) throws { throw DatabaseError(resultCode: ResultCode(rawValue: 123), message: "custom error message") } - func finalize() -> DatabaseValueConvertible? { - fatalError() - } + func finalize() -> DatabaseValueConvertible? { fatalError() } } let dbQueue = try makeDatabaseQueue() let fn = DatabaseFunction("f", aggregate: Aggregate.self) @@ -413,9 +375,7 @@ class DatabaseAggregateTests: GRDBTestCase { func step(_ dbValues: [DatabaseValue]) throws { throw NSError(domain: "CustomErrorDomain", code: 123, userInfo: [NSLocalizedDescriptionKey: "custom error message"]) } - func finalize() -> DatabaseValueConvertible? { - fatalError() - } + func finalize() -> DatabaseValueConvertible? { fatalError() } } let dbQueue = try makeDatabaseQueue() let fn = DatabaseFunction("f", aggregate: Aggregate.self) @@ -531,9 +491,7 @@ class DatabaseAggregateTests: GRDBTestCase { sum = (sum ?? 0) + int } } - func finalize() throws -> DatabaseValueConvertible? { - return sum - } + func finalize() throws -> DatabaseValueConvertible? { sum } } let dbQueue = try makeDatabaseQueue() let fn = DatabaseFunction("f", argumentCount: 1, aggregate: Aggregate.self) @@ -551,9 +509,7 @@ class DatabaseAggregateTests: GRDBTestCase { sum = (sum ?? 0) + int } } - func finalize() throws -> DatabaseValueConvertible? { - return sum - } + func finalize() throws -> DatabaseValueConvertible? { sum } } let dbQueue = try makeDatabaseQueue() let fn = DatabaseFunction("f", argumentCount: 1, aggregate: Aggregate.self) @@ -574,9 +530,7 @@ class DatabaseAggregateTests: GRDBTestCase { init() { Aggregate.onInit?() } deinit { Aggregate.onDeinit?() } func step(_ dbValues: [DatabaseValue]) { } - func finalize() -> DatabaseValueConvertible? { - return nil - } + func finalize() -> DatabaseValueConvertible? { nil } } var allocationCount = 0 var aliveCount = 0 @@ -609,9 +563,7 @@ class DatabaseAggregateTests: GRDBTestCase { func step(_ dbValues: [DatabaseValue]) throws { throw DatabaseError(message: "boo") } - func finalize() -> DatabaseValueConvertible? { - fatalError() - } + func finalize() -> DatabaseValueConvertible? { fatalError() } } var allocationCount = 0 var aliveCount = 0 diff --git a/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift index d2b13e337..d89ecc18c 100644 --- a/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift @@ -49,12 +49,12 @@ private enum StrategyCustom: StrategyProvider { } private struct RecordWithDate: FetchableRecord, Decodable { - static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { return Strategy.strategy } + static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { Strategy.strategy } var date: Date } private struct RecordWithOptionalDate: FetchableRecord, Decodable { - static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { return Strategy.strategy } + static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { Strategy.strategy } var date: Date? } diff --git a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift index a1bea43ab..fee7b51ef 100644 --- a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift @@ -51,12 +51,12 @@ private enum StrategyCustom: StrategyProvider { } private struct RecordWithDate: PersistableRecord, Encodable { - static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { return Strategy.strategy } + static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { Strategy.strategy } var date: Date } private struct RecordWithOptionalDate: PersistableRecord, Encodable { - static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { return Strategy.strategy } + static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { Strategy.strategy } var date: Date? } diff --git a/Tests/GRDBTests/DatabaseFunctionTests.swift b/Tests/GRDBTests/DatabaseFunctionTests.swift index d5cb28ece..1bc47ffa1 100644 --- a/Tests/GRDBTests/DatabaseFunctionTests.swift +++ b/Tests/GRDBTests/DatabaseFunctionTests.swift @@ -6,9 +6,7 @@ import XCTest #endif private struct CustomValueType : DatabaseValueConvertible { - var databaseValue: DatabaseValue { - return "CustomValueType".databaseValue - } + var databaseValue: DatabaseValue { "CustomValueType".databaseValue } static func fromDatabaseValue(_ dbValue: DatabaseValue) -> CustomValueType? { guard let string = String.fromDatabaseValue(dbValue), string == "CustomValueType" else { return nil diff --git a/Tests/GRDBTests/DatabaseSavepointTests.swift b/Tests/GRDBTests/DatabaseSavepointTests.swift index ec07890e8..4178b1358 100644 --- a/Tests/GRDBTests/DatabaseSavepointTests.swift +++ b/Tests/GRDBTests/DatabaseSavepointTests.swift @@ -10,7 +10,7 @@ func insertItem(_ db: Database, name: String) throws { } func fetchAllItemNames(_ dbReader: DatabaseReader) throws -> [String] { - return try dbReader.read { db in + try dbReader.read { db in try String.fetchAll(db, sql: "SELECT * FROM items ORDER BY name") } } @@ -32,9 +32,7 @@ private class Observer : TransactionObserver { } #endif - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - return true - } + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { true } func databaseDidChange(with event: DatabaseEvent) { allRecordedEvents.append(event.copy()) diff --git a/Tests/GRDBTests/DatabaseSnapshotTests.swift b/Tests/GRDBTests/DatabaseSnapshotTests.swift index 03ac26cd0..da581777a 100644 --- a/Tests/GRDBTests/DatabaseSnapshotTests.swift +++ b/Tests/GRDBTests/DatabaseSnapshotTests.swift @@ -22,7 +22,7 @@ class DatabaseSnapshotTests: GRDBTestCase { } func value(_ db: Database) throws -> Int { - return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM counter")! + try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM counter")! } } @@ -88,7 +88,7 @@ class DatabaseSnapshotTests: GRDBTestCase { self.snapshot = snapshot } - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { return false } + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { false } func databaseDidChange(with event: DatabaseEvent) { } func databaseDidCommit(_ db: Database) { snapshot = try! dbPool.makeSnapshot() diff --git a/Tests/GRDBTests/DatabaseTimestampTests.swift b/Tests/GRDBTests/DatabaseTimestampTests.swift index ca721df05..a30873bb8 100644 --- a/Tests/GRDBTests/DatabaseTimestampTests.swift +++ b/Tests/GRDBTests/DatabaseTimestampTests.swift @@ -30,7 +30,7 @@ struct DatabaseTimestamp: DatabaseValueConvertible { /// Returns a value that can be stored in the database. var databaseValue: DatabaseValue { - return date.timeIntervalSince1970.databaseValue + date.timeIntervalSince1970.databaseValue } /// Returns a value initialized from *dbValue*, if possible. diff --git a/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift index b79b5cb11..fb8fc3df1 100644 --- a/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift @@ -19,12 +19,12 @@ private enum StrategyString: StrategyProvider { } private struct RecordWithUUID: PersistableRecord, Encodable { - static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { return Strategy.strategy } + static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { Strategy.strategy } var uuid: UUID } private struct RecordWithOptionalUUID: PersistableRecord, Encodable { - static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { return Strategy.strategy } + static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { Strategy.strategy } var uuid: UUID? } diff --git a/Tests/GRDBTests/DatabaseValueConvertibleFetchTests.swift b/Tests/GRDBTests/DatabaseValueConvertibleFetchTests.swift index edd0995fa..1e28128cc 100644 --- a/Tests/GRDBTests/DatabaseValueConvertibleFetchTests.swift +++ b/Tests/GRDBTests/DatabaseValueConvertibleFetchTests.swift @@ -11,9 +11,7 @@ private struct Fetched: DatabaseValueConvertible { init(int: Int) { self.int = int } - var databaseValue: DatabaseValue { - return int.databaseValue - } + var databaseValue: DatabaseValue { int.databaseValue } static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Fetched? { guard let int = Int.fromDatabaseValue(dbValue) else { return nil diff --git a/Tests/GRDBTests/DatabaseValueConvertibleSubclassTests.swift b/Tests/GRDBTests/DatabaseValueConvertibleSubclassTests.swift index 62b9fafb7..42848a92c 100644 --- a/Tests/GRDBTests/DatabaseValueConvertibleSubclassTests.swift +++ b/Tests/GRDBTests/DatabaseValueConvertibleSubclassTests.swift @@ -6,27 +6,25 @@ import XCTest #endif private class FetchableParent : DatabaseValueConvertible, CustomStringConvertible { - var databaseValue: DatabaseValue { - return "Parent".databaseValue - } + var databaseValue: DatabaseValue { "Parent".databaseValue } class func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { - return self.init() + self.init() } required init() { } - var description: String { return "Parent" } + var description: String { "Parent" } } private class FetchableChild : FetchableParent { /// Returns a value that can be stored in the database. override var databaseValue: DatabaseValue { - return "Child".databaseValue + "Child".databaseValue } - override var description: String { return "Child" } + override var description: String { "Child" } } class DatabaseValueConvertibleSubclassTests: GRDBTestCase { diff --git a/Tests/GRDBTests/DerivableRequestTests.swift b/Tests/GRDBTests/DerivableRequestTests.swift index f728d68e6..cd162f5ea 100644 --- a/Tests/GRDBTests/DerivableRequestTests.swift +++ b/Tests/GRDBTests/DerivableRequestTests.swift @@ -11,7 +11,7 @@ private struct Author: FetchableRecord, PersistableRecord, Codable { var lastName: String? var country: String var fullName: String { - return [firstName, lastName] + [firstName, lastName] .compactMap { $0 } .joined(separator: " ") } @@ -19,9 +19,7 @@ private struct Author: FetchableRecord, PersistableRecord, Codable { static let databaseTableName = "author" static let books = hasMany(Book.self) - var books: QueryInterfaceRequest { - return request(for: Author.books) - } + var books: QueryInterfaceRequest { request(for: Author.books) } } private struct Book: FetchableRecord, PersistableRecord, Codable { @@ -36,9 +34,7 @@ private struct Book: FetchableRecord, PersistableRecord, Codable { static let bookFts5 = hasOne(BookFts5.self, using: ForeignKey([Column.rowID])) #endif - var author: QueryInterfaceRequest { - return request(for: Book.author) - } + var author: QueryInterfaceRequest { request(for: Book.author) } } private struct BookFts4: TableRecord { } @@ -85,17 +81,17 @@ private var libraryMigrator: DatabaseMigrator = { extension DerivableRequest where RowDecoder == Author { // SelectionRequest func selectCountry() -> Self { - return select(Column("country")) + select(Column("country")) } // FilteredRequest func filter(country: String) -> Self { - return filter(Column("country") == country) + filter(Column("country") == country) } // OrderedRequest func orderByFullName() -> Self { - return order( + order( Column("lastName").collating(.localizedCaseInsensitiveCompare), Column("firstName").collating(.localizedCaseInsensitiveCompare)) } @@ -104,35 +100,31 @@ extension DerivableRequest where RowDecoder == Author { extension DerivableRequest where RowDecoder == Book { // OrderedRequest func orderByTitle() -> Self { - return order(Column("title").collating(.localizedCaseInsensitiveCompare)) + order(Column("title").collating(.localizedCaseInsensitiveCompare)) } // JoinableRequest func filter(authorCountry: String) -> Self { - return joining(required: Book.author.filter(country: authorCountry)) + joining(required: Book.author.filter(country: authorCountry)) } // TableRequest & FilteredRequest - func filter(id: Int) -> Self { - return filter(key: id) - } + func filter(id: Int) -> Self { filter(key: id) } // TableRequest & FilteredRequest func matchingFts4(_ pattern: FTS3Pattern?) -> Self { - return joining(required: Book.bookFts4.matching(pattern)) + joining(required: Book.bookFts4.matching(pattern)) } #if SQLITE_ENABLE_FTS5 // TableRequest & FilteredRequest func matchingFts5(_ pattern: FTS3Pattern?) -> Self { - return joining(required: Book.bookFts5.matching(pattern)) + joining(required: Book.bookFts5.matching(pattern)) } #endif // TableRequest & OrderedRequest - func orderById() -> Self { - return orderByPrimaryKey() - } + func orderById() -> Self { orderByPrimaryKey() } } class DerivableRequestTests: GRDBTestCase { diff --git a/Tests/GRDBTests/FTS5WrapperTokenizerTests.swift b/Tests/GRDBTests/FTS5WrapperTokenizerTests.swift index 6d4e329f2..91e9eb455 100644 --- a/Tests/GRDBTests/FTS5WrapperTokenizerTests.swift +++ b/Tests/GRDBTests/FTS5WrapperTokenizerTests.swift @@ -20,9 +20,7 @@ private final class StopWordsTokenizer : FTS5WrapperTokenizer { } } - func ignores(_ token: String) -> Bool { - return token == "bar" - } + func ignores(_ token: String) -> Bool { token == "bar" } func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws { // Notify token unless ignored @@ -71,7 +69,7 @@ private final class SynonymsTokenizer : FTS5WrapperTokenizer { } func synonyms(for token: String) -> Set? { - return synonyms.first { $0.contains(token) } + synonyms.first { $0.contains(token) } } func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws { diff --git a/Tests/GRDBTests/FetchRequestTests.swift b/Tests/GRDBTests/FetchRequestTests.swift index 9da752b03..21e6f2c2f 100644 --- a/Tests/GRDBTests/FetchRequestTests.swift +++ b/Tests/GRDBTests/FetchRequestTests.swift @@ -11,7 +11,7 @@ class FetchRequestTests: GRDBTestCase { struct CustomRequest : FetchRequest { typealias RowDecoder = Row func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { - return try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT * FROM table1")) + try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT * FROM table1")) } } @@ -36,7 +36,7 @@ class FetchRequestTests: GRDBTestCase { struct CustomRequest : FetchRequest { typealias RowDecoder = Int func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { - return try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT id FROM table1")) + try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT id FROM table1")) } } @@ -64,7 +64,7 @@ class FetchRequestTests: GRDBTestCase { struct CustomRequest : FetchRequest { typealias RowDecoder = CustomRecord func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { - return try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT id FROM table1")) + try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT id FROM table1")) } } @@ -89,7 +89,7 @@ class FetchRequestTests: GRDBTestCase { struct CustomRequest : FetchRequest { typealias RowDecoder = Row func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { - return try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT * FROM table1")) + try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT * FROM table1")) } } @@ -112,12 +112,10 @@ class FetchRequestTests: GRDBTestCase { struct CustomRequest : FetchRequest { typealias RowDecoder = Row func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { - return try PreparedRequest(statement: db.makeSelectStatement(sql: "INVALID")) + try PreparedRequest(statement: db.makeSelectStatement(sql: "INVALID")) } - func fetchCount(_ db: Database) throws -> Int { - return 2 - } + func fetchCount(_ db: Database) throws -> Int { 2 } } let dbQueue = try makeDatabaseQueue() @@ -195,9 +193,9 @@ class FetchRequestTests: GRDBTestCase { do { struct Value: DatabaseValueConvertible { var string: String - var databaseValue: DatabaseValue { return string.databaseValue } + var databaseValue: DatabaseValue { string.databaseValue } static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Value? { - return String.fromDatabaseValue(dbValue).map(Value.init) + String.fromDatabaseValue(dbValue).map(Value.init) } } do { @@ -248,9 +246,9 @@ class FetchRequestTests: GRDBTestCase { init(sqliteStatement: SQLiteStatement, index: Int32) { self.init(string: String(sqliteStatement: sqliteStatement, index: index)) } - var databaseValue: DatabaseValue { return string.databaseValue } + var databaseValue: DatabaseValue { string.databaseValue } static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Value? { - return String.fromDatabaseValue(dbValue).map { Value(string: $0) } + String.fromDatabaseValue(dbValue).map { Value(string: $0) } } } do { diff --git a/Tests/GRDBTests/FetchableRecordDecodableTests.swift b/Tests/GRDBTests/FetchableRecordDecodableTests.swift index 00d1668a0..13bd1b7a4 100644 --- a/Tests/GRDBTests/FetchableRecordDecodableTests.swift +++ b/Tests/GRDBTests/FetchableRecordDecodableTests.swift @@ -224,9 +224,7 @@ extension FetchableRecordDecodableTests { // DatabaseValueConvertible adoption - var databaseValue: DatabaseValue { - fatalError("irrelevant") - } + var databaseValue: DatabaseValue { fatalError("irrelevant") } static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Value? { if let string = String.fromDatabaseValue(databaseValue) { diff --git a/Tests/GRDBTests/FetchedRecordsControllerTests.swift b/Tests/GRDBTests/FetchedRecordsControllerTests.swift index 80aa75d37..d9270ff2c 100644 --- a/Tests/GRDBTests/FetchedRecordsControllerTests.swift +++ b/Tests/GRDBTests/FetchedRecordsControllerTests.swift @@ -69,7 +69,7 @@ private class Person : Record { } override class var databaseTableName: String { - return "persons" + "persons" } override func encode(to container: inout PersistenceContainer) { diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index 87d684aee..33530ae2f 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -28,7 +28,7 @@ class GRDBTestCase: XCTestCase { // Builds a database queue based on dbConfiguration func makeDatabaseQueue(filename: String? = nil) throws -> DatabaseQueue { - return try makeDatabaseQueue(filename: filename, configuration: dbConfiguration) + try makeDatabaseQueue(filename: filename, configuration: dbConfiguration) } // Builds a database queue @@ -42,7 +42,7 @@ class GRDBTestCase: XCTestCase { // Builds a database pool based on dbConfiguration func makeDatabasePool(filename: String? = nil) throws -> DatabasePool { - return try makeDatabasePool(filename: filename, configuration: dbConfiguration) + try makeDatabasePool(filename: filename, configuration: dbConfiguration) } // Builds a database pool @@ -66,9 +66,7 @@ class GRDBTestCase: XCTestCase { var sqlQueries: [String]! // TODO: protect against concurrent accesses // Populated by default configuration - var lastSQLQuery: String! { - return sqlQueries.last! - } + var lastSQLQuery: String! { sqlQueries.last! } override func setUp() { super.setUp() @@ -171,7 +169,7 @@ class GRDBTestCase: XCTestCase { } func sql(_ databaseReader: DatabaseReader, _ request: Request) -> String { - return try! databaseReader.unsafeRead { db in + try! databaseReader.unsafeRead { db in let request = try request.makePreparedRequest(db, forSingleResult: false) try request.statement.makeCursor().next() return lastSQLQuery diff --git a/Tests/GRDBTests/InflectionsTests.swift b/Tests/GRDBTests/InflectionsTests.swift index e8848f9a5..fcae9afbe 100644 --- a/Tests/GRDBTests/InflectionsTests.swift +++ b/Tests/GRDBTests/InflectionsTests.swift @@ -29,7 +29,7 @@ class InflectionsTests: GRDBTestCase { func testStartIndexOfLastWord() { func lastWord(_ string: String) -> String { - return String(string.suffix(from: Inflections.startIndexOfLastWord(string))) + String(string.suffix(from: Inflections.startIndexOfLastWord(string))) } XCTAssertEqual(lastWord(""), "") XCTAssertEqual(lastWord(" "), " ") @@ -265,7 +265,7 @@ struct InflectionTestCases: Decodable { struct AnyCodingKey: CodingKey { var stringValue: String - var intValue: Int? { return nil } + var intValue: Int? { nil } init?(stringValue: String) { self.stringValue = stringValue diff --git a/Tests/GRDBTests/JoinSupportTests.swift b/Tests/GRDBTests/JoinSupportTests.swift index bea35f0fd..76ae5b2d6 100644 --- a/Tests/GRDBTests/JoinSupportTests.swift +++ b/Tests/GRDBTests/JoinSupportTests.swift @@ -97,7 +97,7 @@ private struct FlatModel: FetchableRecord { } static func all() -> AdaptedFetchRequest> { - return SQLRequest(sql: testedSQL).adapted { db in + SQLRequest(sql: testedSQL).adapted { db in let adapters = try splittingRowAdapters(columnCounts: [ T1.numberOfSelectedColumns(db), T2.numberOfSelectedColumns(db), @@ -113,7 +113,7 @@ private struct FlatModel: FetchableRecord { } static func hierarchicalAll() -> AdaptedFetchRequest> { - return SQLRequest(sql: testedSQL).adapted { db in + SQLRequest(sql: testedSQL).adapted { db in let adapters = try splittingRowAdapters(columnCounts: [ T1.numberOfSelectedColumns(db), T2.numberOfSelectedColumns(db), @@ -138,7 +138,7 @@ private struct CodableFlatModel: FetchableRecord, Codable { var t5count: Int static func all() -> AdaptedFetchRequest> { - return SQLRequest(sql: testedSQL).adapted { db in + SQLRequest(sql: testedSQL).adapted { db in let adapters = try splittingRowAdapters(columnCounts: [ T1.numberOfSelectedColumns(db), T2.numberOfSelectedColumns(db), @@ -153,7 +153,7 @@ private struct CodableFlatModel: FetchableRecord, Codable { } static func hierarchicalAll() -> AdaptedFetchRequest> { - return SQLRequest(sql: testedSQL).adapted { db in + SQLRequest(sql: testedSQL).adapted { db in let adapters = try splittingRowAdapters(columnCounts: [ T1.numberOfSelectedColumns(db), T2.numberOfSelectedColumns(db), @@ -181,7 +181,7 @@ private struct CodableNestedModel: FetchableRecord, Codable { var t5count: Int static func all() -> AdaptedFetchRequest> { - return SQLRequest(sql: testedSQL).adapted { db in + SQLRequest(sql: testedSQL).adapted { db in let adapters = try splittingRowAdapters(columnCounts: [ T1.numberOfSelectedColumns(db), T2.numberOfSelectedColumns(db), diff --git a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift index 10a8824d7..0121b07c8 100644 --- a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift @@ -286,7 +286,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { } override class var databaseTableName: String { - return "myRecord" + "myRecord" } enum Columns: String, ColumnExpression { diff --git a/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift b/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift index 132aa216b..8f51e6ae6 100644 --- a/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift @@ -293,7 +293,7 @@ extension MutablePersistableRecordEncodableTests { // DatabaseValueConvertible adoption var databaseValue: DatabaseValue { - return (string + " (DatabaseValueConvertible)").databaseValue + (string + " (DatabaseValueConvertible)").databaseValue } static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Value? { diff --git a/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift b/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift index 6694564a0..7686f88bb 100644 --- a/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift @@ -164,9 +164,7 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase { var transactionEvents: [DatabaseEvent] = [] var events: [DatabaseEvent] = [] - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - return true - } + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { true } func databaseDidChange(with event: DatabaseEvent) { transactionEvents.append(event.copy()) diff --git a/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift b/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift index 40741059d..eb2162ed3 100644 --- a/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift @@ -19,7 +19,7 @@ extension SQLFunctionName { /// // STRFTIME('%Y', date) /// strftime("%Y", Column("date")) func strftime(_ format: String, _ date: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionFunction(.strftime, arguments: format, date) + SQLExpressionFunction(.strftime, arguments: format, date) } @@ -31,14 +31,14 @@ extension SQLBinaryOperator { } func ~= (_ lhs: SQLExpressible, _ rhs: Column) -> SQLExpression { - return SQLExpressionBinary(.match, rhs, lhs) + SQLExpressionBinary(.match, rhs, lhs) } // CAST private func cast(_ value: T, as type: Database.ColumnType) -> SQLExpression { - return SQLLiteral("CAST(\(value) AS \(sql: type.rawValue))").sqlExpression + SQLLiteral("CAST(\(value) AS \(sql: type.rawValue))").sqlExpression } diff --git a/Tests/GRDBTests/QueryInterfaceRequestTests.swift b/Tests/GRDBTests/QueryInterfaceRequestTests.swift index e7f65d0e2..7d5fba8ab 100644 --- a/Tests/GRDBTests/QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/QueryInterfaceRequestTests.swift @@ -512,7 +512,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { _ = Reader.all().select(literal: SQLLiteral(sql: "name")) as QueryInterfaceRequest func makeRequest() -> QueryInterfaceRequest { - return Reader.select(Col.name) + Reader.select(Col.name) } // Those should be, without any ambiguuity, requests of Reader. diff --git a/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift index bb0ed1c9d..768f9c063 100644 --- a/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift @@ -25,7 +25,7 @@ private class Reader : Record { } override class var databaseTableName: String { - return "readers" + "readers" } override func encode(to container: inout PersistenceContainer) { diff --git a/Tests/GRDBTests/RecordEditedTests.swift b/Tests/GRDBTests/RecordEditedTests.swift index c6bf73226..799d22c82 100644 --- a/Tests/GRDBTests/RecordEditedTests.swift +++ b/Tests/GRDBTests/RecordEditedTests.swift @@ -32,7 +32,7 @@ private class Person : Record { // Record override class var databaseTableName: String { - return "persons" + "persons" } required init(row: Row) { @@ -101,7 +101,7 @@ private class PersonWithModifiedCaseColumns: Record { // Record override class var databaseTableName: String { - return "persons" + "persons" } required init(row: Row) { diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift index 077cba937..74b020f0e 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift @@ -22,7 +22,7 @@ class MinimalRowID : Record { // Record override class var databaseTableName: String { - return "minimalRowIDs" + "minimalRowIDs" } required init(row: Row) { diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift index 7b43b7522..950518cd9 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift @@ -22,7 +22,7 @@ class MinimalSingle: Record { // Record override class var databaseTableName: String { - return "minimalSingles" + "minimalSingles" } required init(row: Row) { diff --git a/Tests/GRDBTests/RecordPersistenceConflictPolicy.swift b/Tests/GRDBTests/RecordPersistenceConflictPolicy.swift index b6cbd0467..b774b9e5d 100644 --- a/Tests/GRDBTests/RecordPersistenceConflictPolicy.swift +++ b/Tests/GRDBTests/RecordPersistenceConflictPolicy.swift @@ -10,7 +10,7 @@ class RecordWithoutPersistenceConflictPolicy : Record { class RecordWithPersistenceConflictPolicy : Record { override class var persistenceConflictPolicy: PersistenceConflictPolicy { - return PersistenceConflictPolicy(insert: .fail, update: .ignore) + PersistenceConflictPolicy(insert: .fail, update: .ignore) } } diff --git a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift index 72b7c52cf..152cf2ec5 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift @@ -32,11 +32,11 @@ private class Person : Record { // Record override static var databaseSelection: [SQLSelectable] { - return [AllColumns(), Column.rowID] + [AllColumns(), Column.rowID] } override class var databaseTableName: String { - return "persons" + "persons" } required init(row: Row) { diff --git a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift index 154ed51f4..2b0d1a902 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift @@ -31,7 +31,7 @@ private class Citizenship : Record { // Record override class var databaseTableName: String { - return "citizenships" + "citizenships" } required init(row: Row) { diff --git a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift index 49c31608a..6b54e2ac1 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift @@ -29,7 +29,7 @@ private class Item : Record { // Record override class var databaseTableName: String { - return "items" + "items" } required init(row: Row) { diff --git a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift index 8cff2d03e..cfb7789f6 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift @@ -33,7 +33,7 @@ private class Person : Record { // Record override class var databaseTableName: String { - return "persons" + "persons" } required init(row: Row) { diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift index b2e4abf0a..0d6bea29a 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift @@ -27,7 +27,7 @@ class Pet : Record { // Record override class var databaseTableName: String { - return "pets" + "pets" } required init(row: Row) { diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift index 7d3425198..0ff4f733e 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift @@ -26,7 +26,7 @@ class Email : Record { // Record override class var databaseTableName: String { - return "emails" + "emails" } required init(row: Row) { diff --git a/Tests/GRDBTests/RecordSubClassTests.swift b/Tests/GRDBTests/RecordSubClassTests.swift index cd50de393..9afa49b48 100644 --- a/Tests/GRDBTests/RecordSubClassTests.swift +++ b/Tests/GRDBTests/RecordSubClassTests.swift @@ -32,7 +32,7 @@ private class Person : Record { // Record override class var databaseTableName: String { - return "persons" + "persons" } required init(row: Row) { diff --git a/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift b/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift index 7a6f2d0b9..01d5e9676 100644 --- a/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift +++ b/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift @@ -24,7 +24,7 @@ class BadlyMangledStuff : Record { // Record override class var databaseTableName: String { - return "stuffs" + "stuffs" } required init(row: Row) { diff --git a/Tests/GRDBTests/SQLLiteralTests.swift b/Tests/GRDBTests/SQLLiteralTests.swift index 825bc0231..8168018b0 100644 --- a/Tests/GRDBTests/SQLLiteralTests.swift +++ b/Tests/GRDBTests/SQLLiteralTests.swift @@ -260,11 +260,11 @@ extension SQLLiteralTests { struct V: DatabaseValueConvertible { var databaseValue: DatabaseValue { - return "V".databaseValue + "V".databaseValue } static func fromDatabaseValue(_ dbValue: DatabaseValue) -> V? { - return nil + nil } } @@ -477,7 +477,7 @@ extension SQLLiteralTests { // Here we test that users can define functions that return // literal expressions. func date(_ value: SQLExpressible) -> SQLExpression { - return SQLLiteral("DATE(\(value))").sqlExpression + SQLLiteral("DATE(\(value))").sqlExpression } let createdAt = Column("createdAt") let request = Player.filter(date(createdAt) == "2020-01-23") @@ -491,7 +491,7 @@ extension SQLLiteralTests { // return literal expressions with the previously // supported technique. func date(_ value: SQLExpressible) -> SQLExpression { - return SQLLiteral("DATE(\(value.sqlExpression))").sqlExpression + SQLLiteral("DATE(\(value.sqlExpression))").sqlExpression } let createdAt = Column("createdAt") let request = Player.filter(date(createdAt) == "2020-01-23") diff --git a/Tests/GRDBTests/SQLRequestTests.swift b/Tests/GRDBTests/SQLRequestTests.swift index 0d4f47035..67f668e42 100644 --- a/Tests/GRDBTests/SQLRequestTests.swift +++ b/Tests/GRDBTests/SQLRequestTests.swift @@ -136,27 +136,27 @@ class SQLRequestTests: GRDBTestCase { var name: String static func filter(id: Int64) -> SQLRequest { - return """ - SELECT * - FROM \(self) - WHERE \(CodingKeys.id) = \(id) - """ + """ + SELECT * + FROM \(self) + WHERE \(CodingKeys.id) = \(id) + """ } static func filter(ids: [Int64]) -> SQLRequest { - return """ - SELECT * - FROM \(self) - WHERE \(CodingKeys.id) IN \(ids) - """ + """ + SELECT * + FROM \(self) + WHERE \(CodingKeys.id) IN \(ids) + """ } static func filter(excludedIds: S) -> SQLRequest where S: Sequence, S.Element == Int64 { - return """ - SELECT * - FROM \(self) - WHERE \(CodingKeys.id) NOT IN \(excludedIds) - """ + """ + SELECT * + FROM \(self) + WHERE \(CodingKeys.id) NOT IN \(excludedIds) + """ } // The test pass if this method compiles. diff --git a/Tests/GRDBTests/SelectStatementTests.swift b/Tests/GRDBTests/SelectStatementTests.swift index 9db5b0cc9..e33c798da 100644 --- a/Tests/GRDBTests/SelectStatementTests.swift +++ b/Tests/GRDBTests/SelectStatementTests.swift @@ -187,7 +187,7 @@ class SelectStatementTests : GRDBTestCase { } func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - return region.isModified(byEventsOfKind: eventKind) + region.isModified(byEventsOfKind: eventKind) } func databaseDidChange(with event: DatabaseEvent) { diff --git a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift index 33155db93..dac068914 100644 --- a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift +++ b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift @@ -26,9 +26,7 @@ private struct Fetched: DatabaseValueConvertible, StatementColumnConvertible { self.init(int: Int(sqlite3_column_int64(sqliteStatement, index)), fast: true) } - var databaseValue: DatabaseValue { - return int.databaseValue - } + var databaseValue: DatabaseValue { int.databaseValue } static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Fetched? { guard let int = Int.fromDatabaseValue(dbValue) else { diff --git a/Tests/GRDBTests/TableRecordTests.swift b/Tests/GRDBTests/TableRecordTests.swift index 760034fac..b5aaf316b 100644 --- a/Tests/GRDBTests/TableRecordTests.swift +++ b/Tests/GRDBTests/TableRecordTests.swift @@ -9,17 +9,17 @@ private struct RecordStruct: TableRecord { } private struct CustomizedRecordStruct: TableRecord { static let databaseTableName = "CustomizedRecordStruct" } private class RecordClass: TableRecord { } private class RecordSubClass: RecordClass { } -private class CustomizedRecordClass: TableRecord { class var databaseTableName: String { return "CustomizedRecordClass" } } -private class CustomizedRecordSubClass: CustomizedRecordClass { override class var databaseTableName: String { return "CustomizedRecordSubClass" } } -private class CustomizedPlainRecord: Record { override class var databaseTableName: String { return "CustomizedPlainRecord" } } +private class CustomizedRecordClass: TableRecord { class var databaseTableName: String { "CustomizedRecordClass" } } +private class CustomizedRecordSubClass: CustomizedRecordClass { override class var databaseTableName: String { "CustomizedRecordSubClass" } } +private class CustomizedPlainRecord: Record { override class var databaseTableName: String { "CustomizedPlainRecord" } } private enum Namespace { struct RecordStruct: TableRecord { } struct CustomizedRecordStruct: TableRecord { static let databaseTableName = "CustomizedRecordStruct" } class RecordClass: TableRecord { } class RecordSubClass: RecordClass { } - class CustomizedRecordClass: TableRecord { class var databaseTableName: String { return "CustomizedRecordClass" } } - class CustomizedRecordSubClass: CustomizedRecordClass { override class var databaseTableName: String { return "CustomizedRecordSubClass" } } - class CustomizedPlainRecord: Record { override class var databaseTableName: String { return "CustomizedPlainRecord" } } + class CustomizedRecordClass: TableRecord { class var databaseTableName: String { "CustomizedRecordClass" } } + class CustomizedRecordSubClass: CustomizedRecordClass { override class var databaseTableName: String { "CustomizedRecordSubClass" } } + class CustomizedPlainRecord: Record { override class var databaseTableName: String { "CustomizedPlainRecord" } } } struct HTTPRequest: TableRecord { } struct TOEFL: TableRecord { } @@ -31,9 +31,9 @@ class TableRecordTests: GRDBTestCase { struct InnerCustomizedRecordStruct: TableRecord { static let databaseTableName = "InnerCustomizedRecordStruct" } class InnerRecordClass: TableRecord { } class InnerRecordSubClass: InnerRecordClass { } - class InnerCustomizedRecordClass: TableRecord { class var databaseTableName: String { return "InnerCustomizedRecordClass" } } - class InnerCustomizedRecordSubClass: InnerCustomizedRecordClass { override class var databaseTableName: String { return "InnerCustomizedRecordSubClass" } } - class InnerCustomizedPlainRecord: Record { override class var databaseTableName: String { return "InnerCustomizedPlainRecord" } } + class InnerCustomizedRecordClass: TableRecord { class var databaseTableName: String { "InnerCustomizedRecordClass" } } + class InnerCustomizedRecordSubClass: InnerCustomizedRecordClass { override class var databaseTableName: String { "InnerCustomizedRecordSubClass" } } + class InnerCustomizedPlainRecord: Record { override class var databaseTableName: String { "InnerCustomizedPlainRecord" } } XCTAssertEqual(RecordStruct.databaseTableName, "recordStruct") XCTAssertEqual(CustomizedRecordStruct.databaseTableName, "CustomizedRecordStruct") @@ -62,9 +62,7 @@ class TableRecordTests: GRDBTestCase { XCTAssertEqual(HTTPRequest.databaseTableName, "httpRequest") XCTAssertEqual(TOEFL.databaseTableName, "toefl") - func tableName(_ type: T.Type) -> String { - return T.databaseTableName - } + func tableName(_ type: T.Type) -> String { T.databaseTableName } XCTAssertEqual(tableName(RecordStruct.self), "recordStruct") XCTAssertEqual(tableName(CustomizedRecordStruct.self), "CustomizedRecordStruct") diff --git a/Tests/GRDBTests/TransactionObserverSavepointsTests.swift b/Tests/GRDBTests/TransactionObserverSavepointsTests.swift index c2ac13edd..fbf7a9736 100644 --- a/Tests/GRDBTests/TransactionObserverSavepointsTests.swift +++ b/Tests/GRDBTests/TransactionObserverSavepointsTests.swift @@ -16,9 +16,7 @@ private class Observer : TransactionObserver { } #endif - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - return true - } + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { true } func databaseDidChange(with event: DatabaseEvent) { events.append(event.copy()) @@ -38,7 +36,7 @@ private class Observer : TransactionObserver { class TransactionObserverSavepointsTests: GRDBTestCase { private func match(event: DatabaseEvent, kind: DatabaseEvent.Kind, tableName: String, rowId: Int64) -> Bool { - return (event.tableName == tableName) && (event.rowID == rowId) && (event.kind == kind) + (event.tableName == tableName) && (event.rowID == rowId) && (event.kind == kind) } #if SQLITE_ENABLE_PREUPDATE_HOOK diff --git a/Tests/GRDBTests/TransactionObserverTests.swift b/Tests/GRDBTests/TransactionObserverTests.swift index 079683086..580fb0e40 100644 --- a/Tests/GRDBTests/TransactionObserverTests.swift +++ b/Tests/GRDBTests/TransactionObserverTests.swift @@ -51,7 +51,7 @@ private class Observer : TransactionObserver { #endif func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - return observesBlock(eventKind) + observesBlock(eventKind) } func databaseDidChange(with event: DatabaseEvent) { @@ -140,7 +140,7 @@ class TransactionObserverTests: GRDBTestCase { } private func match(event: DatabaseEvent, kind: DatabaseEvent.Kind, tableName: String, rowId: Int64) -> Bool { - return (event.tableName == tableName) && (event.rowID == rowId) && (event.kind == kind) + (event.tableName == tableName) && (event.rowID == rowId) && (event.kind == kind) } #if SQLITE_ENABLE_PREUPDATE_HOOK @@ -1645,14 +1645,10 @@ class TransactionObserverTests: GRDBTestCase { #if SQLITE_ENABLE_PREUPDATE_HOOK var willChangeCount: Int = 0 - func databaseWillChange(with event: DatabasePreUpdateEvent) { - willChangeCount += 1 - } + func databaseWillChange(with event: DatabasePreUpdateEvent) { willChangeCount += 1 } #endif - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - return true - } + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { true } func databaseDidChange(with event: DatabaseEvent) { didChangeCount += 1 @@ -1661,17 +1657,9 @@ class TransactionObserverTests: GRDBTestCase { } } - func databaseWillCommit() throws { - willCommitCount += 1 - } - - func databaseDidCommit(_ db: Database) { - didCommitCount += 1 - } - - func databaseDidRollback(_ db: Database) { - didRollbackCount += 1 - } + func databaseWillCommit() throws { willCommitCount += 1 } + func databaseDidCommit(_ db: Database) { didCommitCount += 1 } + func databaseDidRollback(_ db: Database) { didRollbackCount += 1 } } let observer = Observer() diff --git a/Tests/GRDBTests/TruncateOptimizationTests.swift b/Tests/GRDBTests/TruncateOptimizationTests.swift index 8bc94adf0..6d3bcea51 100644 --- a/Tests/GRDBTests/TruncateOptimizationTests.swift +++ b/Tests/GRDBTests/TruncateOptimizationTests.swift @@ -37,9 +37,7 @@ class TruncateOptimizationTests: GRDBTestCase { self.notify = notify } - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - return true - } + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { true } func databaseDidChange(with event: DatabaseEvent) { if case .delete = event.kind { @@ -60,7 +58,7 @@ class TruncateOptimizationTests: GRDBTestCase { } class UniversalObserver : TransactionObserver { - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { return true } + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { true } func databaseDidChange(with event: DatabaseEvent) { } func databaseDidCommit(_ db: Database) { } func databaseDidRollback(_ db: Database) { } diff --git a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift index 4ddd9a1fe..3f24b9187 100644 --- a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift +++ b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift @@ -15,9 +15,7 @@ import XCTest private struct Name: DatabaseValueConvertible { var rawValue: String - var databaseValue: DatabaseValue { - return rawValue.databaseValue - } + var databaseValue: DatabaseValue { rawValue.databaseValue } static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Name? { guard let rawValue = String.fromDatabaseValue(dbValue) else { diff --git a/Tests/GRDBTests/ValueObservationRecordTests.swift b/Tests/GRDBTests/ValueObservationRecordTests.swift index e8875986f..fcad4d439 100644 --- a/Tests/GRDBTests/ValueObservationRecordTests.swift +++ b/Tests/GRDBTests/ValueObservationRecordTests.swift @@ -20,9 +20,7 @@ private struct Player: TableRecord, FetchableRecord { self.name = row["name"] } - var row: Row { - return ["id": id, "name": name] - } + var row: Row { ["id": id, "name": name] } } class ValueObservationRecordTests: GRDBTestCase { diff --git a/Tests/GRDBTests/VirtualTableModuleTests.swift b/Tests/GRDBTests/VirtualTableModuleTests.swift index ab6a3ec9a..6f3b6a995 100644 --- a/Tests/GRDBTests/VirtualTableModuleTests.swift +++ b/Tests/GRDBTests/VirtualTableModuleTests.swift @@ -9,7 +9,7 @@ private struct FTS3TokenizeModule : VirtualTableModule { let moduleName = "fts3tokenize" func makeTableDefinition() -> FTS3TokenizeTableDefinition { - return FTS3TokenizeTableDefinition() + FTS3TokenizeTableDefinition() } func moduleArguments(for definition: FTS3TokenizeTableDefinition, in db: Database) -> [String] { @@ -27,7 +27,7 @@ private struct ThrowingFTS3TokenizeModule : VirtualTableModule { let moduleName = "fts3tokenize" func makeTableDefinition() -> FTS3TokenizeTableDefinition { - return FTS3TokenizeTableDefinition() + FTS3TokenizeTableDefinition() } func moduleArguments(for definition: FTS3TokenizeTableDefinition, in db: Database) -> [String] { diff --git a/Tests/Performance/GRDBPerformance/PerformanceTests.swift b/Tests/Performance/GRDBPerformance/PerformanceTests.swift index f6e89e149..0f8dc2a00 100644 --- a/Tests/Performance/GRDBPerformance/PerformanceTests.swift +++ b/Tests/Performance/GRDBPerformance/PerformanceTests.swift @@ -116,7 +116,7 @@ class ItemClass : Record { } override class var databaseTableName: String { - return "items" + "items" } required init(row: GRDB.Row) { diff --git a/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift b/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift index 3eb6bc4cb..2c605702d 100644 --- a/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift +++ b/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift @@ -111,7 +111,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { } func _fetchStructs(_ db: Database) throws -> [ItemStruct] { - return try ItemStruct.fetchAll(db) + try ItemStruct.fetchAll(db) } // MARK: - @@ -127,7 +127,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { } func _fetchCodables(_ db: Database) throws -> [ItemCodable] { - return try ItemCodable.fetchAll(db) + try ItemCodable.fetchAll(db) } // MARK: - @@ -143,7 +143,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { } func _fetchRecords(_ db: Database) throws -> [ItemRecord] { - return try ItemRecord.fetchAll(db) + try ItemRecord.fetchAll(db) } // MARK: - @@ -316,7 +316,7 @@ class ItemRecord : Record { } override class var databaseTableName: String { - return "items" + "items" } required init(row: GRDB.Row) { From 1698afadb9e71991fb0dee49eb5e2e6b50b3b513 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 9 Mar 2020 07:33:30 +0100 Subject: [PATCH 2/5] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8eb6ec726..91a6e9006 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -94,6 +94,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [#720](https://github.com/groue/GRDB.swift/pull/720): Turn deprecated APIs into unavailable ones - [#721](https://github.com/groue/GRDB.swift/pull/721): SE-0249: Key Path Expressions as Functions - [#722](https://github.com/groue/GRDB.swift/pull/722): SE-0253: Callable values of user-defined nominal types +- [#723](https://github.com/groue/GRDB.swift/pull/723): SE-0255: Implicit returns from single-expression functions ## 4.11.0 From 4d60dc6cbbaffc9c236d787ade9fe03b7328f5c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 9 Mar 2020 07:52:35 +0100 Subject: [PATCH 3/5] Remove more redundant return keywords --- Documentation/GoodPracticesForDesigningRecordTypes.md | 2 +- README.md | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 7ebd92353..2ff2659c8 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -231,7 +231,7 @@ extension DerivableRequest where RowDecoder == Book { // A book is from a country if it can be // joined with an author from that country: // ---------------------------------v - return joining(required: Book.author.filter(country: authorCountry)) + self.joining(required: Book.author.filter(country: authorCountry)) } } diff --git a/README.md b/README.md index 37e95cdb4..517b59c10 100644 --- a/README.md +++ b/README.md @@ -3340,7 +3340,7 @@ struct Place: Codable { var coordinate: CLLocationCoordinate2D { get { - return CLLocationCoordinate2D( + CLLocationCoordinate2D( latitude: latitude, longitude: longitude) } @@ -3448,7 +3448,7 @@ struct Place: Encodable { var coordinate: CLLocationCoordinate2D { get { - return CLLocationCoordinate2D( + CLLocationCoordinate2D( latitude: latitude, longitude: longitude) } @@ -7393,7 +7393,7 @@ let futureCount: DatabaseFuture = try dbPool.writeWithoutTransaction { db i // <- not in a transaction here let futureCount = dbPool.concurrentRead { db - return try Player.fetchCount(db) + try Player.fetchCount(db) } return futureCount } @@ -7414,7 +7414,7 @@ try dbPool.writeWithoutTransaction { db in let futureCount = dbPool.concurrentRead { db // Guaranteed to be non-zero - return try Player.fetchCount(db) + try Player.fetchCount(db) } try Player.deleteAll(db) From 93aa9bf3e5412c9875db04a66d872b59f307c06c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 9 Mar 2020 07:56:02 +0100 Subject: [PATCH 4/5] Comment out debugging configuration --- Support/GRDB.xcconfig | 6 +++--- Support/GRDBDeploymentTarget.xcconfig | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Support/GRDB.xcconfig b/Support/GRDB.xcconfig index 4e0acd506..d4961f646 100644 --- a/Support/GRDB.xcconfig +++ b/Support/GRDB.xcconfig @@ -7,6 +7,6 @@ MODULEMAP_FILE = $(SRCROOT)/Support/module.modulemap // Slow compilation hunt: // OTHER_SWIFT_FLAGS = $(inherited) -Xfrontend -warn-long-expression-type-checking=100 -Xfrontend -warn-long-function-bodies=100 -// Compile with all opt-in APIs -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 -OTHER_SWIFT_FLAGS = $(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK +//// Compile with all opt-in APIs +//GCC_PREPROCESSOR_DEFINITIONS = $(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 +//OTHER_SWIFT_FLAGS = $(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK diff --git a/Support/GRDBDeploymentTarget.xcconfig b/Support/GRDBDeploymentTarget.xcconfig index 5f4964a87..6188f42d7 100644 --- a/Support/GRDBDeploymentTarget.xcconfig +++ b/Support/GRDBDeploymentTarget.xcconfig @@ -3,6 +3,6 @@ MACOSX_DEPLOYMENT_TARGET = 10.10 TVOS_DEPLOYMENT_TARGET = 9.0 WATCHOS_DEPLOYMENT_TARGET = 2.0 -// Compile with all opt-in APIs -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 -OTHER_SWIFT_FLAGS = $(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK +//// Compile with all opt-in APIs +//GCC_PREPROCESSOR_DEFINITIONS = $(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 +//OTHER_SWIFT_FLAGS = $(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK From f48180549d5d5728aff976aa82a39f0319df54bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 9 Mar 2020 08:03:01 +0100 Subject: [PATCH 5/5] make smokeTest For "quick" sanity checks --- Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 365a12074..c78c647a5 100644 --- a/Makefile +++ b/Makefile @@ -8,7 +8,7 @@ # make distclean - Restore repository to a pristine state default: test - +smokeTest: test_framework_GRDBiOS_maxTarget test_framework_GRDBiOS_minTarget test_framework_SQLCipher4 test_framework_GRDBCustomSQLiteiOS_maxTarget test_SPM # Requirements # ============ @@ -436,4 +436,4 @@ clean: if [ -a Tests/Performance/Realm/build.sh ]; then cd Tests/Performance/Realm && sh build.sh clean; fi find . -name Package.resolved | xargs rm -f -.PHONY: distclean clean doc test SQLiteCustom +.PHONY: distclean clean doc test smokeTest SQLiteCustom