diff --git a/.cocoadocs.yml b/.cocoadocs.yml deleted file mode 100644 index 27840032..00000000 --- a/.cocoadocs.yml +++ /dev/null @@ -1,2 +0,0 @@ -additional_guides: - - Documentation/Index.md diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 1c47e3a6..af6666ba 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -14,6 +14,13 @@ jobs: gem install xcpretty --no-document brew update brew outdated carthage || brew upgrade carthage + brew outdated swiftlint || brew upgrade swiftlint + - name: "Lint" + run: make lint + - name: "Run tests (PACKAGE_MANAGER_COMMAND: test)" + env: + PACKAGE_MANAGER_COMMAND: test -Xswiftc -warnings-as-errors + run: ./run-tests.sh - name: "Run tests (BUILD_SCHEME: SQLite iOS)" env: BUILD_SCHEME: SQLite iOS @@ -54,7 +61,3 @@ jobs: env: CARTHAGE_PLATFORM: tvOS run: ./run-tests.sh - - name: "Run tests (PACKAGE_MANAGER_COMMAND: test)" - env: - PACKAGE_MANAGER_COMMAND: test - run: ./run-tests.sh diff --git a/.swiftlint.yml b/.swiftlint.yml new file mode 100644 index 00000000..b5e53d56 --- /dev/null +++ b/.swiftlint.yml @@ -0,0 +1,42 @@ +disabled_rules: # rule identifiers to exclude from running + - todo + - operator_whitespace + - large_tuple + - closure_parameter_position +included: # paths to include during linting. `--path` is ignored if present. takes precendence over `excluded`. + - Sources + - Tests +excluded: # paths to ignore during linting. overridden by `included`. + +identifier_name: + excluded: + - db + - in + - to + - by + - or + - eq + - gt + - lt + - fn + - a + - b + - q + - SQLITE_TRANSIENT + +type_body_length: + warning: 260 + error: 260 + +function_body_length: + warning: 60 + error: 60 + +line_length: + warning: 150 + error: 150 + ignores_comments: true + +file_length: + warning: 900 + error: 900 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6c367b95..6969a705 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -19,7 +19,7 @@ addresses everything. If it doesn’t, continue the conversation there. If your searches return empty, see the [bug](#bugs) or [feature request](#feature-requests) guidelines below. -[Ask on Stack Overflow]: http://stackoverflow.com/questions/tagged/sqlite.swift +[Ask on Stack Overflow]: https://stackoverflow.com/questions/tagged/sqlite.swift [Search]: https://github.com/stephencelis/SQLite.swift/search?type=Issues diff --git a/Documentation/Release.md b/Documentation/Release.md new file mode 100644 index 00000000..0177fc8f --- /dev/null +++ b/Documentation/Release.md @@ -0,0 +1,11 @@ +# SQLite.swift Release checklist + +* [ ] Make sure current master branch has a green build +* [ ] Make sure `CHANGELOG.md` is up-to-date +* [ ] Update the version number in `SQLite.swift.podspec` +* [ ] Run `pod lib lint` locally +* [ ] Update the version numbers mentioned in `README.md`, `Documentation/Index.md` +* [ ] Update `MARKETING_VERSION` in `SQLite.xcodeproj/project.pbxproj` +* [ ] Create a tag with the version number (`x.y.z`) +* [ ] Publish to CocoaPods: `pod trunk push` +* [ ] Update the release information on GitHub diff --git a/Makefile b/Makefile index f3f355ab..0b9a1606 100644 --- a/Makefile +++ b/Makefile @@ -9,8 +9,6 @@ else endif XCPRETTY := $(shell command -v xcpretty) -SWIFTCOV := $(shell command -v swiftcov) -GCOVR := $(shell command -v gcovr) TEST_ACTIONS := clean build build-for-testing test-without-building default: test @@ -18,6 +16,9 @@ default: test build: $(BUILD_TOOL) $(BUILD_ARGUMENTS) +lint: + swiftlint --strict + test: ifdef XCPRETTY @set -o pipefail && $(BUILD_TOOL) $(BUILD_ARGUMENTS) $(TEST_ACTIONS) | $(XCPRETTY) -c @@ -25,36 +26,14 @@ else $(BUILD_TOOL) $(BUILD_ARGUMENTS) $(TEST_ACTIONS) endif -coverage: -ifdef SWIFTCOV - $(SWIFTCOV) generate --output coverage \ - $(BUILD_TOOL) $(BUILD_ARGUMENTS) -configuration Release test \ - -- ./SQLite/*.swift -ifdef GCOVR - $(GCOVR) \ - --root . \ - --use-gcov-files \ - --html \ - --html-details \ - --output coverage/index.html \ - --keep -else - @echo gcovr must be installed for HTML output: https://github.com/gcovr/gcovr -endif -else - @echo swiftcov must be installed for coverage: https://github.com/realm/SwiftCov - @exit 1 -endif - clean: $(BUILD_TOOL) $(BUILD_ARGUMENTS) clean - rm -r coverage repl: @$(BUILD_TOOL) $(BUILD_ARGUMENTS) -derivedDataPath $(TMPDIR)/SQLite.swift > /dev/null && \ swift -F '$(TMPDIR)/SQLite.swift/Build/Products/Debug' sloc: - @zsh -c "grep -vE '^ *//|^$$' SQLite/*/*.{swift,h,m} | wc -l" + @zsh -c "grep -vE '^ *//|^$$' Sources/**/*.{swift,h,m} | wc -l" -.PHONY: test coverage clean repl sloc +.PHONY: test clean repl sloc diff --git a/README.md b/README.md index 98a625c4..ac044dc0 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ syntax _and_ intent. - Extensively tested - [SQLCipher][] support via CocoaPods - Active support at - [StackOverflow](http://stackoverflow.com/questions/tagged/sqlite.swift), + [StackOverflow](https://stackoverflow.com/questions/tagged/sqlite.swift), and [Gitter Chat Room](https://gitter.im/stephencelis/SQLite.swift) (_experimental_) @@ -119,7 +119,7 @@ For a more comprehensive example, see and the [companion repository][SQLiteDataAccessLayer2]. -[Create a Data Access Layer with SQLite.swift and Swift 2]: http://masteringswift.blogspot.com/2015/09/create-data-access-layer-with.html +[Create a Data Access Layer with SQLite.swift and Swift 2]: https://masteringswift.blogspot.com/2015/09/create-data-access-layer-with.html [SQLiteDataAccessLayer2]: https://github.com/hoffmanjon/SQLiteDataAccessLayer2/tree/master ## Installation @@ -226,7 +226,7 @@ device: [Xcode]: https://developer.apple.com/xcode/downloads/ -[Submodule]: http://git-scm.com/book/en/Git-Tools-Submodules +[Submodule]: https://git-scm.com/book/en/Git-Tools-Submodules [download]: https://github.com/stephencelis/SQLite.swift/archive/master.zip @@ -243,7 +243,7 @@ device: [See the planning document]: /Documentation/Planning.md [Read the contributing guidelines]: ./CONTRIBUTING.md#contributing -[Ask on Stack Overflow]: http://stackoverflow.com/questions/tagged/sqlite.swift +[Ask on Stack Overflow]: https://stackoverflow.com/questions/tagged/sqlite.swift [Open an issue]: https://github.com/stephencelis/SQLite.swift/issues/new [Submit a pull request]: https://github.com/stephencelis/SQLite.swift/fork @@ -280,16 +280,16 @@ Looking for something else? Try another Swift wrapper (or [FMDB][]): - [SwiftSQLite](https://github.com/chrismsimpson/SwiftSQLite) [Swift]: https://swift.org/ -[SQLite3]: http://www.sqlite.org +[SQLite3]: https://www.sqlite.org [SQLite.swift]: https://github.com/stephencelis/SQLite.swift [GitHubActionBadge]: https://img.shields.io/github/workflow/status/stephencelis/SQLite.swift/Build%20and%20test [CocoaPodsVersionBadge]: https://cocoapod-badges.herokuapp.com/v/SQLite.swift/badge.png -[CocoaPodsVersionLink]: http://cocoadocs.org/docsets/SQLite.swift +[CocoaPodsVersionLink]: https://cocoapods.org/pods/SQLite.swift [PlatformBadge]: https://cocoapod-badges.herokuapp.com/p/SQLite.swift/badge.png -[PlatformLink]: http://cocoadocs.org/docsets/SQLite.swift +[PlatformLink]: https://cocoapods.org/pods/SQLite.swift [CartagheBadge]: https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat [CarthageLink]: https://github.com/Carthage/Carthage diff --git a/SQLite.swift.podspec b/SQLite.swift.podspec index 499012c1..f273ffd8 100644 --- a/SQLite.swift.podspec +++ b/SQLite.swift.podspec @@ -1,7 +1,7 @@ Pod::Spec.new do |s| s.name = "SQLite.swift" s.version = "0.13.0" - s.summary = "A type-safe, Swift-language layer over SQLite3 for iOS and macOS." + s.summary = "A type-safe, Swift-language layer over SQLite3." s.description = <<-DESC SQLite.swift provides compile-time confidence in SQL statement syntax and @@ -17,13 +17,12 @@ Pod::Spec.new do |s| s.module_name = 'SQLite' s.default_subspec = 'standard' s.swift_versions = ['5'] - - + ios_deployment_target = '9.0' tvos_deployment_target = '9.1' osx_deployment_target = '10.15' watchos_deployment_target = '3.0' - + s.ios.deployment_target = ios_deployment_target s.tvos.deployment_target = tvos_deployment_target s.osx.deployment_target = osx_deployment_target diff --git a/SQLite.xcodeproj/project.pbxproj b/SQLite.xcodeproj/project.pbxproj index 03d8b326..ea7ab871 100644 --- a/SQLite.xcodeproj/project.pbxproj +++ b/SQLite.xcodeproj/project.pbxproj @@ -231,6 +231,7 @@ 19A17B93B48B5560E6E51791 /* Fixtures.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Fixtures.swift; sourceTree = ""; }; 19A17BA55DABB480F9020C8A /* DateAndTimeFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DateAndTimeFunctions.swift; sourceTree = ""; }; 19A17E2695737FAB5D6086E3 /* fixtures */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = folder; path = fixtures; sourceTree = ""; }; + 19A17EA3A313F129011B3FA0 /* Release.md */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = net.daringfireball.markdown; path = Release.md; sourceTree = ""; }; 3717F907221F5D7C00B9BD3D /* CustomAggregationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomAggregationTests.swift; sourceTree = ""; }; 3D67B3E51DB2469200A4F4C6 /* libsqlite3.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libsqlite3.tbd; path = Platforms/WatchOS.platform/Developer/SDKs/WatchOS3.0.sdk/usr/lib/libsqlite3.tbd; sourceTree = DEVELOPER_DIR; }; 3DDC112E26CDBA0200CE369F /* SQLiteObjc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = SQLiteObjc.h; path = ../SQLiteObjc/include/SQLiteObjc.h; sourceTree = ""; }; @@ -496,6 +497,7 @@ children = ( EE247B8F1C3F822500AE3E12 /* Index.md */, EE247B901C3F822500AE3E12 /* Resources */, + 19A17EA3A313F129011B3FA0 /* Release.md */, ); path = Documentation; sourceTree = ""; @@ -1040,6 +1042,7 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_TREAT_WARNINGS_AS_ERRORS = YES; INFOPLIST_FILE = "$(SRCROOT)/Sources/SQLite/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; @@ -1047,6 +1050,7 @@ PRODUCT_NAME = SQLite; SDKROOT = appletvos; SKIP_INSTALL = YES; + SWIFT_TREAT_WARNINGS_AS_ERRORS = YES; TVOS_DEPLOYMENT_TARGET = 12.0; }; name = Debug; @@ -1060,6 +1064,7 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_TREAT_WARNINGS_AS_ERRORS = YES; INFOPLIST_FILE = "$(SRCROOT)/Sources/SQLite/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; @@ -1067,6 +1072,7 @@ PRODUCT_NAME = SQLite; SDKROOT = appletvos; SKIP_INSTALL = YES; + SWIFT_TREAT_WARNINGS_AS_ERRORS = YES; TVOS_DEPLOYMENT_TARGET = 12.0; }; name = Release; @@ -1074,11 +1080,13 @@ 03A65E6D1C6BB0F60062603F /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + GCC_TREAT_WARNINGS_AS_ERRORS = YES; INFOPLIST_FILE = Tests/SQLiteTests/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.stephencelis.SQLiteTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = appletvos; + SWIFT_TREAT_WARNINGS_AS_ERRORS = YES; TVOS_DEPLOYMENT_TARGET = 12.0; }; name = Debug; @@ -1086,11 +1094,13 @@ 03A65E6E1C6BB0F60062603F /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + GCC_TREAT_WARNINGS_AS_ERRORS = YES; INFOPLIST_FILE = Tests/SQLiteTests/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.stephencelis.SQLiteTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = appletvos; + SWIFT_TREAT_WARNINGS_AS_ERRORS = YES; TVOS_DEPLOYMENT_TARGET = 12.0; }; name = Release; @@ -1105,6 +1115,7 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_TREAT_WARNINGS_AS_ERRORS = YES; INFOPLIST_FILE = "$(SRCROOT)/Sources/SQLite/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; @@ -1112,6 +1123,7 @@ PRODUCT_NAME = SQLite; SDKROOT = watchos; SKIP_INSTALL = YES; + SWIFT_TREAT_WARNINGS_AS_ERRORS = YES; TARGETED_DEVICE_FAMILY = 4; WATCHOS_DEPLOYMENT_TARGET = 3.0; }; @@ -1127,6 +1139,7 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_TREAT_WARNINGS_AS_ERRORS = YES; INFOPLIST_FILE = "$(SRCROOT)/Sources/SQLite/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; @@ -1134,6 +1147,7 @@ PRODUCT_NAME = SQLite; SDKROOT = watchos; SKIP_INSTALL = YES; + SWIFT_TREAT_WARNINGS_AS_ERRORS = YES; TARGETED_DEVICE_FAMILY = 4; WATCHOS_DEPLOYMENT_TARGET = 3.0; }; @@ -1269,6 +1283,7 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_TREAT_WARNINGS_AS_ERRORS = YES; INFOPLIST_FILE = "$(SRCROOT)/Sources/SQLite/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 9.0; @@ -1278,6 +1293,7 @@ PRODUCT_NAME = SQLite; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_TREAT_WARNINGS_AS_ERRORS = YES; }; name = Debug; }; @@ -1291,6 +1307,7 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_TREAT_WARNINGS_AS_ERRORS = YES; INFOPLIST_FILE = "$(SRCROOT)/Sources/SQLite/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 9.0; @@ -1299,26 +1316,31 @@ PRODUCT_BUNDLE_IDENTIFIER = com.stephencelis.SQLite; PRODUCT_NAME = SQLite; SKIP_INSTALL = YES; + SWIFT_TREAT_WARNINGS_AS_ERRORS = YES; }; name = Release; }; EE247AEB1C3F04ED00AE3E12 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + GCC_TREAT_WARNINGS_AS_ERRORS = YES; INFOPLIST_FILE = Tests/SQLiteTests/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.stephencelis.SQLiteTests; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_TREAT_WARNINGS_AS_ERRORS = YES; }; name = Debug; }; EE247AEC1C3F04ED00AE3E12 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + GCC_TREAT_WARNINGS_AS_ERRORS = YES; INFOPLIST_FILE = Tests/SQLiteTests/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.stephencelis.SQLiteTests; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_TREAT_WARNINGS_AS_ERRORS = YES; }; name = Release; }; @@ -1333,6 +1355,7 @@ DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; FRAMEWORK_VERSION = A; + GCC_TREAT_WARNINGS_AS_ERRORS = YES; INFOPLIST_FILE = "$(SRCROOT)/Sources/SQLite/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; @@ -1341,6 +1364,7 @@ SDKROOT = macosx; SKIP_INSTALL = YES; SWIFT_INCLUDE_PATHS = ""; + SWIFT_TREAT_WARNINGS_AS_ERRORS = YES; }; name = Debug; }; @@ -1355,6 +1379,7 @@ DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; FRAMEWORK_VERSION = A; + GCC_TREAT_WARNINGS_AS_ERRORS = YES; INFOPLIST_FILE = "$(SRCROOT)/Sources/SQLite/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; @@ -1363,6 +1388,7 @@ SDKROOT = macosx; SKIP_INSTALL = YES; SWIFT_INCLUDE_PATHS = ""; + SWIFT_TREAT_WARNINGS_AS_ERRORS = YES; }; name = Release; }; @@ -1371,11 +1397,13 @@ buildSettings = { CODE_SIGN_IDENTITY = "-"; COMBINE_HIDPI_IMAGES = YES; + GCC_TREAT_WARNINGS_AS_ERRORS = YES; INFOPLIST_FILE = Tests/SQLiteTests/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.stephencelis.SQLiteTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; + SWIFT_TREAT_WARNINGS_AS_ERRORS = YES; }; name = Debug; }; @@ -1384,11 +1412,13 @@ buildSettings = { CODE_SIGN_IDENTITY = "-"; COMBINE_HIDPI_IMAGES = YES; + GCC_TREAT_WARNINGS_AS_ERRORS = YES; INFOPLIST_FILE = Tests/SQLiteTests/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.stephencelis.SQLiteTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; + SWIFT_TREAT_WARNINGS_AS_ERRORS = YES; }; name = Release; }; diff --git a/Sources/SQLite/Core/Blob.swift b/Sources/SQLite/Core/Blob.swift index 2f5d2a14..cd31483b 100644 --- a/Sources/SQLite/Core/Blob.swift +++ b/Sources/SQLite/Core/Blob.swift @@ -36,25 +36,25 @@ public struct Blob { } public func toHex() -> String { - return bytes.map { + bytes.map { ($0 < 16 ? "0" : "") + String($0, radix: 16, uppercase: false) }.joined(separator: "") } } -extension Blob : CustomStringConvertible { +extension Blob: CustomStringConvertible { public var description: String { - return "x'\(toHex())'" + "x'\(toHex())'" } } -extension Blob : Equatable { +extension Blob: Equatable { } public func ==(lhs: Blob, rhs: Blob) -> Bool { - return lhs.bytes == rhs.bytes + lhs.bytes == rhs.bytes } diff --git a/Sources/SQLite/Core/Connection.swift b/Sources/SQLite/Core/Connection.swift index 9273b36a..fa086181 100644 --- a/Sources/SQLite/Core/Connection.swift +++ b/Sources/SQLite/Core/Connection.swift @@ -35,6 +35,7 @@ import SQLite3 #endif /// A connection to SQLite. +// swiftlint:disable:next type_body_length public final class Connection { /// The location of a SQLite database. @@ -70,7 +71,7 @@ public final class Connection { /// A DELETE operation. case delete - fileprivate init(rawValue:Int32) { + fileprivate init(rawValue: Int32) { switch rawValue { case SQLITE_INSERT: self = .insert @@ -84,9 +85,9 @@ public final class Connection { } } - public var handle: OpaquePointer { return _handle! } + public var handle: OpaquePointer { _handle! } - fileprivate var _handle: OpaquePointer? = nil + fileprivate var _handle: OpaquePointer? /// Initializes a new SQLite connection. /// @@ -133,23 +134,23 @@ public final class Connection { // MARK: - /// Whether or not the database was opened in a read-only state. - public var readonly: Bool { return sqlite3_db_readonly(handle, nil) == 1 } + public var readonly: Bool { sqlite3_db_readonly(handle, nil) == 1 } /// The last rowid inserted into the database via this connection. public var lastInsertRowid: Int64 { - return sqlite3_last_insert_rowid(handle) + sqlite3_last_insert_rowid(handle) } /// The last number of changes (inserts, updates, or deletes) made to the /// database via this connection. public var changes: Int { - return Int(sqlite3_changes(handle)) + Int(sqlite3_changes(handle)) } /// The total number of changes (inserts, updates, or deletes) made to the /// database via this connection. public var totalChanges: Int { - return Int(sqlite3_total_changes(handle)) + Int(sqlite3_total_changes(handle)) } // MARK: - Execute @@ -161,7 +162,7 @@ public final class Connection { /// /// - Throws: `Result.Error` if query execution fails. public func execute(_ SQL: String) throws { - _ = try sync { try self.check(sqlite3_exec(self.handle, SQL, nil, nil, nil)) } + _ = try sync { try check(sqlite3_exec(handle, SQL, nil, nil, nil)) } } // MARK: - Prepare @@ -190,7 +191,7 @@ public final class Connection { /// /// - Returns: A prepared statement. public func prepare(_ statement: String, _ bindings: [Binding?]) throws -> Statement { - return try prepare(statement).bind(bindings) + try prepare(statement).bind(bindings) } /// Prepares a single SQL statement and binds parameters to it. @@ -203,7 +204,7 @@ public final class Connection { /// /// - Returns: A prepared statement. public func prepare(_ statement: String, _ bindings: [String: Binding?]) throws -> Statement { - return try prepare(statement).bind(bindings) + try prepare(statement).bind(bindings) } // MARK: - Run @@ -220,7 +221,7 @@ public final class Connection { /// /// - Returns: The statement. @discardableResult public func run(_ statement: String, _ bindings: Binding?...) throws -> Statement { - return try run(statement, bindings) + try run(statement, bindings) } /// Prepares, binds, and runs a single SQL statement. @@ -235,7 +236,7 @@ public final class Connection { /// /// - Returns: The statement. @discardableResult public func run(_ statement: String, _ bindings: [Binding?]) throws -> Statement { - return try prepare(statement).run(bindings) + try prepare(statement).run(bindings) } /// Prepares, binds, and runs a single SQL statement. @@ -250,18 +251,18 @@ public final class Connection { /// /// - Returns: The statement. @discardableResult public func run(_ statement: String, _ bindings: [String: Binding?]) throws -> Statement { - return try prepare(statement).run(bindings) + try prepare(statement).run(bindings) } - + // MARK: - VACUUM - + /// Run a vacuum on the database /// /// - Throws: `Result.Error` if query execution fails. /// /// - Returns: The statement. @discardableResult public func vacuum() throws -> Statement { - return try run("VACUUM") + try run("VACUUM") } // MARK: - Scalar @@ -277,7 +278,7 @@ public final class Connection { /// /// - Returns: The first value of the first row returned. public func scalar(_ statement: String, _ bindings: Binding?...) throws -> Binding? { - return try scalar(statement, bindings) + try scalar(statement, bindings) } /// Runs a single SQL statement (with optional parameter bindings), @@ -291,7 +292,7 @@ public final class Connection { /// /// - Returns: The first value of the first row returned. public func scalar(_ statement: String, _ bindings: [Binding?]) throws -> Binding? { - return try prepare(statement).scalar(bindings) + try prepare(statement).scalar(bindings) } /// Runs a single SQL statement (with optional parameter bindings), @@ -305,13 +306,13 @@ public final class Connection { /// /// - Returns: The first value of the first row returned. public func scalar(_ statement: String, _ bindings: [String: Binding?]) throws -> Binding? { - return try prepare(statement).scalar(bindings) + try prepare(statement).scalar(bindings) } // MARK: - Transactions /// The mode in which a transaction acquires a lock. - public enum TransactionMode : String { + public enum TransactionMode: String { /// Defers locking the database till the first read/write executes. case deferred = "DEFERRED" @@ -433,7 +434,7 @@ public final class Connection { } } - @available(OSX, deprecated: 10.2) + @available(OSX, deprecated: 10.12) @available(iOS, deprecated: 10.0) @available(watchOS, deprecated: 3.0) @available(tvOS, deprecated: 10.0) @@ -446,11 +447,9 @@ public final class Connection { let box: Trace = { (pointer: UnsafeRawPointer) in callback(String(cString: pointer.assumingMemoryBound(to: UInt8.self))) } - sqlite3_trace(handle, - { - (C: UnsafeMutableRawPointer?, SQL: UnsafePointer?) in - if let C = C, let SQL = SQL { - unsafeBitCast(C, to: Trace.self)(SQL) + sqlite3_trace(handle, { (context: UnsafeMutableRawPointer?, SQL: UnsafePointer?) in + if let context = context, let SQL = SQL { + unsafeBitCast(context, to: Trace.self)(SQL) } }, unsafeBitCast(box, to: UnsafeMutableRawPointer.self) @@ -470,16 +469,15 @@ public final class Connection { let box: Trace = { (pointer: UnsafeRawPointer) in callback(String(cString: pointer.assumingMemoryBound(to: UInt8.self))) } - sqlite3_trace_v2(handle, UInt32(SQLITE_TRACE_STMT) /* mask */, - { + sqlite3_trace_v2(handle, UInt32(SQLITE_TRACE_STMT) /* mask */, { // A trace callback is invoked with four arguments: callback(T,C,P,X). // The T argument is one of the SQLITE_TRACE constants to indicate why the // callback was invoked. The C argument is a copy of the context pointer. // The P and X arguments are pointers whose meanings depend on T. - (T: UInt32, C: UnsafeMutableRawPointer?, P: UnsafeMutableRawPointer?, X: UnsafeMutableRawPointer?) in - if let P = P, - let expandedSQL = sqlite3_expanded_sql(OpaquePointer(P)) { - unsafeBitCast(C, to: Trace.self)(expandedSQL) + (_: UInt32, context: UnsafeMutableRawPointer?, pointer: UnsafeMutableRawPointer?, _: UnsafeMutableRawPointer?) in + if let pointer = pointer, + let expandedSQL = sqlite3_expanded_sql(OpaquePointer(pointer)) { + unsafeBitCast(context, to: Trace.self)(expandedSQL) sqlite3_free(expandedSQL) } return Int32(0) // currently ignored @@ -588,7 +586,9 @@ public final class Connection { /// - block: A block of code to run when the function is called. The block /// is called with an array of raw SQL values mapped to the function’s /// parameters and should return a raw SQL value (or nil). - public func createFunction(_ function: String, argumentCount: UInt? = nil, deterministic: Bool = false, _ block: @escaping (_ args: [Binding?]) -> Binding?) { + // swiftlint:disable:next cyclomatic_complexity + public func createFunction(_ function: String, argumentCount: UInt? = nil, deterministic: Bool = false, + _ block: @escaping (_ args: [Binding?]) -> Binding?) { let argc = argumentCount.map { Int($0) } ?? -1 let box: Function = { context, argc, argv in let arguments: [Binding?] = (0..( _ aggregate: String, argumentCount: UInt? = nil, deterministic: Bool = false, - step: @escaping ([Binding?], UnsafeMutablePointer) -> (), + step: @escaping ([Binding?], UnsafeMutablePointer) -> Void, final: @escaping (UnsafeMutablePointer) -> Binding?, state: @escaping () -> UnsafeMutablePointer) { - - + let argc = argumentCount.map { Int($0) } ?? -1 - let box : Aggregate = { (stepFlag: Int, context: OpaquePointer?, argc: Int32, argv: UnsafeMutablePointer?) in + let box: Aggregate = { (stepFlag: Int, context: OpaquePointer?, argc: Int32, argv: UnsafeMutablePointer?) in let ptr = sqlite3_aggregate_context(context, 64)! // needs to be at least as large as uintptr_t; better way to do this? - let p = ptr.assumingMemoryBound(to: UnsafeMutableRawPointer.self) + let mutablePointer = ptr.assumingMemoryBound(to: UnsafeMutableRawPointer.self) if stepFlag > 0 { let arguments: [Binding?] = (0.. Statement { - return bind(values) + bind(values) } /// Binds a list of parameters to a statement. @@ -140,7 +140,7 @@ public final class Statement { /// /// - Returns: The statement object (useful for chaining). @discardableResult public func run(_ bindings: [Binding?]) throws -> Statement { - return try bind(bindings).run() + try bind(bindings).run() } /// - Parameter bindings: A dictionary of named parameters to bind to the @@ -150,7 +150,7 @@ public final class Statement { /// /// - Returns: The statement object (useful for chaining). @discardableResult public func run(_ bindings: [String: Binding?]) throws -> Statement { - return try bind(bindings).run() + try bind(bindings).run() } /// - Parameter bindings: A list of parameters to bind to the statement. @@ -170,30 +170,29 @@ public final class Statement { /// /// - Returns: The first value of the first row returned. public func scalar(_ bindings: [Binding?]) throws -> Binding? { - return try bind(bindings).scalar() + try bind(bindings).scalar() } - /// - Parameter bindings: A dictionary of named parameters to bind to the /// statement. /// /// - Returns: The first value of the first row returned. public func scalar(_ bindings: [String: Binding?]) throws -> Binding? { - return try bind(bindings).scalar() + try bind(bindings).scalar() } public func step() throws -> Bool { - return try connection.sync { try self.connection.check(sqlite3_step(self.handle)) == SQLITE_ROW } + try connection.sync { try connection.check(sqlite3_step(handle)) == SQLITE_ROW } } fileprivate func reset(clearBindings shouldClear: Bool = true) { sqlite3_reset(handle) - if (shouldClear) { sqlite3_clear_bindings(handle) } + if shouldClear { sqlite3_clear_bindings(handle) } } } -extension Statement : Sequence { +extension Statement: Sequence { public func makeIterator() -> Statement { reset(clearBindings: false) @@ -202,13 +201,13 @@ extension Statement : Sequence { } -public protocol FailableIterator : IteratorProtocol { +public protocol FailableIterator: IteratorProtocol { func failableNext() throws -> Self.Element? } extension FailableIterator { public func next() -> Element? { - return try? failableNext() + try? failableNext() } } @@ -221,17 +220,17 @@ extension Array { } } -extension Statement : FailableIterator { +extension Statement: FailableIterator { public typealias Element = [Binding?] public func failableNext() throws -> [Binding?]? { - return try step() ? Array(row) : nil + try step() ? Array(row) : nil } } -extension Statement : CustomStringConvertible { +extension Statement: CustomStringConvertible { public var description: String { - return String(cString: sqlite3_sql(handle)) + String(cString: sqlite3_sql(handle)) } } @@ -248,15 +247,15 @@ public struct Cursor { } public subscript(idx: Int) -> Double { - return sqlite3_column_double(handle, Int32(idx)) + sqlite3_column_double(handle, Int32(idx)) } public subscript(idx: Int) -> Int64 { - return sqlite3_column_int64(handle, Int32(idx)) + sqlite3_column_int64(handle, Int32(idx)) } public subscript(idx: Int) -> String { - return String(cString: UnsafePointer(sqlite3_column_text(handle, Int32(idx)))) + String(cString: UnsafePointer(sqlite3_column_text(handle, Int32(idx)))) } public subscript(idx: Int) -> Blob { @@ -273,17 +272,17 @@ public struct Cursor { // MARK: - public subscript(idx: Int) -> Bool { - return Bool.fromDatatypeValue(self[idx]) + Bool.fromDatatypeValue(self[idx]) } public subscript(idx: Int) -> Int { - return Int.fromDatatypeValue(self[idx]) + Int.fromDatatypeValue(self[idx]) } } /// Cursors provide direct access to a statement’s current row. -extension Cursor : Sequence { +extension Cursor: Sequence { public subscript(idx: Int) -> Binding? { switch sqlite3_column_type(handle, Int32(idx)) { @@ -305,8 +304,8 @@ extension Cursor : Sequence { public func makeIterator() -> AnyIterator { var idx = 0 return AnyIterator { - if idx >= self.columnCount { - return Optional.none + if idx >= columnCount { + return .none } else { idx += 1 return self[idx - 1] diff --git a/Sources/SQLite/Core/Value.swift b/Sources/SQLite/Core/Value.swift index 608f0ce6..9c463f0c 100644 --- a/Sources/SQLite/Core/Value.swift +++ b/Sources/SQLite/Core/Value.swift @@ -29,13 +29,13 @@ /// protocol, instead. public protocol Binding {} -public protocol Number : Binding {} +public protocol Number: Binding {} -public protocol Value : Expressible { // extensions cannot have inheritance clauses +public protocol Value: Expressible { // extensions cannot have inheritance clauses associatedtype ValueType = Self - associatedtype Datatype : Binding + associatedtype Datatype: Binding static var declaredDatatype: String { get } @@ -45,88 +45,88 @@ public protocol Value : Expressible { // extensions cannot have inheritance clau } -extension Double : Number, Value { +extension Double: Number, Value { public static let declaredDatatype = "REAL" public static func fromDatatypeValue(_ datatypeValue: Double) -> Double { - return datatypeValue + datatypeValue } public var datatypeValue: Double { - return self + self } } -extension Int64 : Number, Value { +extension Int64: Number, Value { public static let declaredDatatype = "INTEGER" public static func fromDatatypeValue(_ datatypeValue: Int64) -> Int64 { - return datatypeValue + datatypeValue } public var datatypeValue: Int64 { - return self + self } } -extension String : Binding, Value { +extension String: Binding, Value { public static let declaredDatatype = "TEXT" public static func fromDatatypeValue(_ datatypeValue: String) -> String { - return datatypeValue + datatypeValue } public var datatypeValue: String { - return self + self } } -extension Blob : Binding, Value { +extension Blob: Binding, Value { public static let declaredDatatype = "BLOB" public static func fromDatatypeValue(_ datatypeValue: Blob) -> Blob { - return datatypeValue + datatypeValue } public var datatypeValue: Blob { - return self + self } } // MARK: - -extension Bool : Binding, Value { +extension Bool: Binding, Value { public static var declaredDatatype = Int64.declaredDatatype public static func fromDatatypeValue(_ datatypeValue: Int64) -> Bool { - return datatypeValue != 0 + datatypeValue != 0 } public var datatypeValue: Int64 { - return self ? 1 : 0 + self ? 1 : 0 } } -extension Int : Number, Value { +extension Int: Number, Value { public static var declaredDatatype = Int64.declaredDatatype public static func fromDatatypeValue(_ datatypeValue: Int64) -> Int { - return Int(datatypeValue) + Int(datatypeValue) } public var datatypeValue: Int64 { - return Int64(self) + Int64(self) } } diff --git a/Sources/SQLite/Extensions/Cipher.swift b/Sources/SQLite/Extensions/Cipher.swift index 44919aab..25d20158 100644 --- a/Sources/SQLite/Extensions/Cipher.swift +++ b/Sources/SQLite/Extensions/Cipher.swift @@ -1,14 +1,13 @@ #if SQLITE_SWIFT_SQLCIPHER import SQLCipher - /// Extension methods for [SQLCipher](https://www.zetetic.net/sqlcipher/). /// @see [sqlcipher api](https://www.zetetic.net/sqlcipher/sqlcipher-api/) extension Connection { /// - Returns: the SQLCipher version public var cipherVersion: String? { - return (try? scalar("PRAGMA cipher_version")) as? String + (try? scalar("PRAGMA cipher_version")) as? String } /// Specify the key for an encrypted database. This routine should be @@ -32,7 +31,6 @@ extension Connection { try _key_v2(db: db, keyPointer: key.bytes, keySize: key.bytes.count) } - /// Change the key on an open database. If the current database is not encrypted, this routine /// will encrypt it. /// To change the key on an existing encrypted database, it must first be unlocked with the @@ -60,7 +58,7 @@ extension Connection { // the key provided is incorrect. To test that the database can be successfully opened with the // provided key, it is necessary to perform some operation on the database (i.e. read from it). private func cipher_key_check() throws { - let _ = try scalar("SELECT count(*) FROM sqlite_master;") + _ = try scalar("SELECT count(*) FROM sqlite_master;") } } #endif diff --git a/Sources/SQLite/Extensions/FTS4.swift b/Sources/SQLite/Extensions/FTS4.swift index f0184565..115b146a 100644 --- a/Sources/SQLite/Extensions/FTS4.swift +++ b/Sources/SQLite/Extensions/FTS4.swift @@ -29,15 +29,15 @@ import SQLiteObjc extension Module { public static func FTS4(_ column: Expressible, _ more: Expressible...) -> Module { - return FTS4([column] + more) + FTS4([column] + more) } public static func FTS4(_ columns: [Expressible] = [], tokenize tokenizer: Tokenizer? = nil) -> Module { - return FTS4(FTS4Config().columns(columns).tokenizer(tokenizer)) + FTS4(FTS4Config().columns(columns).tokenizer(tokenizer)) } public static func FTS4(_ config: FTS4Config) -> Module { - return Module(name: "fts4", arguments: config.arguments()) + Module(name: "fts4", arguments: config.arguments()) } } @@ -56,15 +56,15 @@ extension VirtualTable { /// - Returns: An expression appended with a `MATCH` query against the given /// pattern. public func match(_ pattern: String) -> Expression { - return "MATCH".infix(tableName(), pattern) + "MATCH".infix(tableName(), pattern) } public func match(_ pattern: Expression) -> Expression { - return "MATCH".infix(tableName(), pattern) + "MATCH".infix(tableName(), pattern) } public func match(_ pattern: Expression) -> Expression { - return "MATCH".infix(tableName(), pattern) + "MATCH".infix(tableName(), pattern) } /// Builds a copy of the query with a `WHERE … MATCH` clause. @@ -78,26 +78,28 @@ extension VirtualTable { /// /// - Returns: A query with the given `WHERE … MATCH` clause applied. public func match(_ pattern: String) -> QueryType { - return filter(match(pattern)) + filter(match(pattern)) } public func match(_ pattern: Expression) -> QueryType { - return filter(match(pattern)) + filter(match(pattern)) } public func match(_ pattern: Expression) -> QueryType { - return filter(match(pattern)) + filter(match(pattern)) } } +// swiftlint:disable identifier_name public struct Tokenizer { public static let Simple = Tokenizer("simple") public static let Porter = Tokenizer("porter") - public static func Unicode61(removeDiacritics: Bool? = nil, tokenchars: Set = [], separators: Set = []) -> Tokenizer { + public static func Unicode61(removeDiacritics: Bool? = nil, tokenchars: Set = [], + separators: Set = []) -> Tokenizer { var arguments = [String]() if let removeDiacritics = removeDiacritics { @@ -118,7 +120,7 @@ public struct Tokenizer { } public static func Custom(_ name: String) -> Tokenizer { - return Tokenizer(Tokenizer.moduleName.quote(), [name.quote()]) + Tokenizer(Tokenizer.moduleName.quote(), [name.quote()]) } public let name: String @@ -134,10 +136,10 @@ public struct Tokenizer { } -extension Tokenizer : CustomStringConvertible { +extension Tokenizer: CustomStringConvertible { public var description: String { - return ([name] + arguments).joined(separator: " ") + ([name] + arguments).joined(separator: " ") } } @@ -145,13 +147,13 @@ extension Tokenizer : CustomStringConvertible { extension Connection { public func registerTokenizer(_ submoduleName: String, next: @escaping (String) -> (String, Range)?) throws { - try check(_SQLiteRegisterTokenizer(handle, Tokenizer.moduleName, submoduleName) { ( - input: UnsafePointer, offset: UnsafeMutablePointer, length: UnsafeMutablePointer) in + try check(_SQLiteRegisterTokenizer(handle, Tokenizer.moduleName, submoduleName) { + (input: UnsafePointer, offset: UnsafeMutablePointer, length: UnsafeMutablePointer) in let string = String(cString: input) guard let (token, range) = next(string) else { return nil } - let view:String.UTF8View = string.utf8 + let view: String.UTF8View = string.utf8 if let from = range.lowerBound.samePosition(in: view), let to = range.upperBound.samePosition(in: view) { @@ -182,7 +184,7 @@ open class FTSConfig { /// Adds a column definition @discardableResult open func column(_ column: Expressible, _ options: [ColumnOption] = []) -> Self { - self.columnDefinitions.append((column, options)) + columnDefinitions.append((column, options)) return self } @@ -201,28 +203,28 @@ open class FTSConfig { /// [The prefix= option](https://www.sqlite.org/fts3.html#section_6_6) @discardableResult open func prefix(_ prefix: [Int]) -> Self { - self.prefixes += prefix + prefixes += prefix return self } /// [The content= option](https://www.sqlite.org/fts3.html#section_6_2) @discardableResult open func externalContent(_ schema: SchemaType) -> Self { - self.externalContentSchema = schema + externalContentSchema = schema return self } /// [Contentless FTS4 Tables](https://www.sqlite.org/fts3.html#section_6_2_1) @discardableResult open func contentless() -> Self { - self.isContentless = true + isContentless = true return self } func formatColumnDefinitions() -> [Expressible] { - return columnDefinitions.map { $0.0 } + columnDefinitions.map { $0.0 } } func arguments() -> [Expressible] { - return options().arguments + options().arguments } func options() -> Options { @@ -231,7 +233,7 @@ open class FTSConfig { if let tokenizer = tokenizer { options.append("tokenize", value: Expression(literal: tokenizer.description)) } - options.appendCommaSeparated("prefix", values:prefixes.sorted().map { String($0) }) + options.appendCommaSeparated("prefix", values: prefixes.sorted().map { String($0) }) if isContentless { options.append("content", value: "") } else if let externalContentSchema = externalContentSchema { @@ -257,11 +259,11 @@ open class FTSConfig { } @discardableResult mutating func append(_ key: String, value: CustomStringConvertible?) -> Options { - return append(key, value: value?.description) + append(key, value: value?.description) } @discardableResult mutating func append(_ key: String, value: String?) -> Options { - return append(key, value: value.map { Expression($0) }) + append(key, value: value.map { Expression($0) }) } @discardableResult mutating func append(_ key: String, value: Expressible?) -> Options { @@ -274,17 +276,17 @@ open class FTSConfig { } /// Configuration for the [FTS4](https://www.sqlite.org/fts3.html) extension. -open class FTS4Config : FTSConfig { +open class FTS4Config: FTSConfig { /// [The matchinfo= option](https://www.sqlite.org/fts3.html#section_6_4) - public enum MatchInfo : CustomStringConvertible { + public enum MatchInfo: CustomStringConvertible { case fts3 public var description: String { - return "fts3" + "fts3" } } /// [FTS4 options](https://www.sqlite.org/fts3.html#fts4_options) - public enum Order : CustomStringConvertible { + public enum Order: CustomStringConvertible { /// Data structures are optimized for returning results in ascending order by docid (default) case asc /// FTS4 stores its data in such a way as to optimize returning results in descending order by docid. @@ -309,19 +311,19 @@ open class FTS4Config : FTSConfig { /// [The compress= and uncompress= options](https://www.sqlite.org/fts3.html#section_6_1) @discardableResult open func compress(_ functionName: String) -> Self { - self.compressFunction = functionName + compressFunction = functionName return self } /// [The compress= and uncompress= options](https://www.sqlite.org/fts3.html#section_6_1) @discardableResult open func uncompress(_ functionName: String) -> Self { - self.uncompressFunction = functionName + uncompressFunction = functionName return self } /// [The languageid= option](https://www.sqlite.org/fts3.html#section_6_3) @discardableResult open func languageId(_ columnName: String) -> Self { - self.languageId = columnName + languageId = columnName return self } diff --git a/Sources/SQLite/Extensions/FTS5.swift b/Sources/SQLite/Extensions/FTS5.swift index cf13f3d8..f108bbec 100644 --- a/Sources/SQLite/Extensions/FTS5.swift +++ b/Sources/SQLite/Extensions/FTS5.swift @@ -24,7 +24,7 @@ extension Module { public static func FTS5(_ config: FTS5Config) -> Module { - return Module(name: "fts5", arguments: config.arguments()) + Module(name: "fts5", arguments: config.arguments()) } } @@ -32,8 +32,8 @@ extension Module { /// /// **Note:** this is currently only applicable when using SQLite.swift together with a FTS5-enabled version /// of SQLite. -open class FTS5Config : FTSConfig { - public enum Detail : CustomStringConvertible { +open class FTS5Config: FTSConfig { + public enum Detail: CustomStringConvertible { /// store rowid, column number, term offset case full /// store rowid, column number @@ -59,13 +59,13 @@ open class FTS5Config : FTSConfig { /// [External Content Tables](https://www.sqlite.org/fts5.html#section_4_4_2) @discardableResult open func contentRowId(_ column: Expressible) -> Self { - self.contentRowId = column + contentRowId = column return self } /// [The Columnsize Option](https://www.sqlite.org/fts5.html#section_4_5) @discardableResult open func columnSize(_ size: Int) -> Self { - self.columnSize = size + columnSize = size return self } @@ -86,7 +86,7 @@ open class FTS5Config : FTSConfig { } override func formatColumnDefinitions() -> [Expressible] { - return columnDefinitions.map { definition in + columnDefinitions.map { definition in if definition.options.contains(.unindexed) { return " ".join([definition.0, Expression(literal: "UNINDEXED")]) } else { diff --git a/Sources/SQLite/Extensions/RTree.swift b/Sources/SQLite/Extensions/RTree.swift index 4fc1a235..5ecdf78b 100644 --- a/Sources/SQLite/Extensions/RTree.swift +++ b/Sources/SQLite/Extensions/RTree.swift @@ -23,8 +23,9 @@ // extension Module { - - public static func RTree(_ primaryKey: Expression, _ pairs: (Expression, Expression)...) -> Module where T.Datatype == Int64, U.Datatype == Double { + public static func RTree(_ primaryKey: Expression, + _ pairs: (Expression, Expression)...) + -> Module where T.Datatype == Int64, U.Datatype == Double { var arguments: [Expressible] = [primaryKey] for pair in pairs { @@ -33,5 +34,4 @@ extension Module { return Module(name: "rtree", arguments: arguments) } - } diff --git a/Sources/SQLite/Foundation.swift b/Sources/SQLite/Foundation.swift index 9986f581..2acbc00e 100644 --- a/Sources/SQLite/Foundation.swift +++ b/Sources/SQLite/Foundation.swift @@ -24,36 +24,36 @@ import Foundation -extension Data : Value { +extension Data: Value { public static var declaredDatatype: String { - return Blob.declaredDatatype + Blob.declaredDatatype } public static func fromDatatypeValue(_ dataValue: Blob) -> Data { - return Data(dataValue.bytes) + Data(dataValue.bytes) } public var datatypeValue: Blob { - return withUnsafeBytes { (pointer: UnsafeRawBufferPointer) -> Blob in - return Blob(bytes: pointer.baseAddress!, length: count) + withUnsafeBytes { (pointer: UnsafeRawBufferPointer) -> Blob in + Blob(bytes: pointer.baseAddress!, length: count) } } } -extension Date : Value { +extension Date: Value { public static var declaredDatatype: String { - return String.declaredDatatype + String.declaredDatatype } public static func fromDatatypeValue(_ stringValue: String) -> Date { - return dateFormatter.date(from: stringValue)! + dateFormatter.date(from: stringValue)! } public var datatypeValue: String { - return dateFormatter.string(from: self) + dateFormatter.string(from: self) } } @@ -69,18 +69,18 @@ public var dateFormatter: DateFormatter = { return formatter }() -extension UUID : Value { +extension UUID: Value { public static var declaredDatatype: String { - return String.declaredDatatype + String.declaredDatatype } public static func fromDatatypeValue(_ stringValue: String) -> UUID { - return UUID(uuidString: stringValue)! + UUID(uuidString: stringValue)! } public var datatypeValue: String { - return self.uuidString + uuidString } } diff --git a/Sources/SQLite/Helpers.swift b/Sources/SQLite/Helpers.swift index 44aaec19..d4c6828e 100644 --- a/Sources/SQLite/Helpers.swift +++ b/Sources/SQLite/Helpers.swift @@ -35,7 +35,7 @@ import SQLite3 public typealias Star = (Expression?, Expression?) -> Expression public func *(_: Expression?, _: Expression?) -> Expression { - return Expression(literal: "*") + Expression(literal: "*") } public protocol _OptionalType { @@ -44,7 +44,7 @@ public protocol _OptionalType { } -extension Optional : _OptionalType { +extension Optional: _OptionalType { public typealias WrappedType = Wrapped @@ -73,9 +73,9 @@ extension String { } func infix(_ lhs: Expressible, _ rhs: Expressible, wrap: Bool = true) -> Expression { - return infix([lhs, rhs], wrap: wrap) + infix([lhs, rhs], wrap: wrap) } - + func infix(_ terms: [Expressible], wrap: Bool = true) -> Expression { let expression = Expression(" \(self) ".join(terms).expression) guard wrap else { @@ -85,19 +85,19 @@ extension String { } func prefix(_ expressions: Expressible) -> Expressible { - return "\(self) ".wrap(expressions) as Expression + "\(self) ".wrap(expressions) as Expression } func prefix(_ expressions: [Expressible]) -> Expressible { - return "\(self) ".wrap(expressions) as Expression + "\(self) ".wrap(expressions) as Expression } func wrap(_ expression: Expressible) -> Expression { - return Expression("\(self)(\(expression.expression.template))", expression.expression.bindings) + Expression("\(self)(\(expression.expression.template))", expression.expression.bindings) } func wrap(_ expressions: [Expressible]) -> Expression { - return wrap(", ".join(expressions)) + wrap(", ".join(expressions)) } } @@ -115,10 +115,11 @@ func transcode(_ literal: Binding?) -> String { } } -func value(_ v: Binding) -> A { - return A.fromDatatypeValue(v as! A.Datatype) as! A +// swiftlint:disable force_cast +func value(_ binding: Binding) -> A { + A.fromDatatypeValue(binding as! A.Datatype) as! A } -func value(_ v: Binding?) -> A { - return value(v!) +func value(_ binding: Binding?) -> A { + value(binding!) } diff --git a/Sources/SQLite/Typed/AggregateFunctions.swift b/Sources/SQLite/Typed/AggregateFunctions.swift index 2ec28288..bf4fb8fc 100644 --- a/Sources/SQLite/Typed/AggregateFunctions.swift +++ b/Sources/SQLite/Typed/AggregateFunctions.swift @@ -29,13 +29,13 @@ private enum Function: String { case avg case sum case total - + func wrap(_ expression: Expressible) -> Expression { - return self.rawValue.wrap(expression) + self.rawValue.wrap(expression) } } -extension ExpressionType where UnderlyingType : Value { +extension ExpressionType where UnderlyingType: Value { /// Builds a copy of the expression prefixed with the `DISTINCT` keyword. /// @@ -46,7 +46,7 @@ extension ExpressionType where UnderlyingType : Value { /// - Returns: A copy of the expression prefixed with the `DISTINCT` /// keyword. public var distinct: Expression { - return Expression("DISTINCT \(template)", bindings) + Expression("DISTINCT \(template)", bindings) } /// Builds a copy of the expression wrapped with the `count` aggregate @@ -61,12 +61,12 @@ extension ExpressionType where UnderlyingType : Value { /// - Returns: A copy of the expression wrapped with the `count` aggregate /// function. public var count: Expression { - return Function.count.wrap(self) + Function.count.wrap(self) } } -extension ExpressionType where UnderlyingType : _OptionalType, UnderlyingType.WrappedType : Value { +extension ExpressionType where UnderlyingType: _OptionalType, UnderlyingType.WrappedType: Value { /// Builds a copy of the expression prefixed with the `DISTINCT` keyword. /// @@ -77,7 +77,7 @@ extension ExpressionType where UnderlyingType : _OptionalType, UnderlyingType.Wr /// - Returns: A copy of the expression prefixed with the `DISTINCT` /// keyword. public var distinct: Expression { - return Expression("DISTINCT \(template)", bindings) + Expression("DISTINCT \(template)", bindings) } /// Builds a copy of the expression wrapped with the `count` aggregate @@ -92,12 +92,12 @@ extension ExpressionType where UnderlyingType : _OptionalType, UnderlyingType.Wr /// - Returns: A copy of the expression wrapped with the `count` aggregate /// function. public var count: Expression { - return Function.count.wrap(self) + Function.count.wrap(self) } } -extension ExpressionType where UnderlyingType : Value, UnderlyingType.Datatype : Comparable { +extension ExpressionType where UnderlyingType: Value, UnderlyingType.Datatype: Comparable { /// Builds a copy of the expression wrapped with the `max` aggregate /// function. @@ -109,7 +109,7 @@ extension ExpressionType where UnderlyingType : Value, UnderlyingType.Datatype : /// - Returns: A copy of the expression wrapped with the `max` aggregate /// function. public var max: Expression { - return Function.max.wrap(self) + Function.max.wrap(self) } /// Builds a copy of the expression wrapped with the `min` aggregate @@ -122,12 +122,12 @@ extension ExpressionType where UnderlyingType : Value, UnderlyingType.Datatype : /// - Returns: A copy of the expression wrapped with the `min` aggregate /// function. public var min: Expression { - return Function.min.wrap(self) + Function.min.wrap(self) } } -extension ExpressionType where UnderlyingType : _OptionalType, UnderlyingType.WrappedType : Value, UnderlyingType.WrappedType.Datatype : Comparable { +extension ExpressionType where UnderlyingType: _OptionalType, UnderlyingType.WrappedType: Value, UnderlyingType.WrappedType.Datatype: Comparable { /// Builds a copy of the expression wrapped with the `max` aggregate /// function. @@ -139,7 +139,7 @@ extension ExpressionType where UnderlyingType : _OptionalType, UnderlyingType.Wr /// - Returns: A copy of the expression wrapped with the `max` aggregate /// function. public var max: Expression { - return Function.max.wrap(self) + Function.max.wrap(self) } /// Builds a copy of the expression wrapped with the `min` aggregate @@ -152,12 +152,12 @@ extension ExpressionType where UnderlyingType : _OptionalType, UnderlyingType.Wr /// - Returns: A copy of the expression wrapped with the `min` aggregate /// function. public var min: Expression { - return Function.min.wrap(self) + Function.min.wrap(self) } } -extension ExpressionType where UnderlyingType : Value, UnderlyingType.Datatype : Number { +extension ExpressionType where UnderlyingType: Value, UnderlyingType.Datatype: Number { /// Builds a copy of the expression wrapped with the `avg` aggregate /// function. @@ -169,7 +169,7 @@ extension ExpressionType where UnderlyingType : Value, UnderlyingType.Datatype : /// - Returns: A copy of the expression wrapped with the `min` aggregate /// function. public var average: Expression { - return Function.avg.wrap(self) + Function.avg.wrap(self) } /// Builds a copy of the expression wrapped with the `sum` aggregate @@ -182,7 +182,7 @@ extension ExpressionType where UnderlyingType : Value, UnderlyingType.Datatype : /// - Returns: A copy of the expression wrapped with the `min` aggregate /// function. public var sum: Expression { - return Function.sum.wrap(self) + Function.sum.wrap(self) } /// Builds a copy of the expression wrapped with the `total` aggregate @@ -195,12 +195,12 @@ extension ExpressionType where UnderlyingType : Value, UnderlyingType.Datatype : /// - Returns: A copy of the expression wrapped with the `min` aggregate /// function. public var total: Expression { - return Function.total.wrap(self) + Function.total.wrap(self) } } -extension ExpressionType where UnderlyingType : _OptionalType, UnderlyingType.WrappedType : Value, UnderlyingType.WrappedType.Datatype : Number { +extension ExpressionType where UnderlyingType: _OptionalType, UnderlyingType.WrappedType: Value, UnderlyingType.WrappedType.Datatype: Number { /// Builds a copy of the expression wrapped with the `avg` aggregate /// function. @@ -212,7 +212,7 @@ extension ExpressionType where UnderlyingType : _OptionalType, UnderlyingType.Wr /// - Returns: A copy of the expression wrapped with the `min` aggregate /// function. public var average: Expression { - return Function.avg.wrap(self) + Function.avg.wrap(self) } /// Builds a copy of the expression wrapped with the `sum` aggregate @@ -225,7 +225,7 @@ extension ExpressionType where UnderlyingType : _OptionalType, UnderlyingType.Wr /// - Returns: A copy of the expression wrapped with the `min` aggregate /// function. public var sum: Expression { - return Function.sum.wrap(self) + Function.sum.wrap(self) } /// Builds a copy of the expression wrapped with the `total` aggregate @@ -238,7 +238,7 @@ extension ExpressionType where UnderlyingType : _OptionalType, UnderlyingType.Wr /// - Returns: A copy of the expression wrapped with the `min` aggregate /// function. public var total: Expression { - return Function.total.wrap(self) + Function.total.wrap(self) } } @@ -246,7 +246,7 @@ extension ExpressionType where UnderlyingType : _OptionalType, UnderlyingType.Wr extension ExpressionType where UnderlyingType == Int { static func count(_ star: Star) -> Expression { - return Function.count.wrap(star(nil, nil)) + Function.count.wrap(star(nil, nil)) } } @@ -260,5 +260,5 @@ extension ExpressionType where UnderlyingType == Int { /// - Returns: An expression returning `count(*)` (when called with the `*` /// function literal). public func count(_ star: Star) -> Expression { - return Expression.count(star) + Expression.count(star) } diff --git a/Sources/SQLite/Typed/Coding.swift b/Sources/SQLite/Typed/Coding.swift index 7044bc37..3dc1e6cf 100644 --- a/Sources/SQLite/Typed/Coding.swift +++ b/Sources/SQLite/Typed/Coding.swift @@ -39,12 +39,12 @@ extension QueryType { /// - otherSetters: Any other setters to include in the insert /// /// - Returns: An `INSERT` statement for the encodable object - public func insert(_ encodable: Encodable, userInfo: [CodingUserInfoKey:Any] = [:], otherSetters: [Setter] = []) throws -> Insert { + public func insert(_ encodable: Encodable, userInfo: [CodingUserInfoKey: Any] = [:], otherSetters: [Setter] = []) throws -> Insert { let encoder = SQLiteEncoder(userInfo: userInfo) try encodable.encode(to: encoder) return self.insert(encoder.setters + otherSetters) } - + /// Creates an `INSERT` statement by encoding the given object /// This method converts any custom nested types to JSON data and does not handle any sort /// of object relationships. If you want to support relationships between objects you will @@ -63,7 +63,8 @@ extension QueryType { /// - otherSetters: Any other setters to include in the insert /// /// - Returns: An `INSERT` statement fort the encodable object - public func insert(or onConflict: OnConflict, encodable: Encodable, userInfo: [CodingUserInfoKey:Any] = [:], otherSetters: [Setter] = []) throws -> Insert { + public func insert(or onConflict: OnConflict, encodable: Encodable, userInfo: [CodingUserInfoKey: Any] = [:], + otherSetters: [Setter] = []) throws -> Insert { let encoder = SQLiteEncoder(userInfo: userInfo) try encodable.encode(to: encoder) return self.insert(or: onConflict, encoder.setters + otherSetters) @@ -83,7 +84,8 @@ extension QueryType { /// - otherSetters: Any other setters to include in the inserts, per row/object. /// /// - Returns: An `INSERT` statement for the encodable objects - public func insertMany(_ encodables: [Encodable], userInfo: [CodingUserInfoKey:Any] = [:], otherSetters: [Setter] = []) throws -> Insert { + public func insertMany(_ encodables: [Encodable], userInfo: [CodingUserInfoKey: Any] = [:], + otherSetters: [Setter] = []) throws -> Insert { let combinedSetters = try encodables.map { encodable -> [Setter] in let encoder = SQLiteEncoder(userInfo: userInfo) try encodable.encode(to: encoder) @@ -108,7 +110,8 @@ extension QueryType { /// - onConflictOf: The column that if conflicts should trigger an update instead of insert. /// /// - Returns: An `INSERT` statement fort the encodable object - public func upsert(_ encodable: Encodable, userInfo: [CodingUserInfoKey:Any] = [:], otherSetters: [Setter] = [], onConflictOf conflicting: Expressible) throws -> Insert { + public func upsert(_ encodable: Encodable, userInfo: [CodingUserInfoKey: Any] = [:], + otherSetters: [Setter] = [], onConflictOf conflicting: Expressible) throws -> Insert { let encoder = SQLiteEncoder(userInfo: userInfo) try encodable.encode(to: encoder) return self.upsert(encoder.setters + otherSetters, onConflictOf: conflicting) @@ -128,7 +131,8 @@ extension QueryType { /// - otherSetters: Any other setters to include in the insert /// /// - Returns: An `UPDATE` statement fort the encodable object - public func update(_ encodable: Encodable, userInfo: [CodingUserInfoKey:Any] = [:], otherSetters: [Setter] = []) throws -> Update { + public func update(_ encodable: Encodable, userInfo: [CodingUserInfoKey: Any] = [:], + otherSetters: [Setter] = []) throws -> Update { let encoder = SQLiteEncoder(userInfo: userInfo) try encodable.encode(to: encoder) return self.update(encoder.setters + otherSetters) @@ -145,17 +149,18 @@ extension Row { /// /// - Returns: a decoded object from this row public func decode(userInfo: [CodingUserInfoKey: Any] = [:]) throws -> V { - return try V(from: self.decoder(userInfo: userInfo)) + try V(from: decoder(userInfo: userInfo)) } public func decoder(userInfo: [CodingUserInfoKey: Any] = [:]) -> Decoder { - return SQLiteDecoder(row: self, userInfo: userInfo) + SQLiteDecoder(row: self, userInfo: userInfo) } } /// Generates a list of settings for an Encodable object -fileprivate class SQLiteEncoder: Encoder { +private class SQLiteEncoder: Encoder { class SQLiteKeyedEncodingContainer: KeyedEncodingContainerProtocol { + // swiftlint:disable nesting typealias Key = MyKey let encoder: SQLiteEncoder @@ -174,80 +179,87 @@ fileprivate class SQLiteEncoder: Encoder { } func encodeNil(forKey key: SQLiteEncoder.SQLiteKeyedEncodingContainer.Key) throws { - self.encoder.setters.append(Expression(key.stringValue) <- nil) + encoder.setters.append(Expression(key.stringValue) <- nil) } func encode(_ value: Int, forKey key: SQLiteEncoder.SQLiteKeyedEncodingContainer.Key) throws { - self.encoder.setters.append(Expression(key.stringValue) <- value) + encoder.setters.append(Expression(key.stringValue) <- value) } func encode(_ value: Bool, forKey key: Key) throws { - self.encoder.setters.append(Expression(key.stringValue) <- value) + encoder.setters.append(Expression(key.stringValue) <- value) } func encode(_ value: Float, forKey key: Key) throws { - self.encoder.setters.append(Expression(key.stringValue) <- Double(value)) + encoder.setters.append(Expression(key.stringValue) <- Double(value)) } func encode(_ value: Double, forKey key: Key) throws { - self.encoder.setters.append(Expression(key.stringValue) <- value) + encoder.setters.append(Expression(key.stringValue) <- value) } func encode(_ value: String, forKey key: Key) throws { - self.encoder.setters.append(Expression(key.stringValue) <- value) + encoder.setters.append(Expression(key.stringValue) <- value) } - func encode(_ value: T, forKey key: Key) throws where T : Swift.Encodable { + func encode(_ value: T, forKey key: Key) throws where T: Swift.Encodable { if let data = value as? Data { - self.encoder.setters.append(Expression(key.stringValue) <- data) - } - else if let date = value as? Date { - self.encoder.setters.append(Expression(key.stringValue) <- date.datatypeValue) - } - else { + encoder.setters.append(Expression(key.stringValue) <- data) + } else if let date = value as? Date { + encoder.setters.append(Expression(key.stringValue) <- date.datatypeValue) + } else { let encoded = try JSONEncoder().encode(value) let string = String(data: encoded, encoding: .utf8) - self.encoder.setters.append(Expression(key.stringValue) <- string) + encoder.setters.append(Expression(key.stringValue) <- string) } } func encode(_ value: Int8, forKey key: Key) throws { - throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: self.codingPath, debugDescription: "encoding an Int8 is not supported")) + throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: codingPath, + debugDescription: "encoding an Int8 is not supported")) } func encode(_ value: Int16, forKey key: Key) throws { - throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: self.codingPath, debugDescription: "encoding an Int16 is not supported")) + throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: codingPath, + debugDescription: "encoding an Int16 is not supported")) } func encode(_ value: Int32, forKey key: Key) throws { - throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: self.codingPath, debugDescription: "encoding an Int32 is not supported")) + throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: codingPath, + debugDescription: "encoding an Int32 is not supported")) } func encode(_ value: Int64, forKey key: Key) throws { - self.encoder.setters.append(Expression(key.stringValue) <- value) + encoder.setters.append(Expression(key.stringValue) <- value) } func encode(_ value: UInt, forKey key: Key) throws { - throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: self.codingPath, debugDescription: "encoding an UInt is not supported")) + throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: codingPath, + debugDescription: "encoding an UInt is not supported")) } func encode(_ value: UInt8, forKey key: Key) throws { - throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: self.codingPath, debugDescription: "encoding an UInt8 is not supported")) + throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: codingPath, + debugDescription: "encoding an UInt8 is not supported")) } func encode(_ value: UInt16, forKey key: Key) throws { - throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: self.codingPath, debugDescription: "encoding an UInt16 is not supported")) + throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: codingPath, + debugDescription: "encoding an UInt16 is not supported")) } func encode(_ value: UInt32, forKey key: Key) throws { - throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: self.codingPath, debugDescription: "encoding an UInt32 is not supported")) + throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: codingPath, + debugDescription: "encoding an UInt32 is not supported")) } func encode(_ value: UInt64, forKey key: Key) throws { - throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: self.codingPath, debugDescription: "encoding an UInt64 is not supported")) + throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: codingPath, + debugDescription: "encoding an UInt64 is not supported")) } - func nestedContainer(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer where NestedKey : CodingKey { + func nestedContainer(keyedBy keyType: NestedKey.Type, forKey key: Key) + -> KeyedEncodingContainer where NestedKey: CodingKey { fatalError("encoding a nested container is not supported") } @@ -272,13 +284,13 @@ fileprivate class SQLiteEncoder: Encoder { fatalError("not supported") } - func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key : CodingKey { - return KeyedEncodingContainer(SQLiteKeyedEncodingContainer(encoder: self)) + func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key: CodingKey { + KeyedEncodingContainer(SQLiteKeyedEncodingContainer(encoder: self)) } } -fileprivate class SQLiteDecoder : Decoder { - class SQLiteKeyedDecodingContainer : KeyedDecodingContainerProtocol { +private class SQLiteDecoder: Decoder { + class SQLiteKeyedDecodingContainer: KeyedDecodingContainerProtocol { typealias Key = MyKey let codingPath: [CodingKey] = [] @@ -289,106 +301,122 @@ fileprivate class SQLiteDecoder : Decoder { } var allKeys: [Key] { - return self.row.columnNames.keys.compactMap({Key(stringValue: $0)}) + row.columnNames.keys.compactMap({ Key(stringValue: $0) }) } func contains(_ key: Key) -> Bool { - return self.row.hasValue(for: key.stringValue) + row.hasValue(for: key.stringValue) } func decodeNil(forKey key: Key) throws -> Bool { - return !self.contains(key) + !contains(key) } func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { - return try self.row.get(Expression(key.stringValue)) + try row.get(Expression(key.stringValue)) } func decode(_ type: Int.Type, forKey key: Key) throws -> Int { - return try self.row.get(Expression(key.stringValue)) + try row.get(Expression(key.stringValue)) } func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { - throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding an Int8 is not supported")) + throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, + debugDescription: "decoding an Int8 is not supported")) } func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { - throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding an Int16 is not supported")) + throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, + debugDescription: "decoding an Int16 is not supported")) } func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { - throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding an Int32 is not supported")) + throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, + debugDescription: "decoding an Int32 is not supported")) } func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { - return try self.row.get(Expression(key.stringValue)) + try row.get(Expression(key.stringValue)) } func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { - throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding an UInt is not supported")) + throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, + debugDescription: "decoding an UInt is not supported")) } func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { - throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding an UInt8 is not supported")) + throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, + debugDescription: "decoding an UInt8 is not supported")) } func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { - throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding an UInt16 is not supported")) + throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, + debugDescription: "decoding an UInt16 is not supported")) } func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { - throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding an UInt32 is not supported")) + throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, + debugDescription: "decoding an UInt32 is not supported")) } func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { - throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding an UInt64 is not supported")) + throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, + debugDescription: "decoding an UInt64 is not supported")) } func decode(_ type: Float.Type, forKey key: Key) throws -> Float { - return Float(try self.row.get(Expression(key.stringValue))) + Float(try row.get(Expression(key.stringValue))) } func decode(_ type: Double.Type, forKey key: Key) throws -> Double { - return try self.row.get(Expression(key.stringValue)) + try row.get(Expression(key.stringValue)) } func decode(_ type: String.Type, forKey key: Key) throws -> String { - return try self.row.get(Expression(key.stringValue)) + try row.get(Expression(key.stringValue)) } func decode(_ type: T.Type, forKey key: Key) throws -> T where T: Swift.Decodable { + // swiftlint:disable force_cast if type == Data.self { - let data = try self.row.get(Expression(key.stringValue)) + let data = try row.get(Expression(key.stringValue)) return data as! T - } - else if type == Date.self { - let date = try self.row.get(Expression(key.stringValue)) + } else if type == Date.self { + let date = try row.get(Expression(key.stringValue)) return date as! T } - guard let JSONString = try self.row.get(Expression(key.stringValue)) else { - throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "an unsupported type was found")) + // swiftlint:enable force_cast + guard let JSONString = try row.get(Expression(key.stringValue)) else { + throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, + debugDescription: "an unsupported type was found")) } guard let data = JSONString.data(using: .utf8) else { - throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "invalid utf8 data found")) + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, + debugDescription: "invalid utf8 data found")) } return try JSONDecoder().decode(type, from: data) } - func nestedContainer(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer where NestedKey : CodingKey { - throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding nested containers is not supported")) + func nestedContainer(keyedBy type: NestedKey.Type, forKey key: Key) throws + -> KeyedDecodingContainer where NestedKey: CodingKey { + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, + debugDescription: "decoding nested containers is not supported")) } func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { - throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding unkeyed containers is not supported")) + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, + debugDescription: "decoding unkeyed containers is not supported")) } func superDecoder() throws -> Swift.Decoder { - throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding super encoders containers is not supported")) + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, + debugDescription: "decoding super encoders containers is not supported")) } func superDecoder(forKey key: Key) throws -> Swift.Decoder { - throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding super decoders is not supported")) + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, + debugDescription: "decoding super decoders is not supported")) } } @@ -401,16 +429,17 @@ fileprivate class SQLiteDecoder : Decoder { self.userInfo = userInfo } - func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer where Key : CodingKey { - return KeyedDecodingContainer(SQLiteKeyedDecodingContainer(row: self.row)) + func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer where Key: CodingKey { + KeyedDecodingContainer(SQLiteKeyedDecodingContainer(row: row)) } func unkeyedContainer() throws -> UnkeyedDecodingContainer { - throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding an unkeyed container is not supported")) + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, + debugDescription: "decoding an unkeyed container is not supported")) } func singleValueContainer() throws -> SingleValueDecodingContainer { - throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding a single value container is not supported")) + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, + debugDescription: "decoding a single value container is not supported")) } } - diff --git a/Sources/SQLite/Typed/Collation.swift b/Sources/SQLite/Typed/Collation.swift index e2ff9d10..fec66129 100644 --- a/Sources/SQLite/Typed/Collation.swift +++ b/Sources/SQLite/Typed/Collation.swift @@ -43,17 +43,17 @@ public enum Collation { } -extension Collation : Expressible { +extension Collation: Expressible { public var expression: Expression { - return Expression(literal: description) + Expression(literal: description) } } -extension Collation : CustomStringConvertible { +extension Collation: CustomStringConvertible { - public var description : String { + public var description: String { switch self { case .binary: return "BINARY" diff --git a/Sources/SQLite/Typed/CoreFunctions.swift b/Sources/SQLite/Typed/CoreFunctions.swift index 068dcf02..dc6a1044 100644 --- a/Sources/SQLite/Typed/CoreFunctions.swift +++ b/Sources/SQLite/Typed/CoreFunctions.swift @@ -21,7 +21,6 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // - import Foundation private enum Function: String { @@ -45,21 +44,21 @@ private enum Function: String { case regexp = "REGEXP" case collate = "COLLATE" case ifnull - + func infix(_ lhs: Expressible, _ rhs: Expressible, wrap: Bool = true) -> Expression { - return self.rawValue.infix(lhs, rhs, wrap: wrap) + self.rawValue.infix(lhs, rhs, wrap: wrap) } - + func wrap(_ expression: Expressible) -> Expression { - return self.rawValue.wrap(expression) + self.rawValue.wrap(expression) } - + func wrap(_ expressions: [Expressible]) -> Expression { - return self.rawValue.wrap(", ".join(expressions)) + self.rawValue.wrap(", ".join(expressions)) } } -extension ExpressionType where UnderlyingType : Number { +extension ExpressionType where UnderlyingType: Number { /// Builds a copy of the expression wrapped with the `abs` function. /// @@ -68,13 +67,13 @@ extension ExpressionType where UnderlyingType : Number { /// // abs("x") /// /// - Returns: A copy of the expression wrapped with the `abs` function. - public var absoluteValue : Expression { - return Function.abs.wrap(self) + public var absoluteValue: Expression { + Function.abs.wrap(self) } } -extension ExpressionType where UnderlyingType : _OptionalType, UnderlyingType.WrappedType : Number { +extension ExpressionType where UnderlyingType: _OptionalType, UnderlyingType.WrappedType: Number { /// Builds a copy of the expression wrapped with the `abs` function. /// @@ -83,8 +82,8 @@ extension ExpressionType where UnderlyingType : _OptionalType, UnderlyingType.Wr /// // abs("x") /// /// - Returns: A copy of the expression wrapped with the `abs` function. - public var absoluteValue : Expression { - return Function.abs.wrap(self) + public var absoluteValue: Expression { + Function.abs.wrap(self) } } @@ -129,7 +128,7 @@ extension ExpressionType where UnderlyingType == Double? { } -extension ExpressionType where UnderlyingType : Value, UnderlyingType.Datatype == Int64 { +extension ExpressionType where UnderlyingType: Value, UnderlyingType.Datatype == Int64 { /// Builds an expression representing the `random` function. /// @@ -138,7 +137,7 @@ extension ExpressionType where UnderlyingType : Value, UnderlyingType.Datatype = /// /// - Returns: An expression calling the `random` function. public static func random() -> Expression { - return Function.random.wrap([]) + Function.random.wrap([]) } } @@ -154,7 +153,7 @@ extension ExpressionType where UnderlyingType == Data { /// /// - Returns: An expression calling the `randomblob` function. public static func random(_ length: Int) -> Expression { - return Function.randomblob.wrap([]) + Function.randomblob.wrap([]) } /// Builds an expression representing the `zeroblob` function. @@ -166,7 +165,7 @@ extension ExpressionType where UnderlyingType == Data { /// /// - Returns: An expression calling the `zeroblob` function. public static func allZeros(_ length: Int) -> Expression { - return Function.zeroblob.wrap([]) + Function.zeroblob.wrap([]) } /// Builds a copy of the expression wrapped with the `length` function. @@ -177,7 +176,7 @@ extension ExpressionType where UnderlyingType == Data { /// /// - Returns: A copy of the expression wrapped with the `length` function. public var length: Expression { - return Function.length.wrap(self) + Function.length.wrap(self) } } @@ -192,7 +191,7 @@ extension ExpressionType where UnderlyingType == Data? { /// /// - Returns: A copy of the expression wrapped with the `length` function. public var length: Expression { - return Function.length.wrap(self) + Function.length.wrap(self) } } @@ -207,7 +206,7 @@ extension ExpressionType where UnderlyingType == String { /// /// - Returns: A copy of the expression wrapped with the `length` function. public var length: Expression { - return Function.length.wrap(self) + Function.length.wrap(self) } /// Builds a copy of the expression wrapped with the `lower` function. @@ -218,7 +217,7 @@ extension ExpressionType where UnderlyingType == String { /// /// - Returns: A copy of the expression wrapped with the `lower` function. public var lowercaseString: Expression { - return Function.lower.wrap(self) + Function.lower.wrap(self) } /// Builds a copy of the expression wrapped with the `upper` function. @@ -229,7 +228,7 @@ extension ExpressionType where UnderlyingType == String { /// /// - Returns: A copy of the expression wrapped with the `upper` function. public var uppercaseString: Expression { - return Function.upper.wrap(self) + Function.upper.wrap(self) } /// Builds a copy of the expression appended with a `LIKE` query against the @@ -294,7 +293,7 @@ extension ExpressionType where UnderlyingType == String { /// - Returns: A copy of the expression appended with a `GLOB` query against /// the given pattern. public func glob(_ pattern: String) -> Expression { - return Function.glob.infix(self, pattern) + Function.glob.infix(self, pattern) } /// Builds a copy of the expression appended with a `MATCH` query against @@ -309,7 +308,7 @@ extension ExpressionType where UnderlyingType == String { /// - Returns: A copy of the expression appended with a `MATCH` query /// against the given pattern. public func match(_ pattern: String) -> Expression { - return Function.match.infix(self, pattern) + Function.match.infix(self, pattern) } /// Builds a copy of the expression appended with a `REGEXP` query against @@ -320,7 +319,7 @@ extension ExpressionType where UnderlyingType == String { /// - Returns: A copy of the expression appended with a `REGEXP` query /// against the given pattern. public func regexp(_ pattern: String) -> Expression { - return Function.regexp.infix(self, pattern) + Function.regexp.infix(self, pattern) } /// Builds a copy of the expression appended with a `COLLATE` clause with @@ -335,7 +334,7 @@ extension ExpressionType where UnderlyingType == String { /// - Returns: A copy of the expression appended with a `COLLATE` clause /// with the given sequence. public func collate(_ collation: Collation) -> Expression { - return Function.collate.infix(self, collation) + Function.collate.infix(self, collation) } /// Builds a copy of the expression wrapped with the `ltrim` function. @@ -406,7 +405,7 @@ extension ExpressionType where UnderlyingType == String { /// /// - Returns: A copy of the expression wrapped with the `replace` function. public func replace(_ pattern: String, with replacement: String) -> Expression { - return Function.replace.wrap([self, pattern, replacement]) + Function.replace.wrap([self, pattern, replacement]) } public func substring(_ location: Int, length: Int? = nil) -> Expression { @@ -417,7 +416,7 @@ extension ExpressionType where UnderlyingType == String { } public subscript(range: Range) -> Expression { - return substring(range.lowerBound, length: range.upperBound - range.lowerBound) + substring(range.lowerBound, length: range.upperBound - range.lowerBound) } } @@ -432,7 +431,7 @@ extension ExpressionType where UnderlyingType == String? { /// /// - Returns: A copy of the expression wrapped with the `length` function. public var length: Expression { - return Function.length.wrap(self) + Function.length.wrap(self) } /// Builds a copy of the expression wrapped with the `lower` function. @@ -443,7 +442,7 @@ extension ExpressionType where UnderlyingType == String? { /// /// - Returns: A copy of the expression wrapped with the `lower` function. public var lowercaseString: Expression { - return Function.lower.wrap(self) + Function.lower.wrap(self) } /// Builds a copy of the expression wrapped with the `upper` function. @@ -454,7 +453,7 @@ extension ExpressionType where UnderlyingType == String? { /// /// - Returns: A copy of the expression wrapped with the `upper` function. public var uppercaseString: Expression { - return Function.upper.wrap(self) + Function.upper.wrap(self) } /// Builds a copy of the expression appended with a `LIKE` query against the @@ -481,7 +480,7 @@ extension ExpressionType where UnderlyingType == String? { } return Expression("(\(template) LIKE ? ESCAPE ?)", bindings + [pattern, String(character)]) } - + /// Builds a copy of the expression appended with a `LIKE` query against the /// given pattern. /// @@ -519,7 +518,7 @@ extension ExpressionType where UnderlyingType == String? { /// - Returns: A copy of the expression appended with a `GLOB` query against /// the given pattern. public func glob(_ pattern: String) -> Expression { - return Function.glob.infix(self, pattern) + Function.glob.infix(self, pattern) } /// Builds a copy of the expression appended with a `MATCH` query against @@ -534,7 +533,7 @@ extension ExpressionType where UnderlyingType == String? { /// - Returns: A copy of the expression appended with a `MATCH` query /// against the given pattern. public func match(_ pattern: String) -> Expression { - return Function.match.infix(self, pattern) + Function.match.infix(self, pattern) } /// Builds a copy of the expression appended with a `REGEXP` query against @@ -545,7 +544,7 @@ extension ExpressionType where UnderlyingType == String? { /// - Returns: A copy of the expression appended with a `REGEXP` query /// against the given pattern. public func regexp(_ pattern: String) -> Expression { - return Function.regexp.infix(self, pattern) + Function.regexp.infix(self, pattern) } /// Builds a copy of the expression appended with a `COLLATE` clause with @@ -560,7 +559,7 @@ extension ExpressionType where UnderlyingType == String? { /// - Returns: A copy of the expression appended with a `COLLATE` clause /// with the given sequence. public func collate(_ collation: Collation) -> Expression { - return Function.collate.infix(self, collation) + Function.collate.infix(self, collation) } /// Builds a copy of the expression wrapped with the `ltrim` function. @@ -631,7 +630,7 @@ extension ExpressionType where UnderlyingType == String? { /// /// - Returns: A copy of the expression wrapped with the `replace` function. public func replace(_ pattern: String, with replacement: String) -> Expression { - return Function.replace.wrap([self, pattern, replacement]) + Function.replace.wrap([self, pattern, replacement]) } /// Builds a copy of the expression wrapped with the `substr` function. @@ -666,12 +665,12 @@ extension ExpressionType where UnderlyingType == String? { /// /// - Returns: A copy of the expression wrapped with the `substr` function. public subscript(range: Range) -> Expression { - return substring(range.lowerBound, length: range.upperBound - range.lowerBound) + substring(range.lowerBound, length: range.upperBound - range.lowerBound) } } -extension Collection where Iterator.Element : Value { +extension Collection where Iterator.Element: Value { /// Builds a copy of the expression prepended with an `IN` check against the /// collection. @@ -708,7 +707,7 @@ extension Collection where Iterator.Element : Value { } extension String { - + /// Builds a copy of the expression appended with a `LIKE` query against the /// given pattern. /// @@ -751,8 +750,8 @@ extension String { /// /// - Returns: A copy of the given expressions wrapped with the `ifnull` /// function. -public func ??(optional: Expression, defaultValue: V) -> Expression { - return Function.ifnull.wrap([optional, defaultValue]) +public func ??(optional: Expression, defaultValue: V) -> Expression { + Function.ifnull.wrap([optional, defaultValue]) } /// Builds a copy of the given expressions wrapped with the `ifnull` function. @@ -771,8 +770,8 @@ public func ??(optional: Expression, defaultValue: V) -> Expressi /// /// - Returns: A copy of the given expressions wrapped with the `ifnull` /// function. -public func ??(optional: Expression, defaultValue: Expression) -> Expression { - return Function.ifnull.wrap([optional, defaultValue]) +public func ??(optional: Expression, defaultValue: Expression) -> Expression { + Function.ifnull.wrap([optional, defaultValue]) } /// Builds a copy of the given expressions wrapped with the `ifnull` function. @@ -791,6 +790,6 @@ public func ??(optional: Expression, defaultValue: Expression) /// /// - Returns: A copy of the given expressions wrapped with the `ifnull` /// function. -public func ??(optional: Expression, defaultValue: Expression) -> Expression { - return Function.ifnull.wrap([optional, defaultValue]) +public func ??(optional: Expression, defaultValue: Expression) -> Expression { + Function.ifnull.wrap([optional, defaultValue]) } diff --git a/Sources/SQLite/Typed/CustomFunctions.swift b/Sources/SQLite/Typed/CustomFunctions.swift index 4d3e69ee..c38113d1 100644 --- a/Sources/SQLite/Typed/CustomFunctions.swift +++ b/Sources/SQLite/Typed/CustomFunctions.swift @@ -39,83 +39,107 @@ public extension Connection { /// The assigned types must be explicit. /// /// - Returns: A closure returning an SQL expression to call the function. - func createFunction(_ function: String, deterministic: Bool = false, _ block: @escaping () -> Z) throws -> (() -> Expression) { + func createFunction(_ function: String, deterministic: Bool = false, _ block: @escaping () -> Z) throws + -> () -> Expression { let fn = try createFunction(function, 0, deterministic) { _ in block() } return { fn([]) } } - func createFunction(_ function: String, deterministic: Bool = false, _ block: @escaping () -> Z?) throws -> (() -> Expression) { + func createFunction(_ function: String, deterministic: Bool = false, _ block: @escaping () -> Z?) throws + -> () -> Expression { let fn = try createFunction(function, 0, deterministic) { _ in block() } return { fn([]) } } // MARK: - - func createFunction(_ function: String, deterministic: Bool = false, _ block: @escaping (A) -> Z) throws -> ((Expression) -> Expression) { + func createFunction(_ function: String, deterministic: Bool = false, _ block: @escaping (A) -> Z) throws + -> (Expression) -> Expression { let fn = try createFunction(function, 1, deterministic) { args in block(value(args[0])) } return { arg in fn([arg]) } } - func createFunction(_ function: String, deterministic: Bool = false, _ block: @escaping (A?) -> Z) throws -> ((Expression) -> Expression) { + func createFunction(_ function: String, deterministic: Bool = false, _ block: @escaping (A?) -> Z) throws + -> (Expression) -> Expression { let fn = try createFunction(function, 1, deterministic) { args in block(args[0].map(value)) } return { arg in fn([arg]) } } - func createFunction(_ function: String, deterministic: Bool = false, _ block: @escaping (A) -> Z?) throws -> ((Expression) -> Expression) { + func createFunction(_ function: String, deterministic: Bool = false, _ block: @escaping (A) -> Z?) throws + -> (Expression) -> Expression { let fn = try createFunction(function, 1, deterministic) { args in block(value(args[0])) } return { arg in fn([arg]) } } - func createFunction(_ function: String, deterministic: Bool = false, _ block: @escaping (A?) -> Z?) throws -> ((Expression) -> Expression) { + func createFunction(_ function: String, deterministic: Bool = false, _ block: @escaping (A?) -> Z?) throws + -> (Expression) -> Expression { let fn = try createFunction(function, 1, deterministic) { args in block(args[0].map(value)) } return { arg in fn([arg]) } } // MARK: - - func createFunction(_ function: String, deterministic: Bool = false, _ block: @escaping (A, B) -> Z) throws -> (Expression, Expression) -> Expression { + func createFunction(_ function: String, deterministic: Bool = false, + _ block: @escaping (A, B) -> Z) throws -> (Expression, Expression) + -> Expression { let fn = try createFunction(function, 2, deterministic) { args in block(value(args[0]), value(args[1])) } return { a, b in fn([a, b]) } } - func createFunction(_ function: String, deterministic: Bool = false, _ block: @escaping (A?, B) -> Z) throws -> (Expression, Expression) -> Expression { + func createFunction(_ function: String, deterministic: Bool = false, + _ block: @escaping (A?, B) -> Z) throws + -> (Expression, Expression) -> Expression { let fn = try createFunction(function, 2, deterministic) { args in block(args[0].map(value), value(args[1])) } return { a, b in fn([a, b]) } } - func createFunction(_ function: String, deterministic: Bool = false, _ block: @escaping (A, B?) -> Z) throws -> (Expression, Expression) -> Expression { + func createFunction(_ function: String, deterministic: Bool = false, + _ block: @escaping (A, B?) -> Z) throws -> + (Expression, Expression) -> Expression { let fn = try createFunction(function, 2, deterministic) { args in block(value(args[0]), args[1].map(value)) } return { a, b in fn([a, b]) } } - func createFunction(_ function: String, deterministic: Bool = false, _ block: @escaping (A, B) -> Z?) throws -> (Expression, Expression) -> Expression { + func createFunction(_ function: String, deterministic: Bool = false, + _ block: @escaping (A, B) -> Z?) throws + -> (Expression, Expression) -> Expression { let fn = try createFunction(function, 2, deterministic) { args in block(value(args[0]), value(args[1])) } return { a, b in fn([a, b]) } } - func createFunction(_ function: String, deterministic: Bool = false, _ block: @escaping (A?, B?) -> Z) throws -> (Expression, Expression) -> Expression { + func createFunction(_ function: String, deterministic: Bool = false, + _ block: @escaping (A?, B?) -> Z) throws + -> (Expression, Expression) -> Expression { let fn = try createFunction(function, 2, deterministic) { args in block(args[0].map(value), args[1].map(value)) } return { a, b in fn([a, b]) } } - func createFunction(_ function: String, deterministic: Bool = false, _ block: @escaping (A?, B) -> Z?) throws -> (Expression, Expression) -> Expression { + func createFunction(_ function: String, deterministic: Bool = false, + _ block: @escaping (A?, B) -> Z?) throws + -> (Expression, Expression) -> Expression { let fn = try createFunction(function, 2, deterministic) { args in block(args[0].map(value), value(args[1])) } return { a, b in fn([a, b]) } } - func createFunction(_ function: String, deterministic: Bool = false, _ block: @escaping (A, B?) -> Z?) throws -> (Expression, Expression) -> Expression { + func createFunction(_ function: String, deterministic: Bool = false, + _ block: @escaping (A, B?) -> Z?) throws + -> (Expression, Expression) -> Expression { let fn = try createFunction(function, 2, deterministic) { args in block(value(args[0]), args[1].map(value)) } return { a, b in fn([a, b]) } } - func createFunction(_ function: String, deterministic: Bool = false, _ block: @escaping (A?, B?) -> Z?) throws -> (Expression, Expression) -> Expression { + func createFunction(_ function: String, deterministic: Bool = false, + _ block: @escaping (A?, B?) -> Z?) throws + -> (Expression, Expression) -> Expression { let fn = try createFunction(function, 2, deterministic) { args in block(args[0].map(value), args[1].map(value)) } return { a, b in fn([a, b]) } } // MARK: - - fileprivate func createFunction(_ function: String, _ argumentCount: UInt, _ deterministic: Bool, _ block: @escaping ([Binding?]) -> Z) throws -> (([Expressible]) -> Expression) { + fileprivate func createFunction(_ function: String, _ argumentCount: UInt, _ deterministic: Bool, + _ block: @escaping ([Binding?]) -> Z) throws + -> ([Expressible]) -> Expression { createFunction(function, argumentCount: argumentCount, deterministic: deterministic) { arguments in block(arguments).datatypeValue } @@ -124,7 +148,9 @@ public extension Connection { } } - fileprivate func createFunction(_ function: String, _ argumentCount: UInt, _ deterministic: Bool, _ block: @escaping ([Binding?]) -> Z?) throws -> (([Expressible]) -> Expression) { + fileprivate func createFunction(_ function: String, _ argumentCount: UInt, _ deterministic: Bool, + _ block: @escaping ([Binding?]) -> Z?) throws + -> ([Expressible]) -> Expression { createFunction(function, argumentCount: argumentCount, deterministic: deterministic) { arguments in block(arguments)?.datatypeValue } @@ -134,8 +160,8 @@ public extension Connection { } // MARK: - - - public func createAggregation( + + func createAggregation( _ aggregate: String, argumentCount: UInt? = nil, deterministic: Bool = false, @@ -143,32 +169,32 @@ public extension Connection { reduce: @escaping (T, [Binding?]) -> T, result: @escaping (T) -> Binding? ) { - - let step: ([Binding?], UnsafeMutablePointer) -> () = { (bindings, ptr) in - let p = ptr.pointee.assumingMemoryBound(to: T.self) - let current = Unmanaged.fromOpaque(p).takeRetainedValue() + + let step: ([Binding?], UnsafeMutablePointer) -> Void = { (bindings, ptr) in + let pointer = ptr.pointee.assumingMemoryBound(to: T.self) + let current = Unmanaged.fromOpaque(pointer).takeRetainedValue() let next = reduce(current, bindings) ptr.pointee = Unmanaged.passRetained(next).toOpaque() } - + let final: (UnsafeMutablePointer) -> Binding? = { (ptr) in - let p = ptr.pointee.assumingMemoryBound(to: T.self) - let obj = Unmanaged.fromOpaque(p).takeRetainedValue() + let pointer = ptr.pointee.assumingMemoryBound(to: T.self) + let obj = Unmanaged.fromOpaque(pointer).takeRetainedValue() let value = result(obj) ptr.deallocate() return value } - + let state: () -> UnsafeMutablePointer = { - let p = UnsafeMutablePointer.allocate(capacity: 1) - p.pointee = Unmanaged.passRetained(initialValue).toOpaque() - return p + let pointer = UnsafeMutablePointer.allocate(capacity: 1) + pointer.pointee = Unmanaged.passRetained(initialValue).toOpaque() + return pointer } - + createAggregation(aggregate, step: step, final: final, state: state) } - - public func createAggregation( + + func createAggregation( _ aggregate: String, argumentCount: UInt? = nil, deterministic: Bool = false, @@ -176,25 +202,25 @@ public extension Connection { reduce: @escaping (T, [Binding?]) -> T, result: @escaping (T) -> Binding? ) { - - let step: ([Binding?], UnsafeMutablePointer) -> () = { (bindings, p) in - let current = p.pointee + + let step: ([Binding?], UnsafeMutablePointer) -> Void = { (bindings, pointer) in + let current = pointer.pointee let next = reduce(current, bindings) - p.pointee = next + pointer.pointee = next } - - let final: (UnsafeMutablePointer) -> Binding? = { (p) in - let v = result(p.pointee) - p.deallocate() - return v + + let final: (UnsafeMutablePointer) -> Binding? = { pointer in + let value = result(pointer.pointee) + pointer.deallocate() + return value } - + let state: () -> UnsafeMutablePointer = { - let p = UnsafeMutablePointer.allocate(capacity: 1) - p.pointee = initialValue - return p + let pointer = UnsafeMutablePointer.allocate(capacity: 1) + pointer.initialize(to: initialValue) + return pointer } - + createAggregation(aggregate, step: step, final: final, state: state) } diff --git a/Sources/SQLite/Typed/DateAndTimeFunctions.swift b/Sources/SQLite/Typed/DateAndTimeFunctions.swift index 0b9a497f..b4382194 100644 --- a/Sources/SQLite/Typed/DateAndTimeFunctions.swift +++ b/Sources/SQLite/Typed/DateAndTimeFunctions.swift @@ -32,23 +32,23 @@ import Foundation public class DateFunctions { /// The date() function returns the date in this format: YYYY-MM-DD. public static func date(_ timestring: String, _ modifiers: String...) -> Expression { - return timefunction("date", timestring: timestring, modifiers: modifiers) + timefunction("date", timestring: timestring, modifiers: modifiers) } /// The time() function returns the time as HH:MM:SS. public static func time(_ timestring: String, _ modifiers: String...) -> Expression { - return timefunction("time", timestring: timestring, modifiers: modifiers) + timefunction("time", timestring: timestring, modifiers: modifiers) } /// The datetime() function returns "YYYY-MM-DD HH:MM:SS". public static func datetime(_ timestring: String, _ modifiers: String...) -> Expression { - return timefunction("datetime", timestring: timestring, modifiers: modifiers) + timefunction("datetime", timestring: timestring, modifiers: modifiers) } /// The julianday() function returns the Julian day - /// the number of days since noon in Greenwich on November 24, 4714 B.C. public static func julianday(_ timestring: String, _ modifiers: String...) -> Expression { - return timefunction("julianday", timestring: timestring, modifiers: modifiers) + timefunction("julianday", timestring: timestring, modifiers: modifiers) } /// The strftime() routine returns the date formatted according to the format string specified as the first argument. @@ -71,36 +71,36 @@ public class DateFunctions { extension Date { public var date: Expression { - return DateFunctions.date(dateFormatter.string(from: self)) + DateFunctions.date(dateFormatter.string(from: self)) } public var time: Expression { - return DateFunctions.time(dateFormatter.string(from: self)) + DateFunctions.time(dateFormatter.string(from: self)) } public var datetime: Expression { - return DateFunctions.datetime(dateFormatter.string(from: self)) + DateFunctions.datetime(dateFormatter.string(from: self)) } public var julianday: Expression { - return DateFunctions.julianday(dateFormatter.string(from: self)) + DateFunctions.julianday(dateFormatter.string(from: self)) } } extension Expression where UnderlyingType == Date { public var date: Expression { - return Expression("date(\(template))", bindings) + Expression("date(\(template))", bindings) } public var time: Expression { - return Expression("time(\(template))", bindings) + Expression("time(\(template))", bindings) } public var datetime: Expression { - return Expression("datetime(\(template))", bindings) + Expression("datetime(\(template))", bindings) } public var julianday: Expression { - return Expression("julianday(\(template))", bindings) + Expression("julianday(\(template))", bindings) } } diff --git a/Sources/SQLite/Typed/Expression.swift b/Sources/SQLite/Typed/Expression.swift index 76ba04c4..95cdd3b9 100644 --- a/Sources/SQLite/Typed/Expression.swift +++ b/Sources/SQLite/Typed/Expression.swift @@ -22,7 +22,7 @@ // THE SOFTWARE. // -public protocol ExpressionType : Expressible { // extensions cannot have inheritance clauses +public protocol ExpressionType: Expressible { // extensions cannot have inheritance clauses associatedtype UnderlyingType = Void @@ -43,14 +43,14 @@ extension ExpressionType { self.init(literal: identifier.quote()) } - public init(_ expression: U) { + public init(_ expression: U) { self.init(expression.template, expression.bindings) } } /// An `Expression` represents a raw SQL fragment and any associated bindings. -public struct Expression : ExpressionType { +public struct Expression: ExpressionType { public typealias UnderlyingType = Datatype @@ -79,7 +79,7 @@ extension Expressible { var idx = 0 return expressed.template.reduce("") { template, character in let transcoded: String - + if character == "?" { transcoded = transcode(expressed.bindings[idx]) idx += 1 @@ -95,20 +95,20 @@ extension Expressible { extension ExpressionType { public var expression: Expression { - return Expression(template, bindings) + Expression(template, bindings) } public var asc: Expressible { - return " ".join([self, Expression(literal: "ASC")]) + " ".join([self, Expression(literal: "ASC")]) } public var desc: Expressible { - return " ".join([self, Expression(literal: "DESC")]) + " ".join([self, Expression(literal: "DESC")]) } } -extension ExpressionType where UnderlyingType : Value { +extension ExpressionType where UnderlyingType: Value { public init(value: UnderlyingType) { self.init("?", [value.datatypeValue]) @@ -116,10 +116,10 @@ extension ExpressionType where UnderlyingType : Value { } -extension ExpressionType where UnderlyingType : _OptionalType, UnderlyingType.WrappedType : Value { +extension ExpressionType where UnderlyingType: _OptionalType, UnderlyingType.WrappedType: Value { public static var null: Self { - return self.init(value: nil) + self.init(value: nil) } public init(value: UnderlyingType.WrappedType?) { @@ -131,7 +131,7 @@ extension ExpressionType where UnderlyingType : _OptionalType, UnderlyingType.Wr extension Value { public var expression: Expression { - return Expression(value: self).expression + Expression(value: self).expression } } @@ -139,9 +139,9 @@ extension Value { public let rowid = Expression("ROWID") public func cast(_ expression: Expression) -> Expression { - return Expression("CAST (\(expression.template) AS \(U.declaredDatatype))", expression.bindings) + Expression("CAST (\(expression.template) AS \(U.declaredDatatype))", expression.bindings) } public func cast(_ expression: Expression) -> Expression { - return Expression("CAST (\(expression.template) AS \(U.declaredDatatype))", expression.bindings) + Expression("CAST (\(expression.template) AS \(U.declaredDatatype))", expression.bindings) } diff --git a/Sources/SQLite/Typed/Operators.swift b/Sources/SQLite/Typed/Operators.swift index 954a4af4..5ffbbceb 100644 --- a/Sources/SQLite/Typed/Operators.swift +++ b/Sources/SQLite/Typed/Operators.swift @@ -45,628 +45,630 @@ private enum Operator: String { case gte = ">=" case lte = "<=" case concatenate = "||" - + func infix(_ lhs: Expressible, _ rhs: Expressible, wrap: Bool = true) -> Expression { - return self.rawValue.infix(lhs, rhs, wrap: wrap) + self.rawValue.infix(lhs, rhs, wrap: wrap) } - + func wrap(_ expression: Expressible) -> Expression { - return self.rawValue.wrap(expression) + self.rawValue.wrap(expression) } } public func +(lhs: Expression, rhs: Expression) -> Expression { - return Operator.concatenate.infix(lhs, rhs) + Operator.concatenate.infix(lhs, rhs) } public func +(lhs: Expression, rhs: Expression) -> Expression { - return Operator.concatenate.infix(lhs, rhs) + Operator.concatenate.infix(lhs, rhs) } public func +(lhs: Expression, rhs: Expression) -> Expression { - return Operator.concatenate.infix(lhs, rhs) + Operator.concatenate.infix(lhs, rhs) } public func +(lhs: Expression, rhs: Expression) -> Expression { - return Operator.concatenate.infix(lhs, rhs) + Operator.concatenate.infix(lhs, rhs) } public func +(lhs: Expression, rhs: String) -> Expression { - return Operator.concatenate.infix(lhs, rhs) + Operator.concatenate.infix(lhs, rhs) } public func +(lhs: Expression, rhs: String) -> Expression { - return Operator.concatenate.infix(lhs, rhs) + Operator.concatenate.infix(lhs, rhs) } public func +(lhs: String, rhs: Expression) -> Expression { - return Operator.concatenate.infix(lhs, rhs) + Operator.concatenate.infix(lhs, rhs) } public func +(lhs: String, rhs: Expression) -> Expression { - return Operator.concatenate.infix(lhs, rhs) + Operator.concatenate.infix(lhs, rhs) } // MARK: - -public func +(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.plus.infix(lhs, rhs) +public func +(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Number { + Operator.plus.infix(lhs, rhs) } -public func +(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.plus.infix(lhs, rhs) +public func +(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Number { + Operator.plus.infix(lhs, rhs) } -public func +(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.plus.infix(lhs, rhs) +public func +(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Number { + Operator.plus.infix(lhs, rhs) } -public func +(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.plus.infix(lhs, rhs) +public func +(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Number { + Operator.plus.infix(lhs, rhs) } -public func +(lhs: Expression, rhs: V) -> Expression where V.Datatype : Number { - return Operator.plus.infix(lhs, rhs) +public func +(lhs: Expression, rhs: V) -> Expression where V.Datatype: Number { + Operator.plus.infix(lhs, rhs) } -public func +(lhs: Expression, rhs: V) -> Expression where V.Datatype : Number { - return Operator.plus.infix(lhs, rhs) +public func +(lhs: Expression, rhs: V) -> Expression where V.Datatype: Number { + Operator.plus.infix(lhs, rhs) } -public func +(lhs: V, rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.plus.infix(lhs, rhs) +public func +(lhs: V, rhs: Expression) -> Expression where V.Datatype: Number { + Operator.plus.infix(lhs, rhs) } -public func +(lhs: V, rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.plus.infix(lhs, rhs) +public func +(lhs: V, rhs: Expression) -> Expression where V.Datatype: Number { + Operator.plus.infix(lhs, rhs) } -public func -(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.minus.infix(lhs, rhs) +public func -(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Number { + Operator.minus.infix(lhs, rhs) } -public func -(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.minus.infix(lhs, rhs) +public func -(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Number { + Operator.minus.infix(lhs, rhs) } -public func -(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.minus.infix(lhs, rhs) +public func -(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Number { + Operator.minus.infix(lhs, rhs) } -public func -(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.minus.infix(lhs, rhs) +public func -(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Number { + Operator.minus.infix(lhs, rhs) } -public func -(lhs: Expression, rhs: V) -> Expression where V.Datatype : Number { - return Operator.minus.infix(lhs, rhs) +public func -(lhs: Expression, rhs: V) -> Expression where V.Datatype: Number { + Operator.minus.infix(lhs, rhs) } -public func -(lhs: Expression, rhs: V) -> Expression where V.Datatype : Number { - return Operator.minus.infix(lhs, rhs) +public func -(lhs: Expression, rhs: V) -> Expression where V.Datatype: Number { + Operator.minus.infix(lhs, rhs) } -public func -(lhs: V, rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.minus.infix(lhs, rhs) +public func -(lhs: V, rhs: Expression) -> Expression where V.Datatype: Number { + Operator.minus.infix(lhs, rhs) } -public func -(lhs: V, rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.minus.infix(lhs, rhs) +public func -(lhs: V, rhs: Expression) -> Expression where V.Datatype: Number { + Operator.minus.infix(lhs, rhs) } -public func *(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.mul.infix(lhs, rhs) +public func *(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Number { + Operator.mul.infix(lhs, rhs) } -public func *(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.mul.infix(lhs, rhs) +public func *(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Number { + Operator.mul.infix(lhs, rhs) } -public func *(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.mul.infix(lhs, rhs) +public func *(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Number { + Operator.mul.infix(lhs, rhs) } -public func *(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.mul.infix(lhs, rhs) +public func *(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Number { + Operator.mul.infix(lhs, rhs) } -public func *(lhs: Expression, rhs: V) -> Expression where V.Datatype : Number { - return Operator.mul.infix(lhs, rhs) +public func *(lhs: Expression, rhs: V) -> Expression where V.Datatype: Number { + Operator.mul.infix(lhs, rhs) } -public func *(lhs: Expression, rhs: V) -> Expression where V.Datatype : Number { - return Operator.mul.infix(lhs, rhs) +public func *(lhs: Expression, rhs: V) -> Expression where V.Datatype: Number { + Operator.mul.infix(lhs, rhs) } -public func *(lhs: V, rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.mul.infix(lhs, rhs) +public func *(lhs: V, rhs: Expression) -> Expression where V.Datatype: Number { + Operator.mul.infix(lhs, rhs) } -public func *(lhs: V, rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.mul.infix(lhs, rhs) +public func *(lhs: V, rhs: Expression) -> Expression where V.Datatype: Number { + Operator.mul.infix(lhs, rhs) } -public func /(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.div.infix(lhs, rhs) +public func /(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Number { + Operator.div.infix(lhs, rhs) } -public func /(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.div.infix(lhs, rhs) +public func /(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Number { + Operator.div.infix(lhs, rhs) } -public func /(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.div.infix(lhs, rhs) +public func /(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Number { + Operator.div.infix(lhs, rhs) } -public func /(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.div.infix(lhs, rhs) +public func /(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Number { + Operator.div.infix(lhs, rhs) } -public func /(lhs: Expression, rhs: V) -> Expression where V.Datatype : Number { - return Operator.div.infix(lhs, rhs) +public func /(lhs: Expression, rhs: V) -> Expression where V.Datatype: Number { + Operator.div.infix(lhs, rhs) } -public func /(lhs: Expression, rhs: V) -> Expression where V.Datatype : Number { - return Operator.div.infix(lhs, rhs) +public func /(lhs: Expression, rhs: V) -> Expression where V.Datatype: Number { + Operator.div.infix(lhs, rhs) } -public func /(lhs: V, rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.div.infix(lhs, rhs) +public func /(lhs: V, rhs: Expression) -> Expression where V.Datatype: Number { + Operator.div.infix(lhs, rhs) } -public func /(lhs: V, rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.div.infix(lhs, rhs) +public func /(lhs: V, rhs: Expression) -> Expression where V.Datatype: Number { + Operator.div.infix(lhs, rhs) } -public prefix func -(rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.minus.wrap(rhs) +public prefix func -(rhs: Expression) -> Expression where V.Datatype: Number { + Operator.minus.wrap(rhs) } -public prefix func -(rhs: Expression) -> Expression where V.Datatype : Number { - return Operator.minus.wrap(rhs) +public prefix func -(rhs: Expression) -> Expression where V.Datatype: Number { + Operator.minus.wrap(rhs) } // MARK: - -public func %(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.mod.infix(lhs, rhs) +public func %(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.mod.infix(lhs, rhs) } -public func %(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.mod.infix(lhs, rhs) +public func %(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.mod.infix(lhs, rhs) } -public func %(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.mod.infix(lhs, rhs) +public func %(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.mod.infix(lhs, rhs) } -public func %(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.mod.infix(lhs, rhs) +public func %(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.mod.infix(lhs, rhs) } -public func %(lhs: Expression, rhs: V) -> Expression where V.Datatype == Int64 { - return Operator.mod.infix(lhs, rhs) +public func %(lhs: Expression, rhs: V) -> Expression where V.Datatype == Int64 { + Operator.mod.infix(lhs, rhs) } -public func %(lhs: Expression, rhs: V) -> Expression where V.Datatype == Int64 { - return Operator.mod.infix(lhs, rhs) +public func %(lhs: Expression, rhs: V) -> Expression where V.Datatype == Int64 { + Operator.mod.infix(lhs, rhs) } -public func %(lhs: V, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.mod.infix(lhs, rhs) +public func %(lhs: V, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.mod.infix(lhs, rhs) } -public func %(lhs: V, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.mod.infix(lhs, rhs) +public func %(lhs: V, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.mod.infix(lhs, rhs) } -public func <<(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseLeft.infix(lhs, rhs) +public func <<(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseLeft.infix(lhs, rhs) } -public func <<(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseLeft.infix(lhs, rhs) +public func <<(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseLeft.infix(lhs, rhs) } -public func <<(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseLeft.infix(lhs, rhs) +public func <<(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseLeft.infix(lhs, rhs) } -public func <<(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseLeft.infix(lhs, rhs) +public func <<(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseLeft.infix(lhs, rhs) } -public func <<(lhs: Expression, rhs: V) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseLeft.infix(lhs, rhs) +public func <<(lhs: Expression, rhs: V) -> Expression where V.Datatype == Int64 { + Operator.bitwiseLeft.infix(lhs, rhs) } -public func <<(lhs: Expression, rhs: V) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseLeft.infix(lhs, rhs) +public func <<(lhs: Expression, rhs: V) -> Expression where V.Datatype == Int64 { + Operator.bitwiseLeft.infix(lhs, rhs) } -public func <<(lhs: V, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseLeft.infix(lhs, rhs) +public func <<(lhs: V, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseLeft.infix(lhs, rhs) } -public func <<(lhs: V, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseLeft.infix(lhs, rhs) +public func <<(lhs: V, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseLeft.infix(lhs, rhs) } -public func >>(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseRight.infix(lhs, rhs) +public func >>(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseRight.infix(lhs, rhs) } -public func >>(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseRight.infix(lhs, rhs) +public func >>(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseRight.infix(lhs, rhs) } -public func >>(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseRight.infix(lhs, rhs) +public func >>(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseRight.infix(lhs, rhs) } -public func >>(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseRight.infix(lhs, rhs) +public func >>(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseRight.infix(lhs, rhs) } -public func >>(lhs: Expression, rhs: V) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseRight.infix(lhs, rhs) +public func >>(lhs: Expression, rhs: V) -> Expression where V.Datatype == Int64 { + Operator.bitwiseRight.infix(lhs, rhs) } -public func >>(lhs: Expression, rhs: V) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseRight.infix(lhs, rhs) +public func >>(lhs: Expression, rhs: V) -> Expression where V.Datatype == Int64 { + Operator.bitwiseRight.infix(lhs, rhs) } -public func >>(lhs: V, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseRight.infix(lhs, rhs) +public func >>(lhs: V, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseRight.infix(lhs, rhs) } -public func >>(lhs: V, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseRight.infix(lhs, rhs) +public func >>(lhs: V, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseRight.infix(lhs, rhs) } -public func &(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseAnd.infix(lhs, rhs) +public func &(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseAnd.infix(lhs, rhs) } -public func &(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseAnd.infix(lhs, rhs) +public func &(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseAnd.infix(lhs, rhs) } -public func &(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseAnd.infix(lhs, rhs) +public func &(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseAnd.infix(lhs, rhs) } -public func &(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseAnd.infix(lhs, rhs) +public func &(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseAnd.infix(lhs, rhs) } -public func &(lhs: Expression, rhs: V) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseAnd.infix(lhs, rhs) +public func &(lhs: Expression, rhs: V) -> Expression where V.Datatype == Int64 { + Operator.bitwiseAnd.infix(lhs, rhs) } -public func &(lhs: Expression, rhs: V) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseAnd.infix(lhs, rhs) +public func &(lhs: Expression, rhs: V) -> Expression where V.Datatype == Int64 { + Operator.bitwiseAnd.infix(lhs, rhs) } -public func &(lhs: V, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseAnd.infix(lhs, rhs) +public func &(lhs: V, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseAnd.infix(lhs, rhs) } -public func &(lhs: V, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseAnd.infix(lhs, rhs) +public func &(lhs: V, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseAnd.infix(lhs, rhs) } -public func |(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseOr.infix(lhs, rhs) +public func |(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseOr.infix(lhs, rhs) } -public func |(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseOr.infix(lhs, rhs) +public func |(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseOr.infix(lhs, rhs) } -public func |(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseOr.infix(lhs, rhs) +public func |(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseOr.infix(lhs, rhs) } -public func |(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseOr.infix(lhs, rhs) +public func |(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseOr.infix(lhs, rhs) } -public func |(lhs: Expression, rhs: V) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseOr.infix(lhs, rhs) +public func |(lhs: Expression, rhs: V) -> Expression where V.Datatype == Int64 { + Operator.bitwiseOr.infix(lhs, rhs) } -public func |(lhs: Expression, rhs: V) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseOr.infix(lhs, rhs) +public func |(lhs: Expression, rhs: V) -> Expression where V.Datatype == Int64 { + Operator.bitwiseOr.infix(lhs, rhs) } -public func |(lhs: V, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseOr.infix(lhs, rhs) +public func |(lhs: V, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseOr.infix(lhs, rhs) } -public func |(lhs: V, rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseOr.infix(lhs, rhs) +public func |(lhs: V, rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseOr.infix(lhs, rhs) } -public func ^(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { - return (~(lhs & rhs)) & (lhs | rhs) +public func ^(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { + (~(lhs & rhs)) & (lhs | rhs) } -public func ^(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { - return (~(lhs & rhs)) & (lhs | rhs) +public func ^(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { + (~(lhs & rhs)) & (lhs | rhs) } -public func ^(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { - return (~(lhs & rhs)) & (lhs | rhs) +public func ^(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { + (~(lhs & rhs)) & (lhs | rhs) } -public func ^(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { - return (~(lhs & rhs)) & (lhs | rhs) +public func ^(lhs: Expression, rhs: Expression) -> Expression where V.Datatype == Int64 { + (~(lhs & rhs)) & (lhs | rhs) } -public func ^(lhs: Expression, rhs: V) -> Expression where V.Datatype == Int64 { - return (~(lhs & rhs)) & (lhs | rhs) +public func ^(lhs: Expression, rhs: V) -> Expression where V.Datatype == Int64 { + (~(lhs & rhs)) & (lhs | rhs) } -public func ^(lhs: Expression, rhs: V) -> Expression where V.Datatype == Int64 { - return (~(lhs & rhs)) & (lhs | rhs) +public func ^(lhs: Expression, rhs: V) -> Expression where V.Datatype == Int64 { + (~(lhs & rhs)) & (lhs | rhs) } -public func ^(lhs: V, rhs: Expression) -> Expression where V.Datatype == Int64 { - return (~(lhs & rhs)) & (lhs | rhs) +public func ^(lhs: V, rhs: Expression) -> Expression where V.Datatype == Int64 { + (~(lhs & rhs)) & (lhs | rhs) } -public func ^(lhs: V, rhs: Expression) -> Expression where V.Datatype == Int64 { - return (~(lhs & rhs)) & (lhs | rhs) +public func ^(lhs: V, rhs: Expression) -> Expression where V.Datatype == Int64 { + (~(lhs & rhs)) & (lhs | rhs) } -public prefix func ~(rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseXor.wrap(rhs) +public prefix func ~(rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseXor.wrap(rhs) } -public prefix func ~(rhs: Expression) -> Expression where V.Datatype == Int64 { - return Operator.bitwiseXor.wrap(rhs) +public prefix func ~(rhs: Expression) -> Expression where V.Datatype == Int64 { + Operator.bitwiseXor.wrap(rhs) } // MARK: - -public func ==(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Equatable { - return Operator.eq.infix(lhs, rhs) +public func ==(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Equatable { + Operator.eq.infix(lhs, rhs) } -public func ==(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Equatable { - return Operator.eq.infix(lhs, rhs) +public func ==(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Equatable { + Operator.eq.infix(lhs, rhs) } -public func ==(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Equatable { - return Operator.eq.infix(lhs, rhs) +public func ==(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Equatable { + Operator.eq.infix(lhs, rhs) } -public func ==(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Equatable { - return Operator.eq.infix(lhs, rhs) +public func ==(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Equatable { + Operator.eq.infix(lhs, rhs) } -public func ==(lhs: Expression, rhs: V) -> Expression where V.Datatype : Equatable { - return Operator.eq.infix(lhs, rhs) +public func ==(lhs: Expression, rhs: V) -> Expression where V.Datatype: Equatable { + Operator.eq.infix(lhs, rhs) } -public func ==(lhs: Expression, rhs: V?) -> Expression where V.Datatype : Equatable { +public func ==(lhs: Expression, rhs: V?) -> Expression where V.Datatype: Equatable { guard let rhs = rhs else { return "IS".infix(lhs, Expression(value: nil)) } return Operator.eq.infix(lhs, rhs) } -public func ==(lhs: V, rhs: Expression) -> Expression where V.Datatype : Equatable { - return Operator.eq.infix(lhs, rhs) +public func ==(lhs: V, rhs: Expression) -> Expression where V.Datatype: Equatable { + Operator.eq.infix(lhs, rhs) } -public func ==(lhs: V?, rhs: Expression) -> Expression where V.Datatype : Equatable { +public func ==(lhs: V?, rhs: Expression) -> Expression where V.Datatype: Equatable { guard let lhs = lhs else { return "IS".infix(Expression(value: nil), rhs) } return Operator.eq.infix(lhs, rhs) } -public func ===(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Equatable { - return "IS".infix(lhs, rhs) +public func ===(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Equatable { + "IS".infix(lhs, rhs) } -public func ===(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Equatable { - return "IS".infix(lhs, rhs) +public func ===(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Equatable { + "IS".infix(lhs, rhs) } -public func ===(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Equatable { - return "IS".infix(lhs, rhs) +public func ===(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Equatable { + "IS".infix(lhs, rhs) } -public func ===(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Equatable { - return "IS".infix(lhs, rhs) +public func ===(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Equatable { + "IS".infix(lhs, rhs) } -public func ===(lhs: Expression, rhs: V) -> Expression where V.Datatype : Equatable { - return "IS".infix(lhs, rhs) +public func ===(lhs: Expression, rhs: V) -> Expression where V.Datatype: Equatable { + "IS".infix(lhs, rhs) } -public func ===(lhs: Expression, rhs: V?) -> Expression where V.Datatype : Equatable { +public func ===(lhs: Expression, rhs: V?) -> Expression where V.Datatype: Equatable { guard let rhs = rhs else { return "IS".infix(lhs, Expression(value: nil)) } return "IS".infix(lhs, rhs) } -public func ===(lhs: V, rhs: Expression) -> Expression where V.Datatype : Equatable { - return "IS".infix(lhs, rhs) +public func ===(lhs: V, rhs: Expression) -> Expression where V.Datatype: Equatable { + "IS".infix(lhs, rhs) } -public func ===(lhs: V?, rhs: Expression) -> Expression where V.Datatype : Equatable { +public func ===(lhs: V?, rhs: Expression) -> Expression where V.Datatype: Equatable { guard let lhs = lhs else { return "IS".infix(Expression(value: nil), rhs) } return "IS".infix(lhs, rhs) } -public func !=(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Equatable { - return Operator.neq.infix(lhs, rhs) +public func !=(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Equatable { + Operator.neq.infix(lhs, rhs) } -public func !=(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Equatable { - return Operator.neq.infix(lhs, rhs) +public func !=(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Equatable { + Operator.neq.infix(lhs, rhs) } -public func !=(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Equatable { - return Operator.neq.infix(lhs, rhs) +public func !=(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Equatable { + Operator.neq.infix(lhs, rhs) } -public func !=(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Equatable { - return Operator.neq.infix(lhs, rhs) +public func !=(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Equatable { + Operator.neq.infix(lhs, rhs) } -public func !=(lhs: Expression, rhs: V) -> Expression where V.Datatype : Equatable { - return Operator.neq.infix(lhs, rhs) +public func !=(lhs: Expression, rhs: V) -> Expression where V.Datatype: Equatable { + Operator.neq.infix(lhs, rhs) } -public func !=(lhs: Expression, rhs: V?) -> Expression where V.Datatype : Equatable { +public func !=(lhs: Expression, rhs: V?) -> Expression where V.Datatype: Equatable { guard let rhs = rhs else { return "IS NOT".infix(lhs, Expression(value: nil)) } return Operator.neq.infix(lhs, rhs) } -public func !=(lhs: V, rhs: Expression) -> Expression where V.Datatype : Equatable { - return Operator.neq.infix(lhs, rhs) +public func !=(lhs: V, rhs: Expression) -> Expression where V.Datatype: Equatable { + Operator.neq.infix(lhs, rhs) } -public func !=(lhs: V?, rhs: Expression) -> Expression where V.Datatype : Equatable { +public func !=(lhs: V?, rhs: Expression) -> Expression where V.Datatype: Equatable { guard let lhs = lhs else { return "IS NOT".infix(Expression(value: nil), rhs) } return Operator.neq.infix(lhs, rhs) } -public func !==(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Equatable { - return "IS NOT".infix(lhs, rhs) +public func !==(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Equatable { + "IS NOT".infix(lhs, rhs) } -public func !==(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Equatable { - return "IS NOT".infix(lhs, rhs) +public func !==(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Equatable { + "IS NOT".infix(lhs, rhs) } -public func !==(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Equatable { - return "IS NOT".infix(lhs, rhs) +public func !==(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Equatable { + "IS NOT".infix(lhs, rhs) } -public func !==(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Equatable { - return "IS NOT".infix(lhs, rhs) +public func !==(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Equatable { + "IS NOT".infix(lhs, rhs) } -public func !==(lhs: Expression, rhs: V) -> Expression where V.Datatype : Equatable { - return "IS NOT".infix(lhs, rhs) +public func !==(lhs: Expression, rhs: V) -> Expression where V.Datatype: Equatable { + "IS NOT".infix(lhs, rhs) } -public func !==(lhs: Expression, rhs: V?) -> Expression where V.Datatype : Equatable { +public func !==(lhs: Expression, rhs: V?) -> Expression where V.Datatype: Equatable { guard let rhs = rhs else { return "IS NOT".infix(lhs, Expression(value: nil)) } return "IS NOT".infix(lhs, rhs) } -public func !==(lhs: V, rhs: Expression) -> Expression where V.Datatype : Equatable { - return "IS NOT".infix(lhs, rhs) +public func !==(lhs: V, rhs: Expression) -> Expression where V.Datatype: Equatable { + "IS NOT".infix(lhs, rhs) } -public func !==(lhs: V?, rhs: Expression) -> Expression where V.Datatype : Equatable { +public func !==(lhs: V?, rhs: Expression) -> Expression where V.Datatype: Equatable { guard let lhs = lhs else { return "IS NOT".infix(Expression(value: nil), rhs) } return "IS NOT".infix(lhs, rhs) } - -public func >(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Comparable { - return Operator.gt.infix(lhs, rhs) +public func >(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Comparable { + Operator.gt.infix(lhs, rhs) } -public func >(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Comparable { - return Operator.gt.infix(lhs, rhs) +public func >(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Comparable { + Operator.gt.infix(lhs, rhs) } -public func >(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Comparable { - return Operator.gt.infix(lhs, rhs) +public func >(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Comparable { + Operator.gt.infix(lhs, rhs) } -public func >(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Comparable { - return Operator.gt.infix(lhs, rhs) +public func >(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Comparable { + Operator.gt.infix(lhs, rhs) } -public func >(lhs: Expression, rhs: V) -> Expression where V.Datatype : Comparable { - return Operator.gt.infix(lhs, rhs) +public func >(lhs: Expression, rhs: V) -> Expression where V.Datatype: Comparable { + Operator.gt.infix(lhs, rhs) } -public func >(lhs: Expression, rhs: V) -> Expression where V.Datatype : Comparable { - return Operator.gt.infix(lhs, rhs) +public func >(lhs: Expression, rhs: V) -> Expression where V.Datatype: Comparable { + Operator.gt.infix(lhs, rhs) } -public func >(lhs: V, rhs: Expression) -> Expression where V.Datatype : Comparable { - return Operator.gt.infix(lhs, rhs) +public func >(lhs: V, rhs: Expression) -> Expression where V.Datatype: Comparable { + Operator.gt.infix(lhs, rhs) } -public func >(lhs: V, rhs: Expression) -> Expression where V.Datatype : Comparable { - return Operator.gt.infix(lhs, rhs) +public func >(lhs: V, rhs: Expression) -> Expression where V.Datatype: Comparable { + Operator.gt.infix(lhs, rhs) } -public func >=(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Comparable { - return Operator.gte.infix(lhs, rhs) +public func >=(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Comparable { + Operator.gte.infix(lhs, rhs) } -public func >=(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Comparable { - return Operator.gte.infix(lhs, rhs) +public func >=(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Comparable { + Operator.gte.infix(lhs, rhs) } -public func >=(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Comparable { - return Operator.gte.infix(lhs, rhs) +public func >=(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Comparable { + Operator.gte.infix(lhs, rhs) } -public func >=(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Comparable { - return Operator.gte.infix(lhs, rhs) +public func >=(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Comparable { + Operator.gte.infix(lhs, rhs) } -public func >=(lhs: Expression, rhs: V) -> Expression where V.Datatype : Comparable { - return Operator.gte.infix(lhs, rhs) +public func >=(lhs: Expression, rhs: V) -> Expression where V.Datatype: Comparable { + Operator.gte.infix(lhs, rhs) } -public func >=(lhs: Expression, rhs: V) -> Expression where V.Datatype : Comparable { - return Operator.gte.infix(lhs, rhs) +public func >=(lhs: Expression, rhs: V) -> Expression where V.Datatype: Comparable { + Operator.gte.infix(lhs, rhs) } -public func >=(lhs: V, rhs: Expression) -> Expression where V.Datatype : Comparable { - return Operator.gte.infix(lhs, rhs) +public func >=(lhs: V, rhs: Expression) -> Expression where V.Datatype: Comparable { + Operator.gte.infix(lhs, rhs) } -public func >=(lhs: V, rhs: Expression) -> Expression where V.Datatype : Comparable { - return Operator.gte.infix(lhs, rhs) +public func >=(lhs: V, rhs: Expression) -> Expression where V.Datatype: Comparable { + Operator.gte.infix(lhs, rhs) } -public func <(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Comparable { - return Operator.lt.infix(lhs, rhs) +public func <(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Comparable { + Operator.lt.infix(lhs, rhs) } -public func <(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Comparable { - return Operator.lt.infix(lhs, rhs) +public func <(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Comparable { + Operator.lt.infix(lhs, rhs) } -public func <(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Comparable { - return Operator.lt.infix(lhs, rhs) +public func <(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Comparable { + Operator.lt.infix(lhs, rhs) } -public func <(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Comparable { - return Operator.lt.infix(lhs, rhs) +public func <(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Comparable { + Operator.lt.infix(lhs, rhs) } -public func <(lhs: Expression, rhs: V) -> Expression where V.Datatype : Comparable { - return Operator.lt.infix(lhs, rhs) +public func <(lhs: Expression, rhs: V) -> Expression where V.Datatype: Comparable { + Operator.lt.infix(lhs, rhs) } -public func <(lhs: Expression, rhs: V) -> Expression where V.Datatype : Comparable { - return Operator.lt.infix(lhs, rhs) +public func <(lhs: Expression, rhs: V) -> Expression where V.Datatype: Comparable { + Operator.lt.infix(lhs, rhs) } -public func <(lhs: V, rhs: Expression) -> Expression where V.Datatype : Comparable { - return Operator.lt.infix(lhs, rhs) +public func <(lhs: V, rhs: Expression) -> Expression where V.Datatype: Comparable { + Operator.lt.infix(lhs, rhs) } -public func <(lhs: V, rhs: Expression) -> Expression where V.Datatype : Comparable { - return Operator.lt.infix(lhs, rhs) +public func <(lhs: V, rhs: Expression) -> Expression where V.Datatype: Comparable { + Operator.lt.infix(lhs, rhs) } -public func <=(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Comparable { - return Operator.lte.infix(lhs, rhs) +public func <=(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Comparable { + Operator.lte.infix(lhs, rhs) } -public func <=(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Comparable { - return Operator.lte.infix(lhs, rhs) +public func <=(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Comparable { + Operator.lte.infix(lhs, rhs) } -public func <=(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Comparable { - return Operator.lte.infix(lhs, rhs) +public func <=(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Comparable { + Operator.lte.infix(lhs, rhs) } -public func <=(lhs: Expression, rhs: Expression) -> Expression where V.Datatype : Comparable { - return Operator.lte.infix(lhs, rhs) +public func <=(lhs: Expression, rhs: Expression) -> Expression where V.Datatype: Comparable { + Operator.lte.infix(lhs, rhs) } -public func <=(lhs: Expression, rhs: V) -> Expression where V.Datatype : Comparable { - return Operator.lte.infix(lhs, rhs) +public func <=(lhs: Expression, rhs: V) -> Expression where V.Datatype: Comparable { + Operator.lte.infix(lhs, rhs) } -public func <=(lhs: Expression, rhs: V) -> Expression where V.Datatype : Comparable { - return Operator.lte.infix(lhs, rhs) +public func <=(lhs: Expression, rhs: V) -> Expression where V.Datatype: Comparable { + Operator.lte.infix(lhs, rhs) } -public func <=(lhs: V, rhs: Expression) -> Expression where V.Datatype : Comparable { - return Operator.lte.infix(lhs, rhs) +public func <=(lhs: V, rhs: Expression) -> Expression where V.Datatype: Comparable { + Operator.lte.infix(lhs, rhs) } -public func <=(lhs: V, rhs: Expression) -> Expression where V.Datatype : Comparable { - return Operator.lte.infix(lhs, rhs) +public func <=(lhs: V, rhs: Expression) -> Expression where V.Datatype: Comparable { + Operator.lte.infix(lhs, rhs) } -public func ~=(lhs: ClosedRange, rhs: Expression) -> Expression where V.Datatype : Comparable & Value { - return Expression("\(rhs.template) BETWEEN ? AND ?", rhs.bindings + [lhs.lowerBound.datatypeValue, lhs.upperBound.datatypeValue]) +public func ~=(lhs: ClosedRange, rhs: Expression) -> Expression where V.Datatype: Comparable & Value { + Expression("\(rhs.template) BETWEEN ? AND ?", rhs.bindings + [lhs.lowerBound.datatypeValue, lhs.upperBound.datatypeValue]) } -public func ~=(lhs: ClosedRange, rhs: Expression) -> Expression where V.Datatype : Comparable & Value { - return Expression("\(rhs.template) BETWEEN ? AND ?", rhs.bindings + [lhs.lowerBound.datatypeValue, lhs.upperBound.datatypeValue]) +public func ~=(lhs: ClosedRange, rhs: Expression) -> Expression where V.Datatype: Comparable & Value { + Expression("\(rhs.template) BETWEEN ? AND ?", rhs.bindings + [lhs.lowerBound.datatypeValue, lhs.upperBound.datatypeValue]) } -public func ~=(lhs: Range, rhs: Expression) -> Expression where V.Datatype : Comparable & Value { - return Expression("\(rhs.template) >= ? AND \(rhs.template) < ?", rhs.bindings + [lhs.lowerBound.datatypeValue] + rhs.bindings + [lhs.upperBound.datatypeValue]) +public func ~=(lhs: Range, rhs: Expression) -> Expression where V.Datatype: Comparable & Value { + Expression("\(rhs.template) >= ? AND \(rhs.template) < ?", + rhs.bindings + [lhs.lowerBound.datatypeValue] + rhs.bindings + [lhs.upperBound.datatypeValue]) } -public func ~=(lhs: Range, rhs: Expression) -> Expression where V.Datatype : Comparable & Value { - return Expression("\(rhs.template) >= ? AND \(rhs.template) < ?", rhs.bindings + [lhs.lowerBound.datatypeValue] + rhs.bindings + [lhs.upperBound.datatypeValue]) +public func ~=(lhs: Range, rhs: Expression) -> Expression where V.Datatype: Comparable & Value { + Expression("\(rhs.template) >= ? AND \(rhs.template) < ?", + rhs.bindings + [lhs.lowerBound.datatypeValue] + rhs.bindings + [lhs.upperBound.datatypeValue]) } -public func ~=(lhs: PartialRangeThrough, rhs: Expression) -> Expression where V.Datatype : Comparable & Value { - return Expression("\(rhs.template) <= ?", rhs.bindings + [lhs.upperBound.datatypeValue]) +public func ~=(lhs: PartialRangeThrough, rhs: Expression) -> Expression where V.Datatype: Comparable & Value { + Expression("\(rhs.template) <= ?", rhs.bindings + [lhs.upperBound.datatypeValue]) } -public func ~=(lhs: PartialRangeThrough, rhs: Expression) -> Expression where V.Datatype : Comparable & Value { - return Expression("\(rhs.template) <= ?", rhs.bindings + [lhs.upperBound.datatypeValue]) +public func ~=(lhs: PartialRangeThrough, rhs: Expression) -> Expression where V.Datatype: Comparable & Value { + Expression("\(rhs.template) <= ?", rhs.bindings + [lhs.upperBound.datatypeValue]) } -public func ~=(lhs: PartialRangeUpTo, rhs: Expression) -> Expression where V.Datatype : Comparable & Value { - return Expression("\(rhs.template) < ?", rhs.bindings + [lhs.upperBound.datatypeValue]) +public func ~=(lhs: PartialRangeUpTo, rhs: Expression) -> Expression where V.Datatype: Comparable & Value { + Expression("\(rhs.template) < ?", rhs.bindings + [lhs.upperBound.datatypeValue]) } -public func ~=(lhs: PartialRangeUpTo, rhs: Expression) -> Expression where V.Datatype : Comparable & Value { - return Expression("\(rhs.template) < ?", rhs.bindings + [lhs.upperBound.datatypeValue]) +public func ~=(lhs: PartialRangeUpTo, rhs: Expression) -> Expression where V.Datatype: Comparable & Value { + Expression("\(rhs.template) < ?", rhs.bindings + [lhs.upperBound.datatypeValue]) } -public func ~=(lhs: PartialRangeFrom, rhs: Expression) -> Expression where V.Datatype : Comparable & Value { - return Expression("\(rhs.template) >= ?", rhs.bindings + [lhs.lowerBound.datatypeValue]) +public func ~=(lhs: PartialRangeFrom, rhs: Expression) -> Expression where V.Datatype: Comparable & Value { + Expression("\(rhs.template) >= ?", rhs.bindings + [lhs.lowerBound.datatypeValue]) } -public func ~=(lhs: PartialRangeFrom, rhs: Expression) -> Expression where V.Datatype : Comparable & Value { - return Expression("\(rhs.template) >= ?", rhs.bindings + [lhs.lowerBound.datatypeValue]) +public func ~=(lhs: PartialRangeFrom, rhs: Expression) -> Expression where V.Datatype: Comparable & Value { + Expression("\(rhs.template) >= ?", rhs.bindings + [lhs.lowerBound.datatypeValue]) } // MARK: - public func and(_ terms: Expression...) -> Expression { - return "AND".infix(terms) + "AND".infix(terms) } public func and(_ terms: [Expression]) -> Expression { - return "AND".infix(terms) + "AND".infix(terms) } public func &&(lhs: Expression, rhs: Expression) -> Expression { - return Operator.and.infix(lhs, rhs) + Operator.and.infix(lhs, rhs) } public func &&(lhs: Expression, rhs: Expression) -> Expression { - return Operator.and.infix(lhs, rhs) + Operator.and.infix(lhs, rhs) } public func &&(lhs: Expression, rhs: Expression) -> Expression { - return Operator.and.infix(lhs, rhs) + Operator.and.infix(lhs, rhs) } public func &&(lhs: Expression, rhs: Expression) -> Expression { - return Operator.and.infix(lhs, rhs) + Operator.and.infix(lhs, rhs) } public func &&(lhs: Expression, rhs: Bool) -> Expression { - return Operator.and.infix(lhs, rhs) + Operator.and.infix(lhs, rhs) } public func &&(lhs: Expression, rhs: Bool) -> Expression { - return Operator.and.infix(lhs, rhs) + Operator.and.infix(lhs, rhs) } public func &&(lhs: Bool, rhs: Expression) -> Expression { - return Operator.and.infix(lhs, rhs) + Operator.and.infix(lhs, rhs) } public func &&(lhs: Bool, rhs: Expression) -> Expression { - return Operator.and.infix(lhs, rhs) + Operator.and.infix(lhs, rhs) } public func or(_ terms: Expression...) -> Expression { - return "OR".infix(terms) + "OR".infix(terms) } public func or(_ terms: [Expression]) -> Expression { - return "OR".infix(terms) + "OR".infix(terms) } public func ||(lhs: Expression, rhs: Expression) -> Expression { - return Operator.or.infix(lhs, rhs) + Operator.or.infix(lhs, rhs) } public func ||(lhs: Expression, rhs: Expression) -> Expression { - return Operator.or.infix(lhs, rhs) + Operator.or.infix(lhs, rhs) } public func ||(lhs: Expression, rhs: Expression) -> Expression { - return Operator.or.infix(lhs, rhs) + Operator.or.infix(lhs, rhs) } public func ||(lhs: Expression, rhs: Expression) -> Expression { - return Operator.or.infix(lhs, rhs) + Operator.or.infix(lhs, rhs) } public func ||(lhs: Expression, rhs: Bool) -> Expression { - return Operator.or.infix(lhs, rhs) + Operator.or.infix(lhs, rhs) } public func ||(lhs: Expression, rhs: Bool) -> Expression { - return Operator.or.infix(lhs, rhs) + Operator.or.infix(lhs, rhs) } public func ||(lhs: Bool, rhs: Expression) -> Expression { - return Operator.or.infix(lhs, rhs) + Operator.or.infix(lhs, rhs) } public func ||(lhs: Bool, rhs: Expression) -> Expression { - return Operator.or.infix(lhs, rhs) + Operator.or.infix(lhs, rhs) } public prefix func !(rhs: Expression) -> Expression { - return Operator.not.wrap(rhs) + Operator.not.wrap(rhs) } + public prefix func !(rhs: Expression) -> Expression { - return Operator.not.wrap(rhs) + Operator.not.wrap(rhs) } diff --git a/Sources/SQLite/Typed/Query.swift b/Sources/SQLite/Typed/Query.swift index 669001d3..59b24a8d 100644 --- a/Sources/SQLite/Typed/Query.swift +++ b/Sources/SQLite/Typed/Query.swift @@ -21,10 +21,10 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // - +// swiftlint:disable file_length import Foundation -public protocol QueryType : Expressible { +public protocol QueryType: Expressible { var clauses: QueryClauses { get set } @@ -32,7 +32,7 @@ public protocol QueryType : Expressible { } -public protocol SchemaType : QueryType { +public protocol SchemaType: QueryType { static var identifier: String { get } @@ -53,7 +53,7 @@ extension SchemaType { /// /// - Returns: A query with the given `SELECT` clause applied. public func select(_ column1: Expressible, _ more: Expressible...) -> Self { - return select(false, [column1] + more) + select(false, [column1] + more) } /// Builds a copy of the query with the `SELECT DISTINCT` clause applied. @@ -68,7 +68,7 @@ extension SchemaType { /// /// - Returns: A query with the given `SELECT DISTINCT` clause applied. public func select(distinct column1: Expressible, _ more: Expressible...) -> Self { - return select(true, [column1] + more) + select(true, [column1] + more) } /// Builds a copy of the query with the `SELECT` clause applied. @@ -84,7 +84,7 @@ extension SchemaType { /// /// - Returns: A query with the given `SELECT` clause applied. public func select(_ all: [Expressible]) -> Self { - return select(false, all) + select(false, all) } /// Builds a copy of the query with the `SELECT DISTINCT` clause applied. @@ -99,7 +99,7 @@ extension SchemaType { /// /// - Returns: A query with the given `SELECT DISTINCT` clause applied. public func select(distinct columns: [Expressible]) -> Self { - return select(true, columns) + select(true, columns) } /// Builds a copy of the query with the `SELECT *` clause applied. @@ -113,7 +113,7 @@ extension SchemaType { /// /// - Returns: A query with the given `SELECT *` clause applied. public func select(_ star: Star) -> Self { - return select([star(nil, nil)]) + select([star(nil, nil)]) } /// Builds a copy of the query with the `SELECT DISTINCT *` clause applied. @@ -127,7 +127,7 @@ extension SchemaType { /// /// - Returns: A query with the given `SELECT DISTINCT *` clause applied. public func select(distinct star: Star) -> Self { - return select(distinct: [star(nil, nil)]) + select(distinct: [star(nil, nil)]) } /// Builds a scalar copy of the query with the `SELECT` clause applied. @@ -141,11 +141,11 @@ extension SchemaType { /// - Parameter all: A list of expressions to select. /// /// - Returns: A query with the given `SELECT` clause applied. - public func select(_ column: Expression) -> ScalarQuery { - return select(false, [column]) + public func select(_ column: Expression) -> ScalarQuery { + select(false, [column]) } - public func select(_ column: Expression) -> ScalarQuery { - return select(false, [column]) + public func select(_ column: Expression) -> ScalarQuery { + select(false, [column]) } /// Builds a scalar copy of the query with the `SELECT DISTINCT` clause @@ -160,22 +160,22 @@ extension SchemaType { /// - Parameter column: A list of expressions to select. /// /// - Returns: A query with the given `SELECT DISTINCT` clause applied. - public func select(distinct column: Expression) -> ScalarQuery { - return select(true, [column]) + public func select(distinct column: Expression) -> ScalarQuery { + select(true, [column]) } - public func select(distinct column: Expression) -> ScalarQuery { - return select(true, [column]) + public func select(distinct column: Expression) -> ScalarQuery { + select(true, [column]) } public var count: ScalarQuery { - return select(Expression.count(*)) + select(Expression.count(*)) } } extension QueryType { - fileprivate func select(_ distinct: Bool, _ columns: [Expressible]) -> Q { + fileprivate func select(_ distinct: Bool, _ columns: [Expressible]) -> Q { var query = Q.init(clauses.from.name, database: clauses.from.database) query.clauses = clauses query.clauses.select = (distinct, columns) @@ -183,7 +183,7 @@ extension QueryType { } // MARK: UNION - + /// Adds a `UNION` clause to the query. /// /// let users = Table("users") @@ -202,7 +202,7 @@ extension QueryType { query.clauses.union.append(table) return query } - + // MARK: JOIN /// Adds a `JOIN` clause to the query. @@ -223,7 +223,7 @@ extension QueryType { /// /// - Returns: A query with the given `JOIN` clause applied. public func join(_ table: QueryType, on condition: Expression) -> Self { - return join(table, on: Expression(condition)) + join(table, on: Expression(condition)) } /// Adds a `JOIN` clause to the query. @@ -244,7 +244,7 @@ extension QueryType { /// /// - Returns: A query with the given `JOIN` clause applied. public func join(_ table: QueryType, on condition: Expression) -> Self { - return join(.inner, table, on: condition) + join(.inner, table, on: condition) } /// Adds a `JOIN` clause to the query. @@ -267,7 +267,7 @@ extension QueryType { /// /// - Returns: A query with the given `JOIN` clause applied. public func join(_ type: JoinType, _ table: QueryType, on condition: Expression) -> Self { - return join(type, table, on: Expression(condition)) + join(type, table, on: Expression(condition)) } /// Adds a `JOIN` clause to the query. @@ -291,7 +291,8 @@ extension QueryType { /// - Returns: A query with the given `JOIN` clause applied. public func join(_ type: JoinType, _ table: QueryType, on condition: Expression) -> Self { var query = self - query.clauses.join.append((type: type, query: table, condition: table.clauses.filters.map { condition && $0 } ?? condition as Expressible)) + query.clauses.join.append((type: type, query: table, + condition: table.clauses.filters.map { condition && $0 } ?? condition as Expressible)) return query } @@ -309,7 +310,7 @@ extension QueryType { /// /// - Returns: A query with the given `WHERE` clause applied. public func filter(_ predicate: Expression) -> Self { - return filter(Expression(predicate)) + filter(Expression(predicate)) } /// Adds a condition to the query’s `WHERE` clause. @@ -332,13 +333,13 @@ extension QueryType { /// Adds a condition to the query’s `WHERE` clause. /// This is an alias for `filter(predicate)` public func `where`(_ predicate: Expression) -> Self { - return `where`(Expression(predicate)) + `where`(Expression(predicate)) } /// Adds a condition to the query’s `WHERE` clause. /// This is an alias for `filter(predicate)` public func `where`(_ predicate: Expression) -> Self { - return filter(predicate) + filter(predicate) } // MARK: GROUP BY @@ -349,7 +350,7 @@ extension QueryType { /// /// - Returns: A query with the given `GROUP BY` clause applied. public func group(_ by: Expressible...) -> Self { - return group(by) + group(by) } /// Sets a `GROUP BY` clause on the query. @@ -358,7 +359,7 @@ extension QueryType { /// /// - Returns: A query with the given `GROUP BY` clause applied. public func group(_ by: [Expressible]) -> Self { - return group(by, nil) + group(by, nil) } /// Sets a `GROUP BY`-`HAVING` clause on the query. @@ -371,7 +372,7 @@ extension QueryType { /// /// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied. public func group(_ by: Expressible, having: Expression) -> Self { - return group([by], having: having) + group([by], having: having) } /// Sets a `GROUP BY`-`HAVING` clause on the query. @@ -384,7 +385,7 @@ extension QueryType { /// /// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied. public func group(_ by: Expressible, having: Expression) -> Self { - return group([by], having: having) + group([by], having: having) } /// Sets a `GROUP BY`-`HAVING` clause on the query. @@ -397,7 +398,7 @@ extension QueryType { /// /// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied. public func group(_ by: [Expressible], having: Expression) -> Self { - return group(by, Expression(having)) + group(by, Expression(having)) } /// Sets a `GROUP BY`-`HAVING` clause on the query. @@ -410,7 +411,7 @@ extension QueryType { /// /// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied. public func group(_ by: [Expressible], having: Expression) -> Self { - return group(by, having) + group(by, having) } fileprivate func group(_ by: [Expressible], _ having: Expression?) -> Self { @@ -434,7 +435,7 @@ extension QueryType { /// /// - Returns: A query with the given `ORDER BY` clause applied. public func order(_ by: Expressible...) -> Self { - return order(by) + order(by) } /// Sets an `ORDER BY` clause on the query. @@ -469,7 +470,7 @@ extension QueryType { /// /// - Returns: A query with the given LIMIT clause applied. public func limit(_ length: Int?) -> Self { - return limit(length, nil) + limit(length, nil) } /// Sets LIMIT and OFFSET clauses on the query. @@ -487,7 +488,7 @@ extension QueryType { /// /// - Returns: A query with the given LIMIT and OFFSET clauses applied. public func limit(_ length: Int, offset: Int) -> Self { - return limit(length, offset) + limit(length, offset) } // prevents limit(nil, offset: 5) @@ -504,12 +505,13 @@ extension QueryType { // MARK: - fileprivate var selectClause: Expressible { - return " ".join([ - Expression(literal: clauses.select.distinct ? "SELECT DISTINCT" : "SELECT"), - ", ".join(clauses.select.columns), - Expression(literal: "FROM"), - tableName(alias: true) - ]) + " ".join([ + Expression(literal: + clauses.select.distinct ? "SELECT DISTINCT" : "SELECT"), + ", ".join(clauses.select.columns), + Expression(literal: "FROM"), + tableName(alias: true) + ]) } fileprivate var joinClause: Expressible? { @@ -589,12 +591,12 @@ extension QueryType { Expression(literal: "OFFSET \(offset)") ]) } - + fileprivate var unionClause: Expressible? { guard !clauses.union.isEmpty else { return nil } - + return " ".join(clauses.union.map { query in " ".join([ Expression(literal: "UNION"), @@ -616,31 +618,31 @@ extension QueryType { // MARK: INSERT public func insert(_ value: Setter, _ more: Setter...) -> Insert { - return insert([value] + more) + insert([value] + more) } public func insert(_ values: [Setter]) -> Insert { - return insert(nil, values) + insert(nil, values) } public func insert(or onConflict: OnConflict, _ values: Setter...) -> Insert { - return insert(or: onConflict, values) + insert(or: onConflict, values) } public func insert(or onConflict: OnConflict, _ values: [Setter]) -> Insert { - return insert(onConflict, values) + insert(onConflict, values) } public func insertMany( _ values: [[Setter]]) -> Insert { - return insertMany(nil, values) + insertMany(nil, values) } public func insertMany(or onConflict: OnConflict, _ values: [[Setter]]) -> Insert { - return insertMany(onConflict, values) + insertMany(onConflict, values) } public func insertMany(or onConflict: OnConflict, _ values: [Setter]...) -> Insert { - return insertMany(onConflict, values) + insertMany(onConflict, values) } fileprivate func insert(_ or: OnConflict?, _ values: [Setter]) -> Insert { @@ -689,7 +691,7 @@ extension QueryType { /// Runs an `INSERT` statement against the query with `DEFAULT VALUES`. public func insert() -> Insert { - return Insert(" ".join([ + Insert(" ".join([ Expression(literal: "INSERT INTO"), tableName(), Expression(literal: "DEFAULT VALUES") @@ -703,34 +705,34 @@ extension QueryType { /// /// - Returns: The number of updated rows and statement. public func insert(_ query: QueryType) -> Update { - return Update(" ".join([ + Update(" ".join([ Expression(literal: "INSERT INTO"), tableName(), query.expression - ]).expression) + ]).expression) } - + // MARK: UPSERT - + public func upsert(_ insertValues: Setter..., onConflictOf conflicting: Expressible) -> Insert { - return upsert(insertValues, onConflictOf: conflicting) + upsert(insertValues, onConflictOf: conflicting) } - + public func upsert(_ insertValues: [Setter], onConflictOf conflicting: Expressible) -> Insert { let setValues = insertValues.filter { $0.column.asSQL() != conflicting.asSQL() } .map { Setter(excluded: $0.column) } return upsert(insertValues, onConflictOf: conflicting, set: setValues) } - + public func upsert(_ insertValues: Setter..., onConflictOf conflicting: Expressible, set setValues: [Setter]) -> Insert { - return upsert(insertValues, onConflictOf: conflicting, set: setValues) + upsert(insertValues, onConflictOf: conflicting, set: setValues) } - + public func upsert(_ insertValues: [Setter], onConflictOf conflicting: Expressible, set setValues: [Setter]) -> Insert { let insert = insertValues.reduce((columns: [Expressible](), values: [Expressible]())) { insert, setter in (insert.columns + [setter.column], insert.values + [setter.value]) } - + let clauses: [Expressible?] = [ Expression(literal: "INSERT"), Expression(literal: "INTO"), @@ -744,15 +746,14 @@ extension QueryType { Expression(literal: "DO UPDATE SET"), ", ".join(setValues.map { $0.expression }) ] - + return Insert(" ".join(clauses.compactMap { $0 }).expression) } - // MARK: UPDATE public func update(_ values: Setter...) -> Update { - return update(values) + update(values) } public func update(_ values: [Setter]) -> Update { @@ -786,7 +787,7 @@ extension QueryType { // MARK: EXISTS public var exists: Select { - return Select(" ".join([ + Select(" ".join([ Expression(literal: "SELECT EXISTS"), "".wrap(expression) as Expression ]).expression) @@ -801,15 +802,15 @@ extension QueryType { /// - Returns: A column expression namespaced with the query’s table name or /// alias. public func namespace(_ column: Expression) -> Expression { - return Expression(".".join([tableName(), column]).expression) + Expression(".".join([tableName(), column]).expression) } public subscript(column: Expression) -> Expression { - return namespace(column) + namespace(column) } public subscript(column: Expression) -> Expression { - return namespace(column) + namespace(column) } /// Prefixes a star with the query’s table name or alias. @@ -819,14 +820,14 @@ extension QueryType { /// - Returns: A `*` expression namespaced with the query’s table name or /// alias. public subscript(star: Star) -> Expression { - return namespace(star(nil, nil)) + namespace(star(nil, nil)) } // MARK: - // TODO: alias support func tableName(alias aliased: Bool = false) -> Expressible { - guard let alias = clauses.from.alias , aliased else { + guard let alias = clauses.from.alias, aliased else { return database(namespace: clauses.from.alias ?? clauses.from.name) } @@ -874,7 +875,7 @@ extension QueryType { /// Queries a collection of chainable helper functions and expressions to build /// executable SQL statements. -public struct Table : SchemaType { +public struct Table: SchemaType { public static let identifier = "TABLE" @@ -886,7 +887,7 @@ public struct Table : SchemaType { } -public struct View : SchemaType { +public struct View: SchemaType { public static let identifier = "VIEW" @@ -898,7 +899,7 @@ public struct View : SchemaType { } -public struct VirtualTable : SchemaType { +public struct VirtualTable: SchemaType { public static let identifier = "VIRTUAL TABLE" @@ -912,7 +913,7 @@ public struct VirtualTable : SchemaType { // TODO: make `ScalarQuery` work in `QueryType.select()`, `.filter()`, etc. -public struct ScalarQuery : QueryType { +public struct ScalarQuery: QueryType { public var clauses: QueryClauses @@ -924,7 +925,7 @@ public struct ScalarQuery : QueryType { // TODO: decide: simplify the below with a boxed type instead -public struct Select : ExpressionType { +public struct Select: ExpressionType { public var template: String public var bindings: [Binding?] @@ -936,7 +937,7 @@ public struct Select : ExpressionType { } -public struct Insert : ExpressionType { +public struct Insert: ExpressionType { public var template: String public var bindings: [Binding?] @@ -948,7 +949,7 @@ public struct Insert : ExpressionType { } -public struct Update : ExpressionType { +public struct Update: ExpressionType { public var template: String public var bindings: [Binding?] @@ -960,7 +961,7 @@ public struct Update : ExpressionType { } -public struct Delete : ExpressionType { +public struct Delete: ExpressionType { public var template: String public var bindings: [Binding?] @@ -972,14 +973,13 @@ public struct Delete : ExpressionType { } - public struct RowIterator: FailableIterator { public typealias Element = Row let statement: Statement let columnNames: [String: Int] public func failableNext() throws -> Row? { - return try statement.failableNext().flatMap { Row(columnNames, $0) } + try statement.failableNext().flatMap { Row(columnNames, $0) } } public func map(_ transform: (Element) throws -> T) throws -> [T] { @@ -1003,7 +1003,6 @@ extension Connection { AnyIterator { statement.next().map { Row(columnNames, $0) } } } } - public func prepareRowIterator(_ query: QueryType) throws -> RowIterator { let expression = query.expression @@ -1017,18 +1016,18 @@ extension Connection { var names = each.expression.template.split { $0 == "." }.map(String.init) let column = names.removeLast() let namespace = names.joined(separator: ".") - - func expandGlob(_ namespace: Bool) -> ((QueryType) throws -> Void) { - return { (query: QueryType) throws -> (Void) in - var q = type(of: query).init(query.clauses.from.name, database: query.clauses.from.database) - q.clauses.select = query.clauses.select - let e = q.expression - var names = try self.prepare(e.template, e.bindings).columnNames.map { $0.quote() } - if namespace { names = names.map { "\(query.tableName().expression.template).\($0)" } } + + func expandGlob(_ namespace: Bool) -> (QueryType) throws -> Void { + { (queryType: QueryType) throws -> Void in + var query = type(of: queryType).init(queryType.clauses.from.name, database: queryType.clauses.from.database) + query.clauses.select = queryType.clauses.select + let expression = query.expression + var names = try self.prepare(expression.template, expression.bindings).columnNames.map { $0.quote() } + if namespace { names = names.map { "\(queryType.tableName().expression.template).\($0)" } } for name in names { columnNames[name] = idx; idx += 1 } } } - + if column == "*" { var select = query select.clauses.select = (false, [Expression(literal: "*") as Expressible]) @@ -1047,37 +1046,37 @@ extension Connection { } continue } - + columnNames[each.expression.template] = idx idx += 1 } return columnNames } - public func scalar(_ query: ScalarQuery) throws -> V { + public func scalar(_ query: ScalarQuery) throws -> V { let expression = query.expression return value(try scalar(expression.template, expression.bindings)) } - public func scalar(_ query: ScalarQuery) throws -> V.ValueType? { + public func scalar(_ query: ScalarQuery) throws -> V.ValueType? { let expression = query.expression guard let value = try scalar(expression.template, expression.bindings) as? V.Datatype else { return nil } return V.fromDatatypeValue(value) } - public func scalar(_ query: Select) throws -> V { + public func scalar(_ query: Select) throws -> V { let expression = query.expression return value(try scalar(expression.template, expression.bindings)) } - public func scalar(_ query: Select) throws -> V.ValueType? { + public func scalar(_ query: Select) throws -> V.ValueType? { let expression = query.expression guard let value = try scalar(expression.template, expression.bindings) as? V.Datatype else { return nil } return V.fromDatatypeValue(value) } public func pluck(_ query: QueryType) throws -> Row? { - return try prepareRowIterator(query.limit(1, query.clauses.limit?.offset)).failableNext() + try prepareRowIterator(query.limit(1, query.clauses.limit?.offset)).failableNext() } /// Runs an `Insert` query. @@ -1096,7 +1095,7 @@ extension Connection { let expression = query.expression return try sync { try self.run(expression.template, expression.bindings) - return self.lastInsertRowid + return lastInsertRowid } } @@ -1112,7 +1111,7 @@ extension Connection { let expression = query.expression return try sync { try self.run(expression.template, expression.bindings) - return self.changes + return changes } } @@ -1127,7 +1126,7 @@ extension Connection { let expression = query.expression return try sync { try self.run(expression.template, expression.bindings) - return self.changes + return changes } } @@ -1186,17 +1185,19 @@ public struct Row { return valueAtIndex(idx) } - public subscript(column: Expression) -> T { - return try! get(column) + public subscript(column: Expression) -> T { + // swiftlint:disable:next force_try + try! get(column) } - public subscript(column: Expression) -> T? { - return try! get(column) + public subscript(column: Expression) -> T? { + // swiftlint:disable:next force_try + try! get(column) } } /// Determines the join operator for a query’s `JOIN` clause. -public enum JoinType : String { +public enum JoinType: String { /// A `CROSS` join. case cross = "CROSS" @@ -1241,12 +1242,11 @@ public struct QueryClauses { var order = [Expressible]() var limit: (length: Int, offset: Int?)? - + var union = [QueryType]() fileprivate init(_ name: String, alias: String?, database: String?) { - self.from = (name, alias, database) + from = (name, alias, database) } } - diff --git a/Sources/SQLite/Typed/Schema.swift b/Sources/SQLite/Typed/Schema.swift index febfe68c..726f3e27 100644 --- a/Sources/SQLite/Typed/Schema.swift +++ b/Sources/SQLite/Typed/Schema.swift @@ -27,7 +27,7 @@ extension SchemaType { // MARK: - DROP TABLE / VIEW / VIRTUAL TABLE public func drop(ifExists: Bool = false) -> String { - return drop("TABLE", tableName(), ifExists) + drop("TABLE", tableName(), ifExists) } } @@ -36,7 +36,8 @@ extension Table { // MARK: - CREATE TABLE - public func create(temporary: Bool = false, ifNotExists: Bool = false, withoutRowid: Bool = false, block: (TableBuilder) -> Void) -> String { + public func create(temporary: Bool = false, ifNotExists: Bool = false, withoutRowid: Bool = false, + block: (TableBuilder) -> Void) -> String { let builder = TableBuilder() block(builder) @@ -62,56 +63,64 @@ extension Table { // MARK: - ALTER TABLE … ADD COLUMN - public func addColumn(_ name: Expression, check: Expression? = nil, defaultValue: V) -> String { - return addColumn(definition(name, V.declaredDatatype, nil, false, false, check, defaultValue, nil, nil)) + public func addColumn(_ name: Expression, check: Expression? = nil, defaultValue: V) -> String { + addColumn(definition(name, V.declaredDatatype, nil, false, false, check, defaultValue, nil, nil)) } - public func addColumn(_ name: Expression, check: Expression, defaultValue: V) -> String { - return addColumn(definition(name, V.declaredDatatype, nil, false, false, check, defaultValue, nil, nil)) + public func addColumn(_ name: Expression, check: Expression, defaultValue: V) -> String { + addColumn(definition(name, V.declaredDatatype, nil, false, false, check, defaultValue, nil, nil)) } - public func addColumn(_ name: Expression, check: Expression? = nil, defaultValue: V? = nil) -> String { - return addColumn(definition(name, V.declaredDatatype, nil, true, false, check, defaultValue, nil, nil)) + public func addColumn(_ name: Expression, check: Expression? = nil, defaultValue: V? = nil) -> String { + addColumn(definition(name, V.declaredDatatype, nil, true, false, check, defaultValue, nil, nil)) } - public func addColumn(_ name: Expression, check: Expression, defaultValue: V? = nil) -> String { - return addColumn(definition(name, V.declaredDatatype, nil, true, false, check, defaultValue, nil, nil)) + public func addColumn(_ name: Expression, check: Expression, defaultValue: V? = nil) -> String { + addColumn(definition(name, V.declaredDatatype, nil, true, false, check, defaultValue, nil, nil)) } - public func addColumn(_ name: Expression, unique: Bool = false, check: Expression? = nil, references table: QueryType, _ other: Expression) -> String where V.Datatype == Int64 { - return addColumn(definition(name, V.declaredDatatype, nil, false, unique, check, nil, (table, other), nil)) + public func addColumn(_ name: Expression, unique: Bool = false, check: Expression? = nil, + references table: QueryType, _ other: Expression) -> String where V.Datatype == Int64 { + addColumn(definition(name, V.declaredDatatype, nil, false, unique, check, nil, (table, other), nil)) } - public func addColumn(_ name: Expression, unique: Bool = false, check: Expression, references table: QueryType, _ other: Expression) -> String where V.Datatype == Int64 { - return addColumn(definition(name, V.declaredDatatype, nil, false, unique, check, nil, (table, other), nil)) + public func addColumn(_ name: Expression, unique: Bool = false, check: Expression, + references table: QueryType, _ other: Expression) -> String where V.Datatype == Int64 { + addColumn(definition(name, V.declaredDatatype, nil, false, unique, check, nil, (table, other), nil)) } - public func addColumn(_ name: Expression, unique: Bool = false, check: Expression? = nil, references table: QueryType, _ other: Expression) -> String where V.Datatype == Int64 { - return addColumn(definition(name, V.declaredDatatype, nil, true, unique, check, nil, (table, other), nil)) + public func addColumn(_ name: Expression, unique: Bool = false, check: Expression? = nil, + references table: QueryType, _ other: Expression) -> String where V.Datatype == Int64 { + addColumn(definition(name, V.declaredDatatype, nil, true, unique, check, nil, (table, other), nil)) } - public func addColumn(_ name: Expression, unique: Bool = false, check: Expression, references table: QueryType, _ other: Expression) -> String where V.Datatype == Int64 { - return addColumn(definition(name, V.declaredDatatype, nil, true, unique, check, nil, (table, other), nil)) + public func addColumn(_ name: Expression, unique: Bool = false, check: Expression, + references table: QueryType, _ other: Expression) -> String where V.Datatype == Int64 { + addColumn(definition(name, V.declaredDatatype, nil, true, unique, check, nil, (table, other), nil)) } - public func addColumn(_ name: Expression, check: Expression? = nil, defaultValue: V, collate: Collation) -> String where V.Datatype == String { - return addColumn(definition(name, V.declaredDatatype, nil, false, false, check, defaultValue, nil, collate)) + public func addColumn(_ name: Expression, check: Expression? = nil, defaultValue: V, + collate: Collation) -> String where V.Datatype == String { + addColumn(definition(name, V.declaredDatatype, nil, false, false, check, defaultValue, nil, collate)) } - public func addColumn(_ name: Expression, check: Expression, defaultValue: V, collate: Collation) -> String where V.Datatype == String { - return addColumn(definition(name, V.declaredDatatype, nil, false, false, check, defaultValue, nil, collate)) + public func addColumn(_ name: Expression, check: Expression, defaultValue: V, + collate: Collation) -> String where V.Datatype == String { + addColumn(definition(name, V.declaredDatatype, nil, false, false, check, defaultValue, nil, collate)) } - public func addColumn(_ name: Expression, check: Expression? = nil, defaultValue: V? = nil, collate: Collation) -> String where V.Datatype == String { - return addColumn(definition(name, V.declaredDatatype, nil, true, false, check, defaultValue, nil, collate)) + public func addColumn(_ name: Expression, check: Expression? = nil, defaultValue: V? = nil, + collate: Collation) -> String where V.Datatype == String { + addColumn(definition(name, V.declaredDatatype, nil, true, false, check, defaultValue, nil, collate)) } - public func addColumn(_ name: Expression, check: Expression, defaultValue: V? = nil, collate: Collation) -> String where V.Datatype == String { - return addColumn(definition(name, V.declaredDatatype, nil, true, false, check, defaultValue, nil, collate)) + public func addColumn(_ name: Expression, check: Expression, defaultValue: V? = nil, + collate: Collation) -> String where V.Datatype == String { + addColumn(definition(name, V.declaredDatatype, nil, true, false, check, defaultValue, nil, collate)) } fileprivate func addColumn(_ expression: Expressible) -> String { - return " ".join([ + " ".join([ Expression(literal: "ALTER TABLE"), tableName(), Expression(literal: "ADD COLUMN"), @@ -122,7 +131,7 @@ extension Table { // MARK: - ALTER TABLE … RENAME TO public func rename(_ to: Table) -> String { - return rename(to: to) + rename(to: to) } // MARK: - CREATE INDEX @@ -140,9 +149,8 @@ extension Table { // MARK: - DROP INDEX - public func dropIndex(_ columns: Expressible..., ifExists: Bool = false) -> String { - return drop("INDEX", indexName(columns), ifExists) + drop("INDEX", indexName(columns), ifExists) } fileprivate func indexName(_ columns: [Expressible]) -> Expressible { @@ -180,7 +188,7 @@ extension View { // MARK: - DROP VIEW public func drop(ifExists: Bool = false) -> String { - return drop("VIEW", tableName(), ifExists) + drop("VIEW", tableName(), ifExists) } } @@ -202,7 +210,7 @@ extension VirtualTable { // MARK: - ALTER TABLE … RENAME TO public func rename(_ to: VirtualTable) -> String { - return rename(to: to) + rename(to: to) } } @@ -211,138 +219,175 @@ public final class TableBuilder { fileprivate var definitions = [Expressible]() - public func column(_ name: Expression, unique: Bool = false, check: Expression? = nil, defaultValue: Expression? = nil) { + public func column(_ name: Expression, unique: Bool = false, check: Expression? = nil, + defaultValue: Expression? = nil) { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, nil) } - public func column(_ name: Expression, unique: Bool = false, check: Expression? = nil, defaultValue: V) { + public func column(_ name: Expression, unique: Bool = false, check: Expression? = nil, + defaultValue: V) { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, nil) } - public func column(_ name: Expression, unique: Bool = false, check: Expression, defaultValue: Expression? = nil) { + public func column(_ name: Expression, unique: Bool = false, check: Expression, + defaultValue: Expression? = nil) { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, nil) } - public func column(_ name: Expression, unique: Bool = false, check: Expression, defaultValue: V) { + public func column(_ name: Expression, unique: Bool = false, check: Expression, + defaultValue: V) { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, nil) } - public func column(_ name: Expression, unique: Bool = false, check: Expression? = nil, defaultValue: Expression? = nil) { + public func column(_ name: Expression, unique: Bool = false, check: Expression? = nil, + defaultValue: Expression? = nil) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } - public func column(_ name: Expression, unique: Bool = false, check: Expression? = nil, defaultValue: Expression) { + public func column(_ name: Expression, unique: Bool = false, check: Expression? = nil, + defaultValue: Expression) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } - public func column(_ name: Expression, unique: Bool = false, check: Expression? = nil, defaultValue: V) { + public func column(_ name: Expression, unique: Bool = false, check: Expression? = nil, + defaultValue: V) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } - public func column(_ name: Expression, unique: Bool = false, check: Expression, defaultValue: Expression? = nil) { + public func column(_ name: Expression, unique: Bool = false, check: Expression, + defaultValue: Expression? = nil) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } - public func column(_ name: Expression, unique: Bool = false, check: Expression, defaultValue: Expression) { + public func column(_ name: Expression, unique: Bool = false, check: Expression, + defaultValue: Expression) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } - public func column(_ name: Expression, unique: Bool = false, check: Expression, defaultValue: V) { + public func column(_ name: Expression, unique: Bool = false, check: Expression, + defaultValue: V) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } - public func column(_ name: Expression, primaryKey: Bool, check: Expression? = nil, defaultValue: Expression? = nil) { + public func column(_ name: Expression, primaryKey: Bool, check: Expression? = nil, + defaultValue: Expression? = nil) { column(name, V.declaredDatatype, primaryKey ? .default : nil, false, false, check, defaultValue, nil, nil) } - public func column(_ name: Expression, primaryKey: Bool, check: Expression, defaultValue: Expression? = nil) { + public func column(_ name: Expression, primaryKey: Bool, check: Expression, + defaultValue: Expression? = nil) { column(name, V.declaredDatatype, primaryKey ? .default : nil, false, false, check, defaultValue, nil, nil) } - public func column(_ name: Expression, primaryKey: PrimaryKey, check: Expression? = nil) where V.Datatype == Int64 { + public func column(_ name: Expression, primaryKey: PrimaryKey, + check: Expression? = nil) where V.Datatype == Int64 { column(name, V.declaredDatatype, primaryKey, false, false, check, nil, nil, nil) } - public func column(_ name: Expression, primaryKey: PrimaryKey, check: Expression) where V.Datatype == Int64 { + public func column(_ name: Expression, primaryKey: PrimaryKey, + check: Expression) where V.Datatype == Int64 { column(name, V.declaredDatatype, primaryKey, false, false, check, nil, nil, nil) } - public func column(_ name: Expression, unique: Bool = false, check: Expression? = nil, references table: QueryType, _ other: Expression) where V.Datatype == Int64 { + public func column(_ name: Expression, unique: Bool = false, check: Expression? = nil, + references table: QueryType, _ other: Expression) where V.Datatype == Int64 { column(name, V.declaredDatatype, nil, false, unique, check, nil, (table, other), nil) } - public func column(_ name: Expression, unique: Bool = false, check: Expression, references table: QueryType, _ other: Expression) where V.Datatype == Int64 { + public func column(_ name: Expression, unique: Bool = false, check: Expression, + references table: QueryType, _ other: Expression) where V.Datatype == Int64 { column(name, V.declaredDatatype, nil, false, unique, check, nil, (table, other), nil) } - public func column(_ name: Expression, unique: Bool = false, check: Expression? = nil, references table: QueryType, _ other: Expression) where V.Datatype == Int64 { + public func column(_ name: Expression, unique: Bool = false, check: Expression? = nil, + references table: QueryType, _ other: Expression) where V.Datatype == Int64 { column(name, V.declaredDatatype, nil, true, unique, check, nil, (table, other), nil) } - public func column(_ name: Expression, unique: Bool = false, check: Expression, references table: QueryType, _ other: Expression) where V.Datatype == Int64 { + public func column(_ name: Expression, unique: Bool = false, check: Expression, + references table: QueryType, _ other: Expression) where V.Datatype == Int64 { column(name, V.declaredDatatype, nil, true, unique, check, nil, (table, other), nil) } - public func column(_ name: Expression, unique: Bool = false, check: Expression? = nil, defaultValue: Expression? = nil, collate: Collation) where V.Datatype == String { + public func column(_ name: Expression, unique: Bool = false, check: Expression? = nil, + defaultValue: Expression? = nil, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } - public func column(_ name: Expression, unique: Bool = false, check: Expression? = nil, defaultValue: V, collate: Collation) where V.Datatype == String { + public func column(_ name: Expression, unique: Bool = false, check: Expression? = nil, + defaultValue: V, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } - public func column(_ name: Expression, unique: Bool = false, check: Expression, defaultValue: Expression? = nil, collate: Collation) where V.Datatype == String { + public func column(_ name: Expression, unique: Bool = false, check: Expression, + defaultValue: Expression? = nil, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } - public func column(_ name: Expression, unique: Bool = false, check: Expression, defaultValue: V, collate: Collation) where V.Datatype == String { + public func column(_ name: Expression, unique: Bool = false, check: Expression, + defaultValue: V, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } - public func column(_ name: Expression, unique: Bool = false, check: Expression? = nil, defaultValue: Expression? = nil, collate: Collation) where V.Datatype == String { + public func column(_ name: Expression, unique: Bool = false, check: Expression? = nil, + defaultValue: Expression? = nil, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, collate) } - public func column(_ name: Expression, unique: Bool = false, check: Expression? = nil, defaultValue: Expression, collate: Collation) where V.Datatype == String { + public func column(_ name: Expression, unique: Bool = false, check: Expression? = nil, + defaultValue: Expression, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, collate) } - public func column(_ name: Expression, unique: Bool = false, check: Expression? = nil, defaultValue: V, collate: Collation) where V.Datatype == String { + public func column(_ name: Expression, unique: Bool = false, check: Expression? = nil, + defaultValue: V, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, collate) } - public func column(_ name: Expression, unique: Bool = false, check: Expression, defaultValue: Expression? = nil, collate: Collation) where V.Datatype == String { + public func column(_ name: Expression, unique: Bool = false, check: Expression, + defaultValue: Expression? = nil, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, collate) } - public func column(_ name: Expression, unique: Bool = false, check: Expression, defaultValue: Expression, collate: Collation) where V.Datatype == String { + public func column(_ name: Expression, unique: Bool = false, check: Expression, + defaultValue: Expression, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, collate) } - public func column(_ name: Expression, unique: Bool = false, check: Expression, defaultValue: V, collate: Collation) where V.Datatype == String { + public func column(_ name: Expression, unique: Bool = false, check: Expression, + defaultValue: V, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, collate) } - fileprivate func column(_ name: Expressible, _ datatype: String, _ primaryKey: PrimaryKey?, _ null: Bool, _ unique: Bool, _ check: Expressible?, _ defaultValue: Expressible?, _ references: (QueryType, Expressible)?, _ collate: Collation?) { + // swiftlint:disable:next function_parameter_count + fileprivate func column(_ name: Expressible, _ datatype: String, _ primaryKey: PrimaryKey?, _ null: Bool, + _ unique: Bool, _ check: Expressible?, _ defaultValue: Expressible?, + _ references: (QueryType, Expressible)?, _ collate: Collation?) { definitions.append(definition(name, datatype, primaryKey, null, unique, check, defaultValue, references, collate)) } // MARK: - - public func primaryKey(_ column: Expression) { + public func primaryKey(_ column: Expression) { primaryKey([column]) } - public func primaryKey(_ compositeA: Expression, _ b: Expression) { - primaryKey([compositeA, b]) + public func primaryKey(_ compositeA: Expression, + _ expr: Expression) { + primaryKey([compositeA, expr]) } - public func primaryKey(_ compositeA: Expression, _ b: Expression, _ c: Expression) { - primaryKey([compositeA, b, c]) + public func primaryKey(_ compositeA: Expression, + _ expr1: Expression, + _ expr2: Expression) { + primaryKey([compositeA, expr1, expr2]) } - public func primaryKey(_ compositeA: Expression, _ b: Expression, _ c: Expression, _ d: Expression) { - primaryKey([compositeA, b, c, d]) + public func primaryKey(_ compositeA: Expression, + _ expr1: Expression, + _ expr2: Expression, + _ expr3: Expression) { + primaryKey([compositeA, expr1, expr2, expr3]) } fileprivate func primaryKey(_ composite: [Expressible]) { @@ -379,29 +424,37 @@ public final class TableBuilder { } - public func foreignKey(_ column: Expression, references table: QueryType, _ other: Expression, update: Dependency? = nil, delete: Dependency? = nil) { + public func foreignKey(_ column: Expression, references table: QueryType, _ other: Expression, + update: Dependency? = nil, delete: Dependency? = nil) { foreignKey(column, (table, other), update, delete) } - public func foreignKey(_ column: Expression, references table: QueryType, _ other: Expression, update: Dependency? = nil, delete: Dependency? = nil) { + public func foreignKey(_ column: Expression, references table: QueryType, _ other: Expression, + update: Dependency? = nil, delete: Dependency? = nil) { foreignKey(column, (table, other), update, delete) } - public func foreignKey(_ composite: (Expression, Expression), references table: QueryType, _ other: (Expression, Expression), update: Dependency? = nil, delete: Dependency? = nil) { + public func foreignKey(_ composite: (Expression, Expression), + references table: QueryType, _ other: (Expression, Expression), + update: Dependency? = nil, delete: Dependency? = nil) { let composite = ", ".join([composite.0, composite.1]) let references = (table, ", ".join([other.0, other.1])) foreignKey(composite, references, update, delete) } - public func foreignKey(_ composite: (Expression, Expression, Expression), references table: QueryType, _ other: (Expression, Expression, Expression), update: Dependency? = nil, delete: Dependency? = nil) { + public func foreignKey(_ composite: (Expression, Expression, Expression), + references table: QueryType, + _ other: (Expression, Expression, Expression), + update: Dependency? = nil, delete: Dependency? = nil) { let composite = ", ".join([composite.0, composite.1, composite.2]) let references = (table, ", ".join([other.0, other.1, other.2])) foreignKey(composite, references, update, delete) } - fileprivate func foreignKey(_ column: Expressible, _ references: (QueryType, Expressible), _ update: Dependency?, _ delete: Dependency?) { + fileprivate func foreignKey(_ column: Expressible, _ references: (QueryType, Expressible), + _ update: Dependency?, _ delete: Dependency?) { let clauses: [Expressible?] = [ "FOREIGN KEY".prefix(column), reference(references), @@ -439,10 +492,10 @@ public struct Module { } -extension Module : Expressible { +extension Module: Expressible { public var expression: Expression { - return name.wrap(arguments) + name.wrap(arguments) } } @@ -464,7 +517,7 @@ private extension QueryType { } func rename(to: Self) -> String { - return " ".join([ + " ".join([ Expression(literal: "ALTER TABLE"), tableName(), Expression(literal: "RENAME TO"), @@ -484,7 +537,10 @@ private extension QueryType { } -private func definition(_ column: Expressible, _ datatype: String, _ primaryKey: PrimaryKey?, _ null: Bool, _ unique: Bool, _ check: Expressible?, _ defaultValue: Expressible?, _ references: (QueryType, Expressible)?, _ collate: Collation?) -> Expressible { +// swiftlint:disable:next function_parameter_count +private func definition(_ column: Expressible, _ datatype: String, _ primaryKey: PrimaryKey?, _ null: Bool, + _ unique: Bool, _ check: Expressible?, _ defaultValue: Expressible?, + _ references: (QueryType, Expressible)?, _ collate: Collation?) -> Expressible { let clauses: [Expressible?] = [ column, Expression(literal: datatype), @@ -501,14 +557,14 @@ private func definition(_ column: Expressible, _ datatype: String, _ primaryKey: } private func reference(_ primary: (QueryType, Expressible)) -> Expressible { - return " ".join([ + " ".join([ Expression(literal: "REFERENCES"), primary.0.tableName(qualified: false), "".wrap(primary.1) as Expression ]) } -private enum Modifier : String { +private enum Modifier: String { case unique = "UNIQUE" diff --git a/Sources/SQLite/Typed/Setter.swift b/Sources/SQLite/Typed/Setter.swift index 3d3170f6..7910cab8 100644 --- a/Sources/SQLite/Typed/Setter.swift +++ b/Sources/SQLite/Typed/Setter.swift @@ -35,27 +35,27 @@ public struct Setter { let column: Expressible let value: Expressible - fileprivate init(column: Expression, value: Expression) { + fileprivate init(column: Expression, value: Expression) { self.column = column self.value = value } - fileprivate init(column: Expression, value: V) { + fileprivate init(column: Expression, value: V) { self.column = column self.value = value } - fileprivate init(column: Expression, value: Expression) { + fileprivate init(column: Expression, value: Expression) { self.column = column self.value = value } - fileprivate init(column: Expression, value: Expression) { + fileprivate init(column: Expression, value: Expression) { self.column = column self.value = value } - fileprivate init(column: Expression, value: V?) { + fileprivate init(column: Expression, value: V?) { self.column = column self.value = Expression(value: value) } @@ -63,220 +63,220 @@ public struct Setter { init(excluded column: Expressible) { let excluded = Expression("excluded") self.column = column - self.value = ".".join([excluded, column.expression]) + value = ".".join([excluded, column.expression]) } } -extension Setter : Expressible { +extension Setter: Expressible { public var expression: Expression { - return "=".infix(column, value, wrap: false) + "=".infix(column, value, wrap: false) } } -public func <-(column: Expression, value: Expression) -> Setter { - return Setter(column: column, value: value) +public func <-(column: Expression, value: Expression) -> Setter { + Setter(column: column, value: value) } -public func <-(column: Expression, value: V) -> Setter { - return Setter(column: column, value: value) +public func <-(column: Expression, value: V) -> Setter { + Setter(column: column, value: value) } -public func <-(column: Expression, value: Expression) -> Setter { - return Setter(column: column, value: value) +public func <-(column: Expression, value: Expression) -> Setter { + Setter(column: column, value: value) } -public func <-(column: Expression, value: Expression) -> Setter { - return Setter(column: column, value: value) +public func <-(column: Expression, value: Expression) -> Setter { + Setter(column: column, value: value) } -public func <-(column: Expression, value: V?) -> Setter { - return Setter(column: column, value: value) +public func <-(column: Expression, value: V?) -> Setter { + Setter(column: column, value: value) } public func +=(column: Expression, value: Expression) -> Setter { - return column <- column + value + column <- column + value } public func +=(column: Expression, value: String) -> Setter { - return column <- column + value + column <- column + value } public func +=(column: Expression, value: Expression) -> Setter { - return column <- column + value + column <- column + value } public func +=(column: Expression, value: Expression) -> Setter { - return column <- column + value + column <- column + value } public func +=(column: Expression, value: String) -> Setter { - return column <- column + value + column <- column + value } -public func +=(column: Expression, value: Expression) -> Setter where V.Datatype : Number { - return column <- column + value +public func +=(column: Expression, value: Expression) -> Setter where V.Datatype: Number { + column <- column + value } -public func +=(column: Expression, value: V) -> Setter where V.Datatype : Number { - return column <- column + value +public func +=(column: Expression, value: V) -> Setter where V.Datatype: Number { + column <- column + value } -public func +=(column: Expression, value: Expression) -> Setter where V.Datatype : Number { - return column <- column + value +public func +=(column: Expression, value: Expression) -> Setter where V.Datatype: Number { + column <- column + value } -public func +=(column: Expression, value: Expression) -> Setter where V.Datatype : Number { - return column <- column + value +public func +=(column: Expression, value: Expression) -> Setter where V.Datatype: Number { + column <- column + value } -public func +=(column: Expression, value: V) -> Setter where V.Datatype : Number { - return column <- column + value +public func +=(column: Expression, value: V) -> Setter where V.Datatype: Number { + column <- column + value } -public func -=(column: Expression, value: Expression) -> Setter where V.Datatype : Number { - return column <- column - value +public func -=(column: Expression, value: Expression) -> Setter where V.Datatype: Number { + column <- column - value } -public func -=(column: Expression, value: V) -> Setter where V.Datatype : Number { - return column <- column - value +public func -=(column: Expression, value: V) -> Setter where V.Datatype: Number { + column <- column - value } -public func -=(column: Expression, value: Expression) -> Setter where V.Datatype : Number { - return column <- column - value +public func -=(column: Expression, value: Expression) -> Setter where V.Datatype: Number { + column <- column - value } -public func -=(column: Expression, value: Expression) -> Setter where V.Datatype : Number { - return column <- column - value +public func -=(column: Expression, value: Expression) -> Setter where V.Datatype: Number { + column <- column - value } -public func -=(column: Expression, value: V) -> Setter where V.Datatype : Number { - return column <- column - value +public func -=(column: Expression, value: V) -> Setter where V.Datatype: Number { + column <- column - value } -public func *=(column: Expression, value: Expression) -> Setter where V.Datatype : Number { - return column <- column * value +public func *=(column: Expression, value: Expression) -> Setter where V.Datatype: Number { + column <- column * value } -public func *=(column: Expression, value: V) -> Setter where V.Datatype : Number { - return column <- column * value +public func *=(column: Expression, value: V) -> Setter where V.Datatype: Number { + column <- column * value } -public func *=(column: Expression, value: Expression) -> Setter where V.Datatype : Number { - return column <- column * value +public func *=(column: Expression, value: Expression) -> Setter where V.Datatype: Number { + column <- column * value } -public func *=(column: Expression, value: Expression) -> Setter where V.Datatype : Number { - return column <- column * value +public func *=(column: Expression, value: Expression) -> Setter where V.Datatype: Number { + column <- column * value } -public func *=(column: Expression, value: V) -> Setter where V.Datatype : Number { - return column <- column * value +public func *=(column: Expression, value: V) -> Setter where V.Datatype: Number { + column <- column * value } -public func /=(column: Expression, value: Expression) -> Setter where V.Datatype : Number { - return column <- column / value +public func /=(column: Expression, value: Expression) -> Setter where V.Datatype: Number { + column <- column / value } -public func /=(column: Expression, value: V) -> Setter where V.Datatype : Number { - return column <- column / value +public func /=(column: Expression, value: V) -> Setter where V.Datatype: Number { + column <- column / value } -public func /=(column: Expression, value: Expression) -> Setter where V.Datatype : Number { - return column <- column / value +public func /=(column: Expression, value: Expression) -> Setter where V.Datatype: Number { + column <- column / value } -public func /=(column: Expression, value: Expression) -> Setter where V.Datatype : Number { - return column <- column / value +public func /=(column: Expression, value: Expression) -> Setter where V.Datatype: Number { + column <- column / value } -public func /=(column: Expression, value: V) -> Setter where V.Datatype : Number { - return column <- column / value +public func /=(column: Expression, value: V) -> Setter where V.Datatype: Number { + column <- column / value } -public func %=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { - return column <- column % value +public func %=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { + column <- column % value } -public func %=(column: Expression, value: V) -> Setter where V.Datatype == Int64 { - return column <- column % value +public func %=(column: Expression, value: V) -> Setter where V.Datatype == Int64 { + column <- column % value } -public func %=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { - return column <- column % value +public func %=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { + column <- column % value } -public func %=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { - return column <- column % value +public func %=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { + column <- column % value } -public func %=(column: Expression, value: V) -> Setter where V.Datatype == Int64 { - return column <- column % value +public func %=(column: Expression, value: V) -> Setter where V.Datatype == Int64 { + column <- column % value } -public func <<=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { - return column <- column << value +public func <<=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { + column <- column << value } -public func <<=(column: Expression, value: V) -> Setter where V.Datatype == Int64 { - return column <- column << value +public func <<=(column: Expression, value: V) -> Setter where V.Datatype == Int64 { + column <- column << value } -public func <<=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { - return column <- column << value +public func <<=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { + column <- column << value } -public func <<=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { - return column <- column << value +public func <<=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { + column <- column << value } -public func <<=(column: Expression, value: V) -> Setter where V.Datatype == Int64 { - return column <- column << value +public func <<=(column: Expression, value: V) -> Setter where V.Datatype == Int64 { + column <- column << value } -public func >>=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { - return column <- column >> value +public func >>=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { + column <- column >> value } -public func >>=(column: Expression, value: V) -> Setter where V.Datatype == Int64 { - return column <- column >> value +public func >>=(column: Expression, value: V) -> Setter where V.Datatype == Int64 { + column <- column >> value } -public func >>=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { - return column <- column >> value +public func >>=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { + column <- column >> value } -public func >>=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { - return column <- column >> value +public func >>=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { + column <- column >> value } -public func >>=(column: Expression, value: V) -> Setter where V.Datatype == Int64 { - return column <- column >> value +public func >>=(column: Expression, value: V) -> Setter where V.Datatype == Int64 { + column <- column >> value } -public func &=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { - return column <- column & value +public func &=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { + column <- column & value } -public func &=(column: Expression, value: V) -> Setter where V.Datatype == Int64 { - return column <- column & value +public func &=(column: Expression, value: V) -> Setter where V.Datatype == Int64 { + column <- column & value } -public func &=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { - return column <- column & value +public func &=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { + column <- column & value } -public func &=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { - return column <- column & value +public func &=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { + column <- column & value } -public func &=(column: Expression, value: V) -> Setter where V.Datatype == Int64 { - return column <- column & value +public func &=(column: Expression, value: V) -> Setter where V.Datatype == Int64 { + column <- column & value } -public func |=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { - return column <- column | value +public func |=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { + column <- column | value } -public func |=(column: Expression, value: V) -> Setter where V.Datatype == Int64 { - return column <- column | value +public func |=(column: Expression, value: V) -> Setter where V.Datatype == Int64 { + column <- column | value } -public func |=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { - return column <- column | value +public func |=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { + column <- column | value } -public func |=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { - return column <- column | value +public func |=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { + column <- column | value } -public func |=(column: Expression, value: V) -> Setter where V.Datatype == Int64 { - return column <- column | value +public func |=(column: Expression, value: V) -> Setter where V.Datatype == Int64 { + column <- column | value } -public func ^=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { - return column <- column ^ value +public func ^=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { + column <- column ^ value } -public func ^=(column: Expression, value: V) -> Setter where V.Datatype == Int64 { - return column <- column ^ value +public func ^=(column: Expression, value: V) -> Setter where V.Datatype == Int64 { + column <- column ^ value } -public func ^=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { - return column <- column ^ value +public func ^=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { + column <- column ^ value } -public func ^=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { - return column <- column ^ value +public func ^=(column: Expression, value: Expression) -> Setter where V.Datatype == Int64 { + column <- column ^ value } -public func ^=(column: Expression, value: V) -> Setter where V.Datatype == Int64 { - return column <- column ^ value +public func ^=(column: Expression, value: V) -> Setter where V.Datatype == Int64 { + column <- column ^ value } -public postfix func ++(column: Expression) -> Setter where V.Datatype == Int64 { - return Expression(column) += 1 +public postfix func ++(column: Expression) -> Setter where V.Datatype == Int64 { + Expression(column) += 1 } -public postfix func ++(column: Expression) -> Setter where V.Datatype == Int64 { - return Expression(column) += 1 +public postfix func ++(column: Expression) -> Setter where V.Datatype == Int64 { + Expression(column) += 1 } -public postfix func --(column: Expression) -> Setter where V.Datatype == Int64 { - return Expression(column) -= 1 +public postfix func --(column: Expression) -> Setter where V.Datatype == Int64 { + Expression(column) -= 1 } -public postfix func --(column: Expression) -> Setter where V.Datatype == Int64 { - return Expression(column) -= 1 +public postfix func --(column: Expression) -> Setter where V.Datatype == Int64 { + Expression(column) -= 1 } diff --git a/Tests/.swiftlint.yml b/Tests/.swiftlint.yml new file mode 100644 index 00000000..3537085c --- /dev/null +++ b/Tests/.swiftlint.yml @@ -0,0 +1,20 @@ +parent_config: ../.swiftlint.yml + +disabled_rules: + - force_cast + - force_try + - identifier_name + +type_body_length: + warning: 800 + error: 800 + +function_body_length: + warning: 200 + error: 200 + +file_length: + warning: 1000 + error: 1000 + + diff --git a/Tests/CocoaPods/.gitignore b/Tests/CocoaPods/.gitignore deleted file mode 100644 index 4cf24de2..00000000 --- a/Tests/CocoaPods/.gitignore +++ /dev/null @@ -1 +0,0 @@ -gems/ diff --git a/Tests/CocoaPods/Gemfile b/Tests/CocoaPods/Gemfile deleted file mode 100644 index da52ec89..00000000 --- a/Tests/CocoaPods/Gemfile +++ /dev/null @@ -1,4 +0,0 @@ -source 'https://rubygems.org' - -gem 'cocoapods', '~> 1.10.2' -gem 'minitest' diff --git a/Tests/CocoaPods/Gemfile.lock b/Tests/CocoaPods/Gemfile.lock deleted file mode 100644 index e0383a67..00000000 --- a/Tests/CocoaPods/Gemfile.lock +++ /dev/null @@ -1,96 +0,0 @@ -GEM - remote: https://rubygems.org/ - specs: - CFPropertyList (3.0.3) - activesupport (5.2.6) - concurrent-ruby (~> 1.0, >= 1.0.2) - i18n (>= 0.7, < 2) - minitest (~> 5.1) - tzinfo (~> 1.1) - addressable (2.8.0) - public_suffix (>= 2.0.2, < 5.0) - algoliasearch (1.27.5) - httpclient (~> 2.8, >= 2.8.3) - json (>= 1.5.1) - atomos (0.1.3) - claide (1.0.3) - cocoapods (1.10.2) - addressable (~> 2.6) - claide (>= 1.0.2, < 2.0) - cocoapods-core (= 1.10.2) - cocoapods-deintegrate (>= 1.0.3, < 2.0) - cocoapods-downloader (>= 1.4.0, < 2.0) - cocoapods-plugins (>= 1.0.0, < 2.0) - cocoapods-search (>= 1.0.0, < 2.0) - cocoapods-trunk (>= 1.4.0, < 2.0) - cocoapods-try (>= 1.1.0, < 2.0) - colored2 (~> 3.1) - escape (~> 0.0.4) - fourflusher (>= 2.3.0, < 3.0) - gh_inspector (~> 1.0) - molinillo (~> 0.6.6) - nap (~> 1.0) - ruby-macho (~> 1.4) - xcodeproj (>= 1.19.0, < 2.0) - cocoapods-core (1.10.2) - activesupport (> 5.0, < 6) - addressable (~> 2.6) - algoliasearch (~> 1.0) - concurrent-ruby (~> 1.1) - fuzzy_match (~> 2.0.4) - nap (~> 1.0) - netrc (~> 0.11) - public_suffix - typhoeus (~> 1.0) - cocoapods-deintegrate (1.0.5) - cocoapods-downloader (1.4.0) - cocoapods-plugins (1.0.0) - nap - cocoapods-search (1.0.1) - cocoapods-trunk (1.5.0) - nap (>= 0.8, < 2.0) - netrc (~> 0.11) - cocoapods-try (1.2.0) - colored2 (3.1.2) - concurrent-ruby (1.1.9) - escape (0.0.4) - ethon (0.14.0) - ffi (>= 1.15.0) - ffi (1.15.3) - fourflusher (2.3.1) - fuzzy_match (2.0.4) - gh_inspector (1.1.3) - httpclient (2.8.3) - i18n (1.8.10) - concurrent-ruby (~> 1.0) - json (2.5.1) - minitest (5.11.3) - molinillo (0.6.6) - nanaimo (0.3.0) - nap (1.1.0) - netrc (0.11.0) - public_suffix (4.0.6) - rexml (3.2.5) - ruby-macho (1.4.0) - thread_safe (0.3.6) - typhoeus (1.4.0) - ethon (>= 0.9.0) - tzinfo (1.2.9) - thread_safe (~> 0.1) - xcodeproj (1.21.0) - CFPropertyList (>= 2.3.3, < 4.0) - atomos (~> 0.1.3) - claide (>= 1.0.2, < 2.0) - colored2 (~> 3.1) - nanaimo (~> 0.3.0) - rexml (~> 3.2.4) - -PLATFORMS - ruby - -DEPENDENCIES - cocoapods (~> 1.10.2) - minitest - -BUNDLED WITH - 2.2.22 diff --git a/Tests/CocoaPods/Makefile b/Tests/CocoaPods/Makefile deleted file mode 100644 index 532dcbff..00000000 --- a/Tests/CocoaPods/Makefile +++ /dev/null @@ -1,15 +0,0 @@ -XCPRETTY := $(shell command -v xcpretty) - -test: install repo_update - @set -e; \ - for test in *_test.rb; do \ - bundle exec ./$$test | $(XCPRETTY) -c; \ - done - -repo_update: - @bundle exec pod repo update --silent - -install: - @bundle install --path gems - -.PHONY: test install diff --git a/Tests/CocoaPods/integration_test.rb b/Tests/CocoaPods/integration_test.rb deleted file mode 100755 index 67b13385..00000000 --- a/Tests/CocoaPods/integration_test.rb +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env ruby - -require 'cocoapods' -require 'cocoapods/validator' -require 'minitest/autorun' - -class IntegrationTest < Minitest::Test - - def test_validate_project - assert validator.validate, "validation failed: #{validator.failure_reason}" - end - - private - - def validator - @validator ||= Pod::Validator.new(podspec, ['https://github.com/CocoaPods/Specs.git']).tap do |validator| - validator.config.verbose = true - validator.no_clean = true - validator.use_frameworks = true - validator.fail_fast = true - validator.local = true - validator.allow_warnings = true - subspec = ENV['VALIDATOR_SUBSPEC'] - if subspec == 'none' - validator.no_subspecs = true - else - validator.only_subspec = subspec - end - end - end - - def podspec - File.expand_path(File.dirname(__FILE__) + '/../../SQLite.swift.podspec') - end -end diff --git a/Tests/SQLiteTests/AggregateFunctionsTests.swift b/Tests/SQLiteTests/AggregateFunctionsTests.swift index 6b583ccf..71ac79fb 100644 --- a/Tests/SQLiteTests/AggregateFunctionsTests.swift +++ b/Tests/SQLiteTests/AggregateFunctionsTests.swift @@ -1,68 +1,68 @@ import XCTest import SQLite -class AggregateFunctionsTests : XCTestCase { +class AggregateFunctionsTests: XCTestCase { func test_distinct_prependsExpressionsWithDistinctKeyword() { - AssertSQL("DISTINCT \"int\"", int.distinct) - AssertSQL("DISTINCT \"intOptional\"", intOptional.distinct) - AssertSQL("DISTINCT \"double\"", double.distinct) - AssertSQL("DISTINCT \"doubleOptional\"", doubleOptional.distinct) - AssertSQL("DISTINCT \"string\"", string.distinct) - AssertSQL("DISTINCT \"stringOptional\"", stringOptional.distinct) + assertSQL("DISTINCT \"int\"", int.distinct) + assertSQL("DISTINCT \"intOptional\"", intOptional.distinct) + assertSQL("DISTINCT \"double\"", double.distinct) + assertSQL("DISTINCT \"doubleOptional\"", doubleOptional.distinct) + assertSQL("DISTINCT \"string\"", string.distinct) + assertSQL("DISTINCT \"stringOptional\"", stringOptional.distinct) } func test_count_wrapsOptionalExpressionsWithCountFunction() { - AssertSQL("count(\"intOptional\")", intOptional.count) - AssertSQL("count(\"doubleOptional\")", doubleOptional.count) - AssertSQL("count(\"stringOptional\")", stringOptional.count) + assertSQL("count(\"intOptional\")", intOptional.count) + assertSQL("count(\"doubleOptional\")", doubleOptional.count) + assertSQL("count(\"stringOptional\")", stringOptional.count) } func test_max_wrapsComparableExpressionsWithMaxFunction() { - AssertSQL("max(\"int\")", int.max) - AssertSQL("max(\"intOptional\")", intOptional.max) - AssertSQL("max(\"double\")", double.max) - AssertSQL("max(\"doubleOptional\")", doubleOptional.max) - AssertSQL("max(\"string\")", string.max) - AssertSQL("max(\"stringOptional\")", stringOptional.max) - AssertSQL("max(\"date\")", date.max) - AssertSQL("max(\"dateOptional\")", dateOptional.max) + assertSQL("max(\"int\")", int.max) + assertSQL("max(\"intOptional\")", intOptional.max) + assertSQL("max(\"double\")", double.max) + assertSQL("max(\"doubleOptional\")", doubleOptional.max) + assertSQL("max(\"string\")", string.max) + assertSQL("max(\"stringOptional\")", stringOptional.max) + assertSQL("max(\"date\")", date.max) + assertSQL("max(\"dateOptional\")", dateOptional.max) } func test_min_wrapsComparableExpressionsWithMinFunction() { - AssertSQL("min(\"int\")", int.min) - AssertSQL("min(\"intOptional\")", intOptional.min) - AssertSQL("min(\"double\")", double.min) - AssertSQL("min(\"doubleOptional\")", doubleOptional.min) - AssertSQL("min(\"string\")", string.min) - AssertSQL("min(\"stringOptional\")", stringOptional.min) - AssertSQL("min(\"date\")", date.min) - AssertSQL("min(\"dateOptional\")", dateOptional.min) + assertSQL("min(\"int\")", int.min) + assertSQL("min(\"intOptional\")", intOptional.min) + assertSQL("min(\"double\")", double.min) + assertSQL("min(\"doubleOptional\")", doubleOptional.min) + assertSQL("min(\"string\")", string.min) + assertSQL("min(\"stringOptional\")", stringOptional.min) + assertSQL("min(\"date\")", date.min) + assertSQL("min(\"dateOptional\")", dateOptional.min) } func test_average_wrapsNumericExpressionsWithAvgFunction() { - AssertSQL("avg(\"int\")", int.average) - AssertSQL("avg(\"intOptional\")", intOptional.average) - AssertSQL("avg(\"double\")", double.average) - AssertSQL("avg(\"doubleOptional\")", doubleOptional.average) + assertSQL("avg(\"int\")", int.average) + assertSQL("avg(\"intOptional\")", intOptional.average) + assertSQL("avg(\"double\")", double.average) + assertSQL("avg(\"doubleOptional\")", doubleOptional.average) } func test_sum_wrapsNumericExpressionsWithSumFunction() { - AssertSQL("sum(\"int\")", int.sum) - AssertSQL("sum(\"intOptional\")", intOptional.sum) - AssertSQL("sum(\"double\")", double.sum) - AssertSQL("sum(\"doubleOptional\")", doubleOptional.sum) + assertSQL("sum(\"int\")", int.sum) + assertSQL("sum(\"intOptional\")", intOptional.sum) + assertSQL("sum(\"double\")", double.sum) + assertSQL("sum(\"doubleOptional\")", doubleOptional.sum) } func test_total_wrapsNumericExpressionsWithTotalFunction() { - AssertSQL("total(\"int\")", int.total) - AssertSQL("total(\"intOptional\")", intOptional.total) - AssertSQL("total(\"double\")", double.total) - AssertSQL("total(\"doubleOptional\")", doubleOptional.total) + assertSQL("total(\"int\")", int.total) + assertSQL("total(\"intOptional\")", intOptional.total) + assertSQL("total(\"double\")", double.total) + assertSQL("total(\"doubleOptional\")", doubleOptional.total) } func test_count_withStar_wrapsStarWithCountFunction() { - AssertSQL("count(*)", count(*)) + assertSQL("count(*)", count(*)) } } diff --git a/Tests/SQLiteTests/BlobTests.swift b/Tests/SQLiteTests/BlobTests.swift index 817205d6..87eb5709 100644 --- a/Tests/SQLiteTests/BlobTests.swift +++ b/Tests/SQLiteTests/BlobTests.swift @@ -1,7 +1,7 @@ import XCTest import SQLite -class BlobTests : XCTestCase { +class BlobTests: XCTestCase { func test_toHex() { let blob = Blob(bytes: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 150, 250, 255]) diff --git a/Tests/SQLiteTests/CipherTests.swift b/Tests/SQLiteTests/CipherTests.swift index a27ac17d..77e8e7f0 100644 --- a/Tests/SQLiteTests/CipherTests.swift +++ b/Tests/SQLiteTests/CipherTests.swift @@ -77,7 +77,7 @@ class CipherTests: XCTestCase { // sqlite> pragma key = 'sqlcipher-test'; // sqlite> CREATE TABLE foo (bar TEXT); // sqlite> INSERT INTO foo (bar) VALUES ('world'); - guard let cipherVersion:String = db1.cipherVersion, + guard let cipherVersion: String = db1.cipherVersion, cipherVersion.starts(with: "3.") || cipherVersion.starts(with: "4.") else { return } @@ -85,12 +85,12 @@ class CipherTests: XCTestCase { fixture("encrypted-3.x", withExtension: "sqlite") : fixture("encrypted-4.x", withExtension: "sqlite") - try! FileManager.default.setAttributes([FileAttributeKey.immutable : 1], ofItemAtPath: encryptedFile) + try! FileManager.default.setAttributes([FileAttributeKey.immutable: 1], ofItemAtPath: encryptedFile) XCTAssertFalse(FileManager.default.isWritableFile(atPath: encryptedFile)) defer { // ensure file can be cleaned up afterwards - try! FileManager.default.setAttributes([FileAttributeKey.immutable : 0], ofItemAtPath: encryptedFile) + try! FileManager.default.setAttributes([FileAttributeKey.immutable: 0], ofItemAtPath: encryptedFile) } let conn = try! Connection(encryptedFile) diff --git a/Tests/SQLiteTests/ConnectionTests.swift b/Tests/SQLiteTests/ConnectionTests.swift index a05cceb5..37b765ab 100644 --- a/Tests/SQLiteTests/ConnectionTests.swift +++ b/Tests/SQLiteTests/ConnectionTests.swift @@ -13,12 +13,12 @@ import CSQLite import SQLite3 #endif -class ConnectionTests : SQLiteTestCase { +class ConnectionTests: SQLiteTestCase { override func setUp() { super.setUp() - CreateUsersTable() + createUsersTable() } func test_init_withInMemory_returnsInMemoryConnection() { @@ -62,13 +62,13 @@ class ConnectionTests : SQLiteTestCase { } func test_lastInsertRowid_returnsLastIdAfterInserts() { - try! InsertUser("alice") + try! insertUser("alice") XCTAssertEqual(1, db.lastInsertRowid) } func test_lastInsertRowid_doesNotResetAfterError() { XCTAssert(db.lastInsertRowid == 0) - try! InsertUser("alice") + try! insertUser("alice") XCTAssertEqual(1, db.lastInsertRowid) XCTAssertThrowsError( try db.run("INSERT INTO \"users\" (email, age, admin) values ('invalid@example.com', 12, 'invalid')") @@ -83,17 +83,17 @@ class ConnectionTests : SQLiteTestCase { } func test_changes_returnsNumberOfChanges() { - try! InsertUser("alice") + try! insertUser("alice") XCTAssertEqual(1, db.changes) - try! InsertUser("betsy") + try! insertUser("betsy") XCTAssertEqual(1, db.changes) } func test_totalChanges_returnsTotalNumberOfChanges() { XCTAssertEqual(0, db.totalChanges) - try! InsertUser("alice") + try! insertUser("alice") XCTAssertEqual(1, db.totalChanges) - try! InsertUser("betsy") + try! insertUser("betsy") XCTAssertEqual(2, db.totalChanges) } @@ -109,9 +109,9 @@ class ConnectionTests : SQLiteTestCase { try! db.run("SELECT * FROM users WHERE admin = ?", 0) try! db.run("SELECT * FROM users WHERE admin = ?", [0]) try! db.run("SELECT * FROM users WHERE admin = $admin", ["$admin": 0]) - AssertSQL("SELECT * FROM users WHERE admin = 0", 4) + assertSQL("SELECT * FROM users WHERE admin = 0", 4) } - + func test_vacuum() { try! db.vacuum() } @@ -121,31 +121,31 @@ class ConnectionTests : SQLiteTestCase { XCTAssertEqual(0, try! db.scalar("SELECT count(*) FROM users WHERE admin = ?", 0) as? Int64) XCTAssertEqual(0, try! db.scalar("SELECT count(*) FROM users WHERE admin = ?", [0]) as? Int64) XCTAssertEqual(0, try! db.scalar("SELECT count(*) FROM users WHERE admin = $admin", ["$admin": 0]) as? Int64) - AssertSQL("SELECT count(*) FROM users WHERE admin = 0", 4) + assertSQL("SELECT count(*) FROM users WHERE admin = 0", 4) } func test_execute_comment() { try! db.run("-- this is a comment\nSELECT 1") - AssertSQL("-- this is a comment", 0) - AssertSQL("SELECT 1", 0) + assertSQL("-- this is a comment", 0) + assertSQL("SELECT 1", 0) } func test_transaction_executesBeginDeferred() { try! db.transaction(.deferred) {} - AssertSQL("BEGIN DEFERRED TRANSACTION") + assertSQL("BEGIN DEFERRED TRANSACTION") } func test_transaction_executesBeginImmediate() { try! db.transaction(.immediate) {} - AssertSQL("BEGIN IMMEDIATE TRANSACTION") + assertSQL("BEGIN IMMEDIATE TRANSACTION") } func test_transaction_executesBeginExclusive() { try! db.transaction(.exclusive) {} - AssertSQL("BEGIN EXCLUSIVE TRANSACTION") + assertSQL("BEGIN EXCLUSIVE TRANSACTION") } func test_transaction_beginsAndCommitsTransactions() { @@ -155,10 +155,10 @@ class ConnectionTests : SQLiteTestCase { try stmt.run() } - AssertSQL("BEGIN DEFERRED TRANSACTION") - AssertSQL("INSERT INTO users (email) VALUES ('alice@example.com')") - AssertSQL("COMMIT TRANSACTION") - AssertSQL("ROLLBACK TRANSACTION", 0) + assertSQL("BEGIN DEFERRED TRANSACTION") + assertSQL("INSERT INTO users (email) VALUES ('alice@example.com')") + assertSQL("COMMIT TRANSACTION") + assertSQL("ROLLBACK TRANSACTION", 0) } func test_transaction_rollsBackTransactionsIfCommitsFail() { @@ -186,10 +186,10 @@ class ConnectionTests : SQLiteTestCase { XCTFail("unexpected error: \(error)") } - AssertSQL("BEGIN DEFERRED TRANSACTION") - AssertSQL("INSERT INTO users (email, manager_id) VALUES ('alice@example.com', 100)") - AssertSQL("COMMIT TRANSACTION") - AssertSQL("ROLLBACK TRANSACTION") + assertSQL("BEGIN DEFERRED TRANSACTION") + assertSQL("INSERT INTO users (email, manager_id) VALUES ('alice@example.com', 100)") + assertSQL("COMMIT TRANSACTION") + assertSQL("ROLLBACK TRANSACTION") // Run another transaction to ensure that a subsequent transaction does not fail with an "cannot start a // transaction within a transaction" error. @@ -210,32 +210,29 @@ class ConnectionTests : SQLiteTestCase { } catch { } - AssertSQL("BEGIN DEFERRED TRANSACTION") - AssertSQL("INSERT INTO users (email) VALUES ('alice@example.com')", 2) - AssertSQL("ROLLBACK TRANSACTION") - AssertSQL("COMMIT TRANSACTION", 0) + assertSQL("BEGIN DEFERRED TRANSACTION") + assertSQL("INSERT INTO users (email) VALUES ('alice@example.com')", 2) + assertSQL("ROLLBACK TRANSACTION") + assertSQL("COMMIT TRANSACTION", 0) } func test_savepoint_beginsAndCommitsSavepoints() { - let db:Connection = self.db - try! db.savepoint("1") { try db.savepoint("2") { try db.run("INSERT INTO users (email) VALUES (?)", "alice@example.com") } } - AssertSQL("SAVEPOINT '1'") - AssertSQL("SAVEPOINT '2'") - AssertSQL("INSERT INTO users (email) VALUES ('alice@example.com')") - AssertSQL("RELEASE SAVEPOINT '2'") - AssertSQL("RELEASE SAVEPOINT '1'") - AssertSQL("ROLLBACK TO SAVEPOINT '2'", 0) - AssertSQL("ROLLBACK TO SAVEPOINT '1'", 0) + assertSQL("SAVEPOINT '1'") + assertSQL("SAVEPOINT '2'") + assertSQL("INSERT INTO users (email) VALUES ('alice@example.com')") + assertSQL("RELEASE SAVEPOINT '2'") + assertSQL("RELEASE SAVEPOINT '1'") + assertSQL("ROLLBACK TO SAVEPOINT '2'", 0) + assertSQL("ROLLBACK TO SAVEPOINT '1'", 0) } func test_savepoint_beginsAndRollsSavepointsBack() { - let db:Connection = self.db let stmt = try! db.prepare("INSERT INTO users (email) VALUES (?)", "alice@example.com") do { @@ -254,13 +251,13 @@ class ConnectionTests : SQLiteTestCase { } catch { } - AssertSQL("SAVEPOINT '1'") - AssertSQL("SAVEPOINT '2'") - AssertSQL("INSERT INTO users (email) VALUES ('alice@example.com')", 2) - AssertSQL("ROLLBACK TO SAVEPOINT '2'") - AssertSQL("ROLLBACK TO SAVEPOINT '1'") - AssertSQL("RELEASE SAVEPOINT '2'", 0) - AssertSQL("RELEASE SAVEPOINT '1'", 0) + assertSQL("SAVEPOINT '1'") + assertSQL("SAVEPOINT '2'") + assertSQL("INSERT INTO users (email) VALUES ('alice@example.com')", 2) + assertSQL("ROLLBACK TO SAVEPOINT '2'") + assertSQL("ROLLBACK TO SAVEPOINT '1'") + assertSQL("RELEASE SAVEPOINT '2'", 0) + assertSQL("RELEASE SAVEPOINT '1'", 0) } func test_updateHook_setsUpdateHook_withInsert() { @@ -272,12 +269,12 @@ class ConnectionTests : SQLiteTestCase { XCTAssertEqual(1, rowid) done() } - try! InsertUser("alice") + try! insertUser("alice") } } func test_updateHook_setsUpdateHook_withUpdate() { - try! InsertUser("alice") + try! insertUser("alice") async { done in db.updateHook { operation, db, table, rowid in XCTAssertEqual(Connection.Operation.update, operation) @@ -291,7 +288,7 @@ class ConnectionTests : SQLiteTestCase { } func test_updateHook_setsUpdateHook_withDelete() { - try! InsertUser("alice") + try! insertUser("alice") async { done in db.updateHook { operation, db, table, rowid in XCTAssertEqual(Connection.Operation.delete, operation) @@ -310,7 +307,7 @@ class ConnectionTests : SQLiteTestCase { done() } try! db.transaction { - try self.InsertUser("alice") + try insertUser("alice") } XCTAssertEqual(1, try! db.scalar("SELECT count(*) FROM users") as? Int64) } @@ -321,8 +318,8 @@ class ConnectionTests : SQLiteTestCase { db.rollbackHook(done) do { try db.transaction { - try self.InsertUser("alice") - try self.InsertUser("alice") // throw + try insertUser("alice") + try insertUser("alice") // throw } } catch { } @@ -338,7 +335,7 @@ class ConnectionTests : SQLiteTestCase { db.rollbackHook(done) do { try db.transaction { - try self.InsertUser("alice") + try insertUser("alice") } } catch { } @@ -362,21 +359,21 @@ class ConnectionTests : SQLiteTestCase { func test_createCollation_createsCollation() { try! db.createCollation("NODIACRITIC") { lhs, rhs in - return lhs.compare(rhs, options: .diacriticInsensitive) + lhs.compare(rhs, options: .diacriticInsensitive) } XCTAssertEqual(1, try! db.scalar("SELECT ? = ? COLLATE NODIACRITIC", "cafe", "café") as? Int64) } func test_createCollation_createsQuotableCollation() { try! db.createCollation("NO DIACRITIC") { lhs, rhs in - return lhs.compare(rhs, options: .diacriticInsensitive) + lhs.compare(rhs, options: .diacriticInsensitive) } XCTAssertEqual(1, try! db.scalar("SELECT ? = ? COLLATE \"NO DIACRITIC\"", "cafe", "café") as? Int64) } func test_interrupt_interruptsLongRunningQuery() { let semaphore = DispatchSemaphore(value: 0) - db.createFunction("sleep") { args in + db.createFunction("sleep") { _ in DispatchQueue.global(qos: .background).async { self.db.interrupt() semaphore.signal() @@ -396,7 +393,7 @@ class ConnectionTests : SQLiteTestCase { func test_concurrent_access_single_connection() { // test can fail on iOS/tvOS 9.x: SQLite compile-time differences? - guard #available(iOS 10.0, OSX 10.10, tvOS 10.0, watchOS 2.2, *) else { return } + guard #available(iOS 10.0, OSX 10.10, tvOS 10.0, watchOS 2.2, *) else { return } let conn = try! Connection("\(NSTemporaryDirectory())/\(UUID().uuidString)") try! conn.execute("DROP TABLE IF EXISTS test; CREATE TABLE test(value);") @@ -416,8 +413,7 @@ class ConnectionTests : SQLiteTestCase { } } - -class ResultTests : XCTestCase { +class ResultTests: XCTestCase { let connection = try! Connection(.inMemory) func test_init_with_ok_code_returns_nil() { @@ -434,13 +430,13 @@ class ResultTests : XCTestCase { func test_init_with_other_code_returns_error() { if case .some(.error(let message, let code, let statement)) = - Result(errorCode: SQLITE_MISUSE, connection: connection, statement: nil) { + Result(errorCode: SQLITE_MISUSE, connection: connection, statement: nil) { XCTAssertEqual("not an error", message) XCTAssertEqual(SQLITE_MISUSE, code) XCTAssertNil(statement) - XCTAssert(self.connection === connection) + XCTAssert(connection === connection) } else { - XCTFail() + XCTFail("no error") } } diff --git a/Tests/SQLiteTests/CoreFunctionsTests.swift b/Tests/SQLiteTests/CoreFunctionsTests.swift index e7402de3..e03e3769 100644 --- a/Tests/SQLiteTests/CoreFunctionsTests.swift +++ b/Tests/SQLiteTests/CoreFunctionsTests.swift @@ -1,145 +1,145 @@ import XCTest @testable import SQLite -class CoreFunctionsTests : XCTestCase { +class CoreFunctionsTests: XCTestCase { func test_round_wrapsDoubleExpressionsWithRoundFunction() { - AssertSQL("round(\"double\")", double.round()) - AssertSQL("round(\"doubleOptional\")", doubleOptional.round()) + assertSQL("round(\"double\")", double.round()) + assertSQL("round(\"doubleOptional\")", doubleOptional.round()) - AssertSQL("round(\"double\", 1)", double.round(1)) - AssertSQL("round(\"doubleOptional\", 2)", doubleOptional.round(2)) + assertSQL("round(\"double\", 1)", double.round(1)) + assertSQL("round(\"doubleOptional\", 2)", doubleOptional.round(2)) } func test_random_generatesExpressionWithRandomFunction() { - AssertSQL("random()", Expression.random()) - AssertSQL("random()", Expression.random()) + assertSQL("random()", Expression.random()) + assertSQL("random()", Expression.random()) } func test_length_wrapsStringExpressionWithLengthFunction() { - AssertSQL("length(\"string\")", string.length) - AssertSQL("length(\"stringOptional\")", stringOptional.length) + assertSQL("length(\"string\")", string.length) + assertSQL("length(\"stringOptional\")", stringOptional.length) } func test_lowercaseString_wrapsStringExpressionWithLowerFunction() { - AssertSQL("lower(\"string\")", string.lowercaseString) - AssertSQL("lower(\"stringOptional\")", stringOptional.lowercaseString) + assertSQL("lower(\"string\")", string.lowercaseString) + assertSQL("lower(\"stringOptional\")", stringOptional.lowercaseString) } func test_uppercaseString_wrapsStringExpressionWithUpperFunction() { - AssertSQL("upper(\"string\")", string.uppercaseString) - AssertSQL("upper(\"stringOptional\")", stringOptional.uppercaseString) + assertSQL("upper(\"string\")", string.uppercaseString) + assertSQL("upper(\"stringOptional\")", stringOptional.uppercaseString) } func test_like_buildsExpressionWithLikeOperator() { - AssertSQL("(\"string\" LIKE 'a%')", string.like("a%")) - AssertSQL("(\"stringOptional\" LIKE 'b%')", stringOptional.like("b%")) - - AssertSQL("(\"string\" LIKE '%\\%' ESCAPE '\\')", string.like("%\\%", escape: "\\")) - AssertSQL("(\"stringOptional\" LIKE '_\\_' ESCAPE '\\')", stringOptional.like("_\\_", escape: "\\")) - - AssertSQL("(\"string\" LIKE \"a\")", string.like(Expression("a"))) - AssertSQL("(\"stringOptional\" LIKE \"a\")", stringOptional.like(Expression("a"))) - - AssertSQL("(\"string\" LIKE \"a\" ESCAPE '\\')", string.like(Expression("a"), escape: "\\")) - AssertSQL("(\"stringOptional\" LIKE \"a\" ESCAPE '\\')", stringOptional.like(Expression("a"), escape: "\\")) - - AssertSQL("('string' LIKE \"a\")", "string".like(Expression("a"))) - AssertSQL("('string' LIKE \"a\" ESCAPE '\\')", "string".like(Expression("a"), escape: "\\")) + assertSQL("(\"string\" LIKE 'a%')", string.like("a%")) + assertSQL("(\"stringOptional\" LIKE 'b%')", stringOptional.like("b%")) + + assertSQL("(\"string\" LIKE '%\\%' ESCAPE '\\')", string.like("%\\%", escape: "\\")) + assertSQL("(\"stringOptional\" LIKE '_\\_' ESCAPE '\\')", stringOptional.like("_\\_", escape: "\\")) + + assertSQL("(\"string\" LIKE \"a\")", string.like(Expression("a"))) + assertSQL("(\"stringOptional\" LIKE \"a\")", stringOptional.like(Expression("a"))) + + assertSQL("(\"string\" LIKE \"a\" ESCAPE '\\')", string.like(Expression("a"), escape: "\\")) + assertSQL("(\"stringOptional\" LIKE \"a\" ESCAPE '\\')", stringOptional.like(Expression("a"), escape: "\\")) + + assertSQL("('string' LIKE \"a\")", "string".like(Expression("a"))) + assertSQL("('string' LIKE \"a\" ESCAPE '\\')", "string".like(Expression("a"), escape: "\\")) } func test_glob_buildsExpressionWithGlobOperator() { - AssertSQL("(\"string\" GLOB 'a*')", string.glob("a*")) - AssertSQL("(\"stringOptional\" GLOB 'b*')", stringOptional.glob("b*")) + assertSQL("(\"string\" GLOB 'a*')", string.glob("a*")) + assertSQL("(\"stringOptional\" GLOB 'b*')", stringOptional.glob("b*")) } func test_match_buildsExpressionWithMatchOperator() { - AssertSQL("(\"string\" MATCH 'a*')", string.match("a*")) - AssertSQL("(\"stringOptional\" MATCH 'b*')", stringOptional.match("b*")) + assertSQL("(\"string\" MATCH 'a*')", string.match("a*")) + assertSQL("(\"stringOptional\" MATCH 'b*')", stringOptional.match("b*")) } func test_regexp_buildsExpressionWithRegexpOperator() { - AssertSQL("(\"string\" REGEXP '^.+@.+\\.com$')", string.regexp("^.+@.+\\.com$")) - AssertSQL("(\"stringOptional\" REGEXP '^.+@.+\\.net$')", stringOptional.regexp("^.+@.+\\.net$")) + assertSQL("(\"string\" REGEXP '^.+@.+\\.com$')", string.regexp("^.+@.+\\.com$")) + assertSQL("(\"stringOptional\" REGEXP '^.+@.+\\.net$')", stringOptional.regexp("^.+@.+\\.net$")) } func test_collate_buildsExpressionWithCollateOperator() { - AssertSQL("(\"string\" COLLATE BINARY)", string.collate(.binary)) - AssertSQL("(\"string\" COLLATE NOCASE)", string.collate(.nocase)) - AssertSQL("(\"string\" COLLATE RTRIM)", string.collate(.rtrim)) - AssertSQL("(\"string\" COLLATE \"CUSTOM\")", string.collate(.custom("CUSTOM"))) + assertSQL("(\"string\" COLLATE BINARY)", string.collate(.binary)) + assertSQL("(\"string\" COLLATE NOCASE)", string.collate(.nocase)) + assertSQL("(\"string\" COLLATE RTRIM)", string.collate(.rtrim)) + assertSQL("(\"string\" COLLATE \"CUSTOM\")", string.collate(.custom("CUSTOM"))) - AssertSQL("(\"stringOptional\" COLLATE BINARY)", stringOptional.collate(.binary)) - AssertSQL("(\"stringOptional\" COLLATE NOCASE)", stringOptional.collate(.nocase)) - AssertSQL("(\"stringOptional\" COLLATE RTRIM)", stringOptional.collate(.rtrim)) - AssertSQL("(\"stringOptional\" COLLATE \"CUSTOM\")", stringOptional.collate(.custom("CUSTOM"))) + assertSQL("(\"stringOptional\" COLLATE BINARY)", stringOptional.collate(.binary)) + assertSQL("(\"stringOptional\" COLLATE NOCASE)", stringOptional.collate(.nocase)) + assertSQL("(\"stringOptional\" COLLATE RTRIM)", stringOptional.collate(.rtrim)) + assertSQL("(\"stringOptional\" COLLATE \"CUSTOM\")", stringOptional.collate(.custom("CUSTOM"))) } func test_ltrim_wrapsStringWithLtrimFunction() { - AssertSQL("ltrim(\"string\")", string.ltrim()) - AssertSQL("ltrim(\"stringOptional\")", stringOptional.ltrim()) + assertSQL("ltrim(\"string\")", string.ltrim()) + assertSQL("ltrim(\"stringOptional\")", stringOptional.ltrim()) - AssertSQL("ltrim(\"string\", ' ')", string.ltrim([" "])) - AssertSQL("ltrim(\"stringOptional\", ' ')", stringOptional.ltrim([" "])) + assertSQL("ltrim(\"string\", ' ')", string.ltrim([" "])) + assertSQL("ltrim(\"stringOptional\", ' ')", stringOptional.ltrim([" "])) } func test_ltrim_wrapsStringWithRtrimFunction() { - AssertSQL("rtrim(\"string\")", string.rtrim()) - AssertSQL("rtrim(\"stringOptional\")", stringOptional.rtrim()) + assertSQL("rtrim(\"string\")", string.rtrim()) + assertSQL("rtrim(\"stringOptional\")", stringOptional.rtrim()) - AssertSQL("rtrim(\"string\", ' ')", string.rtrim([" "])) - AssertSQL("rtrim(\"stringOptional\", ' ')", stringOptional.rtrim([" "])) + assertSQL("rtrim(\"string\", ' ')", string.rtrim([" "])) + assertSQL("rtrim(\"stringOptional\", ' ')", stringOptional.rtrim([" "])) } func test_ltrim_wrapsStringWithTrimFunction() { - AssertSQL("trim(\"string\")", string.trim()) - AssertSQL("trim(\"stringOptional\")", stringOptional.trim()) + assertSQL("trim(\"string\")", string.trim()) + assertSQL("trim(\"stringOptional\")", stringOptional.trim()) - AssertSQL("trim(\"string\", ' ')", string.trim([" "])) - AssertSQL("trim(\"stringOptional\", ' ')", stringOptional.trim([" "])) + assertSQL("trim(\"string\", ' ')", string.trim([" "])) + assertSQL("trim(\"stringOptional\", ' ')", stringOptional.trim([" "])) } func test_replace_wrapsStringWithReplaceFunction() { - AssertSQL("replace(\"string\", '@example.com', '@example.net')", string.replace("@example.com", with: "@example.net")) - AssertSQL("replace(\"stringOptional\", '@example.net', '@example.com')", stringOptional.replace("@example.net", with: "@example.com")) + assertSQL("replace(\"string\", '@example.com', '@example.net')", string.replace("@example.com", with: "@example.net")) + assertSQL("replace(\"stringOptional\", '@example.net', '@example.com')", stringOptional.replace("@example.net", with: "@example.com")) } func test_substring_wrapsStringWithSubstrFunction() { - AssertSQL("substr(\"string\", 1, 2)", string.substring(1, length: 2)) - AssertSQL("substr(\"stringOptional\", 2, 1)", stringOptional.substring(2, length: 1)) + assertSQL("substr(\"string\", 1, 2)", string.substring(1, length: 2)) + assertSQL("substr(\"stringOptional\", 2, 1)", stringOptional.substring(2, length: 1)) } func test_subscriptWithRange_wrapsStringWithSubstrFunction() { - AssertSQL("substr(\"string\", 1, 2)", string[1..<3]) - AssertSQL("substr(\"stringOptional\", 2, 1)", stringOptional[2..<3]) + assertSQL("substr(\"string\", 1, 2)", string[1..<3]) + assertSQL("substr(\"stringOptional\", 2, 1)", stringOptional[2..<3]) } func test_nilCoalescingOperator_wrapsOptionalsWithIfnullFunction() { - AssertSQL("ifnull(\"intOptional\", 1)", intOptional ?? 1) + assertSQL("ifnull(\"intOptional\", 1)", intOptional ?? 1) // AssertSQL("ifnull(\"doubleOptional\", 1.0)", doubleOptional ?? 1) // rdar://problem/21677256 XCTAssertEqual("ifnull(\"doubleOptional\", 1.0)", (doubleOptional ?? 1).asSQL()) - AssertSQL("ifnull(\"stringOptional\", 'literal')", stringOptional ?? "literal") + assertSQL("ifnull(\"stringOptional\", 'literal')", stringOptional ?? "literal") - AssertSQL("ifnull(\"intOptional\", \"int\")", intOptional ?? int) - AssertSQL("ifnull(\"doubleOptional\", \"double\")", doubleOptional ?? double) - AssertSQL("ifnull(\"stringOptional\", \"string\")", stringOptional ?? string) + assertSQL("ifnull(\"intOptional\", \"int\")", intOptional ?? int) + assertSQL("ifnull(\"doubleOptional\", \"double\")", doubleOptional ?? double) + assertSQL("ifnull(\"stringOptional\", \"string\")", stringOptional ?? string) - AssertSQL("ifnull(\"intOptional\", \"intOptional\")", intOptional ?? intOptional) - AssertSQL("ifnull(\"doubleOptional\", \"doubleOptional\")", doubleOptional ?? doubleOptional) - AssertSQL("ifnull(\"stringOptional\", \"stringOptional\")", stringOptional ?? stringOptional) + assertSQL("ifnull(\"intOptional\", \"intOptional\")", intOptional ?? intOptional) + assertSQL("ifnull(\"doubleOptional\", \"doubleOptional\")", doubleOptional ?? doubleOptional) + assertSQL("ifnull(\"stringOptional\", \"stringOptional\")", stringOptional ?? stringOptional) } func test_absoluteValue_wrapsNumberWithAbsFucntion() { - AssertSQL("abs(\"int\")", int.absoluteValue) - AssertSQL("abs(\"intOptional\")", intOptional.absoluteValue) + assertSQL("abs(\"int\")", int.absoluteValue) + assertSQL("abs(\"intOptional\")", intOptional.absoluteValue) - AssertSQL("abs(\"double\")", double.absoluteValue) - AssertSQL("abs(\"doubleOptional\")", doubleOptional.absoluteValue) + assertSQL("abs(\"double\")", double.absoluteValue) + assertSQL("abs(\"doubleOptional\")", doubleOptional.absoluteValue) } func test_contains_buildsExpressionWithInOperator() { - AssertSQL("(\"string\" IN ('hello', 'world'))", ["hello", "world"].contains(string)) - AssertSQL("(\"stringOptional\" IN ('hello', 'world'))", ["hello", "world"].contains(stringOptional)) + assertSQL("(\"string\" IN ('hello', 'world'))", ["hello", "world"].contains(string)) + assertSQL("(\"stringOptional\" IN ('hello', 'world'))", ["hello", "world"].contains(stringOptional)) } } diff --git a/Tests/SQLiteTests/CustomAggregationTests.swift b/Tests/SQLiteTests/CustomAggregationTests.swift index f8efc7e4..d4569eef 100644 --- a/Tests/SQLiteTests/CustomAggregationTests.swift +++ b/Tests/SQLiteTests/CustomAggregationTests.swift @@ -13,41 +13,41 @@ import CSQLite import SQLite3 #endif -class CustomAggregationTests : SQLiteTestCase { +class CustomAggregationTests: SQLiteTestCase { override func setUp() { super.setUp() - CreateUsersTable() - try! InsertUser("Alice", age: 30, admin: true) - try! InsertUser("Bob", age: 25, admin: true) - try! InsertUser("Eve", age: 28, admin: false) + createUsersTable() + try! insertUser("Alice", age: 30, admin: true) + try! insertUser("Bob", age: 25, admin: true) + try! insertUser("Eve", age: 28, admin: false) } - + func testUnsafeCustomSum() { let step = { (bindings: [Binding?], state: UnsafeMutablePointer) in if let v = bindings[0] as? Int64 { state.pointee += v } } - + let final = { (state: UnsafeMutablePointer) -> Binding? in let v = state.pointee let p = UnsafeMutableBufferPointer(start: state, count: 1) p.deallocate() return v } - let _ = db.createAggregation("mySUM1", step: step, final: final) { + db.createAggregation("mySUM1", step: step, final: final) { let v = UnsafeMutableBufferPointer.allocate(capacity: 1) v[0] = 0 return v.baseAddress! } let result = try! db.prepare("SELECT mySUM1(age) AS s FROM users") - let i = result.columnNames.index(of: "s")! + let i = result.columnNames.firstIndex(of: "s")! for row in result { let value = row[i] as? Int64 XCTAssertEqual(83, value) } } - + func testUnsafeCustomSumGrouping() { let step = { (bindings: [Binding?], state: UnsafeMutablePointer) in if let v = bindings[0] as? Int64 { @@ -60,25 +60,25 @@ class CustomAggregationTests : SQLiteTestCase { p.deallocate() return v } - let _ = db.createAggregation("mySUM2", step: step, final: final) { + db.createAggregation("mySUM2", step: step, final: final) { let v = UnsafeMutableBufferPointer.allocate(capacity: 1) v[0] = 0 return v.baseAddress! } let result = try! db.prepare("SELECT mySUM2(age) AS s FROM users GROUP BY admin ORDER BY s") - let i = result.columnNames.index(of: "s")! + let i = result.columnNames.firstIndex(of: "s")! let values = result.compactMap { $0[i] as? Int64 } XCTAssertTrue(values.elementsEqual([28, 55])) } - + func testCustomSum() { - let reduce : (Int64, [Binding?]) -> Int64 = { (last, bindings) in + let reduce: (Int64, [Binding?]) -> Int64 = { (last, bindings) in let v = (bindings[0] as? Int64) ?? 0 return last + v } - let _ = db.createAggregation("myReduceSUM1", initialValue: Int64(2000), reduce: reduce, result: { $0 }) + db.createAggregation("myReduceSUM1", initialValue: Int64(2000), reduce: reduce, result: { $0 }) let result = try! db.prepare("SELECT myReduceSUM1(age) AS s FROM users") - let i = result.columnNames.index(of: "s")! + let i = result.columnNames.firstIndex(of: "s")! for row in result { let value = row[i] as? Int64 XCTAssertEqual(2083, value) @@ -86,47 +86,50 @@ class CustomAggregationTests : SQLiteTestCase { } func testCustomSumGrouping() { - let reduce : (Int64, [Binding?]) -> Int64 = { (last, bindings) in + let reduce: (Int64, [Binding?]) -> Int64 = { (last, bindings) in let v = (bindings[0] as? Int64) ?? 0 return last + v } - let _ = db.createAggregation("myReduceSUM2", initialValue: Int64(3000), reduce: reduce, result: { $0 }) + db.createAggregation("myReduceSUM2", initialValue: Int64(3000), reduce: reduce, result: { $0 }) let result = try! db.prepare("SELECT myReduceSUM2(age) AS s FROM users GROUP BY admin ORDER BY s") - let i = result.columnNames.index(of: "s")! + let i = result.columnNames.firstIndex(of: "s")! let values = result.compactMap { $0[i] as? Int64 } XCTAssertTrue(values.elementsEqual([3028, 3055])) } - + func testCustomStringAgg() { let initial = String(repeating: " ", count: 64) - let reduce : (String, [Binding?]) -> String = { (last, bindings) in + let reduce: (String, [Binding?]) -> String = { (last, bindings) in let v = (bindings[0] as? String) ?? "" return last + v } - let _ = db.createAggregation("myReduceSUM3", initialValue: initial, reduce: reduce, result: { $0 }) + db.createAggregation("myReduceSUM3", initialValue: initial, reduce: reduce, result: { $0 }) let result = try! db.prepare("SELECT myReduceSUM3(email) AS s FROM users") - let i = result.columnNames.index(of: "s")! + + let i = result.columnNames.firstIndex(of: "s")! for row in result { let value = row[i] as? String XCTAssertEqual("\(initial)Alice@example.comBob@example.comEve@example.com", value) } } - + func testCustomObjectSum() { { let initial = TestObject(value: 1000) - let reduce : (TestObject, [Binding?]) -> TestObject = { (last, bindings) in + let reduce: (TestObject, [Binding?]) -> TestObject = { (last, bindings) in let v = (bindings[0] as? Int64) ?? 0 return TestObject(value: last.value + v) } - let _ = db.createAggregation("myReduceSUMX", initialValue: initial, reduce: reduce, result: { $0.value }) + db.createAggregation("myReduceSUMX", initialValue: initial, reduce: reduce, result: { $0.value }) // end this scope to ensure that the initial value is retained // by the createAggregation call. + // swiftlint:disable:next trailing_semicolon }(); + { XCTAssertEqual(TestObject.inits, 1) let result = try! db.prepare("SELECT myReduceSUMX(age) AS s FROM users") - let i = result.columnNames.index(of: "s")! + let i = result.columnNames.firstIndex(of: "s")! for row in result { let value = row[i] as? Int64 XCTAssertEqual(1083, value) @@ -143,7 +146,7 @@ class CustomAggregationTests : SQLiteTestCase { class TestObject { static var inits = 0 static var deinits = 0 - + var value: Int64 init(value: Int64) { self.value = value diff --git a/Tests/SQLiteTests/CustomFunctionsTests.swift b/Tests/SQLiteTests/CustomFunctionsTests.swift index 919986b6..af1ef110 100644 --- a/Tests/SQLiteTests/CustomFunctionsTests.swift +++ b/Tests/SQLiteTests/CustomFunctionsTests.swift @@ -1,13 +1,13 @@ import XCTest import SQLite -class CustomFunctionNoArgsTests : SQLiteTestCase { +class CustomFunctionNoArgsTests: SQLiteTestCase { typealias FunctionNoOptional = () -> Expression typealias FunctionResultOptional = () -> Expression func testFunctionNoOptional() { let _: FunctionNoOptional = try! db.createFunction("test", deterministic: true) { - return "a" + "a" } let result = try! db.prepare("SELECT test()").scalar() as! String XCTAssertEqual("a", result) @@ -15,14 +15,14 @@ class CustomFunctionNoArgsTests : SQLiteTestCase { func testFunctionResultOptional() { let _: FunctionResultOptional = try! db.createFunction("test", deterministic: true) { - return "a" + "a" } let result = try! db.prepare("SELECT test()").scalar() as! String? XCTAssertEqual("a", result) } } -class CustomFunctionWithOneArgTests : SQLiteTestCase { +class CustomFunctionWithOneArgTests: SQLiteTestCase { typealias FunctionNoOptional = (Expression) -> Expression typealias FunctionLeftOptional = (Expression) -> Expression typealias FunctionResultOptional = (Expression) -> Expression @@ -30,7 +30,7 @@ class CustomFunctionWithOneArgTests : SQLiteTestCase { func testFunctionNoOptional() { let _: FunctionNoOptional = try! db.createFunction("test", deterministic: true) { a in - return "b"+a + "b" + a } let result = try! db.prepare("SELECT test(?)").scalar("a") as! String XCTAssertEqual("ba", result) @@ -38,7 +38,7 @@ class CustomFunctionWithOneArgTests : SQLiteTestCase { func testFunctionLeftOptional() { let _: FunctionLeftOptional = try! db.createFunction("test", deterministic: true) { a in - return "b"+a! + "b" + a! } let result = try! db.prepare("SELECT test(?)").scalar("a") as! String XCTAssertEqual("ba", result) @@ -46,34 +46,34 @@ class CustomFunctionWithOneArgTests : SQLiteTestCase { func testFunctionResultOptional() { let _: FunctionResultOptional = try! db.createFunction("test", deterministic: true) { a in - return "b"+a + "b" + a } let result = try! db.prepare("SELECT test(?)").scalar("a") as! String XCTAssertEqual("ba", result) } func testFunctionLeftResultOptional() { - let _: FunctionLeftResultOptional = try! db.createFunction("test", deterministic: true) { (a:String?) -> String? in - return "b"+a! + let _: FunctionLeftResultOptional = try! db.createFunction("test", deterministic: true) { (a: String?) -> String? in + "b" + a! } let result = try! db.prepare("SELECT test(?)").scalar("a") as! String XCTAssertEqual("ba", result) } } -class CustomFunctionWithTwoArgsTests : SQLiteTestCase { - typealias FunctionNoOptional = (Expression, Expression) -> Expression +class CustomFunctionWithTwoArgsTests: SQLiteTestCase { + typealias FunctionNoOptional = (Expression, Expression) -> Expression typealias FunctionLeftOptional = (Expression, Expression) -> Expression - typealias FunctionRightOptional = (Expression, Expression) -> Expression - typealias FunctionResultOptional = (Expression, Expression) -> Expression + typealias FunctionRightOptional = (Expression, Expression) -> Expression + typealias FunctionResultOptional = (Expression, Expression) -> Expression typealias FunctionLeftRightOptional = (Expression, Expression) -> Expression typealias FunctionLeftResultOptional = (Expression, Expression) -> Expression - typealias FunctionRightResultOptional = (Expression, Expression) -> Expression + typealias FunctionRightResultOptional = (Expression, Expression) -> Expression typealias FunctionLeftRightResultOptional = (Expression, Expression) -> Expression func testNoOptional() { let _: FunctionNoOptional = try! db.createFunction("test", deterministic: true) { a, b in - return a+b + a + b } let result = try! db.prepare("SELECT test(?, ?)").scalar("a", "b") as! String XCTAssertEqual("ab", result) @@ -81,7 +81,7 @@ class CustomFunctionWithTwoArgsTests : SQLiteTestCase { func testLeftOptional() { let _: FunctionLeftOptional = try! db.createFunction("test", deterministic: true) { a, b in - return a!+b + a! + b } let result = try! db.prepare("SELECT test(?, ?)").scalar("a", "b") as! String XCTAssertEqual("ab", result) @@ -89,7 +89,7 @@ class CustomFunctionWithTwoArgsTests : SQLiteTestCase { func testRightOptional() { let _: FunctionRightOptional = try! db.createFunction("test", deterministic: true) { a, b in - return a+b! + a + b! } let result = try! db.prepare("SELECT test(?, ?)").scalar("a", "b") as! String XCTAssertEqual("ab", result) @@ -97,7 +97,7 @@ class CustomFunctionWithTwoArgsTests : SQLiteTestCase { func testResultOptional() { let _: FunctionResultOptional = try! db.createFunction("test", deterministic: true) { a, b in - return a+b + a + b } let result = try! db.prepare("SELECT test(?, ?)").scalar("a", "b") as! String? XCTAssertEqual("ab", result) @@ -105,7 +105,7 @@ class CustomFunctionWithTwoArgsTests : SQLiteTestCase { func testFunctionLeftRightOptional() { let _: FunctionLeftRightOptional = try! db.createFunction("test", deterministic: true) { a, b in - return a!+b! + a! + b! } let result = try! db.prepare("SELECT test(?, ?)").scalar("a", "b") as! String XCTAssertEqual("ab", result) @@ -113,7 +113,7 @@ class CustomFunctionWithTwoArgsTests : SQLiteTestCase { func testFunctionLeftResultOptional() { let _: FunctionLeftResultOptional = try! db.createFunction("test", deterministic: true) { a, b in - return a!+b + a! + b } let result = try! db.prepare("SELECT test(?, ?)").scalar("a", "b") as! String? XCTAssertEqual("ab", result) @@ -121,7 +121,7 @@ class CustomFunctionWithTwoArgsTests : SQLiteTestCase { func testFunctionRightResultOptional() { let _: FunctionRightResultOptional = try! db.createFunction("test", deterministic: true) { a, b in - return a+b! + a + b! } let result = try! db.prepare("SELECT test(?, ?)").scalar("a", "b") as! String? XCTAssertEqual("ab", result) @@ -129,7 +129,7 @@ class CustomFunctionWithTwoArgsTests : SQLiteTestCase { func testFunctionLeftRightResultOptional() { let _: FunctionLeftRightResultOptional = try! db.createFunction("test", deterministic: true) { a, b in - return a!+b! + a! + b! } let result = try! db.prepare("SELECT test(?, ?)").scalar("a", "b") as! String? XCTAssertEqual("ab", result) diff --git a/Tests/SQLiteTests/DateAndTimeFunctionTests.swift b/Tests/SQLiteTests/DateAndTimeFunctionTests.swift index 628b5910..393e9c7c 100644 --- a/Tests/SQLiteTests/DateAndTimeFunctionTests.swift +++ b/Tests/SQLiteTests/DateAndTimeFunctionTests.swift @@ -1,66 +1,66 @@ import XCTest @testable import SQLite -class DateAndTimeFunctionsTests : XCTestCase { +class DateAndTimeFunctionsTests: XCTestCase { func test_date() { - AssertSQL("date('now')", DateFunctions.date("now")) - AssertSQL("date('now', 'localtime')", DateFunctions.date("now", "localtime")) + assertSQL("date('now')", DateFunctions.date("now")) + assertSQL("date('now', 'localtime')", DateFunctions.date("now", "localtime")) } func test_time() { - AssertSQL("time('now')", DateFunctions.time("now")) - AssertSQL("time('now', 'localtime')", DateFunctions.time("now", "localtime")) + assertSQL("time('now')", DateFunctions.time("now")) + assertSQL("time('now', 'localtime')", DateFunctions.time("now", "localtime")) } func test_datetime() { - AssertSQL("datetime('now')", DateFunctions.datetime("now")) - AssertSQL("datetime('now', 'localtime')", DateFunctions.datetime("now", "localtime")) + assertSQL("datetime('now')", DateFunctions.datetime("now")) + assertSQL("datetime('now', 'localtime')", DateFunctions.datetime("now", "localtime")) } func test_julianday() { - AssertSQL("julianday('now')", DateFunctions.julianday("now")) - AssertSQL("julianday('now', 'localtime')", DateFunctions.julianday("now", "localtime")) + assertSQL("julianday('now')", DateFunctions.julianday("now")) + assertSQL("julianday('now', 'localtime')", DateFunctions.julianday("now", "localtime")) } func test_strftime() { - AssertSQL("strftime('%Y-%m-%d', 'now')", DateFunctions.strftime("%Y-%m-%d", "now")) - AssertSQL("strftime('%Y-%m-%d', 'now', 'localtime')", DateFunctions.strftime("%Y-%m-%d", "now", "localtime")) + assertSQL("strftime('%Y-%m-%d', 'now')", DateFunctions.strftime("%Y-%m-%d", "now")) + assertSQL("strftime('%Y-%m-%d', 'now', 'localtime')", DateFunctions.strftime("%Y-%m-%d", "now", "localtime")) } } -class DateExtensionTests : XCTestCase { +class DateExtensionTests: XCTestCase { func test_time() { - AssertSQL("time('1970-01-01T00:00:00.000')", Date(timeIntervalSince1970: 0).time) + assertSQL("time('1970-01-01T00:00:00.000')", Date(timeIntervalSince1970: 0).time) } func test_date() { - AssertSQL("date('1970-01-01T00:00:00.000')", Date(timeIntervalSince1970: 0).date) + assertSQL("date('1970-01-01T00:00:00.000')", Date(timeIntervalSince1970: 0).date) } func test_datetime() { - AssertSQL("datetime('1970-01-01T00:00:00.000')", Date(timeIntervalSince1970: 0).datetime) + assertSQL("datetime('1970-01-01T00:00:00.000')", Date(timeIntervalSince1970: 0).datetime) } func test_julianday() { - AssertSQL("julianday('1970-01-01T00:00:00.000')", Date(timeIntervalSince1970: 0).julianday) + assertSQL("julianday('1970-01-01T00:00:00.000')", Date(timeIntervalSince1970: 0).julianday) } } -class DateExpressionTests : XCTestCase { +class DateExpressionTests: XCTestCase { func test_date() { - AssertSQL("date(\"date\")", date.date) + assertSQL("date(\"date\")", date.date) } func test_time() { - AssertSQL("time(\"date\")", date.time) + assertSQL("time(\"date\")", date.time) } func test_datetime() { - AssertSQL("datetime(\"date\")", date.datetime) + assertSQL("datetime(\"date\")", date.datetime) } func test_julianday() { - AssertSQL("julianday(\"date\")", date.julianday) + assertSQL("julianday(\"date\")", date.julianday) } } diff --git a/Tests/SQLiteTests/ExpressionTests.swift b/Tests/SQLiteTests/ExpressionTests.swift index 036e10ce..32100d4d 100644 --- a/Tests/SQLiteTests/ExpressionTests.swift +++ b/Tests/SQLiteTests/ExpressionTests.swift @@ -1,6 +1,5 @@ import XCTest import SQLite -class ExpressionTests : XCTestCase { - +class ExpressionTests: XCTestCase { } diff --git a/Tests/SQLiteTests/FTS4Tests.swift b/Tests/SQLiteTests/FTS4Tests.swift index 79f0a8e2..33be422c 100644 --- a/Tests/SQLiteTests/FTS4Tests.swift +++ b/Tests/SQLiteTests/FTS4Tests.swift @@ -1,7 +1,7 @@ import XCTest import SQLite -class FTS4Tests : XCTestCase { +class FTS4Tests: XCTestCase { func test_create_onVirtualTable_withFTS4_compilesCreateVirtualTableExpression() { XCTAssertEqual( @@ -25,26 +25,33 @@ class FTS4Tests : XCTestCase { virtualTable.create(.FTS4(tokenize: .Unicode61(removeDiacritics: false))) ) XCTAssertEqual( - "CREATE VIRTUAL TABLE \"virtual_table\" USING fts4(tokenize=unicode61 \"removeDiacritics=1\" \"tokenchars=.\" \"separators=X\")", - virtualTable.create(.FTS4(tokenize: .Unicode61(removeDiacritics: true, tokenchars: ["."], separators: ["X"]))) + """ + CREATE VIRTUAL TABLE \"virtual_table\" USING fts4(tokenize=unicode61 \"removeDiacritics=1\" + \"tokenchars=.\" \"separators=X\") + """.replacingOccurrences(of: "\n", with: ""), + virtualTable.create(.FTS4(tokenize: .Unicode61(removeDiacritics: true, + tokenchars: ["."], separators: ["X"]))) ) } func test_match_onVirtualTableAsExpression_compilesMatchExpression() { - AssertSQL("(\"virtual_table\" MATCH 'string')", virtualTable.match("string") as Expression) - AssertSQL("(\"virtual_table\" MATCH \"string\")", virtualTable.match(string) as Expression) - AssertSQL("(\"virtual_table\" MATCH \"stringOptional\")", virtualTable.match(stringOptional) as Expression) + assertSQL("(\"virtual_table\" MATCH 'string')", virtualTable.match("string") as Expression) + assertSQL("(\"virtual_table\" MATCH \"string\")", virtualTable.match(string) as Expression) + assertSQL("(\"virtual_table\" MATCH \"stringOptional\")", virtualTable.match(stringOptional) as Expression) } func test_match_onVirtualTableAsQueryType_compilesMatchExpression() { - AssertSQL("SELECT * FROM \"virtual_table\" WHERE (\"virtual_table\" MATCH 'string')", virtualTable.match("string") as QueryType) - AssertSQL("SELECT * FROM \"virtual_table\" WHERE (\"virtual_table\" MATCH \"string\")", virtualTable.match(string) as QueryType) - AssertSQL("SELECT * FROM \"virtual_table\" WHERE (\"virtual_table\" MATCH \"stringOptional\")", virtualTable.match(stringOptional) as QueryType) + assertSQL("SELECT * FROM \"virtual_table\" WHERE (\"virtual_table\" MATCH 'string')", + virtualTable.match("string") as QueryType) + assertSQL("SELECT * FROM \"virtual_table\" WHERE (\"virtual_table\" MATCH \"string\")", + virtualTable.match(string) as QueryType) + assertSQL("SELECT * FROM \"virtual_table\" WHERE (\"virtual_table\" MATCH \"stringOptional\")", + virtualTable.match(stringOptional) as QueryType) } } -class FTS4ConfigTests : XCTestCase { +class FTS4ConfigTests: XCTestCase { var config: FTS4Config! override func setUp() { @@ -108,7 +115,10 @@ class FTS4ConfigTests : XCTestCase { func test_tokenizer_unicode61_with_options() { XCTAssertEqual( - "CREATE VIRTUAL TABLE \"virtual_table\" USING fts4(tokenize=unicode61 \"removeDiacritics=1\" \"tokenchars=.\" \"separators=X\")", + """ + CREATE VIRTUAL TABLE \"virtual_table\" USING fts4(tokenize=unicode61 \"removeDiacritics=1\" + \"tokenchars=.\" \"separators=X\") + """.replacingOccurrences(of: "\n", with: ""), sql(config.tokenizer(.Unicode61(removeDiacritics: true, tokenchars: ["."], separators: ["X"])))) } @@ -156,7 +166,11 @@ class FTS4ConfigTests : XCTestCase { func test_config_all() { XCTAssertEqual( - "CREATE VIRTUAL TABLE \"virtual_table\" USING fts4(\"int\", \"string\", \"date\", tokenize=porter, prefix=\"2,4\", content=\"table\", notindexed=\"string\", notindexed=\"date\", languageid=\"lid\", matchinfo=\"fts3\", order=\"desc\")", + """ + CREATE VIRTUAL TABLE \"virtual_table\" USING fts4(\"int\", \"string\", \"date\", + tokenize=porter, prefix=\"2,4\", content=\"table\", notindexed=\"string\", notindexed=\"date\", + languageid=\"lid\", matchinfo=\"fts3\", order=\"desc\") + """.replacingOccurrences(of: "\n", with: ""), sql(config .tokenizer(.Porter) .column(int) @@ -171,11 +185,11 @@ class FTS4ConfigTests : XCTestCase { } func sql(_ config: FTS4Config) -> String { - return virtualTable.create(.FTS4(config)) + virtualTable.create(.FTS4(config)) } } -class FTS4IntegrationTests : SQLiteTestCase { +class FTS4IntegrationTests: SQLiteTestCase { #if !SQLITE_SWIFT_STANDALONE && !SQLITE_SWIFT_SQLCIPHER func test_registerTokenizer_registersTokenizer() { let emails = VirtualTable("emails") @@ -184,9 +198,11 @@ class FTS4IntegrationTests : SQLiteTestCase { let locale = CFLocaleCopyCurrent() let tokenizerName = "tokenizer" - let tokenizer = CFStringTokenizerCreate(nil, "" as CFString, CFRangeMake(0, 0), UInt(kCFStringTokenizerUnitWord), locale) + let tokenizer = CFStringTokenizerCreate(nil, "" as CFString, CFRangeMake(0, 0), + UInt(kCFStringTokenizerUnitWord), locale) try! db.registerTokenizer(tokenizerName) { string in - CFStringTokenizerSetString(tokenizer, string as CFString, CFRangeMake(0, CFStringGetLength(string as CFString))) + CFStringTokenizerSetString(tokenizer, string as CFString, + CFRangeMake(0, CFStringGetLength(string as CFString))) if CFStringTokenizerAdvanceToNextToken(tokenizer).isEmpty { return nil } @@ -199,7 +215,10 @@ class FTS4IntegrationTests : SQLiteTestCase { } try! db.run(emails.create(.FTS4([subject, body], tokenize: .Custom(tokenizerName)))) - AssertSQL("CREATE VIRTUAL TABLE \"emails\" USING fts4(\"subject\", \"body\", tokenize=\"SQLite.swift\" \"tokenizer\")") + assertSQL(""" + CREATE VIRTUAL TABLE \"emails\" USING fts4(\"subject\", \"body\", + tokenize=\"SQLite.swift\" \"tokenizer\") + """.replacingOccurrences(of: "\n", with: "")) try! _ = db.run(emails.insert(subject <- "Aún más cáfe!")) XCTAssertEqual(1, try! db.scalar(emails.filter(emails.match("aun")).count)) diff --git a/Tests/SQLiteTests/FTS5Tests.swift b/Tests/SQLiteTests/FTS5Tests.swift index 63d8dc40..4cce4523 100644 --- a/Tests/SQLiteTests/FTS5Tests.swift +++ b/Tests/SQLiteTests/FTS5Tests.swift @@ -107,7 +107,10 @@ class FTS5Tests: XCTestCase { func test_fts5_config_all() { XCTAssertEqual( - "CREATE VIRTUAL TABLE \"virtual_table\" USING fts5(\"int\", \"string\" UNINDEXED, \"date\" UNINDEXED, tokenize=porter, prefix=\"2,4\", content=\"table\")", + """ + CREATE VIRTUAL TABLE \"virtual_table\" USING fts5(\"int\", \"string\" UNINDEXED, \"date\" UNINDEXED, + tokenize=porter, prefix=\"2,4\", content=\"table\") + """.replacingOccurrences(of: "\n", with: ""), sql(config .tokenizer(.Porter) .column(int) @@ -119,6 +122,6 @@ class FTS5Tests: XCTestCase { } func sql(_ config: FTS5Config) -> String { - return virtualTable.create(.FTS5(config)) + virtualTable.create(.FTS5(config)) } } diff --git a/Tests/SQLiteTests/FoundationTests.swift b/Tests/SQLiteTests/FoundationTests.swift index ba9685b7..cef485fc 100644 --- a/Tests/SQLiteTests/FoundationTests.swift +++ b/Tests/SQLiteTests/FoundationTests.swift @@ -1,7 +1,7 @@ import XCTest import SQLite -class FoundationTests : XCTestCase { +class FoundationTests: XCTestCase { func testDataFromBlob() { let data = Data([1, 2, 3]) let blob = data.datatypeValue diff --git a/Tests/SQLiteTests/OperatorsTests.swift b/Tests/SQLiteTests/OperatorsTests.swift index c9665671..370b910b 100644 --- a/Tests/SQLiteTests/OperatorsTests.swift +++ b/Tests/SQLiteTests/OperatorsTests.swift @@ -1,378 +1,378 @@ import XCTest import SQLite -class OperatorsTests : XCTestCase { +class OperatorsTests: XCTestCase { func test_stringExpressionPlusStringExpression_buildsConcatenatingStringExpression() { - AssertSQL("(\"string\" || \"string\")", string + string) - AssertSQL("(\"string\" || \"stringOptional\")", string + stringOptional) - AssertSQL("(\"stringOptional\" || \"string\")", stringOptional + string) - AssertSQL("(\"stringOptional\" || \"stringOptional\")", stringOptional + stringOptional) - AssertSQL("(\"string\" || 'literal')", string + "literal") - AssertSQL("(\"stringOptional\" || 'literal')", stringOptional + "literal") - AssertSQL("('literal' || \"string\")", "literal" + string) - AssertSQL("('literal' || \"stringOptional\")", "literal" + stringOptional) + assertSQL("(\"string\" || \"string\")", string + string) + assertSQL("(\"string\" || \"stringOptional\")", string + stringOptional) + assertSQL("(\"stringOptional\" || \"string\")", stringOptional + string) + assertSQL("(\"stringOptional\" || \"stringOptional\")", stringOptional + stringOptional) + assertSQL("(\"string\" || 'literal')", string + "literal") + assertSQL("(\"stringOptional\" || 'literal')", stringOptional + "literal") + assertSQL("('literal' || \"string\")", "literal" + string) + assertSQL("('literal' || \"stringOptional\")", "literal" + stringOptional) } func test_numberExpression_plusNumberExpression_buildsAdditiveNumberExpression() { - AssertSQL("(\"int\" + \"int\")", int + int) - AssertSQL("(\"int\" + \"intOptional\")", int + intOptional) - AssertSQL("(\"intOptional\" + \"int\")", intOptional + int) - AssertSQL("(\"intOptional\" + \"intOptional\")", intOptional + intOptional) - AssertSQL("(\"int\" + 1)", int + 1) - AssertSQL("(\"intOptional\" + 1)", intOptional + 1) - AssertSQL("(1 + \"int\")", 1 + int) - AssertSQL("(1 + \"intOptional\")", 1 + intOptional) - - AssertSQL("(\"double\" + \"double\")", double + double) - AssertSQL("(\"double\" + \"doubleOptional\")", double + doubleOptional) - AssertSQL("(\"doubleOptional\" + \"double\")", doubleOptional + double) - AssertSQL("(\"doubleOptional\" + \"doubleOptional\")", doubleOptional + doubleOptional) - AssertSQL("(\"double\" + 1.0)", double + 1) - AssertSQL("(\"doubleOptional\" + 1.0)", doubleOptional + 1) - AssertSQL("(1.0 + \"double\")", 1 + double) - AssertSQL("(1.0 + \"doubleOptional\")", 1 + doubleOptional) + assertSQL("(\"int\" + \"int\")", int + int) + assertSQL("(\"int\" + \"intOptional\")", int + intOptional) + assertSQL("(\"intOptional\" + \"int\")", intOptional + int) + assertSQL("(\"intOptional\" + \"intOptional\")", intOptional + intOptional) + assertSQL("(\"int\" + 1)", int + 1) + assertSQL("(\"intOptional\" + 1)", intOptional + 1) + assertSQL("(1 + \"int\")", 1 + int) + assertSQL("(1 + \"intOptional\")", 1 + intOptional) + + assertSQL("(\"double\" + \"double\")", double + double) + assertSQL("(\"double\" + \"doubleOptional\")", double + doubleOptional) + assertSQL("(\"doubleOptional\" + \"double\")", doubleOptional + double) + assertSQL("(\"doubleOptional\" + \"doubleOptional\")", doubleOptional + doubleOptional) + assertSQL("(\"double\" + 1.0)", double + 1) + assertSQL("(\"doubleOptional\" + 1.0)", doubleOptional + 1) + assertSQL("(1.0 + \"double\")", 1 + double) + assertSQL("(1.0 + \"doubleOptional\")", 1 + doubleOptional) } func test_numberExpression_minusNumberExpression_buildsSubtractiveNumberExpression() { - AssertSQL("(\"int\" - \"int\")", int - int) - AssertSQL("(\"int\" - \"intOptional\")", int - intOptional) - AssertSQL("(\"intOptional\" - \"int\")", intOptional - int) - AssertSQL("(\"intOptional\" - \"intOptional\")", intOptional - intOptional) - AssertSQL("(\"int\" - 1)", int - 1) - AssertSQL("(\"intOptional\" - 1)", intOptional - 1) - AssertSQL("(1 - \"int\")", 1 - int) - AssertSQL("(1 - \"intOptional\")", 1 - intOptional) - - AssertSQL("(\"double\" - \"double\")", double - double) - AssertSQL("(\"double\" - \"doubleOptional\")", double - doubleOptional) - AssertSQL("(\"doubleOptional\" - \"double\")", doubleOptional - double) - AssertSQL("(\"doubleOptional\" - \"doubleOptional\")", doubleOptional - doubleOptional) - AssertSQL("(\"double\" - 1.0)", double - 1) - AssertSQL("(\"doubleOptional\" - 1.0)", doubleOptional - 1) - AssertSQL("(1.0 - \"double\")", 1 - double) - AssertSQL("(1.0 - \"doubleOptional\")", 1 - doubleOptional) + assertSQL("(\"int\" - \"int\")", int - int) + assertSQL("(\"int\" - \"intOptional\")", int - intOptional) + assertSQL("(\"intOptional\" - \"int\")", intOptional - int) + assertSQL("(\"intOptional\" - \"intOptional\")", intOptional - intOptional) + assertSQL("(\"int\" - 1)", int - 1) + assertSQL("(\"intOptional\" - 1)", intOptional - 1) + assertSQL("(1 - \"int\")", 1 - int) + assertSQL("(1 - \"intOptional\")", 1 - intOptional) + + assertSQL("(\"double\" - \"double\")", double - double) + assertSQL("(\"double\" - \"doubleOptional\")", double - doubleOptional) + assertSQL("(\"doubleOptional\" - \"double\")", doubleOptional - double) + assertSQL("(\"doubleOptional\" - \"doubleOptional\")", doubleOptional - doubleOptional) + assertSQL("(\"double\" - 1.0)", double - 1) + assertSQL("(\"doubleOptional\" - 1.0)", doubleOptional - 1) + assertSQL("(1.0 - \"double\")", 1 - double) + assertSQL("(1.0 - \"doubleOptional\")", 1 - doubleOptional) } func test_numberExpression_timesNumberExpression_buildsMultiplicativeNumberExpression() { - AssertSQL("(\"int\" * \"int\")", int * int) - AssertSQL("(\"int\" * \"intOptional\")", int * intOptional) - AssertSQL("(\"intOptional\" * \"int\")", intOptional * int) - AssertSQL("(\"intOptional\" * \"intOptional\")", intOptional * intOptional) - AssertSQL("(\"int\" * 1)", int * 1) - AssertSQL("(\"intOptional\" * 1)", intOptional * 1) - AssertSQL("(1 * \"int\")", 1 * int) - AssertSQL("(1 * \"intOptional\")", 1 * intOptional) - - AssertSQL("(\"double\" * \"double\")", double * double) - AssertSQL("(\"double\" * \"doubleOptional\")", double * doubleOptional) - AssertSQL("(\"doubleOptional\" * \"double\")", doubleOptional * double) - AssertSQL("(\"doubleOptional\" * \"doubleOptional\")", doubleOptional * doubleOptional) - AssertSQL("(\"double\" * 1.0)", double * 1) - AssertSQL("(\"doubleOptional\" * 1.0)", doubleOptional * 1) - AssertSQL("(1.0 * \"double\")", 1 * double) - AssertSQL("(1.0 * \"doubleOptional\")", 1 * doubleOptional) + assertSQL("(\"int\" * \"int\")", int * int) + assertSQL("(\"int\" * \"intOptional\")", int * intOptional) + assertSQL("(\"intOptional\" * \"int\")", intOptional * int) + assertSQL("(\"intOptional\" * \"intOptional\")", intOptional * intOptional) + assertSQL("(\"int\" * 1)", int * 1) + assertSQL("(\"intOptional\" * 1)", intOptional * 1) + assertSQL("(1 * \"int\")", 1 * int) + assertSQL("(1 * \"intOptional\")", 1 * intOptional) + + assertSQL("(\"double\" * \"double\")", double * double) + assertSQL("(\"double\" * \"doubleOptional\")", double * doubleOptional) + assertSQL("(\"doubleOptional\" * \"double\")", doubleOptional * double) + assertSQL("(\"doubleOptional\" * \"doubleOptional\")", doubleOptional * doubleOptional) + assertSQL("(\"double\" * 1.0)", double * 1) + assertSQL("(\"doubleOptional\" * 1.0)", doubleOptional * 1) + assertSQL("(1.0 * \"double\")", 1 * double) + assertSQL("(1.0 * \"doubleOptional\")", 1 * doubleOptional) } func test_numberExpression_dividedByNumberExpression_buildsDivisiveNumberExpression() { - AssertSQL("(\"int\" / \"int\")", int / int) - AssertSQL("(\"int\" / \"intOptional\")", int / intOptional) - AssertSQL("(\"intOptional\" / \"int\")", intOptional / int) - AssertSQL("(\"intOptional\" / \"intOptional\")", intOptional / intOptional) - AssertSQL("(\"int\" / 1)", int / 1) - AssertSQL("(\"intOptional\" / 1)", intOptional / 1) - AssertSQL("(1 / \"int\")", 1 / int) - AssertSQL("(1 / \"intOptional\")", 1 / intOptional) - - AssertSQL("(\"double\" / \"double\")", double / double) - AssertSQL("(\"double\" / \"doubleOptional\")", double / doubleOptional) - AssertSQL("(\"doubleOptional\" / \"double\")", doubleOptional / double) - AssertSQL("(\"doubleOptional\" / \"doubleOptional\")", doubleOptional / doubleOptional) - AssertSQL("(\"double\" / 1.0)", double / 1) - AssertSQL("(\"doubleOptional\" / 1.0)", doubleOptional / 1) - AssertSQL("(1.0 / \"double\")", 1 / double) - AssertSQL("(1.0 / \"doubleOptional\")", 1 / doubleOptional) + assertSQL("(\"int\" / \"int\")", int / int) + assertSQL("(\"int\" / \"intOptional\")", int / intOptional) + assertSQL("(\"intOptional\" / \"int\")", intOptional / int) + assertSQL("(\"intOptional\" / \"intOptional\")", intOptional / intOptional) + assertSQL("(\"int\" / 1)", int / 1) + assertSQL("(\"intOptional\" / 1)", intOptional / 1) + assertSQL("(1 / \"int\")", 1 / int) + assertSQL("(1 / \"intOptional\")", 1 / intOptional) + + assertSQL("(\"double\" / \"double\")", double / double) + assertSQL("(\"double\" / \"doubleOptional\")", double / doubleOptional) + assertSQL("(\"doubleOptional\" / \"double\")", doubleOptional / double) + assertSQL("(\"doubleOptional\" / \"doubleOptional\")", doubleOptional / doubleOptional) + assertSQL("(\"double\" / 1.0)", double / 1) + assertSQL("(\"doubleOptional\" / 1.0)", doubleOptional / 1) + assertSQL("(1.0 / \"double\")", 1 / double) + assertSQL("(1.0 / \"doubleOptional\")", 1 / doubleOptional) } func test_numberExpression_prefixedWithMinus_buildsInvertedNumberExpression() { - AssertSQL("-(\"int\")", -int) - AssertSQL("-(\"intOptional\")", -intOptional) + assertSQL("-(\"int\")", -int) + assertSQL("-(\"intOptional\")", -intOptional) - AssertSQL("-(\"double\")", -double) - AssertSQL("-(\"doubleOptional\")", -doubleOptional) + assertSQL("-(\"double\")", -double) + assertSQL("-(\"doubleOptional\")", -doubleOptional) } func test_integerExpression_moduloIntegerExpression_buildsModuloIntegerExpression() { - AssertSQL("(\"int\" % \"int\")", int % int) - AssertSQL("(\"int\" % \"intOptional\")", int % intOptional) - AssertSQL("(\"intOptional\" % \"int\")", intOptional % int) - AssertSQL("(\"intOptional\" % \"intOptional\")", intOptional % intOptional) - AssertSQL("(\"int\" % 1)", int % 1) - AssertSQL("(\"intOptional\" % 1)", intOptional % 1) - AssertSQL("(1 % \"int\")", 1 % int) - AssertSQL("(1 % \"intOptional\")", 1 % intOptional) + assertSQL("(\"int\" % \"int\")", int % int) + assertSQL("(\"int\" % \"intOptional\")", int % intOptional) + assertSQL("(\"intOptional\" % \"int\")", intOptional % int) + assertSQL("(\"intOptional\" % \"intOptional\")", intOptional % intOptional) + assertSQL("(\"int\" % 1)", int % 1) + assertSQL("(\"intOptional\" % 1)", intOptional % 1) + assertSQL("(1 % \"int\")", 1 % int) + assertSQL("(1 % \"intOptional\")", 1 % intOptional) } func test_integerExpression_bitShiftLeftIntegerExpression_buildsLeftShiftedIntegerExpression() { - AssertSQL("(\"int\" << \"int\")", int << int) - AssertSQL("(\"int\" << \"intOptional\")", int << intOptional) - AssertSQL("(\"intOptional\" << \"int\")", intOptional << int) - AssertSQL("(\"intOptional\" << \"intOptional\")", intOptional << intOptional) - AssertSQL("(\"int\" << 1)", int << 1) - AssertSQL("(\"intOptional\" << 1)", intOptional << 1) - AssertSQL("(1 << \"int\")", 1 << int) - AssertSQL("(1 << \"intOptional\")", 1 << intOptional) + assertSQL("(\"int\" << \"int\")", int << int) + assertSQL("(\"int\" << \"intOptional\")", int << intOptional) + assertSQL("(\"intOptional\" << \"int\")", intOptional << int) + assertSQL("(\"intOptional\" << \"intOptional\")", intOptional << intOptional) + assertSQL("(\"int\" << 1)", int << 1) + assertSQL("(\"intOptional\" << 1)", intOptional << 1) + assertSQL("(1 << \"int\")", 1 << int) + assertSQL("(1 << \"intOptional\")", 1 << intOptional) } func test_integerExpression_bitShiftRightIntegerExpression_buildsRightShiftedIntegerExpression() { - AssertSQL("(\"int\" >> \"int\")", int >> int) - AssertSQL("(\"int\" >> \"intOptional\")", int >> intOptional) - AssertSQL("(\"intOptional\" >> \"int\")", intOptional >> int) - AssertSQL("(\"intOptional\" >> \"intOptional\")", intOptional >> intOptional) - AssertSQL("(\"int\" >> 1)", int >> 1) - AssertSQL("(\"intOptional\" >> 1)", intOptional >> 1) - AssertSQL("(1 >> \"int\")", 1 >> int) - AssertSQL("(1 >> \"intOptional\")", 1 >> intOptional) + assertSQL("(\"int\" >> \"int\")", int >> int) + assertSQL("(\"int\" >> \"intOptional\")", int >> intOptional) + assertSQL("(\"intOptional\" >> \"int\")", intOptional >> int) + assertSQL("(\"intOptional\" >> \"intOptional\")", intOptional >> intOptional) + assertSQL("(\"int\" >> 1)", int >> 1) + assertSQL("(\"intOptional\" >> 1)", intOptional >> 1) + assertSQL("(1 >> \"int\")", 1 >> int) + assertSQL("(1 >> \"intOptional\")", 1 >> intOptional) } func test_integerExpression_bitwiseAndIntegerExpression_buildsAndedIntegerExpression() { - AssertSQL("(\"int\" & \"int\")", int & int) - AssertSQL("(\"int\" & \"intOptional\")", int & intOptional) - AssertSQL("(\"intOptional\" & \"int\")", intOptional & int) - AssertSQL("(\"intOptional\" & \"intOptional\")", intOptional & intOptional) - AssertSQL("(\"int\" & 1)", int & 1) - AssertSQL("(\"intOptional\" & 1)", intOptional & 1) - AssertSQL("(1 & \"int\")", 1 & int) - AssertSQL("(1 & \"intOptional\")", 1 & intOptional) + assertSQL("(\"int\" & \"int\")", int & int) + assertSQL("(\"int\" & \"intOptional\")", int & intOptional) + assertSQL("(\"intOptional\" & \"int\")", intOptional & int) + assertSQL("(\"intOptional\" & \"intOptional\")", intOptional & intOptional) + assertSQL("(\"int\" & 1)", int & 1) + assertSQL("(\"intOptional\" & 1)", intOptional & 1) + assertSQL("(1 & \"int\")", 1 & int) + assertSQL("(1 & \"intOptional\")", 1 & intOptional) } func test_integerExpression_bitwiseOrIntegerExpression_buildsOredIntegerExpression() { - AssertSQL("(\"int\" | \"int\")", int | int) - AssertSQL("(\"int\" | \"intOptional\")", int | intOptional) - AssertSQL("(\"intOptional\" | \"int\")", intOptional | int) - AssertSQL("(\"intOptional\" | \"intOptional\")", intOptional | intOptional) - AssertSQL("(\"int\" | 1)", int | 1) - AssertSQL("(\"intOptional\" | 1)", intOptional | 1) - AssertSQL("(1 | \"int\")", 1 | int) - AssertSQL("(1 | \"intOptional\")", 1 | intOptional) + assertSQL("(\"int\" | \"int\")", int | int) + assertSQL("(\"int\" | \"intOptional\")", int | intOptional) + assertSQL("(\"intOptional\" | \"int\")", intOptional | int) + assertSQL("(\"intOptional\" | \"intOptional\")", intOptional | intOptional) + assertSQL("(\"int\" | 1)", int | 1) + assertSQL("(\"intOptional\" | 1)", intOptional | 1) + assertSQL("(1 | \"int\")", 1 | int) + assertSQL("(1 | \"intOptional\")", 1 | intOptional) } func test_integerExpression_bitwiseExclusiveOrIntegerExpression_buildsOredIntegerExpression() { - AssertSQL("(~((\"int\" & \"int\")) & (\"int\" | \"int\"))", int ^ int) - AssertSQL("(~((\"int\" & \"intOptional\")) & (\"int\" | \"intOptional\"))", int ^ intOptional) - AssertSQL("(~((\"intOptional\" & \"int\")) & (\"intOptional\" | \"int\"))", intOptional ^ int) - AssertSQL("(~((\"intOptional\" & \"intOptional\")) & (\"intOptional\" | \"intOptional\"))", intOptional ^ intOptional) - AssertSQL("(~((\"int\" & 1)) & (\"int\" | 1))", int ^ 1) - AssertSQL("(~((\"intOptional\" & 1)) & (\"intOptional\" | 1))", intOptional ^ 1) - AssertSQL("(~((1 & \"int\")) & (1 | \"int\"))", 1 ^ int) - AssertSQL("(~((1 & \"intOptional\")) & (1 | \"intOptional\"))", 1 ^ intOptional) + assertSQL("(~((\"int\" & \"int\")) & (\"int\" | \"int\"))", int ^ int) + assertSQL("(~((\"int\" & \"intOptional\")) & (\"int\" | \"intOptional\"))", int ^ intOptional) + assertSQL("(~((\"intOptional\" & \"int\")) & (\"intOptional\" | \"int\"))", intOptional ^ int) + assertSQL("(~((\"intOptional\" & \"intOptional\")) & (\"intOptional\" | \"intOptional\"))", intOptional ^ intOptional) + assertSQL("(~((\"int\" & 1)) & (\"int\" | 1))", int ^ 1) + assertSQL("(~((\"intOptional\" & 1)) & (\"intOptional\" | 1))", intOptional ^ 1) + assertSQL("(~((1 & \"int\")) & (1 | \"int\"))", 1 ^ int) + assertSQL("(~((1 & \"intOptional\")) & (1 | \"intOptional\"))", 1 ^ intOptional) } func test_bitwiseNot_integerExpression_buildsComplementIntegerExpression() { - AssertSQL("~(\"int\")", ~int) - AssertSQL("~(\"intOptional\")", ~intOptional) + assertSQL("~(\"int\")", ~int) + assertSQL("~(\"intOptional\")", ~intOptional) } func test_equalityOperator_withEquatableExpressions_buildsBooleanExpression() { - AssertSQL("(\"bool\" = \"bool\")", bool == bool) - AssertSQL("(\"bool\" = \"boolOptional\")", bool == boolOptional) - AssertSQL("(\"boolOptional\" = \"bool\")", boolOptional == bool) - AssertSQL("(\"boolOptional\" = \"boolOptional\")", boolOptional == boolOptional) - AssertSQL("(\"bool\" = 1)", bool == true) - AssertSQL("(\"boolOptional\" = 1)", boolOptional == true) - AssertSQL("(1 = \"bool\")", true == bool) - AssertSQL("(1 = \"boolOptional\")", true == boolOptional) + assertSQL("(\"bool\" = \"bool\")", bool == bool) + assertSQL("(\"bool\" = \"boolOptional\")", bool == boolOptional) + assertSQL("(\"boolOptional\" = \"bool\")", boolOptional == bool) + assertSQL("(\"boolOptional\" = \"boolOptional\")", boolOptional == boolOptional) + assertSQL("(\"bool\" = 1)", bool == true) + assertSQL("(\"boolOptional\" = 1)", boolOptional == true) + assertSQL("(1 = \"bool\")", true == bool) + assertSQL("(1 = \"boolOptional\")", true == boolOptional) - AssertSQL("(\"boolOptional\" IS NULL)", boolOptional == nil) - AssertSQL("(NULL IS \"boolOptional\")", nil == boolOptional) + assertSQL("(\"boolOptional\" IS NULL)", boolOptional == nil) + assertSQL("(NULL IS \"boolOptional\")", nil == boolOptional) } func test_isOperator_withEquatableExpressions_buildsBooleanExpression() { - AssertSQL("(\"bool\" IS \"bool\")", bool === bool) - AssertSQL("(\"bool\" IS \"boolOptional\")", bool === boolOptional) - AssertSQL("(\"boolOptional\" IS \"bool\")", boolOptional === bool) - AssertSQL("(\"boolOptional\" IS \"boolOptional\")", boolOptional === boolOptional) - AssertSQL("(\"bool\" IS 1)", bool === true) - AssertSQL("(\"boolOptional\" IS 1)", boolOptional === true) - AssertSQL("(1 IS \"bool\")", true === bool) - AssertSQL("(1 IS \"boolOptional\")", true === boolOptional) - - AssertSQL("(\"boolOptional\" IS NULL)", boolOptional === nil) - AssertSQL("(NULL IS \"boolOptional\")", nil === boolOptional) - } - + assertSQL("(\"bool\" IS \"bool\")", bool === bool) + assertSQL("(\"bool\" IS \"boolOptional\")", bool === boolOptional) + assertSQL("(\"boolOptional\" IS \"bool\")", boolOptional === bool) + assertSQL("(\"boolOptional\" IS \"boolOptional\")", boolOptional === boolOptional) + assertSQL("(\"bool\" IS 1)", bool === true) + assertSQL("(\"boolOptional\" IS 1)", boolOptional === true) + assertSQL("(1 IS \"bool\")", true === bool) + assertSQL("(1 IS \"boolOptional\")", true === boolOptional) + + assertSQL("(\"boolOptional\" IS NULL)", boolOptional === nil) + assertSQL("(NULL IS \"boolOptional\")", nil === boolOptional) + } + func test_isNotOperator_withEquatableExpressions_buildsBooleanExpression() { - AssertSQL("(\"bool\" IS NOT \"bool\")", bool !== bool) - AssertSQL("(\"bool\" IS NOT \"boolOptional\")", bool !== boolOptional) - AssertSQL("(\"boolOptional\" IS NOT \"bool\")", boolOptional !== bool) - AssertSQL("(\"boolOptional\" IS NOT \"boolOptional\")", boolOptional !== boolOptional) - AssertSQL("(\"bool\" IS NOT 1)", bool !== true) - AssertSQL("(\"boolOptional\" IS NOT 1)", boolOptional !== true) - AssertSQL("(1 IS NOT \"bool\")", true !== bool) - AssertSQL("(1 IS NOT \"boolOptional\")", true !== boolOptional) - - AssertSQL("(\"boolOptional\" IS NOT NULL)", boolOptional !== nil) - AssertSQL("(NULL IS NOT \"boolOptional\")", nil !== boolOptional) + assertSQL("(\"bool\" IS NOT \"bool\")", bool !== bool) + assertSQL("(\"bool\" IS NOT \"boolOptional\")", bool !== boolOptional) + assertSQL("(\"boolOptional\" IS NOT \"bool\")", boolOptional !== bool) + assertSQL("(\"boolOptional\" IS NOT \"boolOptional\")", boolOptional !== boolOptional) + assertSQL("(\"bool\" IS NOT 1)", bool !== true) + assertSQL("(\"boolOptional\" IS NOT 1)", boolOptional !== true) + assertSQL("(1 IS NOT \"bool\")", true !== bool) + assertSQL("(1 IS NOT \"boolOptional\")", true !== boolOptional) + + assertSQL("(\"boolOptional\" IS NOT NULL)", boolOptional !== nil) + assertSQL("(NULL IS NOT \"boolOptional\")", nil !== boolOptional) } func test_inequalityOperator_withEquatableExpressions_buildsBooleanExpression() { - AssertSQL("(\"bool\" != \"bool\")", bool != bool) - AssertSQL("(\"bool\" != \"boolOptional\")", bool != boolOptional) - AssertSQL("(\"boolOptional\" != \"bool\")", boolOptional != bool) - AssertSQL("(\"boolOptional\" != \"boolOptional\")", boolOptional != boolOptional) - AssertSQL("(\"bool\" != 1)", bool != true) - AssertSQL("(\"boolOptional\" != 1)", boolOptional != true) - AssertSQL("(1 != \"bool\")", true != bool) - AssertSQL("(1 != \"boolOptional\")", true != boolOptional) + assertSQL("(\"bool\" != \"bool\")", bool != bool) + assertSQL("(\"bool\" != \"boolOptional\")", bool != boolOptional) + assertSQL("(\"boolOptional\" != \"bool\")", boolOptional != bool) + assertSQL("(\"boolOptional\" != \"boolOptional\")", boolOptional != boolOptional) + assertSQL("(\"bool\" != 1)", bool != true) + assertSQL("(\"boolOptional\" != 1)", boolOptional != true) + assertSQL("(1 != \"bool\")", true != bool) + assertSQL("(1 != \"boolOptional\")", true != boolOptional) - AssertSQL("(\"boolOptional\" IS NOT NULL)", boolOptional != nil) - AssertSQL("(NULL IS NOT \"boolOptional\")", nil != boolOptional) + assertSQL("(\"boolOptional\" IS NOT NULL)", boolOptional != nil) + assertSQL("(NULL IS NOT \"boolOptional\")", nil != boolOptional) } func test_greaterThanOperator_withComparableExpressions_buildsBooleanExpression() { - AssertSQL("(\"bool\" > \"bool\")", bool > bool) - AssertSQL("(\"bool\" > \"boolOptional\")", bool > boolOptional) - AssertSQL("(\"boolOptional\" > \"bool\")", boolOptional > bool) - AssertSQL("(\"boolOptional\" > \"boolOptional\")", boolOptional > boolOptional) - AssertSQL("(\"bool\" > 1)", bool > true) - AssertSQL("(\"boolOptional\" > 1)", boolOptional > true) - AssertSQL("(1 > \"bool\")", true > bool) - AssertSQL("(1 > \"boolOptional\")", true > boolOptional) + assertSQL("(\"bool\" > \"bool\")", bool > bool) + assertSQL("(\"bool\" > \"boolOptional\")", bool > boolOptional) + assertSQL("(\"boolOptional\" > \"bool\")", boolOptional > bool) + assertSQL("(\"boolOptional\" > \"boolOptional\")", boolOptional > boolOptional) + assertSQL("(\"bool\" > 1)", bool > true) + assertSQL("(\"boolOptional\" > 1)", boolOptional > true) + assertSQL("(1 > \"bool\")", true > bool) + assertSQL("(1 > \"boolOptional\")", true > boolOptional) } func test_greaterThanOrEqualToOperator_withComparableExpressions_buildsBooleanExpression() { - AssertSQL("(\"bool\" >= \"bool\")", bool >= bool) - AssertSQL("(\"bool\" >= \"boolOptional\")", bool >= boolOptional) - AssertSQL("(\"boolOptional\" >= \"bool\")", boolOptional >= bool) - AssertSQL("(\"boolOptional\" >= \"boolOptional\")", boolOptional >= boolOptional) - AssertSQL("(\"bool\" >= 1)", bool >= true) - AssertSQL("(\"boolOptional\" >= 1)", boolOptional >= true) - AssertSQL("(1 >= \"bool\")", true >= bool) - AssertSQL("(1 >= \"boolOptional\")", true >= boolOptional) + assertSQL("(\"bool\" >= \"bool\")", bool >= bool) + assertSQL("(\"bool\" >= \"boolOptional\")", bool >= boolOptional) + assertSQL("(\"boolOptional\" >= \"bool\")", boolOptional >= bool) + assertSQL("(\"boolOptional\" >= \"boolOptional\")", boolOptional >= boolOptional) + assertSQL("(\"bool\" >= 1)", bool >= true) + assertSQL("(\"boolOptional\" >= 1)", boolOptional >= true) + assertSQL("(1 >= \"bool\")", true >= bool) + assertSQL("(1 >= \"boolOptional\")", true >= boolOptional) } func test_lessThanOperator_withComparableExpressions_buildsBooleanExpression() { - AssertSQL("(\"bool\" < \"bool\")", bool < bool) - AssertSQL("(\"bool\" < \"boolOptional\")", bool < boolOptional) - AssertSQL("(\"boolOptional\" < \"bool\")", boolOptional < bool) - AssertSQL("(\"boolOptional\" < \"boolOptional\")", boolOptional < boolOptional) - AssertSQL("(\"bool\" < 1)", bool < true) - AssertSQL("(\"boolOptional\" < 1)", boolOptional < true) - AssertSQL("(1 < \"bool\")", true < bool) - AssertSQL("(1 < \"boolOptional\")", true < boolOptional) + assertSQL("(\"bool\" < \"bool\")", bool < bool) + assertSQL("(\"bool\" < \"boolOptional\")", bool < boolOptional) + assertSQL("(\"boolOptional\" < \"bool\")", boolOptional < bool) + assertSQL("(\"boolOptional\" < \"boolOptional\")", boolOptional < boolOptional) + assertSQL("(\"bool\" < 1)", bool < true) + assertSQL("(\"boolOptional\" < 1)", boolOptional < true) + assertSQL("(1 < \"bool\")", true < bool) + assertSQL("(1 < \"boolOptional\")", true < boolOptional) } func test_lessThanOrEqualToOperator_withComparableExpressions_buildsBooleanExpression() { - AssertSQL("(\"bool\" <= \"bool\")", bool <= bool) - AssertSQL("(\"bool\" <= \"boolOptional\")", bool <= boolOptional) - AssertSQL("(\"boolOptional\" <= \"bool\")", boolOptional <= bool) - AssertSQL("(\"boolOptional\" <= \"boolOptional\")", boolOptional <= boolOptional) - AssertSQL("(\"bool\" <= 1)", bool <= true) - AssertSQL("(\"boolOptional\" <= 1)", boolOptional <= true) - AssertSQL("(1 <= \"bool\")", true <= bool) - AssertSQL("(1 <= \"boolOptional\")", true <= boolOptional) + assertSQL("(\"bool\" <= \"bool\")", bool <= bool) + assertSQL("(\"bool\" <= \"boolOptional\")", bool <= boolOptional) + assertSQL("(\"boolOptional\" <= \"bool\")", boolOptional <= bool) + assertSQL("(\"boolOptional\" <= \"boolOptional\")", boolOptional <= boolOptional) + assertSQL("(\"bool\" <= 1)", bool <= true) + assertSQL("(\"boolOptional\" <= 1)", boolOptional <= true) + assertSQL("(1 <= \"bool\")", true <= bool) + assertSQL("(1 <= \"boolOptional\")", true <= boolOptional) } func test_patternMatchingOperator_withComparableCountableClosedRange_buildsBetweenBooleanExpression() { - AssertSQL("\"int\" BETWEEN 0 AND 5", 0...5 ~= int) - AssertSQL("\"intOptional\" BETWEEN 0 AND 5", 0...5 ~= intOptional) + assertSQL("\"int\" BETWEEN 0 AND 5", 0...5 ~= int) + assertSQL("\"intOptional\" BETWEEN 0 AND 5", 0...5 ~= intOptional) } func test_patternMatchingOperator_withComparableClosedRange_buildsBetweenBooleanExpression() { - AssertSQL("\"double\" BETWEEN 1.2 AND 4.5", 1.2...4.5 ~= double) - AssertSQL("\"doubleOptional\" BETWEEN 1.2 AND 4.5", 1.2...4.5 ~= doubleOptional) + assertSQL("\"double\" BETWEEN 1.2 AND 4.5", 1.2...4.5 ~= double) + assertSQL("\"doubleOptional\" BETWEEN 1.2 AND 4.5", 1.2...4.5 ~= doubleOptional) } func test_patternMatchingOperator_withComparableRange_buildsBooleanExpression() { - AssertSQL("\"double\" >= 1.2 AND \"double\" < 4.5", 1.2..<4.5 ~= double) - AssertSQL("\"doubleOptional\" >= 1.2 AND \"doubleOptional\" < 4.5", 1.2..<4.5 ~= doubleOptional) + assertSQL("\"double\" >= 1.2 AND \"double\" < 4.5", 1.2..<4.5 ~= double) + assertSQL("\"doubleOptional\" >= 1.2 AND \"doubleOptional\" < 4.5", 1.2..<4.5 ~= doubleOptional) } func test_patternMatchingOperator_withComparablePartialRangeThrough_buildsBooleanExpression() { - AssertSQL("\"double\" <= 4.5", ...4.5 ~= double) - AssertSQL("\"doubleOptional\" <= 4.5", ...4.5 ~= doubleOptional) + assertSQL("\"double\" <= 4.5", ...4.5 ~= double) + assertSQL("\"doubleOptional\" <= 4.5", ...4.5 ~= doubleOptional) } func test_patternMatchingOperator_withComparablePartialRangeUpTo_buildsBooleanExpression() { - AssertSQL("\"double\" < 4.5", ..<4.5 ~= double) - AssertSQL("\"doubleOptional\" < 4.5", ..<4.5 ~= doubleOptional) + assertSQL("\"double\" < 4.5", ..<4.5 ~= double) + assertSQL("\"doubleOptional\" < 4.5", ..<4.5 ~= doubleOptional) } func test_patternMatchingOperator_withComparablePartialRangeFrom_buildsBooleanExpression() { - AssertSQL("\"double\" >= 4.5", 4.5... ~= double) - AssertSQL("\"doubleOptional\" >= 4.5", 4.5... ~= doubleOptional) + assertSQL("\"double\" >= 4.5", 4.5... ~= double) + assertSQL("\"doubleOptional\" >= 4.5", 4.5... ~= doubleOptional) } func test_patternMatchingOperator_withComparableClosedRangeString_buildsBetweenBooleanExpression() { - AssertSQL("\"string\" BETWEEN 'a' AND 'b'", "a"..."b" ~= string) - AssertSQL("\"stringOptional\" BETWEEN 'a' AND 'b'", "a"..."b" ~= stringOptional) + assertSQL("\"string\" BETWEEN 'a' AND 'b'", "a"..."b" ~= string) + assertSQL("\"stringOptional\" BETWEEN 'a' AND 'b'", "a"..."b" ~= stringOptional) } func test_doubleAndOperator_withBooleanExpressions_buildsCompoundExpression() { - AssertSQL("(\"bool\" AND \"bool\")", bool && bool) - AssertSQL("(\"bool\" AND \"boolOptional\")", bool && boolOptional) - AssertSQL("(\"boolOptional\" AND \"bool\")", boolOptional && bool) - AssertSQL("(\"boolOptional\" AND \"boolOptional\")", boolOptional && boolOptional) - AssertSQL("(\"bool\" AND 1)", bool && true) - AssertSQL("(\"boolOptional\" AND 1)", boolOptional && true) - AssertSQL("(1 AND \"bool\")", true && bool) - AssertSQL("(1 AND \"boolOptional\")", true && boolOptional) - } - + assertSQL("(\"bool\" AND \"bool\")", bool && bool) + assertSQL("(\"bool\" AND \"boolOptional\")", bool && boolOptional) + assertSQL("(\"boolOptional\" AND \"bool\")", boolOptional && bool) + assertSQL("(\"boolOptional\" AND \"boolOptional\")", boolOptional && boolOptional) + assertSQL("(\"bool\" AND 1)", bool && true) + assertSQL("(\"boolOptional\" AND 1)", boolOptional && true) + assertSQL("(1 AND \"bool\")", true && bool) + assertSQL("(1 AND \"boolOptional\")", true && boolOptional) + } + func test_andFunction_withBooleanExpressions_buildsCompoundExpression() { - AssertSQL("(\"bool\" AND \"bool\" AND \"bool\")", and([bool, bool, bool])) - AssertSQL("(\"bool\" AND \"bool\")", and([bool, bool])) - AssertSQL("(\"bool\")", and([bool])) - - AssertSQL("(\"bool\" AND \"bool\" AND \"bool\")", and(bool, bool, bool)) - AssertSQL("(\"bool\" AND \"bool\")", and(bool, bool)) - AssertSQL("(\"bool\")", and(bool)) + assertSQL("(\"bool\" AND \"bool\" AND \"bool\")", and([bool, bool, bool])) + assertSQL("(\"bool\" AND \"bool\")", and([bool, bool])) + assertSQL("(\"bool\")", and([bool])) + + assertSQL("(\"bool\" AND \"bool\" AND \"bool\")", and(bool, bool, bool)) + assertSQL("(\"bool\" AND \"bool\")", and(bool, bool)) + assertSQL("(\"bool\")", and(bool)) } func test_doubleOrOperator_withBooleanExpressions_buildsCompoundExpression() { - AssertSQL("(\"bool\" OR \"bool\")", bool || bool) - AssertSQL("(\"bool\" OR \"boolOptional\")", bool || boolOptional) - AssertSQL("(\"boolOptional\" OR \"bool\")", boolOptional || bool) - AssertSQL("(\"boolOptional\" OR \"boolOptional\")", boolOptional || boolOptional) - AssertSQL("(\"bool\" OR 1)", bool || true) - AssertSQL("(\"boolOptional\" OR 1)", boolOptional || true) - AssertSQL("(1 OR \"bool\")", true || bool) - AssertSQL("(1 OR \"boolOptional\")", true || boolOptional) - } - + assertSQL("(\"bool\" OR \"bool\")", bool || bool) + assertSQL("(\"bool\" OR \"boolOptional\")", bool || boolOptional) + assertSQL("(\"boolOptional\" OR \"bool\")", boolOptional || bool) + assertSQL("(\"boolOptional\" OR \"boolOptional\")", boolOptional || boolOptional) + assertSQL("(\"bool\" OR 1)", bool || true) + assertSQL("(\"boolOptional\" OR 1)", boolOptional || true) + assertSQL("(1 OR \"bool\")", true || bool) + assertSQL("(1 OR \"boolOptional\")", true || boolOptional) + } + func test_orFunction_withBooleanExpressions_buildsCompoundExpression() { - AssertSQL("(\"bool\" OR \"bool\" OR \"bool\")", or([bool, bool, bool])) - AssertSQL("(\"bool\" OR \"bool\")", or([bool, bool])) - AssertSQL("(\"bool\")", or([bool])) - - AssertSQL("(\"bool\" OR \"bool\" OR \"bool\")", or(bool, bool, bool)) - AssertSQL("(\"bool\" OR \"bool\")", or(bool, bool)) - AssertSQL("(\"bool\")", or(bool)) + assertSQL("(\"bool\" OR \"bool\" OR \"bool\")", or([bool, bool, bool])) + assertSQL("(\"bool\" OR \"bool\")", or([bool, bool])) + assertSQL("(\"bool\")", or([bool])) + + assertSQL("(\"bool\" OR \"bool\" OR \"bool\")", or(bool, bool, bool)) + assertSQL("(\"bool\" OR \"bool\")", or(bool, bool)) + assertSQL("(\"bool\")", or(bool)) } func test_unaryNotOperator_withBooleanExpressions_buildsNotExpression() { - AssertSQL("NOT (\"bool\")", !bool) - AssertSQL("NOT (\"boolOptional\")", !boolOptional) + assertSQL("NOT (\"bool\")", !bool) + assertSQL("NOT (\"boolOptional\")", !boolOptional) } func test_precedencePreserved() { let n = Expression(value: 1) - AssertSQL("(((1 = 1) AND (1 = 1)) OR (1 = 1))", (n == n && n == n) || n == n) - AssertSQL("((1 = 1) AND ((1 = 1) OR (1 = 1)))", n == n && (n == n || n == n)) + assertSQL("(((1 = 1) AND (1 = 1)) OR (1 = 1))", (n == n && n == n) || n == n) + assertSQL("((1 = 1) AND ((1 = 1) OR (1 = 1)))", n == n && (n == n || n == n)) } func test_dateExpressionLessGreater() { let begin = Date(timeIntervalSince1970: 0) - AssertSQL("(\"date\" < '1970-01-01T00:00:00.000')", date < begin) - AssertSQL("(\"date\" > '1970-01-01T00:00:00.000')", date > begin) - AssertSQL("(\"date\" >= '1970-01-01T00:00:00.000')", date >= begin) - AssertSQL("(\"date\" <= '1970-01-01T00:00:00.000')", date <= begin) + assertSQL("(\"date\" < '1970-01-01T00:00:00.000')", date < begin) + assertSQL("(\"date\" > '1970-01-01T00:00:00.000')", date > begin) + assertSQL("(\"date\" >= '1970-01-01T00:00:00.000')", date >= begin) + assertSQL("(\"date\" <= '1970-01-01T00:00:00.000')", date <= begin) } func test_dateExpressionRange() { let begin = Date(timeIntervalSince1970: 0) let end = Date(timeIntervalSince1970: 5000) - AssertSQL( + assertSQL( "\"date\" >= '1970-01-01T00:00:00.000' AND \"date\" < '1970-01-01T01:23:20.000'", (begin..("id") @@ -28,65 +28,65 @@ class QueryTests : XCTestCase { let tag = Expression("tag") func test_select_withExpression_compilesSelectClause() { - AssertSQL("SELECT \"email\" FROM \"users\"", users.select(email)) + assertSQL("SELECT \"email\" FROM \"users\"", users.select(email)) } func test_select_withStarExpression_compilesSelectClause() { - AssertSQL("SELECT * FROM \"users\"", users.select(*)) + assertSQL("SELECT * FROM \"users\"", users.select(*)) } func test_select_withNamespacedStarExpression_compilesSelectClause() { - AssertSQL("SELECT \"users\".* FROM \"users\"", users.select(users[*])) + assertSQL("SELECT \"users\".* FROM \"users\"", users.select(users[*])) } func test_select_withVariadicExpressions_compilesSelectClause() { - AssertSQL("SELECT \"email\", count(*) FROM \"users\"", users.select(email, count(*))) + assertSQL("SELECT \"email\", count(*) FROM \"users\"", users.select(email, count(*))) } func test_select_withExpressions_compilesSelectClause() { - AssertSQL("SELECT \"email\", count(*) FROM \"users\"", users.select([email, count(*)])) + assertSQL("SELECT \"email\", count(*) FROM \"users\"", users.select([email, count(*)])) } func test_selectDistinct_withExpression_compilesSelectClause() { - AssertSQL("SELECT DISTINCT \"age\" FROM \"users\"", users.select(distinct: age)) + assertSQL("SELECT DISTINCT \"age\" FROM \"users\"", users.select(distinct: age)) } func test_selectDistinct_withExpressions_compilesSelectClause() { - AssertSQL("SELECT DISTINCT \"age\", \"admin\" FROM \"users\"", users.select(distinct: [age, admin])) + assertSQL("SELECT DISTINCT \"age\", \"admin\" FROM \"users\"", users.select(distinct: [age, admin])) } func test_selectDistinct_withStar_compilesSelectClause() { - AssertSQL("SELECT DISTINCT * FROM \"users\"", users.select(distinct: *)) + assertSQL("SELECT DISTINCT * FROM \"users\"", users.select(distinct: *)) } func test_join_compilesJoinClause() { - AssertSQL( + assertSQL( "SELECT * FROM \"users\" INNER JOIN \"posts\" ON (\"posts\".\"user_id\" = \"users\".\"id\")", users.join(posts, on: posts[userId] == users[id]) ) } func test_join_withExplicitType_compilesJoinClauseWithType() { - AssertSQL( + assertSQL( "SELECT * FROM \"users\" LEFT OUTER JOIN \"posts\" ON (\"posts\".\"user_id\" = \"users\".\"id\")", users.join(.leftOuter, posts, on: posts[userId] == users[id]) ) - AssertSQL( + assertSQL( "SELECT * FROM \"users\" CROSS JOIN \"posts\" ON (\"posts\".\"user_id\" = \"users\".\"id\")", users.join(.cross, posts, on: posts[userId] == users[id]) ) } func test_join_withTableCondition_compilesJoinClauseWithTableCondition() { - AssertSQL( + assertSQL( "SELECT * FROM \"users\" INNER JOIN \"posts\" ON ((\"posts\".\"user_id\" = \"users\".\"id\") AND \"published\")", users.join(posts.filter(published), on: posts[userId] == users[id]) ) } func test_join_whenChained_compilesAggregateJoinClause() { - AssertSQL( + assertSQL( "SELECT * FROM \"users\" " + "INNER JOIN \"posts\" ON (\"posts\".\"user_id\" = \"users\".\"id\") " + "INNER JOIN \"categories\" ON (\"categories\".\"id\" = \"posts\".\"category_id\")", @@ -95,79 +95,79 @@ class QueryTests : XCTestCase { } func test_filter_compilesWhereClause() { - AssertSQL("SELECT * FROM \"users\" WHERE (\"admin\" = 1)", users.filter(admin == true)) + assertSQL("SELECT * FROM \"users\" WHERE (\"admin\" = 1)", users.filter(admin == true)) } func test_filter_compilesWhereClause_false() { - AssertSQL("SELECT * FROM \"users\" WHERE (\"admin\" = 0)", users.filter(admin == false)) + assertSQL("SELECT * FROM \"users\" WHERE (\"admin\" = 0)", users.filter(admin == false)) } func test_filter_compilesWhereClause_optional() { - AssertSQL("SELECT * FROM \"users\" WHERE (\"admin\" = 1)", users.filter(optionalAdmin == true)) + assertSQL("SELECT * FROM \"users\" WHERE (\"admin\" = 1)", users.filter(optionalAdmin == true)) } func test_filter_compilesWhereClause_optional_false() { - AssertSQL("SELECT * FROM \"users\" WHERE (\"admin\" = 0)", users.filter(optionalAdmin == false)) + assertSQL("SELECT * FROM \"users\" WHERE (\"admin\" = 0)", users.filter(optionalAdmin == false)) } func test_where_compilesWhereClause() { - AssertSQL("SELECT * FROM \"users\" WHERE (\"admin\" = 1)", users.where(admin == true)) + assertSQL("SELECT * FROM \"users\" WHERE (\"admin\" = 1)", users.where(admin == true)) } func test_where_compilesWhereClause_false() { - AssertSQL("SELECT * FROM \"users\" WHERE (\"admin\" = 0)", users.where(admin == false)) + assertSQL("SELECT * FROM \"users\" WHERE (\"admin\" = 0)", users.where(admin == false)) } func test_where_compilesWhereClause_optional() { - AssertSQL("SELECT * FROM \"users\" WHERE (\"admin\" = 1)", users.where(optionalAdmin == true)) + assertSQL("SELECT * FROM \"users\" WHERE (\"admin\" = 1)", users.where(optionalAdmin == true)) } func test_where_compilesWhereClause_optional_false() { - AssertSQL("SELECT * FROM \"users\" WHERE (\"admin\" = 0)", users.where(optionalAdmin == false)) + assertSQL("SELECT * FROM \"users\" WHERE (\"admin\" = 0)", users.where(optionalAdmin == false)) } func test_filter_whenChained_compilesAggregateWhereClause() { - AssertSQL( + assertSQL( "SELECT * FROM \"users\" WHERE ((\"age\" >= 35) AND \"admin\")", users.filter(age >= 35).filter(admin) ) } func test_group_withSingleExpressionName_compilesGroupClause() { - AssertSQL("SELECT * FROM \"users\" GROUP BY \"age\"", + assertSQL("SELECT * FROM \"users\" GROUP BY \"age\"", users.group(age)) } func test_group_withVariadicExpressionNames_compilesGroupClause() { - AssertSQL("SELECT * FROM \"users\" GROUP BY \"age\", \"admin\"", users.group(age, admin)) + assertSQL("SELECT * FROM \"users\" GROUP BY \"age\", \"admin\"", users.group(age, admin)) } func test_group_withExpressionNameAndHavingBindings_compilesGroupClause() { - AssertSQL("SELECT * FROM \"users\" GROUP BY \"age\" HAVING \"admin\"", users.group(age, having: admin)) - AssertSQL("SELECT * FROM \"users\" GROUP BY \"age\" HAVING (\"age\" >= 30)", users.group(age, having: age >= 30)) + assertSQL("SELECT * FROM \"users\" GROUP BY \"age\" HAVING \"admin\"", users.group(age, having: admin)) + assertSQL("SELECT * FROM \"users\" GROUP BY \"age\" HAVING (\"age\" >= 30)", users.group(age, having: age >= 30)) } func test_group_withExpressionNamesAndHavingBindings_compilesGroupClause() { - AssertSQL( + assertSQL( "SELECT * FROM \"users\" GROUP BY \"age\", \"admin\" HAVING \"admin\"", users.group([age, admin], having: admin) ) - AssertSQL( + assertSQL( "SELECT * FROM \"users\" GROUP BY \"age\", \"admin\" HAVING (\"age\" >= 30)", users.group([age, admin], having: age >= 30) ) } func test_order_withSingleExpressionName_compilesOrderClause() { - AssertSQL("SELECT * FROM \"users\" ORDER BY \"age\"", users.order(age)) + assertSQL("SELECT * FROM \"users\" ORDER BY \"age\"", users.order(age)) } func test_order_withVariadicExpressionNames_compilesOrderClause() { - AssertSQL("SELECT * FROM \"users\" ORDER BY \"age\", \"email\"", users.order(age, email)) + assertSQL("SELECT * FROM \"users\" ORDER BY \"age\", \"email\"", users.order(age, email)) } func test_order_withArrayExpressionNames_compilesOrderClause() { - AssertSQL("SELECT * FROM \"users\" ORDER BY \"age\", \"email\"", users.order([age, email])) + assertSQL("SELECT * FROM \"users\" ORDER BY \"age\", \"email\"", users.order([age, email])) } func test_order_withExpressionAndSortDirection_compilesOrderClause() { @@ -175,7 +175,7 @@ class QueryTests : XCTestCase { } func test_order_whenChained_resetsOrderClause() { - AssertSQL("SELECT * FROM \"users\" ORDER BY \"age\"", users.order(email).order(age)) + assertSQL("SELECT * FROM \"users\" ORDER BY \"age\"", users.order(email).order(age)) } func test_reverse_withoutOrder_ordersByRowIdDescending() { @@ -187,25 +187,25 @@ class QueryTests : XCTestCase { } func test_limit_compilesLimitClause() { - AssertSQL("SELECT * FROM \"users\" LIMIT 5", users.limit(5)) + assertSQL("SELECT * FROM \"users\" LIMIT 5", users.limit(5)) } func test_limit_withOffset_compilesOffsetClause() { - AssertSQL("SELECT * FROM \"users\" LIMIT 5 OFFSET 5", users.limit(5, offset: 5)) + assertSQL("SELECT * FROM \"users\" LIMIT 5 OFFSET 5", users.limit(5, offset: 5)) } func test_limit_whenChained_overridesLimit() { let query = users.limit(5) - AssertSQL("SELECT * FROM \"users\" LIMIT 10", query.limit(10)) - AssertSQL("SELECT * FROM \"users\"", query.limit(nil)) + assertSQL("SELECT * FROM \"users\" LIMIT 10", query.limit(10)) + assertSQL("SELECT * FROM \"users\"", query.limit(nil)) } func test_limit_whenChained_withOffset_overridesOffset() { let query = users.limit(5, offset: 5) - AssertSQL("SELECT * FROM \"users\" LIMIT 10 OFFSET 20", query.limit(10, offset: 20)) - AssertSQL("SELECT * FROM \"users\"", query.limit(nil)) + assertSQL("SELECT * FROM \"users\" LIMIT 10 OFFSET 20", query.limit(10, offset: 20)) + assertSQL("SELECT * FROM \"users\"", query.limit(nil)) } func test_alias_aliasesTable() { @@ -213,7 +213,7 @@ class QueryTests : XCTestCase { let managers = users.alias("managers") - AssertSQL( + assertSQL( "SELECT * FROM \"users\" " + "INNER JOIN \"users\" AS \"managers\" ON (\"managers\".\"id\" = \"users\".\"manager_id\")", users.join(managers, on: managers[id] == users[managerId]) @@ -221,78 +221,99 @@ class QueryTests : XCTestCase { } func test_insert_compilesInsertExpression() { - AssertSQL( + assertSQL( "INSERT INTO \"users\" (\"email\", \"age\") VALUES ('alice@example.com', 30)", users.insert(email <- "alice@example.com", age <- 30) ) } func test_insert_withOnConflict_compilesInsertOrOnConflictExpression() { - AssertSQL( + assertSQL( "INSERT OR REPLACE INTO \"users\" (\"email\", \"age\") VALUES ('alice@example.com', 30)", users.insert(or: .replace, email <- "alice@example.com", age <- 30) ) } func test_insert_compilesInsertExpressionWithDefaultValues() { - AssertSQL("INSERT INTO \"users\" DEFAULT VALUES", users.insert()) + assertSQL("INSERT INTO \"users\" DEFAULT VALUES", users.insert()) } func test_insert_withQuery_compilesInsertExpressionWithSelectStatement() { let emails = Table("emails") - AssertSQL( + assertSQL( "INSERT INTO \"emails\" SELECT \"email\" FROM \"users\" WHERE \"admin\"", emails.insert(users.select(email).filter(admin)) ) } func test_insert_many_compilesInsertManyExpression() { - AssertSQL( - "INSERT INTO \"users\" (\"email\", \"age\") VALUES ('alice@example.com', 30), ('geoff@example.com', 32), ('alex@example.com', 83)", - users.insertMany([[email <- "alice@example.com", age <- 30], [email <- "geoff@example.com", age <- 32], [email <- "alex@example.com", age <- 83]]) + assertSQL( + """ + INSERT INTO \"users\" (\"email\", \"age\") VALUES ('alice@example.com', 30), ('geoff@example.com', 32), + ('alex@example.com', 83) + """.replacingOccurrences(of: "\n", with: ""), + users.insertMany([[email <- "alice@example.com", age <- 30], + [email <- "geoff@example.com", age <- 32], [email <- "alex@example.com", age <- 83]]) ) } func test_insert_many_compilesInsertManyNoneExpression() { - AssertSQL( + assertSQL( "INSERT INTO \"users\" DEFAULT VALUES", users.insertMany([]) ) } func test_insert_many_withOnConflict_compilesInsertManyOrOnConflictExpression() { - AssertSQL( - "INSERT OR REPLACE INTO \"users\" (\"email\", \"age\") VALUES ('alice@example.com', 30), ('geoff@example.com', 32), ('alex@example.com', 83)", - users.insertMany(or: .replace, [[email <- "alice@example.com", age <- 30], [email <- "geoff@example.com", age <- 32], [email <- "alex@example.com", age <- 83]]) + assertSQL( + """ + INSERT OR REPLACE INTO \"users\" (\"email\", \"age\") VALUES ('alice@example.com', 30), + ('geoff@example.com', 32), ('alex@example.com', 83) + """.replacingOccurrences(of: "\n", with: ""), + users.insertMany(or: .replace, [[email <- "alice@example.com", age <- 30], + [email <- "geoff@example.com", age <- 32], + [email <- "alex@example.com", age <- 83]]) ) } func test_insert_encodable() throws { let emails = Table("emails") - let value = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4, date: Date(timeIntervalSince1970: 0), optional: nil, sub: nil) + let value = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4, + date: Date(timeIntervalSince1970: 0), optional: nil, sub: nil) let insert = try emails.insert(value) - AssertSQL( - "INSERT INTO \"emails\" (\"int\", \"string\", \"bool\", \"float\", \"double\", \"date\") VALUES (1, '2', 1, 3.0, 4.0, '1970-01-01T00:00:00.000')", + assertSQL( + """ + INSERT INTO \"emails\" (\"int\", \"string\", \"bool\", \"float\", \"double\", \"date\") + VALUES (1, '2', 1, 3.0, 4.0, '1970-01-01T00:00:00.000') + """.replacingOccurrences(of: "\n", with: ""), insert ) } func test_insert_encodable_with_nested_encodable() throws { let emails = Table("emails") - let value1 = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4, date: Date(timeIntervalSince1970: 0), optional: nil, sub: nil) - let value = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4, date: Date(timeIntervalSince1970: 0), optional: "optional", sub: value1) + let value1 = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4, + date: Date(timeIntervalSince1970: 0), optional: nil, sub: nil) + let value = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4, + date: Date(timeIntervalSince1970: 0), optional: "optional", sub: value1) let insert = try emails.insert(value) let encodedJSON = try JSONEncoder().encode(value1) let encodedJSONString = String(data: encodedJSON, encoding: .utf8)! - AssertSQL( - "INSERT INTO \"emails\" (\"int\", \"string\", \"bool\", \"float\", \"double\", \"date\", \"optional\", \"sub\") VALUES (1, '2', 1, 3.0, 4.0, '1970-01-01T00:00:00.000', 'optional', '\(encodedJSONString)')", + assertSQL( + """ + INSERT INTO \"emails\" (\"int\", \"string\", \"bool\", \"float\", \"double\", \"date\", \"optional\", + \"sub\") VALUES (1, '2', 1, 3.0, 4.0, '1970-01-01T00:00:00.000', 'optional', '\(encodedJSONString)') + """.replacingOccurrences(of: "\n", with: ""), insert ) } func test_upsert_withOnConflict_compilesInsertOrOnConflictExpression() { - AssertSQL( - "INSERT INTO \"users\" (\"email\", \"age\") VALUES ('alice@example.com', 30) ON CONFLICT (\"email\") DO UPDATE SET \"age\" = \"excluded\".\"age\"", + assertSQL( + """ + INSERT INTO \"users\" (\"email\", \"age\") VALUES ('alice@example.com', 30) ON CONFLICT (\"email\") + DO UPDATE SET \"age\" = \"excluded\".\"age\" + """.replacingOccurrences(of: "\n", with: ""), users.upsert(email <- "alice@example.com", age <- 30, onConflictOf: email) ) } @@ -300,35 +321,48 @@ class QueryTests : XCTestCase { func test_upsert_encodable() throws { let emails = Table("emails") let string = Expression("string") - let value = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4, date: Date(timeIntervalSince1970: 0), optional: nil, sub: nil) + let value = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4, + date: Date(timeIntervalSince1970: 0), optional: nil, sub: nil) let insert = try emails.upsert(value, onConflictOf: string) - AssertSQL( - "INSERT INTO \"emails\" (\"int\", \"string\", \"bool\", \"float\", \"double\", \"date\") VALUES (1, '2', 1, 3.0, 4.0, '1970-01-01T00:00:00.000') ON CONFLICT (\"string\") DO UPDATE SET \"int\" = \"excluded\".\"int\", \"bool\" = \"excluded\".\"bool\", \"float\" = \"excluded\".\"float\", \"double\" = \"excluded\".\"double\", \"date\" = \"excluded\".\"date\"", + assertSQL( + """ + INSERT INTO \"emails\" (\"int\", \"string\", \"bool\", \"float\", \"double\", \"date\") + VALUES (1, '2', 1, 3.0, 4.0, '1970-01-01T00:00:00.000') ON CONFLICT (\"string\") + DO UPDATE SET \"int\" = \"excluded\".\"int\", \"bool\" = \"excluded\".\"bool\", + \"float\" = \"excluded\".\"float\", \"double\" = \"excluded\".\"double\", \"date\" = \"excluded\".\"date\" + """.replacingOccurrences(of: "\n", with: ""), insert ) } func test_insert_many_encodable() throws { let emails = Table("emails") - let value1 = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4, date: Date(timeIntervalSince1970: 0), optional: nil, sub: nil) - let value2 = TestCodable(int: 2, string: "3", bool: true, float: 3, double: 5, date: Date(timeIntervalSince1970: 0), optional: nil, sub: nil) - let value3 = TestCodable(int: 3, string: "4", bool: true, float: 3, double: 6, date: Date(timeIntervalSince1970: 0), optional: nil, sub: nil) + let value1 = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4, + date: Date(timeIntervalSince1970: 0), optional: nil, sub: nil) + let value2 = TestCodable(int: 2, string: "3", bool: true, float: 3, double: 5, + date: Date(timeIntervalSince1970: 0), optional: nil, sub: nil) + let value3 = TestCodable(int: 3, string: "4", bool: true, float: 3, double: 6, + date: Date(timeIntervalSince1970: 0), optional: nil, sub: nil) let insert = try emails.insertMany([value1, value2, value3]) - AssertSQL( - "INSERT INTO \"emails\" (\"int\", \"string\", \"bool\", \"float\", \"double\", \"date\") VALUES (1, '2', 1, 3.0, 4.0, '1970-01-01T00:00:00.000'), (2, '3', 1, 3.0, 5.0, '1970-01-01T00:00:00.000'), (3, '4', 1, 3.0, 6.0, '1970-01-01T00:00:00.000')", + assertSQL( + """ + INSERT INTO \"emails\" (\"int\", \"string\", \"bool\", \"float\", \"double\", \"date\") + VALUES (1, '2', 1, 3.0, 4.0, '1970-01-01T00:00:00.000'), (2, '3', 1, 3.0, 5.0, '1970-01-01T00:00:00.000'), + (3, '4', 1, 3.0, 6.0, '1970-01-01T00:00:00.000') + """.replacingOccurrences(of: "\n", with: ""), insert ) } func test_update_compilesUpdateExpression() { - AssertSQL( + assertSQL( "UPDATE \"users\" SET \"age\" = 30, \"admin\" = 1 WHERE (\"id\" = 1)", users.filter(id == 1).update(age <- 30, admin <- true) ) } func test_update_compilesUpdateLimitOrderExpression() { - AssertSQL( + assertSQL( "UPDATE \"users\" SET \"age\" = 30 ORDER BY \"id\" LIMIT 1", users.order(id).limit(1).update(age <- 30) ) @@ -336,95 +370,104 @@ class QueryTests : XCTestCase { func test_update_encodable() throws { let emails = Table("emails") - let value = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4, date: Date(timeIntervalSince1970: 0), optional: nil, sub: nil) + let value = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4, + date: Date(timeIntervalSince1970: 0), optional: nil, sub: nil) let update = try emails.update(value) - AssertSQL( - "UPDATE \"emails\" SET \"int\" = 1, \"string\" = '2', \"bool\" = 1, \"float\" = 3.0, \"double\" = 4.0, \"date\" = '1970-01-01T00:00:00.000'", + assertSQL( + """ + UPDATE \"emails\" SET \"int\" = 1, \"string\" = '2', \"bool\" = 1, \"float\" = 3.0, \"double\" = 4.0, + \"date\" = '1970-01-01T00:00:00.000' + """.replacingOccurrences(of: "\n", with: ""), update ) } func test_update_encodable_with_nested_encodable() throws { let emails = Table("emails") - let value1 = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4, date: Date(timeIntervalSince1970: 0), optional: nil, sub: nil) - let value = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4, date: Date(timeIntervalSince1970: 0), optional: nil, sub: value1) + let value1 = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4, + date: Date(timeIntervalSince1970: 0), optional: nil, sub: nil) + let value = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4, + date: Date(timeIntervalSince1970: 0), optional: nil, sub: value1) let update = try emails.update(value) let encodedJSON = try JSONEncoder().encode(value1) let encodedJSONString = String(data: encodedJSON, encoding: .utf8)! - AssertSQL( - "UPDATE \"emails\" SET \"int\" = 1, \"string\" = '2', \"bool\" = 1, \"float\" = 3.0, \"double\" = 4.0, \"date\" = '1970-01-01T00:00:00.000', \"sub\" = '\(encodedJSONString)'", + assertSQL( + """ + UPDATE \"emails\" SET \"int\" = 1, \"string\" = '2', \"bool\" = 1, \"float\" = 3.0, \"double\" = 4.0, + \"date\" = '1970-01-01T00:00:00.000', \"sub\" = '\(encodedJSONString)' + """.replacingOccurrences(of: "\n", with: ""), update ) } func test_delete_compilesDeleteExpression() { - AssertSQL( + assertSQL( "DELETE FROM \"users\" WHERE (\"id\" = 1)", users.filter(id == 1).delete() ) } func test_delete_compilesDeleteLimitOrderExpression() { - AssertSQL( + assertSQL( "DELETE FROM \"users\" ORDER BY \"id\" LIMIT 1", users.order(id).limit(1).delete() ) } func test_delete_compilesExistsExpression() { - AssertSQL( + assertSQL( "SELECT EXISTS (SELECT * FROM \"users\")", users.exists ) } func test_count_returnsCountExpression() { - AssertSQL("SELECT count(*) FROM \"users\"", users.count) + assertSQL("SELECT count(*) FROM \"users\"", users.count) } func test_scalar_returnsScalarExpression() { - AssertSQL("SELECT \"int\" FROM \"table\"", table.select(int) as ScalarQuery) - AssertSQL("SELECT \"intOptional\" FROM \"table\"", table.select(intOptional) as ScalarQuery) - AssertSQL("SELECT DISTINCT \"int\" FROM \"table\"", table.select(distinct: int) as ScalarQuery) - AssertSQL("SELECT DISTINCT \"intOptional\" FROM \"table\"", table.select(distinct: intOptional) as ScalarQuery) + assertSQL("SELECT \"int\" FROM \"table\"", table.select(int) as ScalarQuery) + assertSQL("SELECT \"intOptional\" FROM \"table\"", table.select(intOptional) as ScalarQuery) + assertSQL("SELECT DISTINCT \"int\" FROM \"table\"", table.select(distinct: int) as ScalarQuery) + assertSQL("SELECT DISTINCT \"intOptional\" FROM \"table\"", table.select(distinct: intOptional) as ScalarQuery) } func test_subscript_withExpression_returnsNamespacedExpression() { let query = Table("query") - AssertSQL("\"query\".\"blob\"", query[data]) - AssertSQL("\"query\".\"blobOptional\"", query[dataOptional]) + assertSQL("\"query\".\"blob\"", query[data]) + assertSQL("\"query\".\"blobOptional\"", query[dataOptional]) - AssertSQL("\"query\".\"bool\"", query[bool]) - AssertSQL("\"query\".\"boolOptional\"", query[boolOptional]) + assertSQL("\"query\".\"bool\"", query[bool]) + assertSQL("\"query\".\"boolOptional\"", query[boolOptional]) - AssertSQL("\"query\".\"date\"", query[date]) - AssertSQL("\"query\".\"dateOptional\"", query[dateOptional]) + assertSQL("\"query\".\"date\"", query[date]) + assertSQL("\"query\".\"dateOptional\"", query[dateOptional]) - AssertSQL("\"query\".\"double\"", query[double]) - AssertSQL("\"query\".\"doubleOptional\"", query[doubleOptional]) + assertSQL("\"query\".\"double\"", query[double]) + assertSQL("\"query\".\"doubleOptional\"", query[doubleOptional]) - AssertSQL("\"query\".\"int\"", query[int]) - AssertSQL("\"query\".\"intOptional\"", query[intOptional]) + assertSQL("\"query\".\"int\"", query[int]) + assertSQL("\"query\".\"intOptional\"", query[intOptional]) - AssertSQL("\"query\".\"int64\"", query[int64]) - AssertSQL("\"query\".\"int64Optional\"", query[int64Optional]) + assertSQL("\"query\".\"int64\"", query[int64]) + assertSQL("\"query\".\"int64Optional\"", query[int64Optional]) - AssertSQL("\"query\".\"string\"", query[string]) - AssertSQL("\"query\".\"stringOptional\"", query[stringOptional]) + assertSQL("\"query\".\"string\"", query[string]) + assertSQL("\"query\".\"stringOptional\"", query[stringOptional]) - AssertSQL("\"query\".*", query[*]) + assertSQL("\"query\".*", query[*]) } func test_tableNamespacedByDatabase() { let table = Table("table", database: "attached") - AssertSQL("SELECT * FROM \"attached\".\"table\"", table) + assertSQL("SELECT * FROM \"attached\".\"table\"", table) } } -class QueryIntegrationTests : SQLiteTestCase { +class QueryIntegrationTests: SQLiteTestCase { let id = Expression("id") let email = Expression("email") @@ -433,7 +476,7 @@ class QueryIntegrationTests : SQLiteTestCase { override func setUp() { super.setUp() - CreateUsersTable() + createUsersTable() } // MARK: - @@ -452,7 +495,7 @@ class QueryIntegrationTests : SQLiteTestCase { func test_prepareRowIterator() { let names = ["a", "b", "c"] - try! InsertUsers(names) + try! insertUsers(names) let emailColumn = Expression("email") let emails = try! db.prepareRowIterator(users).map { $0[emailColumn] } @@ -462,7 +505,7 @@ class QueryIntegrationTests : SQLiteTestCase { func test_ambiguousMap() { let names = ["a", "b", "c"] - try! InsertUsers(names) + try! insertUsers(names) let emails = try! db.prepare("select email from users", []).map { $0[0] as! String } @@ -494,8 +537,10 @@ class QueryIntegrationTests : SQLiteTestCase { builder.column(Expression("sub")) }) - let value1 = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4, date: Date(timeIntervalSince1970: 0), optional: nil, sub: nil) - let value = TestCodable(int: 5, string: "6", bool: true, float: 7, double: 8, date: Date(timeIntervalSince1970: 5000), optional: "optional", sub: value1) + let value1 = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4, + date: Date(timeIntervalSince1970: 0), optional: nil, sub: nil) + let value = TestCodable(int: 5, string: "6", bool: true, float: 7, double: 8, + date: Date(timeIntervalSince1970: 5000), optional: "optional", sub: value1) try db.run(table.insert(value)) @@ -523,7 +568,7 @@ class QueryIntegrationTests : SQLiteTestCase { XCTAssertEqual(0, try! db.scalar(users.count)) XCTAssertEqual(false, try! db.scalar(users.exists)) - try! InsertUsers("alice") + try! insertUsers("alice") XCTAssertEqual(1, try! db.scalar(users.select(id.average))) } @@ -590,7 +635,7 @@ class QueryIntegrationTests : SQLiteTestCase { func test_no_such_column() throws { let doesNotExist = Expression("doesNotExist") - try! InsertUser("alice") + try! insertUser("alice") let row = try! db.pluck(users.filter(email == "alice@example.com"))! XCTAssertThrowsError(try row.get(doesNotExist)) { error in diff --git a/Tests/SQLiteTests/RTreeTests.swift b/Tests/SQLiteTests/RTreeTests.swift index 7147533e..5525da26 100644 --- a/Tests/SQLiteTests/RTreeTests.swift +++ b/Tests/SQLiteTests/RTreeTests.swift @@ -1,7 +1,7 @@ import XCTest import SQLite -class RTreeTests : XCTestCase { +class RTreeTests: XCTestCase { func test_create_onVirtualTable_withRTree_createVirtualTableExpression() { XCTAssertEqual( @@ -14,4 +14,4 @@ class RTreeTests : XCTestCase { ) } -} \ No newline at end of file +} diff --git a/Tests/SQLiteTests/RowTests.swift b/Tests/SQLiteTests/RowTests.swift index 17873e71..36721f80 100644 --- a/Tests/SQLiteTests/RowTests.swift +++ b/Tests/SQLiteTests/RowTests.swift @@ -1,7 +1,7 @@ import XCTest @testable import SQLite -class RowTests : XCTestCase { +class RowTests: XCTestCase { public func test_get_value() { let row = Row(["\"foo\"": 0], ["value"]) diff --git a/Tests/SQLiteTests/SchemaTests.swift b/Tests/SQLiteTests/SchemaTests.swift index 30646b98..495a5e51 100644 --- a/Tests/SQLiteTests/SchemaTests.swift +++ b/Tests/SQLiteTests/SchemaTests.swift @@ -1,7 +1,7 @@ import XCTest import SQLite -class SchemaTests : XCTestCase { +class SchemaTests: XCTestCase { func test_drop_compilesDropTableExpression() { XCTAssertEqual("DROP TABLE \"table\"", table.drop()) @@ -330,7 +330,10 @@ class SchemaTests : XCTestCase { table.create { t in t.column(int64, unique: true, check: int64 > 0, references: table, int64) } ) XCTAssertEqual( - "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\"))", + """ + CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0) REFERENCES + \"table\" (\"int64\")) + """.replacingOccurrences(of: "\n", with: ""), table.create { t in t.column(int64, unique: true, check: int64Optional > 0, references: table, int64) } ) @@ -487,48 +490,95 @@ class SchemaTests : XCTestCase { table.create { t in t.column(stringOptional, unique: true, check: string != "", defaultValue: string, collate: .rtrim) } ) XCTAssertEqual( - "CREATE TABLE \"table\" (\"stringOptional\" TEXT UNIQUE CHECK (\"string\" != '') DEFAULT (\"stringOptional\") COLLATE RTRIM)", - table.create { t in t.column(stringOptional, unique: true, check: string != "", defaultValue: stringOptional, collate: .rtrim) } + """ + CREATE TABLE \"table\" (\"stringOptional\" TEXT UNIQUE CHECK (\"string\" != '') + DEFAULT (\"stringOptional\") COLLATE RTRIM) + """.replacingOccurrences(of: "\n", with: ""), + table.create { t in t.column(stringOptional, + unique: true, + check: string != "", + defaultValue: stringOptional, + collate: .rtrim) } ) XCTAssertEqual( - "CREATE TABLE \"table\" (\"stringOptional\" TEXT UNIQUE CHECK (\"stringOptional\" != '') DEFAULT (\"string\") COLLATE RTRIM)", - table.create { t in t.column(stringOptional, unique: true, check: stringOptional != "", defaultValue: string, collate: .rtrim) } + """ + CREATE TABLE \"table\" (\"stringOptional\" TEXT UNIQUE CHECK (\"stringOptional\" != '') + DEFAULT (\"string\") COLLATE RTRIM) + """.replacingOccurrences(of: "\n", with: ""), + table.create { t in t.column(stringOptional, unique: true, check: stringOptional != "", + defaultValue: string, collate: .rtrim) } ) XCTAssertEqual( - "CREATE TABLE \"table\" (\"stringOptional\" TEXT UNIQUE CHECK (\"stringOptional\" != '') DEFAULT (\"stringOptional\") COLLATE RTRIM)", - table.create { t in t.column(stringOptional, unique: true, check: stringOptional != "", defaultValue: stringOptional, collate: .rtrim) } + """ + CREATE TABLE \"table\" (\"stringOptional\" TEXT UNIQUE CHECK (\"stringOptional\" != '') + DEFAULT (\"stringOptional\") COLLATE RTRIM) + """.replacingOccurrences(of: "\n", with: ""), + table.create { t in t.column(stringOptional, unique: true, check: stringOptional != "", + defaultValue: stringOptional, collate: .rtrim) } ) XCTAssertEqual( - "CREATE TABLE \"table\" (\"stringOptional\" TEXT UNIQUE CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM)", - table.create { t in t.column(stringOptional, unique: true, check: string != "", defaultValue: "string", collate: .rtrim) } + """ + CREATE TABLE \"table\" (\"stringOptional\" TEXT UNIQUE CHECK (\"string\" != '') + DEFAULT ('string') COLLATE RTRIM) + """.replacingOccurrences(of: "\n", with: ""), + table.create { t in t.column(stringOptional, unique: true, check: string != "", + defaultValue: "string", collate: .rtrim) } ) XCTAssertEqual( - "CREATE TABLE \"table\" (\"stringOptional\" TEXT UNIQUE CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM)", - table.create { t in t.column(stringOptional, unique: true, check: stringOptional != "", defaultValue: "string", collate: .rtrim) } + """ + CREATE TABLE \"table\" (\"stringOptional\" TEXT UNIQUE CHECK (\"stringOptional\" != '') + DEFAULT ('string') COLLATE RTRIM) + """.replacingOccurrences(of: "\n", with: ""), + table.create { t in t.column(stringOptional, unique: true, check: stringOptional != "", + defaultValue: "string", collate: .rtrim) } ) XCTAssertEqual( - "CREATE TABLE \"table\" (\"stringOptional\" TEXT CHECK (\"string\" != '') DEFAULT (\"string\") COLLATE RTRIM)", - table.create { t in t.column(stringOptional, check: string != "", defaultValue: string, collate: .rtrim) } + """ + CREATE TABLE \"table\" (\"stringOptional\" TEXT CHECK (\"string\" != '') + DEFAULT (\"string\") COLLATE RTRIM) + """.replacingOccurrences(of: "\n", with: ""), + table.create { t in t.column(stringOptional, check: string != "", + defaultValue: string, collate: .rtrim) } ) XCTAssertEqual( - "CREATE TABLE \"table\" (\"stringOptional\" TEXT CHECK (\"stringOptional\" != '') DEFAULT (\"string\") COLLATE RTRIM)", - table.create { t in t.column(stringOptional, check: stringOptional != "", defaultValue: string, collate: .rtrim) } + """ + CREATE TABLE \"table\" (\"stringOptional\" TEXT CHECK (\"stringOptional\" != '') + DEFAULT (\"string\") COLLATE RTRIM) + """.replacingOccurrences(of: "\n", with: ""), + table.create { t in t.column(stringOptional, check: stringOptional != "", + defaultValue: string, collate: .rtrim) } ) XCTAssertEqual( - "CREATE TABLE \"table\" (\"stringOptional\" TEXT CHECK (\"string\" != '') DEFAULT (\"stringOptional\") COLLATE RTRIM)", - table.create { t in t.column(stringOptional, check: string != "", defaultValue: stringOptional, collate: .rtrim) } + """ + CREATE TABLE \"table\" (\"stringOptional\" TEXT CHECK (\"string\" != '') + DEFAULT (\"stringOptional\") COLLATE RTRIM) + """.replacingOccurrences(of: "\n", with: ""), + table.create { t in t.column(stringOptional, check: string != "", + defaultValue: stringOptional, collate: .rtrim) } ) XCTAssertEqual( - "CREATE TABLE \"table\" (\"stringOptional\" TEXT CHECK (\"stringOptional\" != '') DEFAULT (\"stringOptional\") COLLATE RTRIM)", - table.create { t in t.column(stringOptional, check: stringOptional != "", defaultValue: stringOptional, collate: .rtrim) } + """ + CREATE TABLE \"table\" (\"stringOptional\" TEXT CHECK (\"stringOptional\" != '') + DEFAULT (\"stringOptional\") COLLATE RTRIM) + """.replacingOccurrences(of: "\n", with: ""), + table.create { t in t.column(stringOptional, check: stringOptional != "", + defaultValue: stringOptional, collate: .rtrim) } ) XCTAssertEqual( - "CREATE TABLE \"table\" (\"stringOptional\" TEXT CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM)", - table.create { t in t.column(stringOptional, check: string != "", defaultValue: "string", collate: .rtrim) } + """ + CREATE TABLE \"table\" (\"stringOptional\" TEXT CHECK (\"string\" != '') + DEFAULT ('string') COLLATE RTRIM) + """.replacingOccurrences(of: "\n", with: ""), + table.create { t in t.column(stringOptional, check: string != "", + defaultValue: "string", collate: .rtrim) } ) XCTAssertEqual( - "CREATE TABLE \"table\" (\"stringOptional\" TEXT CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM)", - table.create { t in t.column(stringOptional, check: stringOptional != "", defaultValue: "string", collate: .rtrim) } + """ + CREATE TABLE \"table\" (\"stringOptional\" TEXT CHECK (\"stringOptional\" != '') + DEFAULT ('string') COLLATE RTRIM) + """.replacingOccurrences(of: "\n", with: ""), + table.create { t in t.column(stringOptional, check: stringOptional != "", + defaultValue: "string", collate: .rtrim) } ) } diff --git a/Tests/SQLiteTests/SelectTests.swift b/Tests/SQLiteTests/SelectTests.swift index bca01092..c66d401d 100644 --- a/Tests/SQLiteTests/SelectTests.swift +++ b/Tests/SQLiteTests/SelectTests.swift @@ -2,14 +2,14 @@ import XCTest @testable import SQLite class SelectTests: SQLiteTestCase { - + override func setUp() { super.setUp() - CreateUsersTable() - CreateUsersDataTable() + createUsersTable() + createUsersDataTable() } - - func CreateUsersDataTable() { + + func createUsersDataTable() { try! db.execute(""" CREATE TABLE users_name ( id INTEGER, @@ -19,27 +19,26 @@ class SelectTests: SQLiteTestCase { """ ) } - + func test_select_columns_from_multiple_tables() { let usersData = Table("users_name") let users = Table("users") - + let name = Expression("name") let id = Expression("id") let userID = Expression("user_id") let email = Expression("email") - - try! InsertUser("Joey") + + try! insertUser("Joey") try! db.run(usersData.insert( id <- 1, userID <- 1, name <- "Joey" )) - + try! db.prepare(users.select(name, email).join(usersData, on: userID == users[id])).forEach { XCTAssertEqual($0[name], "Joey") XCTAssertEqual($0[email], "Joey@example.com") } } - } diff --git a/Tests/SQLiteTests/SetterTests.swift b/Tests/SQLiteTests/SetterTests.swift index d4f189d7..938dd013 100644 --- a/Tests/SQLiteTests/SetterTests.swift +++ b/Tests/SQLiteTests/SetterTests.swift @@ -1,137 +1,137 @@ import XCTest import SQLite -class SetterTests : XCTestCase { +class SetterTests: XCTestCase { func test_setterAssignmentOperator_buildsSetter() { - AssertSQL("\"int\" = \"int\"", int <- int) - AssertSQL("\"int\" = 1", int <- 1) - AssertSQL("\"intOptional\" = \"int\"", intOptional <- int) - AssertSQL("\"intOptional\" = \"intOptional\"", intOptional <- intOptional) - AssertSQL("\"intOptional\" = 1", intOptional <- 1) - AssertSQL("\"intOptional\" = NULL", intOptional <- nil) + assertSQL("\"int\" = \"int\"", int <- int) + assertSQL("\"int\" = 1", int <- 1) + assertSQL("\"intOptional\" = \"int\"", intOptional <- int) + assertSQL("\"intOptional\" = \"intOptional\"", intOptional <- intOptional) + assertSQL("\"intOptional\" = 1", intOptional <- 1) + assertSQL("\"intOptional\" = NULL", intOptional <- nil) } func test_plusEquals_withStringExpression_buildsSetter() { - AssertSQL("\"string\" = (\"string\" || \"string\")", string += string) - AssertSQL("\"string\" = (\"string\" || 'literal')", string += "literal") - AssertSQL("\"stringOptional\" = (\"stringOptional\" || \"string\")", stringOptional += string) - AssertSQL("\"stringOptional\" = (\"stringOptional\" || \"stringOptional\")", stringOptional += stringOptional) - AssertSQL("\"stringOptional\" = (\"stringOptional\" || 'literal')", stringOptional += "literal") + assertSQL("\"string\" = (\"string\" || \"string\")", string += string) + assertSQL("\"string\" = (\"string\" || 'literal')", string += "literal") + assertSQL("\"stringOptional\" = (\"stringOptional\" || \"string\")", stringOptional += string) + assertSQL("\"stringOptional\" = (\"stringOptional\" || \"stringOptional\")", stringOptional += stringOptional) + assertSQL("\"stringOptional\" = (\"stringOptional\" || 'literal')", stringOptional += "literal") } func test_plusEquals_withNumberExpression_buildsSetter() { - AssertSQL("\"int\" = (\"int\" + \"int\")", int += int) - AssertSQL("\"int\" = (\"int\" + 1)", int += 1) - AssertSQL("\"intOptional\" = (\"intOptional\" + \"int\")", intOptional += int) - AssertSQL("\"intOptional\" = (\"intOptional\" + \"intOptional\")", intOptional += intOptional) - AssertSQL("\"intOptional\" = (\"intOptional\" + 1)", intOptional += 1) - - AssertSQL("\"double\" = (\"double\" + \"double\")", double += double) - AssertSQL("\"double\" = (\"double\" + 1.0)", double += 1) - AssertSQL("\"doubleOptional\" = (\"doubleOptional\" + \"double\")", doubleOptional += double) - AssertSQL("\"doubleOptional\" = (\"doubleOptional\" + \"doubleOptional\")", doubleOptional += doubleOptional) - AssertSQL("\"doubleOptional\" = (\"doubleOptional\" + 1.0)", doubleOptional += 1) + assertSQL("\"int\" = (\"int\" + \"int\")", int += int) + assertSQL("\"int\" = (\"int\" + 1)", int += 1) + assertSQL("\"intOptional\" = (\"intOptional\" + \"int\")", intOptional += int) + assertSQL("\"intOptional\" = (\"intOptional\" + \"intOptional\")", intOptional += intOptional) + assertSQL("\"intOptional\" = (\"intOptional\" + 1)", intOptional += 1) + + assertSQL("\"double\" = (\"double\" + \"double\")", double += double) + assertSQL("\"double\" = (\"double\" + 1.0)", double += 1) + assertSQL("\"doubleOptional\" = (\"doubleOptional\" + \"double\")", doubleOptional += double) + assertSQL("\"doubleOptional\" = (\"doubleOptional\" + \"doubleOptional\")", doubleOptional += doubleOptional) + assertSQL("\"doubleOptional\" = (\"doubleOptional\" + 1.0)", doubleOptional += 1) } func test_minusEquals_withNumberExpression_buildsSetter() { - AssertSQL("\"int\" = (\"int\" - \"int\")", int -= int) - AssertSQL("\"int\" = (\"int\" - 1)", int -= 1) - AssertSQL("\"intOptional\" = (\"intOptional\" - \"int\")", intOptional -= int) - AssertSQL("\"intOptional\" = (\"intOptional\" - \"intOptional\")", intOptional -= intOptional) - AssertSQL("\"intOptional\" = (\"intOptional\" - 1)", intOptional -= 1) - - AssertSQL("\"double\" = (\"double\" - \"double\")", double -= double) - AssertSQL("\"double\" = (\"double\" - 1.0)", double -= 1) - AssertSQL("\"doubleOptional\" = (\"doubleOptional\" - \"double\")", doubleOptional -= double) - AssertSQL("\"doubleOptional\" = (\"doubleOptional\" - \"doubleOptional\")", doubleOptional -= doubleOptional) - AssertSQL("\"doubleOptional\" = (\"doubleOptional\" - 1.0)", doubleOptional -= 1) + assertSQL("\"int\" = (\"int\" - \"int\")", int -= int) + assertSQL("\"int\" = (\"int\" - 1)", int -= 1) + assertSQL("\"intOptional\" = (\"intOptional\" - \"int\")", intOptional -= int) + assertSQL("\"intOptional\" = (\"intOptional\" - \"intOptional\")", intOptional -= intOptional) + assertSQL("\"intOptional\" = (\"intOptional\" - 1)", intOptional -= 1) + + assertSQL("\"double\" = (\"double\" - \"double\")", double -= double) + assertSQL("\"double\" = (\"double\" - 1.0)", double -= 1) + assertSQL("\"doubleOptional\" = (\"doubleOptional\" - \"double\")", doubleOptional -= double) + assertSQL("\"doubleOptional\" = (\"doubleOptional\" - \"doubleOptional\")", doubleOptional -= doubleOptional) + assertSQL("\"doubleOptional\" = (\"doubleOptional\" - 1.0)", doubleOptional -= 1) } func test_timesEquals_withNumberExpression_buildsSetter() { - AssertSQL("\"int\" = (\"int\" * \"int\")", int *= int) - AssertSQL("\"int\" = (\"int\" * 1)", int *= 1) - AssertSQL("\"intOptional\" = (\"intOptional\" * \"int\")", intOptional *= int) - AssertSQL("\"intOptional\" = (\"intOptional\" * \"intOptional\")", intOptional *= intOptional) - AssertSQL("\"intOptional\" = (\"intOptional\" * 1)", intOptional *= 1) - - AssertSQL("\"double\" = (\"double\" * \"double\")", double *= double) - AssertSQL("\"double\" = (\"double\" * 1.0)", double *= 1) - AssertSQL("\"doubleOptional\" = (\"doubleOptional\" * \"double\")", doubleOptional *= double) - AssertSQL("\"doubleOptional\" = (\"doubleOptional\" * \"doubleOptional\")", doubleOptional *= doubleOptional) - AssertSQL("\"doubleOptional\" = (\"doubleOptional\" * 1.0)", doubleOptional *= 1) + assertSQL("\"int\" = (\"int\" * \"int\")", int *= int) + assertSQL("\"int\" = (\"int\" * 1)", int *= 1) + assertSQL("\"intOptional\" = (\"intOptional\" * \"int\")", intOptional *= int) + assertSQL("\"intOptional\" = (\"intOptional\" * \"intOptional\")", intOptional *= intOptional) + assertSQL("\"intOptional\" = (\"intOptional\" * 1)", intOptional *= 1) + + assertSQL("\"double\" = (\"double\" * \"double\")", double *= double) + assertSQL("\"double\" = (\"double\" * 1.0)", double *= 1) + assertSQL("\"doubleOptional\" = (\"doubleOptional\" * \"double\")", doubleOptional *= double) + assertSQL("\"doubleOptional\" = (\"doubleOptional\" * \"doubleOptional\")", doubleOptional *= doubleOptional) + assertSQL("\"doubleOptional\" = (\"doubleOptional\" * 1.0)", doubleOptional *= 1) } func test_dividedByEquals_withNumberExpression_buildsSetter() { - AssertSQL("\"int\" = (\"int\" / \"int\")", int /= int) - AssertSQL("\"int\" = (\"int\" / 1)", int /= 1) - AssertSQL("\"intOptional\" = (\"intOptional\" / \"int\")", intOptional /= int) - AssertSQL("\"intOptional\" = (\"intOptional\" / \"intOptional\")", intOptional /= intOptional) - AssertSQL("\"intOptional\" = (\"intOptional\" / 1)", intOptional /= 1) - - AssertSQL("\"double\" = (\"double\" / \"double\")", double /= double) - AssertSQL("\"double\" = (\"double\" / 1.0)", double /= 1) - AssertSQL("\"doubleOptional\" = (\"doubleOptional\" / \"double\")", doubleOptional /= double) - AssertSQL("\"doubleOptional\" = (\"doubleOptional\" / \"doubleOptional\")", doubleOptional /= doubleOptional) - AssertSQL("\"doubleOptional\" = (\"doubleOptional\" / 1.0)", doubleOptional /= 1) + assertSQL("\"int\" = (\"int\" / \"int\")", int /= int) + assertSQL("\"int\" = (\"int\" / 1)", int /= 1) + assertSQL("\"intOptional\" = (\"intOptional\" / \"int\")", intOptional /= int) + assertSQL("\"intOptional\" = (\"intOptional\" / \"intOptional\")", intOptional /= intOptional) + assertSQL("\"intOptional\" = (\"intOptional\" / 1)", intOptional /= 1) + + assertSQL("\"double\" = (\"double\" / \"double\")", double /= double) + assertSQL("\"double\" = (\"double\" / 1.0)", double /= 1) + assertSQL("\"doubleOptional\" = (\"doubleOptional\" / \"double\")", doubleOptional /= double) + assertSQL("\"doubleOptional\" = (\"doubleOptional\" / \"doubleOptional\")", doubleOptional /= doubleOptional) + assertSQL("\"doubleOptional\" = (\"doubleOptional\" / 1.0)", doubleOptional /= 1) } func test_moduloEquals_withIntegerExpression_buildsSetter() { - AssertSQL("\"int\" = (\"int\" % \"int\")", int %= int) - AssertSQL("\"int\" = (\"int\" % 1)", int %= 1) - AssertSQL("\"intOptional\" = (\"intOptional\" % \"int\")", intOptional %= int) - AssertSQL("\"intOptional\" = (\"intOptional\" % \"intOptional\")", intOptional %= intOptional) - AssertSQL("\"intOptional\" = (\"intOptional\" % 1)", intOptional %= 1) + assertSQL("\"int\" = (\"int\" % \"int\")", int %= int) + assertSQL("\"int\" = (\"int\" % 1)", int %= 1) + assertSQL("\"intOptional\" = (\"intOptional\" % \"int\")", intOptional %= int) + assertSQL("\"intOptional\" = (\"intOptional\" % \"intOptional\")", intOptional %= intOptional) + assertSQL("\"intOptional\" = (\"intOptional\" % 1)", intOptional %= 1) } func test_leftShiftEquals_withIntegerExpression_buildsSetter() { - AssertSQL("\"int\" = (\"int\" << \"int\")", int <<= int) - AssertSQL("\"int\" = (\"int\" << 1)", int <<= 1) - AssertSQL("\"intOptional\" = (\"intOptional\" << \"int\")", intOptional <<= int) - AssertSQL("\"intOptional\" = (\"intOptional\" << \"intOptional\")", intOptional <<= intOptional) - AssertSQL("\"intOptional\" = (\"intOptional\" << 1)", intOptional <<= 1) + assertSQL("\"int\" = (\"int\" << \"int\")", int <<= int) + assertSQL("\"int\" = (\"int\" << 1)", int <<= 1) + assertSQL("\"intOptional\" = (\"intOptional\" << \"int\")", intOptional <<= int) + assertSQL("\"intOptional\" = (\"intOptional\" << \"intOptional\")", intOptional <<= intOptional) + assertSQL("\"intOptional\" = (\"intOptional\" << 1)", intOptional <<= 1) } func test_rightShiftEquals_withIntegerExpression_buildsSetter() { - AssertSQL("\"int\" = (\"int\" >> \"int\")", int >>= int) - AssertSQL("\"int\" = (\"int\" >> 1)", int >>= 1) - AssertSQL("\"intOptional\" = (\"intOptional\" >> \"int\")", intOptional >>= int) - AssertSQL("\"intOptional\" = (\"intOptional\" >> \"intOptional\")", intOptional >>= intOptional) - AssertSQL("\"intOptional\" = (\"intOptional\" >> 1)", intOptional >>= 1) + assertSQL("\"int\" = (\"int\" >> \"int\")", int >>= int) + assertSQL("\"int\" = (\"int\" >> 1)", int >>= 1) + assertSQL("\"intOptional\" = (\"intOptional\" >> \"int\")", intOptional >>= int) + assertSQL("\"intOptional\" = (\"intOptional\" >> \"intOptional\")", intOptional >>= intOptional) + assertSQL("\"intOptional\" = (\"intOptional\" >> 1)", intOptional >>= 1) } func test_bitwiseAndEquals_withIntegerExpression_buildsSetter() { - AssertSQL("\"int\" = (\"int\" & \"int\")", int &= int) - AssertSQL("\"int\" = (\"int\" & 1)", int &= 1) - AssertSQL("\"intOptional\" = (\"intOptional\" & \"int\")", intOptional &= int) - AssertSQL("\"intOptional\" = (\"intOptional\" & \"intOptional\")", intOptional &= intOptional) - AssertSQL("\"intOptional\" = (\"intOptional\" & 1)", intOptional &= 1) + assertSQL("\"int\" = (\"int\" & \"int\")", int &= int) + assertSQL("\"int\" = (\"int\" & 1)", int &= 1) + assertSQL("\"intOptional\" = (\"intOptional\" & \"int\")", intOptional &= int) + assertSQL("\"intOptional\" = (\"intOptional\" & \"intOptional\")", intOptional &= intOptional) + assertSQL("\"intOptional\" = (\"intOptional\" & 1)", intOptional &= 1) } func test_bitwiseOrEquals_withIntegerExpression_buildsSetter() { - AssertSQL("\"int\" = (\"int\" | \"int\")", int |= int) - AssertSQL("\"int\" = (\"int\" | 1)", int |= 1) - AssertSQL("\"intOptional\" = (\"intOptional\" | \"int\")", intOptional |= int) - AssertSQL("\"intOptional\" = (\"intOptional\" | \"intOptional\")", intOptional |= intOptional) - AssertSQL("\"intOptional\" = (\"intOptional\" | 1)", intOptional |= 1) + assertSQL("\"int\" = (\"int\" | \"int\")", int |= int) + assertSQL("\"int\" = (\"int\" | 1)", int |= 1) + assertSQL("\"intOptional\" = (\"intOptional\" | \"int\")", intOptional |= int) + assertSQL("\"intOptional\" = (\"intOptional\" | \"intOptional\")", intOptional |= intOptional) + assertSQL("\"intOptional\" = (\"intOptional\" | 1)", intOptional |= 1) } func test_bitwiseExclusiveOrEquals_withIntegerExpression_buildsSetter() { - AssertSQL("\"int\" = (~((\"int\" & \"int\")) & (\"int\" | \"int\"))", int ^= int) - AssertSQL("\"int\" = (~((\"int\" & 1)) & (\"int\" | 1))", int ^= 1) - AssertSQL("\"intOptional\" = (~((\"intOptional\" & \"int\")) & (\"intOptional\" | \"int\"))", intOptional ^= int) - AssertSQL("\"intOptional\" = (~((\"intOptional\" & \"intOptional\")) & (\"intOptional\" | \"intOptional\"))", intOptional ^= intOptional) - AssertSQL("\"intOptional\" = (~((\"intOptional\" & 1)) & (\"intOptional\" | 1))", intOptional ^= 1) + assertSQL("\"int\" = (~((\"int\" & \"int\")) & (\"int\" | \"int\"))", int ^= int) + assertSQL("\"int\" = (~((\"int\" & 1)) & (\"int\" | 1))", int ^= 1) + assertSQL("\"intOptional\" = (~((\"intOptional\" & \"int\")) & (\"intOptional\" | \"int\"))", intOptional ^= int) + assertSQL("\"intOptional\" = (~((\"intOptional\" & \"intOptional\")) & (\"intOptional\" | \"intOptional\"))", intOptional ^= intOptional) + assertSQL("\"intOptional\" = (~((\"intOptional\" & 1)) & (\"intOptional\" | 1))", intOptional ^= 1) } func test_postfixPlus_withIntegerValue_buildsSetter() { - AssertSQL("\"int\" = (\"int\" + 1)", int++) - AssertSQL("\"intOptional\" = (\"intOptional\" + 1)", intOptional++) + assertSQL("\"int\" = (\"int\" + 1)", int++) + assertSQL("\"intOptional\" = (\"intOptional\" + 1)", intOptional++) } func test_postfixMinus_withIntegerValue_buildsSetter() { - AssertSQL("\"int\" = (\"int\" - 1)", int--) - AssertSQL("\"intOptional\" = (\"intOptional\" - 1)", intOptional--) + assertSQL("\"int\" = (\"int\" - 1)", int--) + assertSQL("\"intOptional\" = (\"intOptional\" - 1)", intOptional--) } } diff --git a/Tests/SQLiteTests/StatementTests.swift b/Tests/SQLiteTests/StatementTests.swift index 326259b2..5a05675d 100644 --- a/Tests/SQLiteTests/StatementTests.swift +++ b/Tests/SQLiteTests/StatementTests.swift @@ -1,14 +1,14 @@ import XCTest import SQLite -class StatementTests : SQLiteTestCase { +class StatementTests: SQLiteTestCase { override func setUp() { super.setUp() - CreateUsersTable() + createUsersTable() } func test_cursor_to_blob() { - try! InsertUsers("alice") + try! insertUsers("alice") let statement = try! db.prepare("SELECT email FROM users") XCTAssert(try! statement.step()) let blob = statement.row[0] as Blob diff --git a/Tests/SQLiteTests/TestHelpers.swift b/Tests/SQLiteTests/TestHelpers.swift index 247013b4..0aa918f0 100644 --- a/Tests/SQLiteTests/TestHelpers.swift +++ b/Tests/SQLiteTests/TestHelpers.swift @@ -1,15 +1,15 @@ import XCTest @testable import SQLite -class SQLiteTestCase : XCTestCase { - private var trace:[String: Int]! - var db:Connection! +class SQLiteTestCase: XCTestCase { + private var trace: [String: Int]! + var db: Connection! let users = Table("users") override func setUp() { super.setUp() db = try! Connection() - trace = [String:Int]() + trace = [String: Int]() db.trace { SQL in print(SQL) @@ -17,7 +17,7 @@ class SQLiteTestCase : XCTestCase { } } - func CreateUsersTable() { + func createUsersTable() { try! db.execute(""" CREATE TABLE users ( id INTEGER PRIMARY KEY, @@ -33,22 +33,20 @@ class SQLiteTestCase : XCTestCase { ) } - func InsertUsers(_ names: String...) throws { - try InsertUsers(names) + func insertUsers(_ names: String...) throws { + try insertUsers(names) } - func InsertUsers(_ names: [String]) throws { - for name in names { try InsertUser(name) } + func insertUsers(_ names: [String]) throws { + for name in names { try insertUser(name) } } - @discardableResult func InsertUser(_ name: String, age: Int? = nil, admin: Bool = false) throws -> Statement { - return try db.run( - "INSERT INTO \"users\" (email, age, admin) values (?, ?, ?)", - "\(name)@example.com", age?.datatypeValue, admin.datatypeValue - ) + @discardableResult func insertUser(_ name: String, age: Int? = nil, admin: Bool = false) throws -> Statement { + try db.run("INSERT INTO \"users\" (email, age, admin) values (?, ?, ?)", + "\(name)@example.com", age?.datatypeValue, admin.datatypeValue) } - func AssertSQL(_ SQL: String, _ executions: Int = 1, _ message: String? = nil, file: StaticString = #file, line: UInt = #line) { + func assertSQL(_ SQL: String, _ executions: Int = 1, _ message: String? = nil, file: StaticString = #file, line: UInt = #line) { XCTAssertEqual( executions, trace[SQL] ?? 0, message ?? SQL, @@ -56,9 +54,9 @@ class SQLiteTestCase : XCTestCase { ) } - func AssertSQL(_ SQL: String, _ statement: Statement, _ message: String? = nil, file: StaticString = #file, line: UInt = #line) { + func assertSQL(_ SQL: String, _ statement: Statement, _ message: String? = nil, file: StaticString = #file, line: UInt = #line) { try! statement.run() - AssertSQL(SQL, 1, message, file: file, line: line) + assertSQL(SQL, 1, message, file: file, line: line) if let count = trace[SQL] { trace[SQL] = count - 1 } } @@ -97,7 +95,8 @@ let int64Optional = Expression("int64Optional") let string = Expression("string") let stringOptional = Expression("stringOptional") -func AssertSQL(_ expression1: @autoclosure () -> String, _ expression2: @autoclosure () -> Expressible, file: StaticString = #file, line: UInt = #line) { +func assertSQL(_ expression1: @autoclosure () -> String, _ expression2: @autoclosure () -> Expressible, + file: StaticString = #file, line: UInt = #line) { XCTAssertEqual(expression1(), expression2().asSQL(), file: file, line: line) } diff --git a/Tests/SQLiteTests/ValueTests.swift b/Tests/SQLiteTests/ValueTests.swift index bda2b4b3..f880cb34 100644 --- a/Tests/SQLiteTests/ValueTests.swift +++ b/Tests/SQLiteTests/ValueTests.swift @@ -1,6 +1,6 @@ import XCTest import SQLite -class ValueTests : XCTestCase { +class ValueTests: XCTestCase { } diff --git a/run-tests.sh b/run-tests.sh index 0a105c41..32465388 100755 --- a/run-tests.sh +++ b/run-tests.sh @@ -7,7 +7,11 @@ if [ -n "$BUILD_SCHEME" ]; then make test BUILD_SCHEME="$BUILD_SCHEME" fi elif [ -n "$VALIDATOR_SUBSPEC" ]; then - cd Tests/CocoaPods && make test + if [ "$VALIDATOR_SUBSPEC" == "none" ]; then + pod lib lint --no-subspecs --fail-fast + else + pod lib lint --subspec="${VALIDATOR_SUBSPEC}" --fail-fast + fi elif [ -n "$CARTHAGE_PLATFORM" ]; then cd Tests/Carthage && make test CARTHAGE_PLATFORM="$CARTHAGE_PLATFORM" elif [ -n "${PACKAGE_MANAGER_COMMAND}" ]; then